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