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