[TASK] Make MethodArgumentDroppedMatcherTest notice free
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / DataHandling / DataHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\DataHandling;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Doctrine\DBAL\DBALException;
18 use Doctrine\DBAL\Driver\Statement;
19 use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
20 use Doctrine\DBAL\Platforms\SQLServerPlatform;
21 use Doctrine\DBAL\Types\IntegerType;
22 use Psr\Log\LoggerAwareInterface;
23 use Psr\Log\LoggerAwareTrait;
24 use TYPO3\CMS\Backend\Utility\BackendUtility;
25 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
26 use TYPO3\CMS\Core\Cache\CacheManager;
27 use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
28 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidIdentifierException;
29 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowException;
30 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowLoopException;
31 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidParentRowRootException;
32 use TYPO3\CMS\Core\Configuration\FlexForm\Exception\InvalidPointerFieldValueException;
33 use TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
34 use TYPO3\CMS\Core\Configuration\Richtext;
35 use TYPO3\CMS\Core\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\FrontendInterface
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 string $table
1306 * @param string $row
1307 * @param string $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 $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 (strpos($id, 'NEW') !== false) {
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 < (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 = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1616 if ($onlyAllowedTables) {
1617 // use the real page id (default language)
1618 $recordId = $this->getDefaultLanguagePageId($id);
1619 $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, $value);
1620 if ($theWrongTables) {
1621 if ($this->enableLogging) {
1622 $propArr = $this->getRecordProperties($table, $id);
1623 $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']);
1624 }
1625 return $res;
1626 }
1627 }
1628 }
1629 }
1630
1631 $curValue = null;
1632 if ((int)$id !== 0) {
1633 // Get current value:
1634 $curValueRec = $this->recordInfo($table, $id, $field);
1635 // isset() won't work here, since values can be NULL
1636 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1637 $curValue = $curValueRec[$field];
1638 }
1639 }
1640
1641 // Getting config for the field
1642 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1643
1644 // Create $recFID only for those types that need it
1645 if (
1646 $tcaFieldConf['type'] === 'flex'
1647 || $tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' || $tcaFieldConf['internal_type'] === 'file_reference')
1648 ) {
1649 $recFID = $table . ':' . $id . ':' . $field;
1650 } else {
1651 $recFID = null;
1652 }
1653
1654 // Perform processing:
1655 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1656 return $res;
1657 }
1658
1659 /**
1660 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1661 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1662 *
1663 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1664 * @param string $value The value to set.
1665 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1666 * @param string $table Table name
1667 * @param int $id UID of record
1668 * @param mixed $curValue Current value of the field
1669 * @param string $status 'update' or 'new' flag
1670 * @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.
1671 * @param string $recFID Field identifier [table:uid:field] for flexforms
1672 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1673 * @param array $uploadedFiles
1674 * @param int $tscPID TSconfig PID
1675 * @param array $additionalData Additional data to be forwarded to sub-processors
1676 * @return array Returns the evaluated $value as key "value" in this array.
1677 */
1678 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1679 {
1680 // Convert to NULL value if defined in TCA
1681 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1682 $res = ['value' => null];
1683 return $res;
1684 }
1685
1686 switch ($tcaFieldConf['type']) {
1687 case 'text':
1688 $res = $this->checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field);
1689 break;
1690 case 'passthrough':
1691 case 'imageManipulation':
1692 case 'user':
1693 $res['value'] = $value;
1694 break;
1695 case 'input':
1696 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1697 break;
1698 case 'check':
1699 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1700 break;
1701 case 'radio':
1702 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1703 break;
1704 case 'group':
1705 case 'select':
1706 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1707 break;
1708 case 'inline':
1709 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1710 break;
1711 case 'flex':
1712 // FlexForms are only allowed for real fields.
1713 if ($field) {
1714 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1715 }
1716 break;
1717 default:
1718 // Do nothing
1719 }
1720 $res = $this->checkValueForInternalReferences($res, $value, $tcaFieldConf, $table, $id, $field);
1721 return $res;
1722 }
1723
1724 /**
1725 * Checks values that are used for internal references. If the provided $value
1726 * is a NEW-identifier, the direct processing is stopped. Instead, the value is
1727 * forwarded to the remap-stack to be post-processed and resolved into a proper
1728 * UID after all data has been resolved.
1729 *
1730 * This method considers TCA types that cannot handle and resolve these internal
1731 * values directly, like 'passthrough', 'none' or 'user'. Values are only modified
1732 * here if the $field is used as 'transOrigPointerField' or 'translationSource'.
1733 *
1734 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1735 * @param string $value The value to set.
1736 * @param array $tcaFieldConf Field configuration from TCA
1737 * @param string $table Table name
1738 * @param int $id UID of record
1739 * @param string $field The field name
1740 * @return array The result array. The processed value (if any!) is set in the "value" key.
1741 */
1742 protected function checkValueForInternalReferences(array $res, $value, $tcaFieldConf, $table, $id, $field)
1743 {
1744 $relevantFieldNames = [
1745 $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null,
1746 $GLOBALS['TCA'][$table]['ctrl']['translationSource'] ?? null,
1747 ];
1748
1749 if (
1750 // in case field is empty
1751 empty($field)
1752 // in case the field is not relevant
1753 || !in_array($field, $relevantFieldNames)
1754 // in case the 'value' index has been unset already
1755 || !array_key_exists('value', $res)
1756 // in case it's not a NEW-identifier
1757 || strpos($value, 'NEW') === false
1758 ) {
1759 return $res;
1760 }
1761
1762 $valueArray = [$value];
1763 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
1764 $this->addNewValuesToRemapStackChildIds($valueArray);
1765 $this->remapStack[] = [
1766 'args' => [$valueArray, $tcaFieldConf, $id, $table, $field],
1767 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 3],
1768 'field' => $field
1769 ];
1770 unset($res['value']);
1771
1772 return $res;
1773 }
1774
1775 /**
1776 * Evaluate "text" type values.
1777 *
1778 * @param string $value The value to set.
1779 * @param array $tcaFieldConf Field configuration from TCA
1780 * @param string $table Table name
1781 * @param int $id UID of record
1782 * @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.
1783 * @param string $field Field name
1784 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1785 */
1786 protected function checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field)
1787 {
1788 if (isset($tcaFieldConf['eval']) && $tcaFieldConf['eval'] !== '') {
1789 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1790 $evalCodesArray = $this->runtimeCache->get($cacheId);
1791 if (!is_array($evalCodesArray)) {
1792 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1793 $this->runtimeCache->set($cacheId, $evalCodesArray);
1794 }
1795 $valueArray = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1796 } else {
1797 $valueArray = ['value' => $value];
1798 }
1799
1800 // Handle richtext transformations
1801 if ($this->dontProcessTransformations) {
1802 return $valueArray;
1803 }
1804 $recordType = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1805 $columnsOverridesConfigOfField = $GLOBALS['TCA'][$table]['types'][$recordType]['columnsOverrides'][$field]['config'] ?? null;
1806 if ($columnsOverridesConfigOfField) {
1807 ArrayUtility::mergeRecursiveWithOverrule($tcaFieldConf, $columnsOverridesConfigOfField);
1808 }
1809 if (isset($tcaFieldConf['enableRichtext']) && (bool)$tcaFieldConf['enableRichtext'] === true) {
1810 $richtextConfigurationProvider = GeneralUtility::makeInstance(Richtext::class);
1811 $richtextConfiguration = $richtextConfigurationProvider->getConfiguration($table, $field, $realPid, $recordType, $tcaFieldConf);
1812 $parseHTML = GeneralUtility::makeInstance(RteHtmlParser::class);
1813 $parseHTML->init($table . ':' . $field, $realPid);
1814 $valueArray['value'] = $parseHTML->RTE_transform($value, [], 'db', $richtextConfiguration);
1815 }
1816
1817 return $valueArray;
1818 }
1819
1820 /**
1821 * Evaluate "input" type values.
1822 *
1823 * @param string $value The value to set.
1824 * @param array $tcaFieldConf Field configuration from TCA
1825 * @param string $table Table name
1826 * @param int $id UID of record
1827 * @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.
1828 * @param string $field Field name
1829 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1830 */
1831 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1832 {
1833 // Handle native date/time fields
1834 $isDateOrDateTimeField = false;
1835 $format = '';
1836 $emptyValue = '';
1837 $dateTimeTypes = QueryHelper::getDateTimeTypes();
1838 // normal integer "date" fields (timestamps) are handled in checkValue_input_Eval
1839 if (isset($tcaFieldConf['dbType']) && in_array($tcaFieldConf['dbType'], $dateTimeTypes, true)) {
1840 if (empty($value)) {
1841 $value = null;
1842 } else {
1843 $isDateOrDateTimeField = true;
1844 $dateTimeFormats = QueryHelper::getDateTimeFormats();
1845 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1846
1847 // Convert the date/time into a timestamp for the sake of the checks
1848 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1849 // We store UTC timestamps in the database, which is what getTimestamp() returns.
1850 $dateTime = new \DateTime($value);
1851 $value = $value === $emptyValue ? null : $dateTime->getTimestamp();
1852 }
1853 }
1854 // Secures the string-length to be less than max.
1855 if ((int)$tcaFieldConf['max'] > 0) {
1856 $value = mb_substr((string)$value, 0, (int)$tcaFieldConf['max'], 'utf-8');
1857 }
1858
1859 if (empty($tcaFieldConf['eval'])) {
1860 $res = ['value' => $value];
1861 } else {
1862 // Process evaluation settings:
1863 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1864 $evalCodesArray = $this->runtimeCache->get($cacheId);
1865 if (!is_array($evalCodesArray)) {
1866 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1867 $this->runtimeCache->set($cacheId, $evalCodesArray);
1868 }
1869
1870 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1871 if (isset($tcaFieldConf['dbType']) && isset($res['value']) && !$res['value']) {
1872 // set the value to null if we have an empty value for a native field
1873 $res['value'] = null;
1874 }
1875
1876 // Process UNIQUE settings:
1877 // 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...
1878 if ($field && $realPid >= 0 && !empty($res['value'])) {
1879 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1880 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1881 }
1882 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1883 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1884 }
1885 }
1886 }
1887
1888 // Checking range of value:
1889 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1890 if ($tcaFieldConf['range'] && $res['value'] != $tcaFieldConf['checkbox'] && (int)$res['value'] !== (int)$tcaFieldConf['default']) {
1891 if (isset($tcaFieldConf['range']['upper']) && (int)$res['value'] > (int)$tcaFieldConf['range']['upper']) {
1892 $res['value'] = (int)$tcaFieldConf['range']['upper'];
1893 }
1894 if (isset($tcaFieldConf['range']['lower']) && (int)$res['value'] < (int)$tcaFieldConf['range']['lower']) {
1895 $res['value'] = (int)$tcaFieldConf['range']['lower'];
1896 }
1897 }
1898
1899 // Handle native date/time fields
1900 if ($isDateOrDateTimeField) {
1901 // Convert the timestamp back to a date/time
1902 $res['value'] = $res['value'] ? gmdate($format, $res['value']) : $emptyValue;
1903 }
1904 return $res;
1905 }
1906
1907 /**
1908 * Evaluates 'check' type values.
1909 *
1910 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1911 * @param string $value The value to set.
1912 * @param array $tcaFieldConf Field configuration from TCA
1913 * @param string $table Table name
1914 * @param int $id UID of record
1915 * @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.
1916 * @param string $field Field name
1917 * @return array Modified $res array
1918 */
1919 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1920 {
1921 $items = $tcaFieldConf['items'];
1922 if ($tcaFieldConf['itemsProcFunc']) {
1923 /** @var ItemProcessingService $processingService */
1924 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1925 $items = $processingService->getProcessingItems(
1926 $table,
1927 $realPid,
1928 $field,
1929 $this->checkValue_currentRecord,
1930 $tcaFieldConf,
1931 $tcaFieldConf['items']
1932 );
1933 }
1934
1935 $itemC = 0;
1936 if ($items !== null) {
1937 $itemC = count($items);
1938 }
1939 if (!$itemC) {
1940 $itemC = 1;
1941 }
1942 $maxV = (2 ** $itemC) - 1;
1943 if ($value < 0) {
1944 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
1945 $value = 0;
1946 }
1947 if ($value > $maxV) {
1948 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
1949 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
1950 // @todo: are permanently removed from the value.
1951 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
1952 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
1953 $value = $value & $maxV;
1954 }
1955 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1956 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1957 $otherRecordsWithSameValue = [];
1958 $maxCheckedRecords = 0;
1959 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
1960 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1961 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1962 }
1963 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
1964 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1965 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1966 }
1967
1968 // there are more than enough records with value "1" in the DB
1969 // if so, set this value to "0" again
1970 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1971 $value = 0;
1972 $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]);
1973 }
1974 }
1975 $res['value'] = $value;
1976 return $res;
1977 }
1978
1979 /**
1980 * Evaluates 'radio' type values.
1981 *
1982 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1983 * @param string $value The value to set.
1984 * @param array $tcaFieldConf Field configuration from TCA
1985 * @param string $table The table of the record
1986 * @param int $id The id of the record
1987 * @param int $pid The pid of the record
1988 * @param string $field The field to check
1989 * @return array Modified $res array
1990 */
1991 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
1992 {
1993 if (is_array($tcaFieldConf['items'])) {
1994 foreach ($tcaFieldConf['items'] as $set) {
1995 if ((string)$set[1] === (string)$value) {
1996 $res['value'] = $value;
1997 break;
1998 }
1999 }
2000 }
2001
2002 // if no value was found and an itemsProcFunc is defined, check that for the value
2003 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
2004 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
2005 $processedItems = $processingService->getProcessingItems(
2006 $table,
2007 $pid,
2008 $field,
2009 $this->checkValue_currentRecord,
2010 $tcaFieldConf,
2011 $tcaFieldConf['items']
2012 );
2013
2014 foreach ($processedItems as $set) {
2015 if ((string)$set[1] === (string)$value) {
2016 $res['value'] = $value;
2017 break;
2018 }
2019 }
2020 }
2021
2022 return $res;
2023 }
2024
2025 /**
2026 * Evaluates 'group' or 'select' type values.
2027 *
2028 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2029 * @param string|array $value The value to set.
2030 * @param array $tcaFieldConf Field configuration from TCA
2031 * @param string $table Table name
2032 * @param int $id UID of record
2033 * @param mixed $curValue Current value of the field
2034 * @param string $status 'update' or 'new' flag
2035 * @param string $recFID Field identifier [table:uid:field] for flexforms
2036 * @param array $uploadedFiles
2037 * @param string $field Field name
2038 * @return array Modified $res array
2039 */
2040 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
2041 {
2042 // Detecting if value sent is an array and if so, implode it around a comma:
2043 if (is_array($value)) {
2044 $value = implode(',', $value);
2045 }
2046 // 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.
2047 // Anyway, this should NOT disturb anything else:
2048 $value = $this->convNumEntityToByteValue($value);
2049 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
2050 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
2051 // If multiple is not set, remove duplicates:
2052 if (!$tcaFieldConf['multiple']) {
2053 $valueArray = array_unique($valueArray);
2054 }
2055 // If an exclusive key is found, discard all others:
2056 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['exclusiveKeys']) {
2057 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
2058 foreach ($valueArray as $index => $key) {
2059 if (in_array($key, $exclusiveKeys, true)) {
2060 $valueArray = [$index => $key];
2061 break;
2062 }
2063 }
2064 }
2065 // 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?)
2066 // 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!!
2067 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2068 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
2069 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['authMode']) {
2070 $preCount = count($valueArray);
2071 foreach ($valueArray as $index => $key) {
2072 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
2073 unset($valueArray[$index]);
2074 }
2075 }
2076 // 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.
2077 if ($preCount && empty($valueArray)) {
2078 return [];
2079 }
2080 }
2081 // For group types:
2082 if ($tcaFieldConf['type'] === 'group'
2083 && in_array($tcaFieldConf['internal_type'], ['file', 'file_reference'], true)) {
2084 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
2085 }
2086 // For select types which has a foreign table attached:
2087 $unsetResult = false;
2088 if (
2089 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
2090 || $tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] || isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
2091 ) {
2092 // check, if there is a NEW... id in the value, that should be substituted later
2093 if (strpos($value, 'NEW') !== false) {
2094 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2095 $this->addNewValuesToRemapStackChildIds($valueArray);
2096 $this->remapStack[] = [
2097 'func' => 'checkValue_group_select_processDBdata',
2098 'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
2099 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2100 'field' => $field
2101 ];
2102 $unsetResult = true;
2103 } else {
2104 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2105 }
2106 }
2107 if (!$unsetResult) {
2108 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2109 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2110 } else {
2111 unset($res['value']);
2112 }
2113 return $res;
2114 }
2115
2116 /**
2117 * Applies the filter methods from a column's TCA configuration to a value array.
2118 *
2119 * @param array $tcaFieldConfiguration
2120 * @param array $values
2121 * @return array|mixed
2122 * @throws \RuntimeException
2123 */
2124 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2125 {
2126 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2127 return $values;
2128 }
2129 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2130 if (empty($filter['userFunc'])) {
2131 continue;
2132 }
2133 $parameters = $filter['parameters'] ?: [];
2134 $parameters['values'] = $values;
2135 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2136 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2137 if (!is_array($values)) {
2138 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2139 }
2140 }
2141 return $values;
2142 }
2143
2144 /**
2145 * Handling files for group/select function
2146 *
2147 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2148 * @param array $tcaFieldConf Configuration array from TCA of the field
2149 * @param string $curValue Current value of the field
2150 * @param array $uploadedFileArray Array of uploaded files, if any
2151 * @param string $status 'update' or 'new' flag
2152 * @param string $table tablename of record
2153 * @param int $id UID of record
2154 * @param string $recFID Field identifier [table:uid:field] for flexforms
2155 * @return array Modified value array
2156 *
2157 * @throws \RuntimeException
2158 */
2159 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2160 {
2161 // If file handling should NOT be bypassed, do processing:
2162 if (!$this->bypassFileHandling) {
2163 // If any files are uploaded, add them to value array
2164 // Numeric index means that there are multiple files
2165 if (isset($uploadedFileArray[0])) {
2166 $uploadedFiles = $uploadedFileArray;
2167 } else {
2168 // There is only one file
2169 $uploadedFiles = [$uploadedFileArray];
2170 }
2171 foreach ($uploadedFiles as $uploadedFileArray) {
2172 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2173 $valueArray[] = $uploadedFileArray['tmp_name'];
2174 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2175 }
2176 }
2177 // Creating fileFunc object.
2178 if (!$this->fileFunc) {
2179 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
2180 }
2181 // Setting permitted extensions.
2182 $this->fileFunc->setFileExtensionPermissions($tcaFieldConf['allowed'], $tcaFieldConf['disallowed'] ?: '*');
2183 }
2184 // If there is an upload folder defined:
2185 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] === 'file') {
2186 $currentFilesForHistory = null;
2187 // If filehandling should NOT be bypassed, do processing:
2188 if (!$this->bypassFileHandling) {
2189 // For logging..
2190 $propArr = $this->getRecordProperties($table, $id);
2191 // Get destination path:
2192 $dest = PATH_site . $tcaFieldConf['uploadfolder'];
2193 // If we are updating:
2194 if ($status === 'update') {
2195 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2196 // 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!
2197 // 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_.
2198 // 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.
2199 // Illustration of the problem comes here:
2200 // 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.
2201 // 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.
2202 // 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.
2203 // 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.
2204 if ($this->autoVersioningUpdate === true) {
2205 foreach ($valueArray as $key => $theFile) {
2206 // If it is an already attached file...
2207 if ($theFile === basename($theFile)) {
2208 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2209 }
2210 }
2211 }
2212 // Finding the CURRENT files listed, either from MM or from the current record.
2213 $theFileValues = [];
2214 // If MM relations for the files also!
2215 if ($tcaFieldConf['MM']) {
2216 $dbAnalysis = $this->createRelationHandlerInstance();
2217 /** @var $dbAnalysis RelationHandler */
2218 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2219 foreach ($dbAnalysis->itemArray as $item) {
2220 if ($item['id']) {
2221 $theFileValues[] = $item['id'];
2222 }
2223 }
2224 } else {
2225 $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
2226 }
2227 $currentFilesForHistory = implode(',', $theFileValues);
2228 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2229 if (!empty($theFileValues)) {
2230 // 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!)
2231 foreach ($valueArray as $key => $theFile) {
2232 if ($theFile && strpos(GeneralUtility::fixWindowsFilePath($theFile), '/') === false) {
2233 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
2234 }
2235 }
2236 // This array contains the filenames in the uploadfolder that should be deleted:
2237 foreach ($theFileValues as $key => $theFile) {
2238 $theFile = trim($theFile);
2239 if (@is_file($dest . '/' . $theFile)) {
2240 $this->removeFilesStore[] = $dest . '/' . $theFile;
2241 } elseif ($theFile) {
2242 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, [$dest . '/' . $theFile, $recFID], $propArr['event_pid']);
2243 }
2244 }
2245 }
2246 }
2247 // Traverse the submitted values:
2248 foreach ($valueArray as $key => $theFile) {
2249 // Init:
2250 $maxSize = (int)$tcaFieldConf['max_size'];
2251 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2252 $theDestFile = '';
2253 // a FAL file was added, now resolve the file object and get the absolute path
2254 // @todo in future versions this needs to be modified to handle FAL objects natively
2255 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2256 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2257 $theFile = $fileObject->getForLocalProcessing(false);
2258 }
2259 // NEW FILES? If the value contains '/' it indicates, that the file
2260 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2261 if (strpos(GeneralUtility::fixWindowsFilePath($theFile), '/') !== false) {
2262 // Check various things before copying file:
2263 // File and destination must exist
2264 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2265 // Finding size.
2266 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2267 $fileSize = $uploadedFileArray['size'];
2268 } else {
2269 $fileSize = filesize($theFile);
2270 }
2271 // Check file size:
2272 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2273 // Prepare filename:
2274 $theEndFileName = $this->alternativeFileName[$theFile] ?? $theFile;
2275 $fI = GeneralUtility::split_fileref($theEndFileName);
2276 // Check for allowed extension:
2277 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2278 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2279 // If we have a unique destination filename, then write the file:
2280 if ($theDestFile) {
2281 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2282 // Hook for post-processing the upload action
2283 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] ?? [] as $className) {
2284 $hookObject = GeneralUtility::makeInstance($className);
2285 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2286 throw new \UnexpectedValueException($className . ' must implement interface ' . DataHandlerProcessUploadHookInterface::class, 1279962349);
2287 }
2288 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2289 }
2290 $this->copiedFileMap[$theFile] = $theDestFile;
2291 clearstatcache();
2292 if (!@is_file($theDestFile)) {
2293 $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']);
2294 }
2295 } else {
2296 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2297 }
2298 } else {
2299 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2300 }
2301 } else {
2302 $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']);
2303 }
2304 } else {
2305 $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']);
2306 }
2307 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2308 if (@is_file($theDestFile)) {
2309 $info = GeneralUtility::split_fileref($theDestFile);
2310 // The value is set to the new filename
2311 $valueArray[$key] = $info['file'];
2312 } else {
2313 // The value is set to the new filename
2314 unset($valueArray[$key]);
2315 }
2316 }
2317 }
2318 }
2319 // 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!
2320 if ($tcaFieldConf['MM']) {
2321 /** @var $dbAnalysis RelationHandler */
2322 $dbAnalysis = $this->createRelationHandlerInstance();
2323 // Dummy
2324 $dbAnalysis->tableArray['files'] = [];
2325 foreach ($valueArray as $key => $theFile) {
2326 // Explode files
2327 $dbAnalysis->itemArray[]['id'] = $theFile;
2328 }
2329 if ($status === 'update') {
2330 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2331 $newFiles = implode(',', $dbAnalysis->getValueArray());
2332 list(, , $recFieldName) = explode(':', $recFID);
2333 if ($currentFilesForHistory != $newFiles) {
2334 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2335 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2336 } else {
2337 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2338 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2339 }
2340 } else {
2341 $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, 0];
2342 }
2343 $valueArray = $dbAnalysis->countItems();
2344 }
2345 } else {
2346 if (!empty($valueArray)) {
2347 // If filehandling should NOT be bypassed, do processing:
2348 if (!$this->bypassFileHandling) {
2349 // For logging..
2350 $propArr = $this->getRecordProperties($table, $id);
2351 foreach ($valueArray as &$theFile) {
2352 // FAL handling: it's a UID, thus it is resolved to the absolute path
2353 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2354 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2355 $theFile = $fileObject->getForLocalProcessing(false);
2356 }
2357 if ($this->alternativeFilePath[$theFile]) {
2358 // If alternative File Path is set for the file, then it was an import
2359 // don't import the file if it already exists
2360 if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
2361 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2362 } elseif (@is_file($theFile)) {
2363 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2364 if (!@is_dir($dest)) {
2365 GeneralUtility::mkdir_deep($dest);
2366 }
2367 // Init:
2368 $maxSize = (int)$tcaFieldConf['max_size'];
2369 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2370 $theDestFile = '';
2371 $fileSize = filesize($theFile);
2372 // Check file size:
2373 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2374 // Prepare filename:
2375 $theEndFileName = $this->alternativeFileName[$theFile] ?? $theFile;
2376 $fI = GeneralUtility::split_fileref($theEndFileName);
2377 // Check for allowed extension:
2378 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2379 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2380 // Write the file:
2381 if ($theDestFile) {
2382 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2383 $this->copiedFileMap[$theFile] = $theDestFile;
2384 clearstatcache();
2385 if (!@is_file($theDestFile)) {
2386 $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']);
2387 }
2388 } else {
2389 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2390 }
2391 } else {
2392 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2393 }
2394 } else {
2395 $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']);
2396 }
2397 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2398 if (@is_file($theDestFile)) {
2399 // The value is set to the new filename
2400 $theFile = $theDestFile;
2401 } else {
2402 // The value is set to the new filename
2403 unset($theFile);
2404 }
2405 }
2406 }
2407 if (!empty($theFile)) {
2408 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2409 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2410 $theFile = PathUtility::stripPathSitePrefix($theFile);
2411 }
2412 }
2413 }
2414 unset($theFile);
2415 }
2416 }
2417 }
2418 return $valueArray;
2419 }
2420
2421 /**
2422 * Evaluates 'flex' type values.
2423 *
2424 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2425 * @param string|array $value The value to set.
2426 * @param array $tcaFieldConf Field configuration from TCA
2427 * @param string $table Table name
2428 * @param int $id UID of record
2429 * @param mixed $curValue Current value of the field
2430 * @param string $status 'update' or 'new' flag
2431 * @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.
2432 * @param string $recFID Field identifier [table:uid:field] for flexforms
2433 * @param int $tscPID TSconfig PID
2434 * @param array $uploadedFiles Uploaded files for the field
2435 * @param string $field Field name
2436 * @return array Modified $res array
2437 */
2438 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2439 {
2440 if (is_array($value)) {
2441 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2442 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord
2443 // does not have a uid or pid for that sake, the FlexFormTools->getDataStructureIdentifier() function returns no good DS. For new
2444 // records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
2445 $row = $this->checkValue_currentRecord;
2446 if ($status === 'new') {
2447 $row['pid'] = $realPid;
2448 }
2449
2450 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
2451
2452 // Get data structure. The methods may throw various exceptions, with some of them being
2453 // ok in certain scenarios, for instance on new record rows. Those are ok to "eat" here
2454 // and substitute with a dummy DS.
2455 $dataStructureArray = ['sheets' => ['sDEF' => []]];
2456 try {
2457 $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
2458 ['config' => $tcaFieldConf],
2459 $table,
2460 $field,
2461 $row
2462 );
2463
2464 $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
2465 } catch (InvalidParentRowException $e) {
2466 } catch (InvalidParentRowLoopException $e) {
2467 } catch (InvalidParentRowRootException $e) {
2468 } catch (InvalidPointerFieldValueException $e) {
2469 } catch (InvalidIdentifierException $e) {
2470 }
2471
2472 // Get current value array:
2473 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : [];
2474 if (!is_array($currentValueArray)) {
2475 $currentValueArray = [];
2476 }
2477 // Remove all old meta for languages...
2478 // Evaluation of input values:
2479 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructureArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2480 // Create XML from input value:
2481 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2482
2483 // 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
2484 // (provided that the current value was already stored IN the charset that the new value is converted to).
2485 $arrValue = GeneralUtility::xml2array($xmlValue);
2486
2487 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] ?? [] as $className) {
2488 $hookObject = GeneralUtility::makeInstance($className);
2489 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2490 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2491 }
2492 }
2493
2494 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2495 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2496
2497 // Action commands (sorting order and removals of elements) for flexform sections,
2498 // see FormEngine for the use of this GP parameter
2499 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2500 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2501 $arrValue = GeneralUtility::xml2array($xmlValue);
2502 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2503 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2504 }
2505 // Create the value XML:
2506 $res['value'] = '';
2507 $res['value'] .= $xmlValue;
2508 } else {
2509 // Passthrough...:
2510 $res['value'] = $value;
2511 }
2512
2513 return $res;
2514 }
2515
2516 /**
2517 * Converts an array to FlexForm XML
2518 *
2519 * @param array $array Array with FlexForm data
2520 * @param bool $addPrologue If set, the XML prologue is returned as well.
2521 * @return string Input array converted to XML
2522 */
2523 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2524 {
2525 /** @var $flexObj FlexFormTools */
2526 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2527 return $flexObj->flexArray2Xml($array, $addPrologue);
2528 }
2529
2530 /**
2531 * Actions for flex form element (move, delete)
2532 * allows to remove and move flexform sections
2533 *
2534 * @param array $valueArray by reference
2535 * @param array $actionCMDs
2536 */
2537 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2538 {
2539 if (!is_array($valueArray) || !is_array($actionCMDs)) {
2540 return;
2541 }
2542
2543 foreach ($actionCMDs as $key => $value) {
2544 if ($key === '_ACTION') {
2545 // First, check if there are "commands":
2546 if (current($actionCMDs[$key]) === '') {
2547 continue;
2548 }
2549
2550 asort($actionCMDs[$key]);
2551 $newValueArray = [];
2552 foreach ($actionCMDs[$key] as $idx => $order) {
2553 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost
2554 // files unless we act on this delete operation by traversing and deleting files that were referred to.
2555 if ($order !== 'DELETE') {
2556 $newValueArray[$idx] = $valueArray[$idx];
2557 }
2558 unset($valueArray[$idx]);
2559 }
2560 $valueArray += $newValueArray;
2561 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2562 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2563 }
2564 }
2565 }
2566
2567 /**
2568 * Evaluates 'inline' type values.
2569 * (partly copied from the select_group function on this issue)
2570 *
2571 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2572 * @param string $value The value to set.
2573 * @param array $tcaFieldConf Field configuration from TCA
2574 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2575 * @param string $field Field name
2576 * @param array $additionalData Additional data to be forwarded to sub-processors
2577 * @return array Modified $res array
2578 */
2579 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2580 {
2581 list($table, $id, , $status) = $PP;
2582 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2583 }
2584
2585 /**
2586 * Evaluates 'inline' type values.
2587 * (partly copied from the select_group function on this issue)
2588 *
2589 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2590 * @param string $value The value to set.
2591 * @param array $tcaFieldConf Field configuration from TCA
2592 * @param string $table Table name
2593 * @param int $id UID of record
2594 * @param string $status 'update' or 'new' flag
2595 * @param string $field Field name
2596 * @param array $additionalData Additional data to be forwarded to sub-processors
2597 * @return array|bool Modified $res array
2598 */
2599 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2600 {
2601 if (!$tcaFieldConf['foreign_table']) {
2602 // Fatal error, inline fields should always have a foreign_table defined
2603 return false;
2604 }
2605 // When values are sent they come as comma-separated values which are exploded by this function:
2606 $valueArray = GeneralUtility::trimExplode(',', $value);
2607 // Remove duplicates: (should not be needed)
2608 $valueArray = array_unique($valueArray);
2609 // Example for received data:
2610 // $value = 45,NEW4555fdf59d154,12,123
2611 // We need to decide whether we use the stack or can save the relation directly.
2612 if (!empty($value) && (strpos($value, 'NEW') !== false || !MathUtility::canBeInterpretedAsInteger($id))) {
2613 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2614 $this->addNewValuesToRemapStackChildIds($valueArray);
2615 $this->remapStack[] = [
2616 'func' => 'checkValue_inline_processDBdata',
2617 'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2618 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2619 'additionalData' => $additionalData,
2620 'field' => $field,
2621 ];
2622 unset($res['value']);
2623 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2624 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2625 }
2626 return $res;
2627 }
2628
2629 /**
2630 * Checks if a fields has more items than defined via TCA in maxitems.
2631 * If there are more items than allowed, the item list is truncated to the defined number.
2632 *
2633 * @param array $tcaFieldConf Field configuration from TCA
2634 * @param array $valueArray Current value array of items
2635 * @return array The truncated value array of items
2636 */
2637 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2638 {
2639 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function
2640 // calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check
2641 // before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2642 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first,
2643 // if the field is actual used regarding the CType.
2644 $maxitems = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 99999;
2645 return array_slice($valueArray, 0, $maxitems);
2646 }
2647
2648 /*********************************************
2649 *
2650 * Helper functions for evaluation functions.
2651 *
2652 ********************************************/
2653 /**
2654 * Gets a unique value for $table/$id/$field based on $value
2655 *
2656 * @param string $table Table name
2657 * @param string $field Field name for which $value must be unique
2658 * @param string $value Value string.
2659 * @param int $id UID to filter out in the lookup (the record itself...)
2660 * @param int $newPid If set, the value will be unique for this PID
2661 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2662 */
2663 public function getUnique($table, $field, $value, $id, $newPid = 0)
2664 {
2665 // If the field is configured in TCA, proceed:
2666 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2667 $newValue = $value;
2668 $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2669 // For as long as records with the test-value existing, try again (with incremented numbers appended)
2670 if ($statement->fetchColumn()) {
2671 for ($counter = 0; $counter <= 100; $counter++) {
2672 $newValue = $value . $counter;
2673 $statement->bindValue(1, $newValue);
2674 $statement->execute();
2675 if (!$statement->fetchColumn()) {
2676 break;
2677 }
2678 }
2679 }
2680 $value = $newValue;
2681 }
2682 return $value;
2683 }
2684
2685 /**
2686 * Gets the count of records for a unique field
2687 *
2688 * @param string $value The string value which should be unique
2689 * @param string $table Table name
2690 * @param string $field Field name for which $value must be unique
2691 * @param int $uid UID to filter out in the lookup (the record itself...)
2692 * @param int $pid If set, the value will be unique for this PID
2693 * @return \Doctrine\DBAL\Driver\Statement|int Return the prepared statement to check uniqueness
2694 */
2695 protected function getUniqueCountStatement(
2696 string $value,
2697 string $table,
2698 string $field,
2699 int $uid,
2700 int $pid
2701 ): Statement {
2702 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
2703 $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2704 $queryBuilder
2705 ->count('uid')
2706 ->from($table)
2707 ->where(
2708 $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value, \PDO::PARAM_STR)),
2709 $queryBuilder->expr()->neq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT))
2710 );
2711 if ($pid !== 0) {
2712 $queryBuilder->andWhere(
2713 $queryBuilder->expr()->eq('pid', $queryBuilder->createPositionalParameter($pid, \PDO::PARAM_INT))
2714 );
2715 } else {
2716 // pid>=0 for versioning
2717 $queryBuilder->andWhere(
2718 $queryBuilder->expr()->gte('pid', $queryBuilder->createPositionalParameter(0, \PDO::PARAM_INT))
2719 );
2720 }
2721
2722 return $queryBuilder->execute();
2723 }
2724
2725 /**
2726 * gets all records that have the same value in a field
2727 * excluding the given uid
2728 *
2729 * @param string $tableName Table name
2730 * @param int $uid UID to filter out in the lookup (the record itself...)
2731 * @param string $fieldName Field name for which $value must be unique
2732 * @param string $value Value string.
2733 * @param int $pageId If set, the value will be unique for this PID
2734 * @return array
2735 */
2736 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2737 {
2738 $result = [];
2739 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2740 return $result;
2741 }
2742
2743 $uid = (int)$uid;
2744 $pageId = (int)$pageId;
2745
2746 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
2747 $queryBuilder->getRestrictions()
2748 ->removeAll()
2749 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
2750 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
2751
2752 $queryBuilder->select('*')
2753 ->from($tableName)
2754 ->where(
2755 $queryBuilder->expr()->eq(
2756 $fieldName,
2757 $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR)
2758 ),
2759 $queryBuilder->expr()->neq(
2760 'uid',
2761 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
2762 )
2763 );
2764
2765 if ($pageId) {
2766 $queryBuilder->andWhere(
2767 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT))
2768 );
2769 } else {
2770 $queryBuilder->andWhere(
2771 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
2772 );
2773 }
2774
2775 $result = $queryBuilder->execute()->fetchAll();
2776
2777 return $result;
2778 }
2779
2780 /**
2781 * @param string $value The field value to be evaluated
2782 * @param array $evalArray Array of evaluations to traverse.
2783 * @param string $is_in The "is_in" value of the field configuration from TCA
2784 * @return array
2785 */
2786 public function checkValue_text_Eval($value, $evalArray, $is_in)
2787 {
2788 $res = [];
2789 $set = true;
2790 foreach ($evalArray as $func) {
2791 switch ($func) {
2792 case 'trim':
2793 $value = trim($value);
2794 break;
2795 case 'required':
2796 if (!$value) {
2797 $set = false;
2798 }
2799 break;
2800 default:
2801 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2802 if (class_exists($func)) {
2803 $evalObj = GeneralUtility::makeInstance($func);
2804 if (method_exists($evalObj, 'evaluateFieldValue')) {
2805 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2806 }
2807 }
2808 }
2809 }
2810 }
2811 if ($set) {
2812 $res['value'] = $value;
2813 }
2814 return $res;
2815 }
2816
2817 /**
2818 * Evaluation of 'input'-type values based on 'eval' list
2819 *
2820 * @param string $value Value to evaluate
2821 * @param array $evalArray Array of evaluations to traverse.
2822 * @param string $is_in Is-in string for 'is_in' evaluation
2823 * @return array Modified $value in key 'value' or empty array
2824 */
2825 public function checkValue_input_Eval($value, $evalArray, $is_in)
2826 {
2827 $res = [];
2828 $set = true;
2829 foreach ($evalArray as $func) {
2830 switch ($func) {
2831 case 'int':
2832 case 'year':
2833 $value = (int)$value;
2834 break;
2835 case 'time':
2836 case 'timesec':
2837 // If $value is a pure integer we have the number of seconds, we can store that directly
2838 if ($value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2839 // $value is an ISO 8601 date
2840 $value = (new \DateTime($value))->getTimestamp();
2841 }
2842 break;
2843 case 'date':
2844 case 'datetime':
2845 // If $value is a pure integer we have the number of seconds, we can store that directly
2846 if ($value !== null && $value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2847 // The value we receive from JS is an ISO 8601 date, which is always in UTC. (the JS code works like that, on purpose!)
2848 // For instance "1999-11-11T11:11:11Z"
2849 // Since the user actually specifies the time in the server's local time, we need to mangle this
2850 // to reflect the server TZ. So we make this 1999-11-11T11:11:11+0200 (assuming Europe/Vienna here)
2851 // In the database we store the date in UTC (1999-11-11T09:11:11Z), hence we take the timestamp of this converted value.
2852 // For achieving this we work with timestamps only (which are UTC) and simply adjust it for the
2853 // TZ difference.
2854 try {
2855 // Make the date from JS a timestamp
2856 $value = (new \DateTime($value))->getTimestamp();
2857 } catch (\Exception $e) {
2858 // set the default timezone value to achieve the value of 0 as a result
2859 $value = (int)date('Z', 0);
2860 }
2861
2862 // @todo this hacky part is problematic when it comes to times around DST switch! Add test to prove that this is broken.
2863 $value -= date('Z', $value);
2864 }
2865 break;
2866 case 'double2':
2867 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2868 $negative = $value[0] === '-';
2869 $value = strtr($value, [',' => '.', '-' => '']);
2870 if (strpos($value, '.') === false) {
2871 $value .= '.0';
2872 }
2873 $valueArray = explode('.', $value);
2874 $dec = array_pop($valueArray);
2875 $value = implode('', $valueArray) . '.' . $dec;
2876 if ($negative) {
2877 $value *= -1;
2878 }
2879 $value = number_format($value, 2, '.', '');
2880 break;
2881 case 'md5':
2882 if (strlen($value) !== 32) {
2883 $set = false;
2884 }
2885 break;
2886 case 'trim':
2887 $value = trim($value);
2888 break;
2889 case 'upper':
2890 $value = mb_strtoupper($value, 'utf-8');
2891 break;
2892 case 'lower':
2893 $value = mb_strtolower($value, 'utf-8');
2894 break;
2895 case 'required':
2896 if (!isset($value) || $value === '') {
2897 $set = false;
2898 }
2899 break;
2900 case 'is_in':
2901 $c = mb_strlen($value);
2902 if ($c) {
2903 $newVal = '';
2904 for ($a = 0; $a < $c; $a++) {
2905 $char = mb_substr($value, $a, 1);
2906 if (mb_strpos($is_in, $char) !== false) {
2907 $newVal .= $char;
2908 }
2909 }
2910 $value = $newVal;
2911 }
2912 break;
2913 case 'nospace':
2914 $value = str_replace(' ', '', $value);
2915 break;
2916 case 'alpha':
2917 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2918 break;
2919 case 'num':
2920 $value = preg_replace('/[^0-9]/', '', $value);
2921 break;
2922 case 'alphanum':
2923 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2924 break;
2925 case 'alphanum_x':
2926 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2927 break;
2928 case 'domainname':
2929 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2930 $value = GeneralUtility::idnaEncode($value);
2931 }
2932 break;
2933 case 'email':
2934 if ((string)$value !== '') {
2935 $this->checkValue_input_ValidateEmail($value, $set);
2936 }
2937 break;
2938 default:
2939 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {