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