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