[BUGFIX] Opposite MM relation between both new entities not created
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / DataHandling / DataHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\DataHandling;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Doctrine\DBAL\Driver\Statement;
18 use TYPO3\CMS\Backend\Utility\BackendUtility;
19 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20 use TYPO3\CMS\Core\Cache\CacheManager;
21 use TYPO3\CMS\Core\Cache\Frontend\VariableFrontend;
22 use TYPO3\CMS\Core\Charset\CharsetConverter;
23 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
24 use TYPO3\CMS\Core\Database\ConnectionPool;
25 use TYPO3\CMS\Core\Database\DatabaseConnection;
26 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
27 use TYPO3\CMS\Core\Database\Query\Restriction\QueryRestrictionContainerInterface;
28 use TYPO3\CMS\Core\Database\ReferenceIndex;
29 use TYPO3\CMS\Core\Database\RelationHandler;
30 use TYPO3\CMS\Core\Html\RteHtmlParser;
31 use TYPO3\CMS\Core\Messaging\FlashMessage;
32 use TYPO3\CMS\Core\Messaging\FlashMessageService;
33 use TYPO3\CMS\Core\Resource\ResourceFactory;
34 use TYPO3\CMS\Core\Service\OpcodeCacheService;
35 use TYPO3\CMS\Core\Type\Bitmask\Permission;
36 use TYPO3\CMS\Core\Utility\ArrayUtility;
37 use TYPO3\CMS\Core\Utility\File\BasicFileUtility;
38 use TYPO3\CMS\Core\Utility\GeneralUtility;
39 use TYPO3\CMS\Core\Utility\MathUtility;
40 use TYPO3\CMS\Core\Utility\PathUtility;
41 use TYPO3\CMS\Core\Utility\StringUtility;
42 use TYPO3\CMS\Core\Versioning\VersionState;
43
44 /**
45 * The main data handler class which takes care of correctly updating and inserting records.
46 * This class was formerly known as TCEmain.
47 *
48 * This is the TYPO3 Core Engine class for manipulation of the database
49 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
50 *
51 * Dependencies:
52 * - $GLOBALS['TCA'] must exist
53 * - $GLOBALS['LANG'] must exist
54 *
55 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
56 */
57 class DataHandler
58 {
59 // *********************
60 // Public variables you can configure before using the class:
61 // *********************
62 /**
63 * If TRUE, the default log-messages will be stored. This should not be necessary if the locallang-file for the
64 * log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
65 *
66 * @var bool
67 */
68 public $storeLogMessages = true;
69
70 /**
71 * If TRUE, actions are logged to sys_log.
72 *
73 * @var bool
74 */
75 public $enableLogging = true;
76
77 /**
78 * If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new
79 * bunch of records.
80 *
81 * @var bool
82 */
83 public $reverseOrder = false;
84
85 /**
86 * If TRUE, only fields which are different from the database values are saved! In fact, if a whole input array
87 * is similar, it's not saved then.
88 *
89 * @var bool
90 */
91 public $checkSimilar = true;
92
93 /**
94 * This will read the record after having updated or inserted it. If anything is not properly submitted an error
95 * is written to the log. This feature consumes extra time by selecting records
96 *
97 * @var bool
98 */
99 public $checkStoredRecords = true;
100
101 /**
102 * If set, values '' and 0 will equal each other when the stored records are checked.
103 *
104 * @var bool
105 */
106 public $checkStoredRecords_loose = true;
107
108 /**
109 * If this is set, then a page is deleted by deleting the whole branch under it (user must have
110 * delete permissions to it all). If not set, then the page is deleted ONLY if it has no branch.
111 *
112 * @var bool
113 */
114 public $deleteTree = false;
115
116 /**
117 * If set, then the 'hideAtCopy' flag for tables will be ignored.
118 *
119 * @var bool
120 */
121 public $neverHideAtCopy = false;
122
123 /**
124 * If set, then the TCE class has been instantiated during an import action of a T3D
125 *
126 * @var bool
127 */
128 public $isImporting = false;
129
130 /**
131 * If set, then transformations are NOT performed on the input.
132 *
133 * @var bool
134 */
135 public $dontProcessTransformations = false;
136
137 /**
138 * TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value.
139 * FALSE: Will not update anything.
140 * "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
141 *
142 * @var bool|string
143 */
144 public $updateModeL10NdiffData = true;
145
146 /**
147 * If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again!
148 * It's meant as the opposite of declaring the record translated.
149 *
150 * @var bool
151 */
152 public $updateModeL10NdiffDataClear = false;
153
154 /**
155 * If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()).
156 * YOU MUST KNOW what you do if you use this feature!
157 *
158 * @var bool
159 */
160 public $bypassWorkspaceRestrictions = false;
161
162 /**
163 * If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away.
164 * YOU MUST KNOW what you are doing with this feature!
165 *
166 * @var bool
167 */
168 public $bypassFileHandling = false;
169
170 /**
171 * If TRUE, access check, check for deleted etc. for records is bypassed.
172 * YOU MUST KNOW what you are doing if you use this feature!
173 *
174 * @var bool
175 */
176 public $bypassAccessCheckForRecords = false;
177
178 /**
179 * Comma-separated list. This list of tables decides which tables will be copied. If empty then none will.
180 * If '*' then all will (that the user has permission to of course)
181 *
182 * @var string
183 */
184 public $copyWhichTables = '*';
185
186 /**
187 * If 0 then branch is NOT copied.
188 * If 1 then pages on the 1st level is copied.
189 * If 2 then pages on the second level is copied ... and so on
190 *
191 * @var int
192 */
193 public $copyTree = 0;
194
195 /**
196 * [table][fields]=value: New records are created with default values and you can set this array on the
197 * form $defaultValues[$table][$field] = $value to override the default values fetched from TCA.
198 * If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array
199 * (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
200 *
201 * @var array
202 */
203 public $defaultValues = array();
204
205 /**
206 * [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to
207 * override the incoming data. You must set this externally. You must make sure the fields in this array are also
208 * found in the table, because it's not checked. All columns can be set by this array!
209 *
210 * @var array
211 */
212 public $overrideValues = array();
213
214 /**
215 * [filename]=alternative_filename: Use this array to force another name onto a file.
216 * Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field,
217 * then 'my_file.txt' will be used as the name instead.
218 *
219 * @var array
220 */
221 public $alternativeFileName = array();
222
223 /**
224 * Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
225 *
226 * @var array
227 */
228 public $alternativeFilePath = array();
229
230 /**
231 * If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated.
232 * You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1.
233 * Then an empty checkbox will disable the field.
234 *
235 * @var array
236 */
237 public $data_disableFields = array();
238
239 /**
240 * Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option
241 * since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set
242 * it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete).
243 * The option is used for import of T3D files when synchronizing between two mirrored servers.
244 * As a security measure this feature is available only for Admin Users (for now)
245 *
246 * @var array
247 */
248 public $suggestedInsertUids = array();
249
250 /**
251 * Object. Call back object for FlexForm traversal. Useful when external classes wants to use the
252 * iteration functions inside DataHandler for traversing a FlexForm structure.
253 *
254 * @var object
255 */
256 public $callBackObj;
257
258 // *********************
259 // Internal variables (mapping arrays) which can be used (read-only) from outside
260 // *********************
261 /**
262 * Contains mapping of auto-versionized records.
263 *
264 * @var array
265 */
266 public $autoVersionIdMap = array();
267
268 /**
269 * When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
270 *
271 * @var array
272 */
273 public $substNEWwithIDs = array();
274
275 /**
276 * Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
277 *
278 * @var array
279 */
280 public $substNEWwithIDs_table = array();
281
282 /**
283 * Holds the tables and there the ids of newly created child records from IRRE
284 *
285 * @var array
286 */
287 public $newRelatedIDs = array();
288
289 /**
290 * This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
291 *
292 * @var array
293 */
294 public $copyMappingArray_merged = array();
295
296 /**
297 * A map between input file name and final destination for files being attached to records.
298 *
299 * @var array
300 */
301 public $copiedFileMap = array();
302
303 /**
304 * Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
305 *
306 * @var array
307 */
308 public $RTEmagic_copyIndex = array();
309
310 /**
311 * Errors are collected in this variable.
312 *
313 * @var array
314 */
315 public $errorLog = array();
316
317 /**
318 * Fields from the pages-table for which changes will trigger a pagetree refresh
319 *
320 * @var array
321 */
322 public $pagetreeRefreshFieldsFromPages = array('pid', 'sorting', 'deleted', 'hidden', 'title', 'doktype', 'is_siteroot', 'fe_group', 'nav_hide', 'nav_title', 'module', 'starttime', 'endtime', 'content_from_pid');
323
324 /**
325 * Indicates whether the pagetree needs a refresh because of important changes
326 *
327 * @var bool
328 */
329 public $pagetreeNeedsRefresh = false;
330
331 // *********************
332 // Internal Variables, do not touch.
333 // *********************
334
335 // Variables set in init() function:
336
337 /**
338 * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
339 *
340 * @var BackendUserAuthentication
341 */
342 public $BE_USER;
343
344 /**
345 * Will be set to uid of be_user executing this script
346 *
347 * @var int
348 */
349 public $userid;
350
351 /**
352 * Will be set to username of be_user executing this script
353 *
354 * @var string
355 */
356 public $username;
357
358 /**
359 * Will be set if user is admin
360 *
361 * @var bool
362 */
363 public $admin;
364
365 /**
366 * Can be overridden from $GLOBALS['TYPO3_CONF_VARS']
367 *
368 * @var array
369 */
370 public $defaultPermissions = array(
371 'user' => 'show,edit,delete,new,editcontent',
372 'group' => 'show,edit,new,editcontent',
373 'everybody' => ''
374 );
375
376 /**
377 * The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
378 *
379 * @var array
380 */
381 protected $excludedTablesAndFields = array();
382
383 /**
384 * Data submitted from the form view, used to control behaviours,
385 * e.g. this is used to activate/deactivate fields and thus store NULL values
386 *
387 * @var array
388 */
389 protected $control = array();
390
391 /**
392 * Set with incoming data array
393 *
394 * @var array
395 */
396 public $datamap = array();
397
398 /**
399 * Set with incoming cmd array
400 *
401 * @var array
402 */
403 public $cmdmap = array();
404
405 /**
406 * List of changed old record ids to new records ids
407 *
408 * @var array
409 */
410 protected $mmHistoryRecords = array();
411
412 /**
413 * List of changed old record ids to new records ids
414 *
415 * @var array
416 */
417 protected $historyRecords = array();
418
419 // Internal static:
420 /**
421 * Permission mapping
422 *
423 * @var array
424 */
425 public $pMap = array(
426 'show' => 1,
427 // 1st bit
428 'edit' => 2,
429 // 2nd bit
430 'delete' => 4,
431 // 3rd bit
432 'new' => 8,
433 // 4th bit
434 'editcontent' => 16
435 );
436
437 /**
438 * Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
439 *
440 * @var int
441 */
442 public $sortIntervals = 256;
443
444 // Internal caching arrays
445 /**
446 * Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
447 *
448 * @var array
449 */
450 public $recUpdateAccessCache = array();
451
452 /**
453 * User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
454 *
455 * @var array
456 */
457 public $recInsertAccessCache = array();
458
459 /**
460 * Caching array for check of whether records are in a webmount
461 *
462 * @var array
463 */
464 public $isRecordInWebMount_Cache = array();
465
466 /**
467 * Caching array for page ids in webmounts
468 *
469 * @var array
470 */
471 public $isInWebMount_Cache = array();
472
473 /**
474 * Caching for collecting TSconfig for page ids
475 *
476 * @var array
477 */
478 public $cachedTSconfig = array();
479
480 /**
481 * Used for caching page records in pageInfo()
482 *
483 * @var array
484 */
485 public $pageCache = array();
486
487 /**
488 * Array caching workspace access for BE_USER
489 *
490 * @var array
491 */
492 public $checkWorkspaceCache = array();
493
494 // Other arrays:
495 /**
496 * For accumulation of MM relations that must be written after new records are created.
497 *
498 * @var array
499 */
500 public $dbAnalysisStore = array();
501
502 /**
503 * For accumulation of files which must be deleted after processing of all input content
504 *
505 * @var array
506 */
507 public $removeFilesStore = array();
508
509 /**
510 * Uploaded files, set by process_uploads()
511 *
512 * @var array
513 */
514 public $uploadedFileArray = array();
515
516 /**
517 * Used for tracking references that might need correction after operations
518 *
519 * @var array
520 */
521 public $registerDBList = array();
522
523 /**
524 * Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
525 *
526 * @var array
527 */
528 public $registerDBPids = array();
529
530 /**
531 * Used by the copy action to track the ids of new pages so subpages are correctly inserted!
532 * THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE!
533 * Read from copyMappingArray_merged instead which is accumulating this information.
534 *
535 * NOTE: This is used by some outside scripts (e.g. hooks), as the results in $copyMappingArray_merged
536 * are only available after an action has been completed.
537 *
538 * @var array
539 */
540 public $copyMappingArray = array();
541
542 /**
543 * Array used for remapping uids and values at the end of process_datamap
544 *
545 * @var array
546 */
547 public $remapStack = array();
548
549 /**
550 * Array used for remapping uids and values at the end of process_datamap
551 * (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
552 *
553 * @var array
554 */
555 public $remapStackRecords = array();
556
557 /**
558 * Array used for checking whether new children need to be remapped
559 *
560 * @var array
561 */
562 protected $remapStackChildIds = array();
563
564 /**
565 * Array used for executing addition actions after remapping happened (set processRemapStack())
566 *
567 * @var array
568 */
569 protected $remapStackActions = array();
570
571 /**
572 * Array used for executing post-processing on the reference index
573 *
574 * @var array
575 */
576 protected $remapStackRefIndex = array();
577
578 /**
579 * Array used for additional calls to $this->updateRefIndex
580 *
581 * @var array
582 */
583 public $updateRefIndexStack = array();
584
585 /**
586 * Tells, that this DataHandler instance was called from \TYPO3\CMS\Impext\ImportExport.
587 * This variable is set by \TYPO3\CMS\Impext\ImportExport
588 *
589 * @var array
590 */
591 public $callFromImpExp = false;
592
593 /**
594 * Array for new flexform index mapping
595 *
596 * @var array
597 */
598 public $newIndexMap = array();
599
600 // Various
601 /**
602 * basicFileFunctions object
603 * For "singleton" file-manipulation object
604 *
605 * @var BasicFileUtility
606 */
607 public $fileFunc;
608
609 /**
610 * Set to "currentRecord" during checking of values.
611 *
612 * @var array
613 */
614 public $checkValue_currentRecord = array();
615
616 /**
617 * A signal flag used to tell file processing that auto versioning has happened and hence certain action should be applied.
618 *
619 * @var bool
620 */
621 public $autoVersioningUpdate = false;
622
623 /**
624 * Disable delete clause
625 *
626 * @var bool
627 */
628 protected $disableDeleteClause = false;
629
630 /**
631 * @var array
632 */
633 protected $checkModifyAccessListHookObjects;
634
635 /**
636 * @var array
637 */
638 protected $version_remapMMForVersionSwap_reg;
639
640 /**
641 * The outer most instance of \TYPO3\CMS\Core\DataHandling\DataHandler:
642 * This object instantiates itself on versioning and localization ...
643 *
644 * @var \TYPO3\CMS\Core\DataHandling\DataHandler
645 */
646 protected $outerMostInstance = null;
647
648 /**
649 * Internal cache for collecting records that should trigger cache clearing
650 *
651 * @var array
652 */
653 protected static $recordsToClearCacheFor = array();
654
655 /**
656 * Internal cache for pids of records which were deleted. It's not possible
657 * to retrieve the parent folder/page at a later stage
658 *
659 * @var array
660 */
661 protected static $recordPidsForDeletedRecords = array();
662
663 /**
664 * Database layer. Identical to $GLOBALS['TYPO3_DB']
665 *
666 * @var DatabaseConnection
667 */
668 protected $databaseConnection;
669
670 /**
671 * Runtime Cache to store and retrieve data computed for a single request
672 *
673 * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend
674 */
675 protected $runtimeCache = null;
676
677 /**
678 * Prefix for the cache entries of nested element calls since the runtimeCache has a global scope.
679 *
680 * @var string
681 */
682 protected $cachePrefixNestedElementCalls = 'core-datahandler-nestedElementCalls-';
683
684 /**
685 *
686 */
687 public function __construct()
688 {
689 $this->databaseConnection = $GLOBALS['TYPO3_DB'];
690 $this->runtimeCache = $this->getRuntimeCache();
691 }
692
693 /**
694 * @param array $control
695 */
696 public function setControl(array $control)
697 {
698 $this->control = $control;
699 }
700
701 /**
702 * Initializing.
703 * For details, see 'TYPO3 Core API' document.
704 * This function does not start the processing of data, but merely initializes the object
705 *
706 * @param array $data Data to be modified or inserted in the database
707 * @param array $cmd Commands to copy, move, delete, localize, versionize records.
708 * @param BackendUserAuthentication|NULL $altUserObject An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
709 * @return void
710 */
711 public function start($data, $cmd, $altUserObject = null)
712 {
713 // Initializing BE_USER
714 $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
715 $this->userid = $this->BE_USER->user['uid'];
716 $this->username = $this->BE_USER->user['username'];
717 $this->admin = $this->BE_USER->user['admin'];
718 if ($this->BE_USER->uc['recursiveDelete']) {
719 $this->deleteTree = 1;
720 }
721 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData === true) {
722 $this->updateModeL10NdiffData = false;
723 }
724 // Initializing default permissions for pages
725 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
726 if (isset($defaultPermissions['user'])) {
727 $this->defaultPermissions['user'] = $defaultPermissions['user'];
728 }
729 if (isset($defaultPermissions['group'])) {
730 $this->defaultPermissions['group'] = $defaultPermissions['group'];
731 }
732 if (isset($defaultPermissions['everybody'])) {
733 $this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];
734 }
735 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
736 if (!$this->admin) {
737 $this->excludedTablesAndFields = array_flip($this->getExcludeListArray());
738 }
739 // Setting the data and cmd arrays
740 if (is_array($data)) {
741 reset($data);
742 $this->datamap = $data;
743 }
744 if (is_array($cmd)) {
745 reset($cmd);
746 $this->cmdmap = $cmd;
747 }
748 }
749
750 /**
751 * Function that can mirror input values in datamap-array to other uid numbers.
752 * Example: $mirror[table][11] = '22,33' will look for content in $this->datamap[table][11] and copy it to $this->datamap[table][22] and $this->datamap[table][33]
753 *
754 * @param array $mirror This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
755 * @return void
756 */
757 public function setMirror($mirror)
758 {
759 if (!is_array($mirror)) {
760 return;
761 }
762
763 foreach ($mirror as $table => $uid_array) {
764 if (!isset($this->datamap[$table])) {
765 continue;
766 }
767
768 foreach ($uid_array as $id => $uidList) {
769 if (!isset($this->datamap[$table][$id])) {
770 continue;
771 }
772
773 $theIdsInArray = GeneralUtility::trimExplode(',', $uidList, true);
774 foreach ($theIdsInArray as $copyToUid) {
775 $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
776 }
777 }
778 }
779 }
780
781 /**
782 * Initializes default values coming from User TSconfig
783 *
784 * @param array $userTS User TSconfig array
785 * @return void
786 */
787 public function setDefaultsFromUserTS($userTS)
788 {
789 if (!is_array($userTS)) {
790 return;
791 }
792
793 foreach ($userTS as $k => $v) {
794 $k = substr($k, 0, -1);
795 if (!$k || !is_array($v) || !isset($GLOBALS['TCA'][$k])) {
796 continue;
797 }
798
799 if (is_array($this->defaultValues[$k])) {
800 $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
801 } else {
802 $this->defaultValues[$k] = $v;
803 }
804 }
805 }
806
807 /**
808 * Processing of uploaded files.
809 * It turns out that some versions of PHP arranges submitted data for files different if sent in an array. This function will unify this so the internal array $this->uploadedFileArray will always contain files arranged in the same structure.
810 *
811 * @param array $postFiles $_FILES array
812 * @return void
813 */
814 public function process_uploads($postFiles)
815 {
816 if (!is_array($postFiles)) {
817 return;
818 }
819
820 // Editing frozen:
821 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
822 if ($this->enableLogging) {
823 $this->newlog('All editing in this workspace has been frozen!', 1);
824 }
825 return;
826 }
827 $subA = reset($postFiles);
828 if (is_array($subA)) {
829 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
830 // Initialize the uploadedFilesArray:
831 $this->uploadedFileArray = array();
832 // For each entry:
833 foreach ($subA as $key => $values) {
834 $this->process_uploads_traverseArray($this->uploadedFileArray, $values, $key);
835 }
836 } else {
837 $this->uploadedFileArray = $subA;
838 }
839 }
840 }
841
842 /**
843 * Traverse the upload array if needed to rearrange values.
844 *
845 * @param array $outputArr $this->uploadedFileArray passed by reference
846 * @param array $inputArr Input array ($_FILES parts)
847 * @param string $keyToSet The current $_FILES array key to set on the outermost level.
848 * @return void
849 * @access private
850 * @see process_uploads()
851 */
852 public function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet)
853 {
854 if (is_array($inputArr)) {
855 foreach ($inputArr as $key => $value) {
856 $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
857 }
858 } else {
859 $outputArr[$keyToSet] = $inputArr;
860 }
861 }
862
863 /*********************************************
864 *
865 * HOOKS
866 *
867 *********************************************/
868 /**
869 * Hook: processDatamap_afterDatabaseOperations
870 * (calls $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);)
871 *
872 * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
873 * but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
874 *
875 * @param array $hookObjectsArr (reference) Array with hook objects
876 * @param string $status (reference) Status of the current operation, 'new' or 'update
877 * @param string $table (reference) The table currently processing data for
878 * @param string $id (reference) The record uid currently processing data for, [integer] or [string] (like 'NEW...')
879 * @param array $fieldArray (reference) The field array of a record
880 * @return void
881 */
882 public function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray)
883 {
884 // Process hook directly:
885 if (!isset($this->remapStackRecords[$table][$id])) {
886 foreach ($hookObjectsArr as $hookObj) {
887 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
888 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
889 }
890 }
891 } else {
892 $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
893 'status' => $status,
894 'fieldArray' => $fieldArray,
895 'hookObjectsArr' => $hookObjectsArr
896 );
897 }
898 }
899
900 /**
901 * Gets the 'checkModifyAccessList' hook objects.
902 * The first call initializes the accordant objects.
903 *
904 * @return array The 'checkModifyAccessList' hook objects (if any)
905 * @throws \UnexpectedValueException
906 */
907 protected function getCheckModifyAccessListHookObjects()
908 {
909 if (!isset($this->checkModifyAccessListHookObjects)) {
910 $this->checkModifyAccessListHookObjects = array();
911 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
912 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
913 $hookObject = GeneralUtility::getUserObj($classData);
914 if (!$hookObject instanceof DataHandlerCheckModifyAccessListHookInterface) {
915 throw new \UnexpectedValueException($classData . ' must implement interface ' . DataHandlerCheckModifyAccessListHookInterface::class, 1251892472);
916 }
917 $this->checkModifyAccessListHookObjects[] = $hookObject;
918 }
919 }
920 }
921 return $this->checkModifyAccessListHookObjects;
922 }
923
924 /*********************************************
925 *
926 * PROCESSING DATA
927 *
928 *********************************************/
929 /**
930 * Processing the data-array
931 * Call this function to process the data-array set by start()
932 *
933 * @return void|FALSE
934 */
935 public function process_datamap()
936 {
937 $this->controlActiveElements();
938
939 // Keep versionized(!) relations here locally:
940 $registerDBList = array();
941 $this->registerElementsToBeDeleted();
942 $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
943 // Editing frozen:
944 if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
945 if ($this->enableLogging) {
946 $this->newlog('All editing in this workspace has been frozen!', 1);
947 }
948 return false;
949 }
950 // First prepare user defined objects (if any) for hooks which extend this function:
951 $hookObjectsArr = array();
952 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
953 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
954 $hookObject = GeneralUtility::getUserObj($classRef);
955 if (method_exists($hookObject, 'processDatamap_beforeStart')) {
956 $hookObject->processDatamap_beforeStart($this);
957 }
958 $hookObjectsArr[] = $hookObject;
959 }
960 }
961 // Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
962 $orderOfTables = array();
963 // Set pages first.
964 if (isset($this->datamap['pages'])) {
965 $orderOfTables[] = 'pages';
966 }
967 $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
968 // Process the tables...
969 foreach ($orderOfTables as $table) {
970 // Check if
971 // - table is set in $GLOBALS['TCA'],
972 // - table is NOT readOnly
973 // - the table is set with content in the data-array (if not, there's nothing to process...)
974 // - permissions for tableaccess OK
975 $modifyAccessList = $this->checkModifyAccessList($table);
976 if ($this->enableLogging && !$modifyAccessList) {
977 $this->log($table, 0, 2, 0, 1, 'Attempt to modify table \'%s\' without permission', 1, array($table));
978 }
979 if (!isset($GLOBALS['TCA'][$table]) || $this->tableReadOnly($table) || !is_array($this->datamap[$table]) || !$modifyAccessList) {
980 continue;
981 }
982
983 if ($this->reverseOrder) {
984 $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
985 }
986 // For each record from the table, do:
987 // $id is the record uid, may be a string if new records...
988 // $incomingFieldArray is the array of fields
989 foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
990 if (!is_array($incomingFieldArray)) {
991 continue;
992 }
993 $theRealPid = null;
994
995 // Handle native date/time fields
996 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
997 foreach ($GLOBALS['TCA'][$table]['columns'] as $column => $config) {
998 if (isset($incomingFieldArray[$column])) {
999 if (isset($config['config']['dbType']) && ($config['config']['dbType'] === 'date' || $config['config']['dbType'] === 'datetime')) {
1000 $emptyValue = $dateTimeFormats[$config['config']['dbType']]['empty'];
1001 $format = $dateTimeFormats[$config['config']['dbType']]['format'];
1002 $incomingFieldArray[$column] = $incomingFieldArray[$column] && $incomingFieldArray[$column] !== $emptyValue ? gmdate($format, $incomingFieldArray[$column]) : $emptyValue;
1003 }
1004 }
1005 }
1006 // Hook: processDatamap_preProcessFieldArray
1007 foreach ($hookObjectsArr as $hookObj) {
1008 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
1009 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
1010 }
1011 }
1012 // ******************************
1013 // Checking access to the record
1014 // ******************************
1015 $createNewVersion = false;
1016 $recordAccess = false;
1017 $old_pid_value = '';
1018 $this->autoVersioningUpdate = false;
1019 // Is it a new record? (Then Id is a string)
1020 if (!MathUtility::canBeInterpretedAsInteger($id)) {
1021 // Get a fieldArray with default values
1022 $fieldArray = $this->newFieldArray($table);
1023 // A pid must be set for new records.
1024 if (isset($incomingFieldArray['pid'])) {
1025 // $value = the pid
1026 $pid_value = $incomingFieldArray['pid'];
1027 // Checking and finding numerical pid, it may be a string-reference to another value
1028 $OK = 1;
1029 // If a NEW... id
1030 if (strstr($pid_value, 'NEW')) {
1031 if ($pid_value[0] === '-') {
1032 $negFlag = -1;
1033 $pid_value = substr($pid_value, 1);
1034 } else {
1035 $negFlag = 1;
1036 }
1037 // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
1038 if (isset($this->substNEWwithIDs[$pid_value])) {
1039 if ($negFlag === 1) {
1040 $old_pid_value = $this->substNEWwithIDs[$pid_value];
1041 }
1042 $pid_value = (int)($negFlag * $this->substNEWwithIDs[$pid_value]);
1043 } else {
1044 $OK = 0;
1045 }
1046 }
1047 $pid_value = (int)$pid_value;
1048 // The $pid_value is now the numerical pid at this point
1049 if ($OK) {
1050 $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
1051 // Points to a page on which to insert the element, possibly in the top of the page
1052 if ($pid_value >= 0) {
1053 // If this table is sorted we better find the top sorting number
1054 if ($sortRow) {
1055 $fieldArray[$sortRow] = $this->getSortNumber($table, 0, $pid_value);
1056 }
1057 // The numerical pid is inserted in the data array
1058 $fieldArray['pid'] = $pid_value;
1059 } else {
1060 // points to another record before ifself
1061 // If this table is sorted we better find the top sorting number
1062 if ($sortRow) {
1063 // Because $pid_value is < 0, getSortNumber returns an array
1064 $tempArray = $this->getSortNumber($table, 0, $pid_value);
1065 $fieldArray['pid'] = $tempArray['pid'];
1066 $fieldArray[$sortRow] = $tempArray['sortNumber'];
1067 } else {
1068 // Here we fetch the PID of the record that we point to...
1069 $tempdata = $this->recordInfo($table, abs($pid_value), 'pid');
1070 $fieldArray['pid'] = $tempdata['pid'];
1071 }
1072 }
1073 }
1074 }
1075 $theRealPid = $fieldArray['pid'];
1076 // Now, check if we may insert records on this pid.
1077 if ($theRealPid >= 0) {
1078 // Checks if records can be inserted on this $pid.
1079 $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid);
1080 if ($recordAccess) {
1081 $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
1082 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, true);
1083 if (!$recordAccess) {
1084 if ($this->enableLogging) {
1085 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
1086 }
1087 } elseif (!$this->bypassWorkspaceRestrictions) {
1088 // Workspace related processing:
1089 // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
1090 if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid, $table)) {
1091 if ($res < 0) {
1092 $recordAccess = false;
1093 if ($this->enableLogging) {
1094 $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
1095 }
1096 }
1097 } else {
1098 // So, if no live records were allowed, we have to create a new version of this record:
1099 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1100 $createNewVersion = true;
1101 } else {
1102 $recordAccess = false;
1103 if ($this->enableLogging) {
1104 $this->newlog('Record could not be created in this workspace in this branch', 1);
1105 }
1106 }
1107 }
1108 }
1109 }
1110 } else {
1111 debug('Internal ERROR: pid should not be less than zero!');
1112 }
1113 // Yes new record, change $record_status to 'insert'
1114 $status = 'new';
1115 } else {
1116 // Nope... $id is a number
1117 $fieldArray = array();
1118 $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
1119 if (!$recordAccess) {
1120 if ($this->enableLogging) {
1121 $propArr = $this->getRecordProperties($table, $id);
1122 $this->log($table, $id, 2, 0, 1, 'Attempt to modify record \'%s\' (%s) without permission. Or non-existing page.', 2, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']);
1123 }
1124 continue;
1125 }
1126 // Next check of the record permissions (internals)
1127 $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
1128 if (!$recordAccess) {
1129 if ($this->enableLogging) {
1130 $this->newlog('recordEditAccessInternals() check failed. [' . $this->BE_USER->errorMsg . ']', 1);
1131 }
1132 } else {
1133 // Here we fetch the PID of the record that we point to...
1134 $tempdata = $this->recordInfo($table, $id, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
1135 $theRealPid = $tempdata['pid'];
1136 // Use the new id of the versionized record we're trying to write to:
1137 // (This record is a child record of a parent and has already been versionized.)
1138 if ($this->autoVersionIdMap[$table][$id]) {
1139 // For the reason that creating a new version of this record, automatically
1140 // created related child records (e.g. "IRRE"), update the accordant field:
1141 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1142 // Use the new id of the copied/versionized record:
1143 $id = $this->autoVersionIdMap[$table][$id];
1144 $recordAccess = true;
1145 $this->autoVersioningUpdate = true;
1146 } elseif (!$this->bypassWorkspaceRestrictions && ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata))) {
1147 $recordAccess = false;
1148 // Versioning is required and it must be offline version!
1149 // Check if there already is a workspace version
1150 $WSversion = BackendUtility::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id, 'uid,t3ver_oid');
1151 if ($WSversion) {
1152 $id = $WSversion['uid'];
1153 $recordAccess = true;
1154 } elseif ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
1155 // new version of a record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1156 $this->pagetreeNeedsRefresh = true;
1157
1158 /** @var $tce DataHandler */
1159 $tce = GeneralUtility::makeInstance(__CLASS__);
1160 $tce->enableLogging = $this->enableLogging;
1161 // Setting up command for creating a new version of the record:
1162 $cmd = array();
1163 $cmd[$table][$id]['version'] = array(
1164 'action' => 'new',
1165 'treeLevels' => -1,
1166 // Default is to create a version of the individual records... element versioning that is.
1167 'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
1168 );
1169 $tce->start(array(), $cmd);
1170 $tce->process_cmdmap();
1171 $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
1172 // If copying was successful, share the new uids (also of related children):
1173 if ($tce->copyMappingArray[$table][$id]) {
1174 foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
1175 foreach ($origIdArray as $origId => $newId) {
1176 $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
1177 $this->autoVersionIdMap[$origTable][$origId] = $newId;
1178 }
1179 }
1180 ArrayUtility::mergeRecursiveWithOverrule($this->RTEmagic_copyIndex, $tce->RTEmagic_copyIndex);
1181 // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
1182 // Update registerDBList, that holds the copied relations to child records:
1183 $registerDBList = array_merge($registerDBList, $tce->registerDBList);
1184 // For the reason that creating a new version of this record, automatically
1185 // created related child records (e.g. "IRRE"), update the accordant field:
1186 $this->getVersionizedIncomingFieldArray($table, $id, $incomingFieldArray, $registerDBList);
1187 // Use the new id of the copied/versionized record:
1188 $id = $this->autoVersionIdMap[$table][$id];
1189 $recordAccess = true;
1190 $this->autoVersioningUpdate = true;
1191 } elseif ($this->enableLogging) {
1192 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version failed!', 1);
1193 }
1194 } elseif ($this->enableLogging) {
1195 $this->newlog('Could not be edited in offline workspace in the branch where found (failure state: \'' . $errorCode . '\'). Auto-creation of version not allowed in workspace!', 1);
1196 }
1197 }
1198 }
1199 // The default is 'update'
1200 $status = 'update';
1201 }
1202 // If access was granted above, proceed to create or update record:
1203 if (!$recordAccess) {
1204 continue;
1205 }
1206
1207 // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
1208 list($tscPID) = BackendUtility::getTSCpid($table, $id, $old_pid_value ? $old_pid_value : $fieldArray['pid']);
1209 if ($status === 'new' && $table === 'pages') {
1210 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
1211 if (isset($TSConfig['permissions.']) && is_array($TSConfig['permissions.'])) {
1212 $fieldArray = $this->setTSconfigPermissions($fieldArray, $TSConfig['permissions.']);
1213 }
1214 }
1215 // Processing of all fields in incomingFieldArray and setting them in $fieldArray
1216 $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
1217 $newVersion_placeholderFieldArray = array();
1218 if ($createNewVersion) {
1219 // create a placeholder array with already processed field content
1220 $newVersion_placeholderFieldArray = $fieldArray;
1221 }
1222 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
1223 // Forcing some values unto field array:
1224 // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
1225 $fieldArray = $this->overrideFieldArray($table, $fieldArray);
1226 if ($createNewVersion) {
1227 $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
1228 }
1229 // Setting system fields
1230 if ($status == 'new') {
1231 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1232 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1233 if ($createNewVersion) {
1234 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1235 }
1236 }
1237 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1238 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1239 if ($createNewVersion) {
1240 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
1241 }
1242 }
1243 } elseif ($this->checkSimilar) {
1244 // Removing fields which are equal to the current value:
1245 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
1246 }
1247 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && !empty($fieldArray)) {
1248 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1249 if ($createNewVersion) {
1250 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1251 }
1252 }
1253 // Set stage to "Editing" to make sure we restart the workflow
1254 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
1255 $fieldArray['t3ver_stage'] = 0;
1256 }
1257 // Hook: processDatamap_postProcessFieldArray
1258 foreach ($hookObjectsArr as $hookObj) {
1259 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
1260 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
1261 }
1262 }
1263 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
1264 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
1265 if (is_array($fieldArray)) {
1266 if ($status == 'new') {
1267 if ($table === 'pages') {
1268 // for new pages always a refresh is needed
1269 $this->pagetreeNeedsRefresh = true;
1270 }
1271
1272 // This creates a new version of the record with online placeholder and offline version
1273 if ($createNewVersion) {
1274 // new record created in a workspace - so always refresh pagetree to indicate there is a change in the workspace
1275 $this->pagetreeNeedsRefresh = true;
1276
1277 $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
1278 // Setting placeholder state value for temporary record
1279 $newVersion_placeholderFieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER);
1280 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1281 $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1282 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = $this->getPlaceholderTitleForTableLabel($table);
1283 // Saving placeholder as 'original'
1284 $this->insertDB($table, $id, $newVersion_placeholderFieldArray, false);
1285 // For the actual new offline version, set versioning values to point to placeholder:
1286 $fieldArray['pid'] = -1;
1287 $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
1288 $fieldArray['t3ver_id'] = 1;
1289 // Setting placeholder state value for version (so it can know it is currently a new version...)
1290 $fieldArray['t3ver_state'] = (string)new VersionState(VersionState::NEW_PLACEHOLDER_VERSION);
1291 $fieldArray['t3ver_label'] = 'First draft version';
1292 $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
1293 // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
1294 $phShadowId = $this->insertDB($table, $id, $fieldArray, true, 0, true);
1295 if ($phShadowId) {
1296 // Processes fields of the placeholder record:
1297 $this->triggerRemapAction($table, $id, array($this, 'placeholderShadowing'), array($table, $phShadowId));
1298 // Hold auto-versionized ids of placeholders:
1299 $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
1300 }
1301 } else {
1302 $this->insertDB($table, $id, $fieldArray, false, $incomingFieldArray['uid']);
1303 }
1304 } else {
1305 if ($table === 'pages') {
1306 // only a certain number of fields needs to be checked for updates
1307 // if $this->checkSimilar is TRUE, fields with unchanged values are already removed here
1308 $fieldsToCheck = array_intersect($this->pagetreeRefreshFieldsFromPages, array_keys($fieldArray));
1309 if (!empty($fieldsToCheck)) {
1310 $this->pagetreeNeedsRefresh = true;
1311 }
1312 }
1313 $this->updateDB($table, $id, $fieldArray);
1314 $this->placeholderShadowing($table, $id);
1315 }
1316 }
1317 // Hook: processDatamap_afterDatabaseOperations
1318 // Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
1319 // but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
1320 $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
1321 }
1322 }
1323 // Process the stack of relations to remap/correct
1324 $this->processRemapStack();
1325 $this->dbAnalysisStoreExec();
1326 $this->removeRegisteredFiles();
1327 // Hook: processDatamap_afterAllOperations
1328 // Note: When this hook gets called, all operations on the submitted data have been finished.
1329 foreach ($hookObjectsArr as $hookObj) {
1330 if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
1331 $hookObj->processDatamap_afterAllOperations($this);
1332 }
1333 }
1334 if ($this->isOuterMostInstance()) {
1335 $this->processClearCacheQueue();
1336 $this->resetElementsToBeDeleted();
1337 }
1338 }
1339
1340 /**
1341 * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record:
1342 *
1343 * @param string $table Table name
1344 * @param int $id Record uid
1345 * @return void
1346 */
1347 public function placeholderShadowing($table, $id)
1348 {
1349 if ($liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, '*')) {
1350 if (VersionState::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1351 $justStoredRecord = BackendUtility::getRecord($table, $id);
1352 $newRecord = array();
1353 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1354 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1355 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1356 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1357 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1358 $shadowColumns = array_unique(GeneralUtility::trimExplode(',', $shadowCols, true));
1359 foreach ($shadowColumns as $fieldName) {
1360 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1361 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1362 }
1363 }
1364 if (!empty($newRecord)) {
1365 if ($this->enableLogging) {
1366 $this->newlog2('Shadowing done on fields <i>' . implode(',', array_keys($newRecord)) . '</i> in placeholder record ' . $table . ':' . $liveRec['uid'] . ' (offline version UID=' . $id . ')', $table, $liveRec['uid'], $liveRec['pid']);
1367 }
1368 $this->updateDB($table, $liveRec['uid'], $newRecord);
1369 }
1370 }
1371 }
1372 }
1373
1374 /**
1375 * Create a placeholder title for the label field that does match the field requirements
1376 *
1377 * @param string $table The table name
1378 * @param string $placeholderContent Placeholder content to be used
1379 * @return string placeholder value
1380 */
1381 public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1382 {
1383 if ($placeholderContent === null) {
1384 $placeholderContent = 'PLACEHOLDER';
1385 }
1386
1387 $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER->workspace . ']';
1388 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1389 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1390 return $labelPlaceholder;
1391 }
1392 $evalCodesArray = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1393 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '');
1394 return isset($transformedLabel['value']) ? $transformedLabel['value'] : $labelPlaceholder;
1395 }
1396
1397 /**
1398 * Filling in the field array
1399 * $this->excludedTablesAndFields is used to filter fields if needed.
1400 *
1401 * @param string $table Table name
1402 * @param int $id Record ID
1403 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1404 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1405 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
1406 * @param string $status Is 'new' or 'update'
1407 * @param int $tscPID TSconfig PID
1408 * @return array Field Array
1409 */
1410 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1411 {
1412 // Initialize:
1413 $originalLanguageRecord = null;
1414 $originalLanguage_diffStorage = null;
1415 $diffStorageFlag = false;
1416 // Setting 'currentRecord' and 'checkValueRecord':
1417 if (strstr($id, 'NEW')) {
1418 // Must have the 'current' array - not the values after processing below...
1419 $currentRecord = ($checkValueRecord = $fieldArray);
1420 // IF $incomingFieldArray is an array, overlay it.
1421 // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
1422 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1423 ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1424 }
1425 } else {
1426 // We must use the current values as basis for this!
1427 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1428 // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
1429 BackendUtility::fixVersioningPid($table, $currentRecord);
1430 // Get original language record if available:
1431 if (is_array($currentRecord) && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'] && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
1432 $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ?: $table;
1433 $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1434 BackendUtility::workspaceOL($lookUpTable, $originalLanguageRecord);
1435 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1436 }
1437 }
1438 $this->checkValue_currentRecord = $checkValueRecord;
1439 // In the following all incoming value-fields are tested:
1440 // - Are the user allowed to change the field?
1441 // - Is the field uid/pid (which are already set)
1442 // - perms-fields for pages-table, then do special things...
1443 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1444 // If everything is OK, the field is entered into $fieldArray[]
1445 foreach ($incomingFieldArray as $field => $fieldValue) {
1446 if (isset($this->excludedTablesAndFields[$table . '-' . $field]) || $this->data_disableFields[$table][$id][$field]) {
1447 continue;
1448 }
1449
1450 // The field must be editable.
1451 // Checking if a value for language can be changed:
1452 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER->checkLanguageAccess($fieldValue);
1453 if ($languageDeny) {
1454 continue;
1455 }
1456
1457 switch ($field) {
1458 case 'uid':
1459 case 'pid':
1460 // Nothing happens, already set
1461 break;
1462 case 'perms_userid':
1463 case 'perms_groupid':
1464 case 'perms_user':
1465 case 'perms_group':
1466 case 'perms_everybody':
1467 // Permissions can be edited by the owner or the administrator
1468 if ($table == 'pages' && ($this->admin || $status == 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
1469 $value = (int)$fieldValue;
1470 switch ($field) {
1471 case 'perms_userid':
1472 $fieldArray[$field] = $value;
1473 break;
1474 case 'perms_groupid':
1475 $fieldArray[$field] = $value;
1476 break;
1477 default:
1478 if ($value >= 0 && $value < pow(2, 5)) {
1479 $fieldArray[$field] = $value;
1480 }
1481 }
1482 }
1483 break;
1484 case 't3ver_oid':
1485 case 't3ver_id':
1486 case 't3ver_wsid':
1487 case 't3ver_state':
1488 case 't3ver_count':
1489 case 't3ver_stage':
1490 case 't3ver_tstamp':
1491 // t3ver_label is not here because it CAN be edited as a regular field!
1492 break;
1493 default:
1494 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1495 // Evaluating the value
1496 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
1497 if (array_key_exists('value', $res)) {
1498 $fieldArray[$field] = $res['value'];
1499 }
1500 // Add the value of the original record to the diff-storage content:
1501 if ($this->updateModeL10NdiffData && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1502 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
1503 $diffStorageFlag = true;
1504 }
1505 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1506 // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied.
1507 // That should be TRUE for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
1508 // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
1509 // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
1510 if ($this->autoVersioningUpdate === true) {
1511 if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
1512 foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1513 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1514 }
1515 }
1516 }
1517 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1518 // Allow value for original UID to pass by...
1519 $fieldArray[$field] = $fieldValue;
1520 }
1521 }
1522 }
1523 // Add diff-storage information:
1524 if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
1525 // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
1526 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1527 }
1528 // Checking for RTE-transformations of fields:
1529 $types_fieldConfig = BackendUtility::getTCAtypes($table, $this->checkValue_currentRecord);
1530 $theTypeString = null;
1531 if (is_array($types_fieldConfig)) {
1532 foreach ($types_fieldConfig as $vconf) {
1533 // RTE transformations:
1534 if ($this->dontProcessTransformations || !isset($fieldArray[$vconf['field']])) {
1535 continue;
1536 }
1537
1538 // Look for transformation flag:
1539 if ((string)$incomingFieldArray['_TRANSFORM_' . $vconf['field']] === 'RTE') {
1540 if ($theTypeString === null) {
1541 $theTypeString = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1542 }
1543 $RTEsetup = $this->BE_USER->getTSConfig('RTE', BackendUtility::getPagesTSconfig($tscPID));
1544 $thisConfig = BackendUtility::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1545 $fieldArray[$vconf['field']] = $this->transformRichtextContentToDatabase(
1546 $fieldArray[$vconf['field']], $table, $vconf['field'], $vconf['spec'], $thisConfig, $this->checkValue_currentRecord['pid']
1547 );
1548 }
1549 }
1550 }
1551 // Return fieldArray
1552 return $fieldArray;
1553 }
1554
1555 /**
1556 * Performs transformation of content from richtext element to database.
1557 *
1558 * @param string $value Value to transform.
1559 * @param string $table The table name
1560 * @param string $field The field name
1561 * @param array $defaultExtras Default extras configuration of this field - typically "richtext:rte_transform"
1562 * @param array $thisConfig Configuration for RTEs; A mix between TSconfig and others. Configuration for additional transformation information
1563 * @param int $pid PID value of record (true parent page id)
1564 * @return string Transformed content
1565 */
1566 protected function transformRichtextContentToDatabase($value, $table, $field, $defaultExtras, $thisConfig, $pid)
1567 {
1568 if ($defaultExtras['rte_transform']) {
1569 // Initialize transformation:
1570 $parseHTML = GeneralUtility::makeInstance(RteHtmlParser::class);
1571 $parseHTML->init($table . ':' . $field, $pid);
1572 // Perform transformation:
1573 $value = $parseHTML->RTE_transform($value, $defaultExtras, 'db', $thisConfig);
1574 }
1575 return $value;
1576 }
1577
1578 /*********************************************
1579 *
1580 * Evaluation of input values
1581 *
1582 ********************************************/
1583 /**
1584 * Evaluates a value according to $table/$field settings.
1585 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1586 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
1587 *
1588 * @param string $table Table name
1589 * @param string $field Field name
1590 * @param string $value Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1591 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1592 * @param string $status 'update' or 'new' flag
1593 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1594 * @param int $tscPID TSconfig PID
1595 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1596 */
1597 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID)
1598 {
1599 // Result array
1600 $res = array();
1601
1602 // Processing special case of field pages.doktype
1603 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1604 // If the user may not use this specific doktype, we issue a warning
1605 if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1606 if ($this->enableLogging) {
1607 $propArr = $this->getRecordProperties($table, $id);
1608 $this->log($table, $id, 5, 0, 1, 'You cannot change the \'doktype\' of page \'%s\' to the desired value.', 1, array($propArr['header']), $propArr['event_pid']);
1609 }
1610 return $res;
1611 }
1612 if ($status == 'update') {
1613 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1614 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1615 if ($onlyAllowedTables) {
1616 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1617 if ($theWrongTables) {
1618 if ($this->enableLogging) {
1619 $propArr = $this->getRecordProperties($table, $id);
1620 $this->log($table, $id, 5, 0, 1, '\'doktype\' of page \'%s\' could not be changed because the page contains records from disallowed tables; %s', 2, array($propArr['header'], $theWrongTables), $propArr['event_pid']);
1621 }
1622 return $res;
1623 }
1624 }
1625 }
1626 }
1627
1628 $curValue = null;
1629 if ((int)$id !== 0) {
1630 // Get current value:
1631 $curValueRec = $this->recordInfo($table, $id, $field);
1632 // isset() won't work here, since values can be NULL
1633 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1634 $curValue = $curValueRec[$field];
1635 }
1636 }
1637
1638 // Getting config for the field
1639 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1640
1641 // Create $recFID only for those types that need it
1642 if (
1643 $tcaFieldConf['type'] === 'flex'
1644 || $tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' || $tcaFieldConf['internal_type'] === 'file_reference')
1645 ) {
1646 $recFID = $table . ':' . $id . ':' . $field;
1647 } else {
1648 $recFID = null;
1649 }
1650
1651 // Perform processing:
1652 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1653 return $res;
1654 }
1655
1656 /**
1657 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1658 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1659 *
1660 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1661 * @param string $value The value to set.
1662 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1663 * @param string $table Table name
1664 * @param int $id UID of record
1665 * @param mixed $curValue Current value of the field
1666 * @param string $status 'update' or 'new' flag
1667 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1668 * @param string $recFID Field identifier [table:uid:field] for flexforms
1669 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1670 * @param array $uploadedFiles
1671 * @param int $tscPID TSconfig PID
1672 * @param array $additionalData Additional data to be forwarded to sub-processors
1673 * @return array Returns the evaluated $value as key "value" in this array.
1674 */
1675 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1676 {
1677 // Convert to NULL value if defined in TCA
1678 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1679 $res = array('value' => null);
1680 return $res;
1681 }
1682
1683 switch ($tcaFieldConf['type']) {
1684 case 'text':
1685 $res = $this->checkValueForText($value, $tcaFieldConf);
1686 break;
1687 case 'passthrough':
1688 case 'imageManipulation':
1689 case 'user':
1690 $res['value'] = $value;
1691 break;
1692 case 'input':
1693 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1694 break;
1695 case 'check':
1696 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1697 break;
1698 case 'radio':
1699 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1700 break;
1701 case 'group':
1702 case 'select':
1703 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1704 break;
1705 case 'inline':
1706 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1707 break;
1708 case 'flex':
1709 // FlexForms are only allowed for real fields.
1710 if ($field) {
1711 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1712 }
1713 break;
1714 default:
1715 // Do nothing
1716 }
1717 return $res;
1718 }
1719
1720 /**
1721 * Evaluate "text" type values.
1722 *
1723 * @param string $value The value to set.
1724 * @param array $tcaFieldConf Field configuration from TCA
1725 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1726 */
1727 protected function checkValueForText($value, $tcaFieldConf)
1728 {
1729 if (!isset($tcaFieldConf['eval']) || $tcaFieldConf['eval'] === '') {
1730 return array('value' => $value);
1731 }
1732 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1733 if ($this->runtimeCache->has($cacheId)) {
1734 $evalCodesArray = $this->runtimeCache->get($cacheId);
1735 } else {
1736 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1737 $this->runtimeCache->set($cacheId, $evalCodesArray);
1738 }
1739 return $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1740 }
1741
1742 /**
1743 * Evaluate "input" type values.
1744 *
1745 * @param string $value The value to set.
1746 * @param array $tcaFieldConf Field configuration from TCA
1747 * @param string $table Table name
1748 * @param int $id UID of record
1749 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1750 * @param string $field Field name
1751 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1752 */
1753 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1754 {
1755 // Handle native date/time fields
1756 $isDateOrDateTimeField = false;
1757 $format = '';
1758 $emptyValue = '';
1759 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' || $tcaFieldConf['dbType'] === 'datetime')) {
1760 if (empty($value)) {
1761 $value = 0;
1762 } else {
1763 $isDateOrDateTimeField = true;
1764 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1765 // Convert the date/time into a timestamp for the sake of the checks
1766 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1767 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1768 // At this point in the processing, the timestamps are still based on UTC
1769 $timeZone = new \DateTimeZone('UTC');
1770 $dateTime = \DateTime::createFromFormat('!' . $format, $value, $timeZone);
1771 $value = $value === $emptyValue ? 0 : $dateTime->getTimestamp();
1772 }
1773 }
1774 // Secures the string-length to be less than max.
1775 if ((int)$tcaFieldConf['max'] > 0) {
1776 /** @var CharsetConverter $charsetConverter */
1777 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
1778 $value = $charsetConverter->substr('utf-8', (string)$value, 0, (int)$tcaFieldConf['max']);
1779 }
1780 // Checking range of value:
1781 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1782 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1783 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1784 $value = $tcaFieldConf['range']['upper'];
1785 }
1786 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1787 $value = $tcaFieldConf['range']['lower'];
1788 }
1789 }
1790
1791 if (empty($tcaFieldConf['eval'])) {
1792 $res = array('value' => $value);
1793 } else {
1794 // Process evaluation settings:
1795 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1796 if ($this->runtimeCache->has($cacheId)) {
1797 $evalCodesArray = $this->runtimeCache->get($cacheId);
1798 } else {
1799 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1800 $this->runtimeCache->set($cacheId, $evalCodesArray);
1801 }
1802
1803 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1804
1805 // Process UNIQUE settings:
1806 // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
1807 if ($field && $realPid >= 0 && !empty($res['value'])) {
1808 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1809 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1810 }
1811 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1812 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1813 }
1814 }
1815 }
1816
1817 // Handle native date/time fields
1818 if ($isDateOrDateTimeField) {
1819 // Convert the timestamp back to a date/time
1820 $res['value'] = $res['value'] ? date($format, $res['value']) : $emptyValue;
1821 }
1822 return $res;
1823 }
1824
1825 /**
1826 * Evaluates 'check' type values.
1827 *
1828 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1829 * @param string $value The value to set.
1830 * @param array $tcaFieldConf Field configuration from TCA
1831 * @param string $table Table name
1832 * @param int $id UID of record
1833 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1834 * @param string $field Field name
1835 * @return array Modified $res array
1836 */
1837 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1838 {
1839 $items = $tcaFieldConf['items'];
1840 if ($tcaFieldConf['itemsProcFunc']) {
1841 /** @var ItemProcessingService $processingService */
1842 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1843 $items = $processingService->getProcessingItems($table, $realPid, $field,
1844 $this->checkValue_currentRecord,
1845 $tcaFieldConf, $tcaFieldConf['items']);
1846 }
1847
1848 $itemC = count($items);
1849 if (!$itemC) {
1850 $itemC = 1;
1851 }
1852 $maxV = pow(2, $itemC) - 1;
1853 if ($value < 0) {
1854 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
1855 $value = 0;
1856 }
1857 if ($value > $maxV) {
1858 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
1859 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
1860 // @todo: are permanently removed from the value.
1861 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
1862 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
1863 $value = $value & $maxV;
1864 }
1865 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1866 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1867 $otherRecordsWithSameValue = array();
1868 $maxCheckedRecords = 0;
1869 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
1870 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1871 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1872 }
1873 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
1874 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1875 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1876 }
1877
1878 // there are more than enough records with value "1" in the DB
1879 // if so, set this value to "0" again
1880 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1881 $value = 0;
1882 if ($this->enableLogging) {
1883 $this->log($table, $id, 5, 0, 1, 'Could not activate checkbox for field "%s". A total of %s record(s) can have this checkbox activated. Uncheck other records first in order to activate the checkbox of this record.', -1, array($GLOBALS['LANG']->sL(BackendUtility::getItemLabel($table, $field)), $maxCheckedRecords));
1884 }
1885 }
1886 }
1887 $res['value'] = $value;
1888 return $res;
1889 }
1890
1891 /**
1892 * Evaluates 'radio' type values.
1893 *
1894 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1895 * @param string $value The value to set.
1896 * @param array $tcaFieldConf Field configuration from TCA
1897 * @param array $table The table of the record
1898 * @param int $id The id of the record
1899 * @param int $pid The pid of the record
1900 * @param string $field The field to check
1901 * @return array Modified $res array
1902 */
1903 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
1904 {
1905 if (is_array($tcaFieldConf['items'])) {
1906 foreach ($tcaFieldConf['items'] as $set) {
1907 if ((string)$set[1] === (string)$value) {
1908 $res['value'] = $value;
1909 break;
1910 }
1911 }
1912 }
1913
1914 // if no value was found and an itemsProcFunc is defined, check that for the value
1915 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
1916 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1917 $processedItems = $processingService->getProcessingItems($table, $pid, $field, $this->checkValue_currentRecord,
1918 $tcaFieldConf, $tcaFieldConf['items']);
1919
1920 foreach ($processedItems as $set) {
1921 if ((string)$set[1] === (string)$value) {
1922 $res['value'] = $value;
1923 break;
1924 }
1925 }
1926 }
1927
1928 return $res;
1929 }
1930
1931 /**
1932 * Evaluates 'group' or 'select' type values.
1933 *
1934 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1935 * @param string $value The value to set.
1936 * @param array $tcaFieldConf Field configuration from TCA
1937 * @param string $table Table name
1938 * @param int $id UID of record
1939 * @param mixed $curValue Current value of the field
1940 * @param string $status 'update' or 'new' flag
1941 * @param string $recFID Field identifier [table:uid:field] for flexforms
1942 * @param array $uploadedFiles
1943 * @param string $field Field name
1944 * @return array Modified $res array
1945 */
1946 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
1947 {
1948 // Detecting if value sent is an array and if so, implode it around a comma:
1949 if (is_array($value)) {
1950 $value = implode(',', $value);
1951 }
1952 // This converts all occurrences of '&#123;' to the byte 123 in the string - this is needed in very rare cases where file names with special characters (e.g. ???, umlaut) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
1953 // Anyway, this should NOT disturb anything else:
1954 $value = $this->convNumEntityToByteValue($value);
1955 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1956 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1957 // If multiple is not set, remove duplicates:
1958 if (!$tcaFieldConf['multiple']) {
1959 $valueArray = array_unique($valueArray);
1960 }
1961 // If an exclusive key is found, discard all others:
1962 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1963 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1964 foreach ($valueArray as $index => $key) {
1965 if (in_array($key, $exclusiveKeys, true)) {
1966 $valueArray = array($index => $key);
1967 break;
1968 }
1969 }
1970 }
1971 // This could be a good spot for parsing the array through a validation-function which checks if the values are correct (except that database references are not in their final form - but that is the point, isn't it?)
1972 // NOTE!!! Must check max-items of files before the later check because that check would just leave out file names if there are too many!!
1973 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1974 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1975 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1976 $preCount = count($valueArray);
1977 foreach ($valueArray as $index => $key) {
1978 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1979 unset($valueArray[$index]);
1980 }
1981 }
1982 // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
1983 if ($preCount && empty($valueArray)) {
1984 return array();
1985 }
1986 }
1987 // For group types:
1988 if ($tcaFieldConf['type'] == 'group') {
1989 switch ($tcaFieldConf['internal_type']) {
1990 case 'file_reference':
1991 case 'file':
1992 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
1993 break;
1994 }
1995 }
1996 // For select types which has a foreign table attached:
1997 $unsetResult = false;
1998 if (
1999 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
2000 || $tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] || isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
2001 ) {
2002 // check, if there is a NEW... id in the value, that should be substituted later
2003 if (strpos($value, 'NEW') !== false) {
2004 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2005 $this->addNewValuesToRemapStackChildIds($valueArray);
2006 $this->remapStack[] = array(
2007 'func' => 'checkValue_group_select_processDBdata',
2008 'args' => array($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field),
2009 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
2010 'field' => $field
2011 );
2012 $unsetResult = true;
2013 } else {
2014 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2015 }
2016 }
2017 if (!$unsetResult) {
2018 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2019 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2020 } else {
2021 unset($res['value']);
2022 }
2023 return $res;
2024 }
2025
2026 /**
2027 * Applies the filter methods from a column's TCA configuration to a value array.
2028 *
2029 * @param array $tcaFieldConfiguration
2030 * @param array $values
2031 * @return array|mixed
2032 * @throws \RuntimeException
2033 */
2034 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2035 {
2036 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2037 return $values;
2038 }
2039 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2040 if (empty($filter['userFunc'])) {
2041 continue;
2042 }
2043 $parameters = $filter['parameters'] ?: array();
2044 $parameters['values'] = $values;
2045 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2046 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2047 if (!is_array($values)) {
2048 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2049 }
2050 }
2051 return $values;
2052 }
2053
2054 /**
2055 * Handling files for group/select function
2056 *
2057 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2058 * @param array $tcaFieldConf Configuration array from TCA of the field
2059 * @param string $curValue Current value of the field
2060 * @param array $uploadedFileArray Array of uploaded files, if any
2061 * @param string $status 'update' or 'new' flag
2062 * @param string $table tablename of record
2063 * @param int $id UID of record
2064 * @param string $recFID Field identifier [table:uid:field] for flexforms
2065 * @return array Modified value array
2066 *
2067 * @throws \RuntimeException
2068 */
2069 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2070 {
2071 // If file handling should NOT be bypassed, do processing:
2072 if (!$this->bypassFileHandling) {
2073 // If any files are uploaded, add them to value array
2074 // Numeric index means that there are multiple files
2075 if (isset($uploadedFileArray[0])) {
2076 $uploadedFiles = $uploadedFileArray;
2077 } else {
2078 // There is only one file
2079 $uploadedFiles = array($uploadedFileArray);
2080 }
2081 foreach ($uploadedFiles as $uploadedFileArray) {
2082 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2083 $valueArray[] = $uploadedFileArray['tmp_name'];
2084 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2085 }
2086 }
2087 // Creating fileFunc object.
2088 if (!$this->fileFunc) {
2089 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
2090 }
2091 // Setting permitted extensions.
2092 $all_files = array();
2093 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
2094 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
2095 $all_files['ftpspace'] = $all_files['webspace'];
2096 $this->fileFunc->init('', $all_files);
2097 }
2098 // If there is an upload folder defined:
2099 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
2100 $currentFilesForHistory = null;
2101 // If filehandling should NOT be bypassed, do processing:
2102 if (!$this->bypassFileHandling) {
2103 // For logging..
2104 $propArr = $this->getRecordProperties($table, $id);
2105 // Get destrination path:
2106 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
2107 // If we are updating:
2108 if ($status == 'update') {
2109 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2110 // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
2111 // The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
2112 // Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
2113 // Illustration of the problem comes here:
2114 // We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
2115 // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
2116 // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
2117 // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
2118 if ($this->autoVersioningUpdate === true) {
2119 foreach ($valueArray as $key => $theFile) {
2120 // If it is an already attached file...
2121 if ($theFile === basename($theFile)) {
2122 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2123 }
2124 }
2125 }
2126 // Finding the CURRENT files listed, either from MM or from the current record.
2127 $theFileValues = array();
2128 // If MM relations for the files also!
2129 if ($tcaFieldConf['MM']) {
2130 $dbAnalysis = $this->createRelationHandlerInstance();
2131 /** @var $dbAnalysis RelationHandler */
2132 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2133 foreach ($dbAnalysis->itemArray as $item) {
2134 if ($item['id']) {
2135 $theFileValues[] = $item['id'];
2136 }
2137 }
2138 } else {
2139 $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
2140 }
2141 $currentFilesForHistory = implode(',', $theFileValues);
2142 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2143 if (!empty($theFileValues)) {
2144 // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
2145 foreach ($valueArray as $key => $theFile) {
2146 if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2147 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
2148 }
2149 }
2150 // This array contains the filenames in the uploadfolder that should be deleted:
2151 foreach ($theFileValues as $key => $theFile) {
2152 $theFile = trim($theFile);
2153 if (@is_file(($dest . '/' . $theFile))) {
2154 $this->removeFilesStore[] = $dest . '/' . $theFile;
2155 } elseif ($this->enableLogging && $theFile) {
2156 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
2157 }
2158 }
2159 }
2160 }
2161 // Traverse the submitted values:
2162 foreach ($valueArray as $key => $theFile) {
2163 // Init:
2164 $maxSize = (int)$tcaFieldConf['max_size'];
2165 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2166 $theDestFile = '';
2167 // a FAL file was added, now resolve the file object and get the absolute path
2168 // @todo in future versions this needs to be modified to handle FAL objects natively
2169 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2170 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2171 $theFile = $fileObject->getForLocalProcessing(false);
2172 }
2173 // NEW FILES? If the value contains '/' it indicates, that the file
2174 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2175 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
2176 // Check various things before copying file:
2177 // File and destination must exist
2178 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2179 // Finding size.
2180 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2181 $fileSize = $uploadedFileArray['size'];
2182 } else {
2183 $fileSize = filesize($theFile);
2184 }
2185 // Check file size:
2186 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2187 // Prepare filename:
2188 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2189 $fI = GeneralUtility::split_fileref($theEndFileName);
2190 // Check for allowed extension:
2191 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2192 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2193 // If we have a unique destination filename, then write the file:
2194 if ($theDestFile) {
2195 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2196 // Hook for post-processing the upload action
2197 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2198 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2199 $hookObject = GeneralUtility::getUserObj($classRef);
2200 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2201 throw new \UnexpectedValueException($classRef . ' must implement interface ' . DataHandlerProcessUploadHookInterface::class, 1279962349);
2202 }
2203 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2204 }
2205 }
2206 $this->copiedFileMap[$theFile] = $theDestFile;
2207 clearstatcache();
2208 if ($this->enableLogging && !@is_file($theDestFile)) {
2209 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
2210 }
2211 } elseif ($this->enableLogging) {
2212 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
2213 }
2214 } elseif ($this->enableLogging) {
2215 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2216 }
2217 } elseif ($this->enableLogging) {
2218 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
2219 }
2220 } elseif ($this->enableLogging) {
2221 $this->log($table, $id, 5, 0, 1, 'The destination (%s) or the source file (%s) does not exist. (%s)', 14, array($dest, $theFile, $recFID), $propArr['event_pid']);
2222 }
2223 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2224 if (@is_file($theDestFile)) {
2225 $info = GeneralUtility::split_fileref($theDestFile);
2226 // The value is set to the new filename
2227 $valueArray[$key] = $info['file'];
2228 } else {
2229 // The value is set to the new filename
2230 unset($valueArray[$key]);
2231 }
2232 }
2233 }
2234 }
2235 // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
2236 if ($tcaFieldConf['MM']) {
2237 /** @var $dbAnalysis RelationHandler */
2238 $dbAnalysis = $this->createRelationHandlerInstance();
2239 // Dummy
2240 $dbAnalysis->tableArray['files'] = array();
2241 foreach ($valueArray as $key => $theFile) {
2242 // Explode files
2243 $dbAnalysis->itemArray[]['id'] = $theFile;
2244 }
2245 if ($status == 'update') {
2246 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2247 $newFiles = implode(',', $dbAnalysis->getValueArray());
2248 list(, , $recFieldName) = explode(':', $recFID);
2249 if ($currentFilesForHistory != $newFiles) {
2250 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2251 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2252 } else {
2253 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2254 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2255 }
2256 } else {
2257 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
2258 }
2259 $valueArray = $dbAnalysis->countItems();
2260 }
2261 } else {
2262 if (!empty($valueArray)) {
2263 // If filehandling should NOT be bypassed, do processing:
2264 if (!$this->bypassFileHandling) {
2265 // For logging..
2266 $propArr = $this->getRecordProperties($table, $id);
2267 foreach ($valueArray as &$theFile) {
2268 // FAL handling: it's a UID, thus it is resolved to the absolute path
2269 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2270 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2271 $theFile = $fileObject->getForLocalProcessing(false);
2272 }
2273 if ($this->alternativeFilePath[$theFile]) {
2274 // If alternative File Path is set for the file, then it was an import
2275 // don't import the file if it already exists
2276 if (@is_file((PATH_site . $this->alternativeFilePath[$theFile]))) {
2277 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2278 } elseif (@is_file($theFile)) {
2279 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2280 if (!@is_dir($dest)) {
2281 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
2282 }
2283 // Init:
2284 $maxSize = (int)$tcaFieldConf['max_size'];
2285 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2286 $theDestFile = '';
2287 $fileSize = filesize($theFile);
2288 // Check file size:
2289 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2290 // Prepare filename:
2291 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2292 $fI = GeneralUtility::split_fileref($theEndFileName);
2293 // Check for allowed extension:
2294 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2295 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2296 // Write the file:
2297 if ($theDestFile) {
2298 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2299 $this->copiedFileMap[$theFile] = $theDestFile;
2300 clearstatcache();
2301 if ($this->enableLogging && !@is_file($theDestFile)) {
2302 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)', 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
2303 }
2304 } elseif ($this->enableLogging) {
2305 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, array($theFile, $theDestFile, $recFID), $propArr['event_pid']);
2306 }
2307 } elseif ($this->enableLogging) {
2308 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2309 }
2310 } elseif ($this->enableLogging) {
2311 $this->log($table, $id, 5, 0, 1, 'Filesize (%s) of file \'%s\' exceeds limit (%s). (%s)', 13, array(GeneralUtility::formatSize($fileSize), $theFile, GeneralUtility::formatSize($maxSize * 1024), $recFID), $propArr['event_pid']);
2312 }
2313 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2314 if (@is_file($theDestFile)) {
2315 // The value is set to the new filename
2316 $theFile = $theDestFile;
2317 } else {
2318 // The value is set to the new filename
2319 unset($theFile);
2320 }
2321 }
2322 }
2323 if (!empty($theFile)) {
2324 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2325 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2326 $theFile = PathUtility::stripPathSitePrefix($theFile);
2327 }
2328 }
2329 }
2330 unset($theFile);
2331 }
2332 }
2333 }
2334 return $valueArray;
2335 }
2336
2337 /**
2338 * Evaluates 'flex' type values.
2339 *
2340 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2341 * @param string|array $value The value to set.
2342 * @param array $tcaFieldConf Field configuration from TCA
2343 * @param string $table Table name
2344 * @param int $id UID of record
2345 * @param mixed $curValue Current value of the field
2346 * @param string $status 'update' or 'new' flag
2347 * @param int $realPid The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
2348 * @param string $recFID Field identifier [table:uid:field] for flexforms
2349 * @param int $tscPID TSconfig PID
2350 * @param array $uploadedFiles Uploaded files for the field
2351 * @param string $field Field name
2352 * @return array Modified $res array
2353 */
2354 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2355 {
2356 if (is_array($value)) {
2357 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2358 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that
2359 // sake, the BackendUtility::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter.
2360 // Only active when larger than zero.
2361 $newRecordPidValue = $status == 'new' ? $realPid : 0;
2362 // Get current value array:
2363 $dataStructArray = BackendUtility::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, $field, true, $newRecordPidValue);
2364 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : array();
2365 if (!is_array($currentValueArray)) {
2366 $currentValueArray = array();
2367 }
2368 // Remove all old meta for languages...
2369 // Evaluation of input values:
2370 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID));
2371 // Create XML from input value:
2372 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2373
2374 // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same
2375 // (provided that the current value was already stored IN the charset that the new value is converted to).
2376 $arrValue = GeneralUtility::xml2array($xmlValue);
2377
2378 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2379 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2380 $hookObject = GeneralUtility::getUserObj($classRef);
2381 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2382 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2383 }
2384 }
2385 }
2386
2387 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2388 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2389
2390 // Action commands (sorting order and removals of elements) for flexform sections,
2391 // see FormEngine for the use of this GP parameter
2392 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2393 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2394 $arrValue = GeneralUtility::xml2array($xmlValue);
2395 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2396 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2397 }
2398 // Create the value XML:
2399 $res['value'] = '';
2400 $res['value'] .= $xmlValue;
2401 } else {
2402 // Passthrough...:
2403 $res['value'] = $value;
2404 }
2405
2406 return $res;
2407 }
2408
2409 /**
2410 * Converts an array to FlexForm XML
2411 *
2412 * @param array $array Array with FlexForm data
2413 * @param bool $addPrologue If set, the XML prologue is returned as well.
2414 * @return string Input array converted to XML
2415 */
2416 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2417 {
2418 /** @var $flexObj FlexFormTools */
2419 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2420 return $flexObj->flexArray2Xml($array, $addPrologue);
2421 }
2422
2423 /**
2424 * Actions for flex form element (move, delete)
2425 * allows to remove and move flexform sections
2426 *
2427 * @param array $valueArray by reference
2428 * @param array $actionCMDs
2429 */
2430 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2431 {
2432 if (!is_array($valueArray) || !is_array($actionCMDs)) {
2433 return;
2434 }
2435
2436 foreach ($actionCMDs as $key => $value) {
2437 if ($key == '_ACTION') {
2438 // First, check if there are "commands":
2439 if (current($actionCMDs[$key]) === '') {
2440 continue;
2441 }
2442
2443 asort($actionCMDs[$key]);
2444 $newValueArray = array();
2445 foreach ($actionCMDs[$key] as $idx => $order) {
2446 if (substr($idx, 0, 3) == 'ID-') {
2447 $idx = $this->newIndexMap[$idx];
2448 }
2449 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost files unless we act on this delete operation by traversing and deleting files that were referred to.
2450 if ($order != 'DELETE') {
2451 $newValueArray[$idx] = $valueArray[$idx];
2452 }
2453 unset($valueArray[$idx]);
2454 }
2455 $valueArray = $valueArray + $newValueArray;
2456 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2457 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2458 }
2459 }
2460 }
2461
2462 /**
2463 * Evaluates 'inline' type values.
2464 * (partly copied from the select_group function on this issue)
2465 *
2466 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2467 * @param string $value The value to set.
2468 * @param array $tcaFieldConf Field configuration from TCA
2469 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2470 * @param string $field Field name
2471 * @param array $additionalData Additional data to be forwarded to sub-processors
2472 * @return array Modified $res array
2473 */
2474 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2475 {
2476 list($table, $id, , $status) = $PP;
2477 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2478 }
2479
2480 /**
2481 * Evaluates 'inline' type values.
2482 * (partly copied from the select_group function on this issue)
2483 *
2484 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2485 * @param string $value The value to set.
2486 * @param array $tcaFieldConf Field configuration from TCA
2487 * @param string $table Table name
2488 * @param int $id UID of record
2489 * @param string $status 'update' or 'new' flag
2490 * @param string $field Field name
2491 * @param array $additionalData Additional data to be forwarded to sub-processors
2492 * @return array Modified $res array
2493 */
2494 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2495 {
2496 if (!$tcaFieldConf['foreign_table']) {
2497 // Fatal error, inline fields should always have a foreign_table defined
2498 return false;
2499 }
2500 // When values are sent they come as comma-separated values which are exploded by this function:
2501 $valueArray = GeneralUtility::trimExplode(',', $value);
2502 // Remove duplicates: (should not be needed)
2503 $valueArray = array_unique($valueArray);
2504 // Example for received data:
2505 // $value = 45,NEW4555fdf59d154,12,123
2506 // We need to decide whether we use the stack or can save the relation directly.
2507 if (strpos($value, 'NEW') !== false || !MathUtility::canBeInterpretedAsInteger($id)) {
2508 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2509 $this->addNewValuesToRemapStackChildIds($valueArray);
2510 $this->remapStack[] = array(
2511 'func' => 'checkValue_inline_processDBdata',
2512 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData),
2513 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
2514 'additionalData' => $additionalData,
2515 'field' => $field,
2516 );
2517 unset($res['value']);
2518 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2519 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2520 }
2521 return $res;
2522 }
2523
2524 /**
2525 * Checks if a fields has more items than defined via TCA in maxitems.
2526 * If there are more items than allowd, the item list is truncated to the defined number.
2527 *
2528 * @param array $tcaFieldConf Field configuration from TCA
2529 * @param array $valueArray Current value array of items
2530 * @return array The truncated value array of items
2531 */
2532 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2533 {
2534 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2535 $valueArrayC = count($valueArray);
2536 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
2537 $maxI = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 1;
2538 if ($valueArrayC > $maxI) {
2539 $valueArrayC = $maxI;
2540 }
2541 // Checking for not too many elements
2542 // Dumping array to list
2543 $newVal = array();
2544 foreach ($valueArray as $nextVal) {
2545 if ($valueArrayC == 0) {
2546 break;
2547 }
2548 $valueArrayC--;
2549 $newVal[] = $nextVal;
2550 }
2551 return $newVal;
2552 }
2553
2554 /*********************************************
2555 *
2556 * Helper functions for evaluation functions.
2557 *
2558 ********************************************/
2559 /**
2560 * Gets a unique value for $table/$id/$field based on $value
2561 *
2562 * @param string $table Table name
2563 * @param string $field Field name for which $value must be unique
2564 * @param string $value Value string.
2565 * @param int $id UID to filter out in the lookup (the record itself...)
2566 * @param int $newPid If set, the value will be unique for this PID
2567 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2568 */
2569 public function getUnique($table, $field, $value, $id, $newPid = 0)
2570 {
2571 // If the field is configured in TCA, proceed:
2572 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2573 $newValue = $value;
2574 $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2575 // For as long as records with the test-value existing, try again (with incremented numbers appended)
2576 if ($statement->fetchColumn()) {
2577 $statement->bindParam(1, $newValue);
2578 for ($counter = 0; $counter <= 100; $counter++) {
2579 $newValue = $value . $counter;
2580 $statement->execute();
2581 if (!$statement->fetchColumn()) {
2582 break;
2583 }
2584 }
2585 }
2586 $value = $newValue;
2587 }
2588 return $value;
2589 }
2590
2591 /**
2592 * Gets the count of records for a unique field
2593 *
2594 * @param string $value The string value which should be unique
2595 * @param string $table Table name
2596 * @param string $field Field name for which $value must be unique
2597 * @param int $uid UID to filter out in the lookup (the record itself...)
2598 * @param int $pid If set, the value will be unique for this PID
2599 * @return \Doctrine\DBAL\Statement Return the prepared statement to check uniqueness
2600 */
2601 protected function getUniqueCountStatement(
2602 string $value,
2603 string $table,
2604 string $field,
2605 int $uid,
2606 int $pid
2607 ): Statement {
2608 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
2609 $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2610 $queryBuilder
2611 ->count('uid')
2612 ->from($table)
2613 ->where(
2614 $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value)),
2615 $queryBuilder->expr()->neq('uid', $uid)
2616 );
2617 if ($pid !== 0) {
2618 $queryBuilder->andWhere(
2619 $queryBuilder->expr()->eq('pid', $pid)
2620 );
2621 } else {
2622 // pid>=0 for versioning
2623 $queryBuilder->andWhere(
2624 $queryBuilder->expr()->gte('pid', 0)
2625 );
2626 }
2627
2628 return $queryBuilder->execute();
2629 }
2630
2631 /**
2632 * gets all records that have the same value in a field
2633 * excluding the given uid
2634 *
2635 * @param string $tableName Table name
2636 * @param int $uid UID to filter out in the lookup (the record itself...)
2637 * @param string $fieldName Field name for which $value must be unique
2638 * @param string $value Value string.
2639 * @param int $pageId If set, the value will be unique for this PID
2640 * @return array
2641 */
2642 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2643 {
2644 $result = array();
2645 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2646 $uid = (int)$uid;
2647 $pageId = (int)$pageId;
2648 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ? 'pid = ' . $pageId : 'pid >= 0');
2649 $result = BackendUtility::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2650 }
2651 return $result;
2652 }
2653
2654 /**
2655 * @param string $value The field value to be evaluated
2656 * @param array $evalArray Array of evaluations to traverse.
2657 * @param string $is_in The "is_in" value of the field configuration from TCA
2658 * @return array
2659 */
2660 public function checkValue_text_Eval($value, $evalArray, $is_in)
2661 {
2662 $res = array();
2663 $set = true;
2664 foreach ($evalArray as $func) {
2665 switch ($func) {
2666 case 'trim':
2667 $value = trim($value);
2668 break;
2669 case 'required':
2670 if (!$value) {
2671 $set = false;
2672 }
2673 break;
2674 default:
2675 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2676 if (class_exists($func)) {
2677 $evalObj = GeneralUtility::makeInstance($func);
2678 if (method_exists($evalObj, 'evaluateFieldValue')) {
2679 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2680 }
2681 }
2682 }
2683 }
2684 }
2685 if ($set) {
2686 $res['value'] = $value;
2687 }
2688 return $res;
2689 }
2690
2691 /**
2692 * Evaluation of 'input'-type values based on 'eval' list
2693 *
2694 * @param string $value Value to evaluate
2695 * @param array $evalArray Array of evaluations to traverse.
2696 * @param string $is_in Is-in string for 'is_in' evaluation
2697 * @return array Modified $value in key 'value' or empty array
2698 */
2699 public function checkValue_input_Eval($value, $evalArray, $is_in)
2700 {
2701 $res = array();
2702 $set = true;
2703 foreach ($evalArray as $func) {
2704 switch ($func) {
2705 case 'int':
2706 case 'year':
2707 case 'time':
2708 case 'timesec':
2709 $value = (int)$value;
2710 break;
2711 case 'date':
2712 case 'datetime':
2713 $value = (int)$value;
2714 if ($value !== 0 && !$this->dontProcessTransformations) {
2715 $value -= date('Z', $value);
2716 }
2717 break;
2718 case 'double2':
2719 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2720 $negative = $value[0] === '-';
2721 $value = strtr($value, array(',' => '.', '-' => ''));
2722 if (strpos($value, '.') === false) {
2723 $value .= '.0';
2724 }
2725 $valueArray = explode('.', $value);
2726 $dec = array_pop($valueArray);
2727 $value = join('', $valueArray) . '.' . $dec;
2728 if ($negative) {
2729 $value *= -1;
2730 }
2731 $value = number_format($value, 2, '.', '');
2732 break;
2733 case 'md5':
2734 if (strlen($value) != 32) {
2735 $set = false;
2736 }
2737 break;
2738 case 'trim':
2739 $value = trim($value);
2740 break;
2741 case 'upper':
2742 /** @var CharsetConverter $charsetConverter */
2743 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2744 $value = $charsetConverter->conv_case('utf-8', $value, 'toUpper');
2745 break;
2746 case 'lower':
2747 /** @var CharsetConverter $charsetConverter */
2748 $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
2749 $value = $charsetConverter->conv_case('utf-8', $value, 'toLower');
2750 break;
2751 case 'required':
2752 if (!isset($value) || $value === '') {
2753 $set = false;
2754 }
2755 break;
2756 case 'is_in':
2757 $c = strlen($value);
2758 if ($c) {
2759 $newVal = '';
2760 for ($a = 0; $a < $c; $a++) {
2761 $char = substr($value, $a, 1);
2762 if (strpos($is_in, $char) !== false) {
2763 $newVal .= $char;
2764 }
2765 }
2766 $value = $newVal;
2767 }
2768 break;
2769 case 'nospace':
2770 $value = str_replace(' ', '', $value);
2771 break;
2772 case 'alpha':
2773 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2774 break;
2775 case 'num':
2776 $value = preg_replace('/[^0-9]/', '', $value);
2777 break;
2778 case 'alphanum':
2779 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2780 break;
2781 case 'alphanum_x':
2782 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2783 break;
2784 case 'domainname':
2785 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2786 $value = GeneralUtility::idnaEncode($value);
2787 }
2788 break;
2789 case 'email':
2790 if ((string)$value !== '') {
2791 $this->checkValue_input_ValidateEmail($value, $set);
2792 }
2793 break;
2794 default:
2795 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2796 if (class_exists($func)) {
2797 $evalObj = GeneralUtility::makeInstance($func);
2798 if (method_exists($evalObj, 'evaluateFieldValue')) {
2799 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2800 }
2801 }
2802 }
2803 }
2804 }
2805 if ($set) {
2806 $res['value'] = $value;
2807 }
2808 return $res;
2809 }
2810
2811 /**
2812 * If $value is not a valid e-mail address,
2813 * $set will be set to false and a flash error
2814 * message will be added
2815 *
2816 * @param string $value Value to evaluate
2817 * @param bool $set TRUE if an update should be done
2818 * @throws \InvalidArgumentException
2819 * @throws \TYPO3\CMS\Core\Exception
2820 * @return void
2821 */
2822 protected function checkValue_input_ValidateEmail($value, &$set)
2823 {
2824 if (GeneralUtility::validEmail($value)) {
2825 return;
2826 }
2827
2828 $set = false;
2829 /** @var FlashMessage $message */
2830 $message = GeneralUtility::makeInstance(FlashMessage::class,
2831 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:error.invalidEmail'), $value),
2832 '', // header is optional
2833 FlashMessage::ERROR,
2834 true // whether message should be stored in session
2835 );
2836 /** @var $flashMessageService FlashMessageService */
2837 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2838 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2839 }
2840
2841 /**
2842 * Returns data for group/db and select fields
2843 *
2844 * @param array $valueArray Current value array
2845 * @param array $tcaFieldConf TCA field config
2846 * @param int $id Record id, used for look-up of MM relations (local_uid)
2847 * @param string $status Status string ('update' or 'new')
2848 * @param string $type The type, either 'select', 'group' or 'inline'
2849 * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2850 * @param string $currentField field name, needs to be set for writing to sys_history
2851 * @return array Modified value array
2852 */
2853 public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField)
2854 {
2855 if ($type === 'group') {
2856 $tables = $tcaFieldConf['allowed'];
2857 } elseif (!empty($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages') {
2858 $tables = 'sys_language';
2859 } else {
2860 $tables = $tcaFieldConf['foreign_table'];
2861 }
2862 $prep = $type == 'group' ? $tcaFieldConf['prepend_tname'] : '';
2863 $newRelations = implode(',', $valueArray);
2864 /** @var $dbAnalysis RelationHandler */
2865 $dbAnalysis = $this->createRelationHandlerInstance();
2866 $dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2867 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2868 if ($tcaFieldConf['MM']) {
2869 if ($status == 'update') {
2870 /** @var $oldRelations_dbAnalysis RelationHandler */
2871 $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2872 $oldRelations_dbAnalysis->registerNonTableValues = !empty($tcaFieldConf['allowNonIdValues']);
2873 // Db analysis with $id will initialize with the existing relations
2874 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2875 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2876 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2877 if ($oldRelations != $newRelations) {
2878 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2879 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2880 } else {
2881 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2882 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2883 }
2884 } else {
2885 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable);
2886 }
2887 $valueArray = $dbAnalysis->countItems();
2888 } else {
2889 $valueArray = $dbAnalysis->getValueArray($prep);
2890 }
2891 // Here we should see if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
2892 return $valueArray;
2893 }
2894
2895 /**
2896 * Explodes the $value, which is a list of files/uids (group select)
2897 *
2898 * @param string $value Input string, comma separated values. For each part it will also be detected if a '|' is found and the first part will then be used if that is the case. Further the value will be rawurldecoded.
2899 * @return array The value array.
2900 */