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