[TASK] Cleanup parameter mismatches
[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 $row
1313 * @param string $key
1314 *
1315 * @return string
1316 */
1317 protected function normalizeTimeFormat(string $table, string $value, string $dbType): string
1318 {
1319 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($table);
1320 $platform = $connection->getDatabasePlatform();
1321 if ($platform instanceof SQLServerPlatform) {
1322 $defaultLength = QueryHelper::getDateTimeFormats()[$dbType]['empty'];
1323 $value = substr(
1324 $value,
1325 0,
1326 strlen($defaultLength)
1327 );
1328 }
1329 return $value;
1330 }
1331
1332 /**
1333 * Sets the "sorting" DB field and the "pid" field of an incoming record that should be added (NEW1234)
1334 * depending on the record that should be added or where it should be added.
1335 *
1336 * This method is called from process_datamap()
1337 *
1338 * @param string $table the table name of the record to insert
1339 * @param int $pid the real PID (numeric) where the record should be
1340 * @param array $fieldArray field+value pairs to add
1341 * @return array the modified field array
1342 */
1343 protected function resolveSortingAndPidForNewRecord(string $table, int $pid, array $fieldArray): array
1344 {
1345 $sortColumn = $GLOBALS['TCA'][$table]['ctrl']['sortby'] ?? '';
1346 // Points to a page on which to insert the element, possibly in the top of the page
1347 if ($pid >= 0) {
1348 // Ensure that the "pid" is not a translated page ID, but the default page ID
1349 $pid = $this->getDefaultLanguagePageId($pid);
1350 // The numerical pid is inserted in the data array
1351 $fieldArray['pid'] = $pid;
1352 // If this table is sorted we better find the top sorting number
1353 if ($sortColumn) {
1354 $fieldArray[$sortColumn] = $this->getSortNumber($table, 0, $pid);
1355 }
1356 } elseif ($sortColumn) {
1357 // Points to another record before itself
1358 // If this table is sorted we better find the top sorting number
1359 // Because $pid is < 0, getSortNumber() returns an array
1360 $sortingInfo = $this->getSortNumber($table, 0, $pid);
1361 $fieldArray['pid'] = $sortingInfo['pid'];
1362 $fieldArray[$sortColumn] = $sortingInfo['sortNumber'];
1363 } else {
1364 // Here we fetch the PID of the record that we point to
1365 $record = $this->recordInfo($table, abs($pid), 'pid');
1366 // Ensure that the "pid" is not a translated page ID, but the default page ID
1367 $fieldArray['pid'] = $this->getDefaultLanguagePageId($record['pid']);
1368 }
1369 return $fieldArray;
1370 }
1371
1372 /**
1373 * Fix shadowing of data in case we are editing an offline version of a live "New" placeholder record:
1374 *
1375 * @param string $table Table name
1376 * @param int $id Record uid
1377 */
1378 public function placeholderShadowing($table, $id)
1379 {
1380 if ($liveRec = BackendUtility::getLiveVersionOfRecord($table, $id, '*')) {
1381 if (VersionState::cast($liveRec['t3ver_state'])->indicatesPlaceholder()) {
1382 $justStoredRecord = BackendUtility::getRecord($table, $id);
1383 $newRecord = [];
1384 $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
1385 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
1386 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1387 if (isset($GLOBALS['TCA'][$table]['ctrl']['translationSource'])) {
1388 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['translationSource'];
1389 }
1390 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
1391 $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
1392 $shadowColumns = array_unique(GeneralUtility::trimExplode(',', $shadowCols, true));
1393 foreach ($shadowColumns as $fieldName) {
1394 if ((string)$justStoredRecord[$fieldName] !== (string)$liveRec[$fieldName] && isset($GLOBALS['TCA'][$table]['columns'][$fieldName]) && $fieldName !== 'uid' && $fieldName !== 'pid') {
1395 $newRecord[$fieldName] = $justStoredRecord[$fieldName];
1396 }
1397 }
1398 if (!empty($newRecord)) {
1399 if ($this->enableLogging) {
1400 $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']));
1401 }
1402 $this->updateDB($table, $liveRec['uid'], $newRecord);
1403 }
1404 }
1405 }
1406 }
1407
1408 /**
1409 * Create a placeholder title for the label field that does match the field requirements
1410 *
1411 * @param string $table The table name
1412 * @param string $placeholderContent Placeholder content to be used
1413 * @return string placeholder value
1414 */
1415 public function getPlaceholderTitleForTableLabel($table, $placeholderContent = null)
1416 {
1417 if ($placeholderContent === null) {
1418 $placeholderContent = 'PLACEHOLDER';
1419 }
1420
1421 $labelPlaceholder = '[' . $placeholderContent . ', WS#' . $this->BE_USER->workspace . ']';
1422 $labelField = $GLOBALS['TCA'][$table]['ctrl']['label'];
1423 if (!isset($GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'])) {
1424 return $labelPlaceholder;
1425 }
1426 $evalCodesArray = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['columns'][$labelField]['config']['eval'], true);
1427 $transformedLabel = $this->checkValue_input_Eval($labelPlaceholder, $evalCodesArray, '', $table);
1428 return $transformedLabel['value'] ?? $labelPlaceholder;
1429 }
1430
1431 /**
1432 * Filling in the field array
1433 * $this->excludedTablesAndFields is used to filter fields if needed.
1434 *
1435 * @param string $table Table name
1436 * @param int $id Record ID
1437 * @param array $fieldArray Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
1438 * @param array $incomingFieldArray Is which fields/values you want to set. There are processed and put into $fieldArray if OK
1439 * @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.
1440 * @param string $status Is 'new' or 'update'
1441 * @param int $tscPID TSconfig PID
1442 * @return array Field Array
1443 */
1444 public function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID)
1445 {
1446 // Initialize:
1447 $originalLanguageRecord = null;
1448 $originalLanguage_diffStorage = null;
1449 $diffStorageFlag = false;
1450 // Setting 'currentRecord' and 'checkValueRecord':
1451 if (strpos($id, 'NEW') !== false) {
1452 // Must have the 'current' array - not the values after processing below...
1453 $checkValueRecord = $fieldArray;
1454 // IF $incomingFieldArray is an array, overlay it.
1455 // 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...
1456 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
1457 ArrayUtility::mergeRecursiveWithOverrule($checkValueRecord, $incomingFieldArray);
1458 }
1459 $currentRecord = $checkValueRecord;
1460 } else {
1461 // We must use the current values as basis for this!
1462 $currentRecord = ($checkValueRecord = $this->recordInfo($table, $id, '*'));
1463 // This is done to make the pid positive for offline versions; Necessary to have diff-view for page translations in workspaces.
1464 BackendUtility::fixVersioningPid($table, $currentRecord);
1465 }
1466
1467 // Get original language record if available:
1468 if (is_array($currentRecord)
1469 && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
1470 && $GLOBALS['TCA'][$table]['ctrl']['languageField']
1471 && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
1472 && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
1473 && (int)$currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0
1474 ) {
1475 $originalLanguageRecord = $this->recordInfo($table, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
1476 BackendUtility::workspaceOL($table, $originalLanguageRecord);
1477 $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
1478 }
1479
1480 $this->checkValue_currentRecord = $checkValueRecord;
1481 // In the following all incoming value-fields are tested:
1482 // - Are the user allowed to change the field?
1483 // - Is the field uid/pid (which are already set)
1484 // - perms-fields for pages-table, then do special things...
1485 // - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
1486 // If everything is OK, the field is entered into $fieldArray[]
1487 foreach ($incomingFieldArray as $field => $fieldValue) {
1488 if (isset($this->excludedTablesAndFields[$table . '-' . $field]) || $this->data_disableFields[$table][$id][$field]) {
1489 continue;
1490 }
1491
1492 // The field must be editable.
1493 // Checking if a value for language can be changed:
1494 $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField'] && (string)$GLOBALS['TCA'][$table]['ctrl']['languageField'] === (string)$field && !$this->BE_USER->checkLanguageAccess($fieldValue);
1495 if ($languageDeny) {
1496 continue;
1497 }
1498
1499 switch ($field) {
1500 case 'uid':
1501 case 'pid':
1502 // Nothing happens, already set
1503 break;
1504 case 'perms_userid':
1505 case 'perms_groupid':
1506 case 'perms_user':
1507 case 'perms_group':
1508 case 'perms_everybody':
1509 // Permissions can be edited by the owner or the administrator
1510 if ($table === 'pages' && ($this->admin || $status === 'new' || $this->pageInfo($id, 'perms_userid') == $this->userid)) {
1511 $value = (int)$fieldValue;
1512 switch ($field) {
1513 case 'perms_userid':
1514 case 'perms_groupid':
1515 $fieldArray[$field] = $value;
1516 break;
1517 default:
1518 if ($value >= 0 && $value < (2 ** 5)) {
1519 $fieldArray[$field] = $value;
1520 }
1521 }
1522 }
1523 break;
1524 case 't3ver_oid':
1525 case 't3ver_id':
1526 case 't3ver_wsid':
1527 case 't3ver_state':
1528 case 't3ver_count':
1529 case 't3ver_stage':
1530 case 't3ver_tstamp':
1531 // t3ver_label is not here because it CAN be edited as a regular field!
1532 break;
1533 case 'l10n_state':
1534 $fieldArray[$field] = $fieldValue;
1535 break;
1536 default:
1537 if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
1538 // Evaluating the value
1539 $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID, $incomingFieldArray);
1540 if (array_key_exists('value', $res)) {
1541 $fieldArray[$field] = $res['value'];
1542 }
1543 // Add the value of the original record to the diff-storage content:
1544 if ($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
1545 $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
1546 $diffStorageFlag = true;
1547 }
1548 // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
1549 // 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.
1550 // 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.
1551 // 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.
1552 // 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 !
1553 if ($this->autoVersioningUpdate === true) {
1554 if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
1555 foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
1556 $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
1557 }
1558 }
1559 }
1560 } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
1561 // Allow value for original UID to pass by...
1562 $fieldArray[$field] = $fieldValue;
1563 }
1564 }
1565 }
1566
1567 // Dealing with a page translation, setting "sorting", "pid", "perms_*" to the same values as the original record
1568 if ($table === 'pages' && is_array($originalLanguageRecord)) {
1569 $fieldArray['sorting'] = $originalLanguageRecord['sorting'];
1570 $fieldArray['perms_userid'] = $originalLanguageRecord['perms_userid'];
1571 $fieldArray['perms_groupid'] = $originalLanguageRecord['perms_groupid'];
1572 $fieldArray['perms_user'] = $originalLanguageRecord['perms_user'];
1573 $fieldArray['perms_group'] = $originalLanguageRecord['perms_group'];
1574 $fieldArray['perms_everybody'] = $originalLanguageRecord['perms_everybody'];
1575 }
1576
1577 // Add diff-storage information:
1578 if ($diffStorageFlag
1579 && !array_key_exists($GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField'], $fieldArray)
1580 ) {
1581 // 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...
1582 $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
1583 }
1584 // Return fieldArray
1585 return $fieldArray;
1586 }
1587
1588 /*********************************************
1589 *
1590 * Evaluation of input values
1591 *
1592 ********************************************/
1593 /**
1594 * Evaluates a value according to $table/$field settings.
1595 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1596 * 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() )
1597 *
1598 * @param string $table Table name
1599 * @param string $field Field name
1600 * @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.
1601 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1602 * @param string $status 'update' or 'new' flag
1603 * @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.
1604 * @param int $tscPID TSconfig PID
1605 * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray)
1606 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1607 */
1608 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID, $incomingFieldArray = [])
1609 {
1610 // Result array
1611 $res = [];
1612
1613 // Processing special case of field pages.doktype
1614 if ($table === 'pages' && $field === 'doktype') {
1615 // If the user may not use this specific doktype, we issue a warning
1616 if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1617 if ($this->enableLogging) {
1618 $propArr = $this->getRecordProperties($table, $id);
1619 $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']);
1620 }
1621 return $res;
1622 }
1623 if ($status === 'update') {
1624 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1625 $onlyAllowedTables = $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] ?? $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1626 if ($onlyAllowedTables) {
1627 // use the real page id (default language)
1628 $recordId = $this->getDefaultLanguagePageId($id);
1629 $theWrongTables = $this->doesPageHaveUnallowedTables($recordId, $value);
1630 if ($theWrongTables) {
1631 if ($this->enableLogging) {
1632 $propArr = $this->getRecordProperties($table, $id);
1633 $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']);
1634 }
1635 return $res;
1636 }
1637 }
1638 }
1639 }
1640
1641 $curValue = null;
1642 if ((int)$id !== 0) {
1643 // Get current value:
1644 $curValueRec = $this->recordInfo($table, $id, $field);
1645 // isset() won't work here, since values can be NULL
1646 if ($curValueRec !== null && array_key_exists($field, $curValueRec)) {
1647 $curValue = $curValueRec[$field];
1648 }
1649 }
1650
1651 // Getting config for the field
1652 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1653
1654 // Create $recFID only for those types that need it
1655 if (
1656 $tcaFieldConf['type'] === 'flex'
1657 || $tcaFieldConf['type'] === 'group' && ($tcaFieldConf['internal_type'] === 'file' || $tcaFieldConf['internal_type'] === 'file_reference')
1658 ) {
1659 $recFID = $table . ':' . $id . ':' . $field;
1660 } else {
1661 $recFID = null;
1662 }
1663
1664 // Perform processing:
1665 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID, ['incomingFieldArray' => $incomingFieldArray]);
1666 return $res;
1667 }
1668
1669 /**
1670 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1671 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1672 *
1673 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1674 * @param string $value The value to set.
1675 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1676 * @param string $table Table name
1677 * @param int $id UID of record
1678 * @param mixed $curValue Current value of the field
1679 * @param string $status 'update' or 'new' flag
1680 * @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.
1681 * @param string $recFID Field identifier [table:uid:field] for flexforms
1682 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1683 * @param array $uploadedFiles
1684 * @param int $tscPID TSconfig PID
1685 * @param array $additionalData Additional data to be forwarded to sub-processors
1686 * @return array Returns the evaluated $value as key "value" in this array.
1687 */
1688 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = null)
1689 {
1690 // Convert to NULL value if defined in TCA
1691 if ($value === null && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1692 $res = ['value' => null];
1693 return $res;
1694 }
1695
1696 switch ($tcaFieldConf['type']) {
1697 case 'text':
1698 $res = $this->checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field);
1699 break;
1700 case 'passthrough':
1701 case 'imageManipulation':
1702 case 'user':
1703 $res['value'] = $value;
1704 break;
1705 case 'input':
1706 $res = $this->checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field);
1707 break;
1708 case 'slug':
1709 $res = $this->checkValueForSlug((string)$value, $tcaFieldConf, $table, $id, (int)$realPid, $field, $additionalData['incomingFieldArray'] ?? []);
1710 break;
1711 case 'check':
1712 $res = $this->checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1713 break;
1714 case 'radio':
1715 $res = $this->checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $realPid, $field);
1716 break;
1717 case 'group':
1718 case 'select':
1719 $res = $this->checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field);
1720 break;
1721 case 'inline':
1722 $res = $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
1723 break;
1724 case 'flex':
1725 // FlexForms are only allowed for real fields.
1726 if ($field) {
1727 $res = $this->checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field);
1728 }
1729 break;
1730 default:
1731 // Do nothing
1732 }
1733 $res = $this->checkValueForInternalReferences($res, $value, $tcaFieldConf, $table, $id, $field);
1734 return $res;
1735 }
1736
1737 /**
1738 * Checks values that are used for internal references. If the provided $value
1739 * is a NEW-identifier, the direct processing is stopped. Instead, the value is
1740 * forwarded to the remap-stack to be post-processed and resolved into a proper
1741 * UID after all data has been resolved.
1742 *
1743 * This method considers TCA types that cannot handle and resolve these internal
1744 * values directly, like 'passthrough', 'none' or 'user'. Values are only modified
1745 * here if the $field is used as 'transOrigPointerField' or 'translationSource'.
1746 *
1747 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1748 * @param string $value The value to set.
1749 * @param array $tcaFieldConf Field configuration from TCA
1750 * @param string $table Table name
1751 * @param int $id UID of record
1752 * @param string $field The field name
1753 * @return array The result array. The processed value (if any!) is set in the "value" key.
1754 */
1755 protected function checkValueForInternalReferences(array $res, $value, $tcaFieldConf, $table, $id, $field)
1756 {
1757 $relevantFieldNames = [
1758 $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] ?? null,
1759 $GLOBALS['TCA'][$table]['ctrl']['translationSource'] ?? null,
1760 ];
1761
1762 if (
1763 // in case field is empty
1764 empty($field)
1765 // in case the field is not relevant
1766 || !in_array($field, $relevantFieldNames)
1767 // in case the 'value' index has been unset already
1768 || !array_key_exists('value', $res)
1769 // in case it's not a NEW-identifier
1770 || strpos($value, 'NEW') === false
1771 ) {
1772 return $res;
1773 }
1774
1775 $valueArray = [$value];
1776 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
1777 $this->addNewValuesToRemapStackChildIds($valueArray);
1778 $this->remapStack[] = [
1779 'args' => [$valueArray, $tcaFieldConf, $id, $table, $field],
1780 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 3],
1781 'field' => $field
1782 ];
1783 unset($res['value']);
1784
1785 return $res;
1786 }
1787
1788 /**
1789 * Evaluate "text" type values.
1790 *
1791 * @param string $value The value to set.
1792 * @param array $tcaFieldConf Field configuration from TCA
1793 * @param string $table Table name
1794 * @param int $id UID of record
1795 * @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.
1796 * @param string $field Field name
1797 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1798 */
1799 protected function checkValueForText($value, $tcaFieldConf, $table, $id, $realPid, $field)
1800 {
1801 if (isset($tcaFieldConf['eval']) && $tcaFieldConf['eval'] !== '') {
1802 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1803 $evalCodesArray = $this->runtimeCache->get($cacheId);
1804 if (!is_array($evalCodesArray)) {
1805 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1806 $this->runtimeCache->set($cacheId, $evalCodesArray);
1807 }
1808 $valueArray = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1809 } else {
1810 $valueArray = ['value' => $value];
1811 }
1812
1813 // Handle richtext transformations
1814 if ($this->dontProcessTransformations) {
1815 return $valueArray;
1816 }
1817 $recordType = BackendUtility::getTCAtypeValue($table, $this->checkValue_currentRecord);
1818 $columnsOverridesConfigOfField = $GLOBALS['TCA'][$table]['types'][$recordType]['columnsOverrides'][$field]['config'] ?? null;
1819 if ($columnsOverridesConfigOfField) {
1820 ArrayUtility::mergeRecursiveWithOverrule($tcaFieldConf, $columnsOverridesConfigOfField);
1821 }
1822 if (isset($tcaFieldConf['enableRichtext']) && (bool)$tcaFieldConf['enableRichtext'] === true) {
1823 $richtextConfigurationProvider = GeneralUtility::makeInstance(Richtext::class);
1824 $richtextConfiguration = $richtextConfigurationProvider->getConfiguration($table, $field, $realPid, $recordType, $tcaFieldConf);
1825 $parseHTML = GeneralUtility::makeInstance(RteHtmlParser::class);
1826 $parseHTML->init($table . ':' . $field, $realPid);
1827 $valueArray['value'] = $parseHTML->RTE_transform($value, [], 'db', $richtextConfiguration);
1828 }
1829
1830 return $valueArray;
1831 }
1832
1833 /**
1834 * Evaluate "input" type values.
1835 *
1836 * @param string $value The value to set.
1837 * @param array $tcaFieldConf Field configuration from TCA
1838 * @param string $table Table name
1839 * @param int $id UID of record
1840 * @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.
1841 * @param string $field Field name
1842 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1843 */
1844 protected function checkValueForInput($value, $tcaFieldConf, $table, $id, $realPid, $field)
1845 {
1846 // Handle native date/time fields
1847 $isDateOrDateTimeField = false;
1848 $format = '';
1849 $emptyValue = '';
1850 $dateTimeTypes = QueryHelper::getDateTimeTypes();
1851 // normal integer "date" fields (timestamps) are handled in checkValue_input_Eval
1852 if (isset($tcaFieldConf['dbType']) && in_array($tcaFieldConf['dbType'], $dateTimeTypes, true)) {
1853 if (empty($value)) {
1854 $value = null;
1855 } else {
1856 $isDateOrDateTimeField = true;
1857 $dateTimeFormats = QueryHelper::getDateTimeFormats();
1858 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1859
1860 // Convert the date/time into a timestamp for the sake of the checks
1861 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1862 // We store UTC timestamps in the database, which is what getTimestamp() returns.
1863 $dateTime = new \DateTime($value);
1864 $value = $value === $emptyValue ? null : $dateTime->getTimestamp();
1865 }
1866 }
1867 // Secures the string-length to be less than max.
1868 if (isset($tcaFieldConf['max']) && (int)$tcaFieldConf['max'] > 0) {
1869 $value = mb_substr((string)$value, 0, (int)$tcaFieldConf['max'], 'utf-8');
1870 }
1871
1872 if (empty($tcaFieldConf['eval'])) {
1873 $res = ['value' => $value];
1874 } else {
1875 // Process evaluation settings:
1876 $cacheId = $this->getFieldEvalCacheIdentifier($tcaFieldConf['eval']);
1877 $evalCodesArray = $this->runtimeCache->get($cacheId);
1878 if (!is_array($evalCodesArray)) {
1879 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1880 $this->runtimeCache->set($cacheId, $evalCodesArray);
1881 }
1882
1883 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in'] ?? '', $table);
1884 if (isset($tcaFieldConf['dbType']) && isset($res['value']) && !$res['value']) {
1885 // set the value to null if we have an empty value for a native field
1886 $res['value'] = null;
1887 }
1888
1889 // Process UNIQUE settings:
1890 // 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...
1891 if ($field && $realPid >= 0 && !empty($res['value'])) {
1892 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1893 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1894 }
1895 if ($res['value'] && in_array('unique', $evalCodesArray, true)) {
1896 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1897 }
1898 }
1899 }
1900
1901 // Checking range of value:
1902 // @todo: The "checkbox" option was removed for type=input, this check could be probably relaxed?
1903 if (
1904 isset($tcaFieldConf['range']) && $tcaFieldConf['range']
1905 && (!isset($tcaFieldConf['checkbox']) || $res['value'] != $tcaFieldConf['checkbox'])
1906 && (!isset($tcaFieldConf['default']) || (int)$res['value'] !== (int)$tcaFieldConf['default'])
1907 ) {
1908 if (isset($tcaFieldConf['range']['upper']) && (int)$res['value'] > (int)$tcaFieldConf['range']['upper']) {
1909 $res['value'] = (int)$tcaFieldConf['range']['upper'];
1910 }
1911 if (isset($tcaFieldConf['range']['lower']) && (int)$res['value'] < (int)$tcaFieldConf['range']['lower']) {
1912 $res['value'] = (int)$tcaFieldConf['range']['lower'];
1913 }
1914 }
1915
1916 // Handle native date/time fields
1917 if ($isDateOrDateTimeField) {
1918 // Convert the timestamp back to a date/time
1919 $res['value'] = $res['value'] ? gmdate($format, $res['value']) : $emptyValue;
1920 }
1921 return $res;
1922 }
1923
1924 /**
1925 * Evaluate "slug" type values.
1926 *
1927 * @param string $value The value to set.
1928 * @param array $tcaFieldConf Field configuration from TCA
1929 * @param string $table Table name
1930 * @param int $id UID of record
1931 * @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.
1932 * @param string $field Field name
1933 * @param array $incomingFieldArray the fields being explicitly set by the outside (unlike $fieldArray) for the record
1934 * @return array $res The result array. The processed value (if any!) is set in the "value" key.
1935 */
1936 protected function checkValueForSlug(string $value, array $tcaFieldConf, string $table, $id, int $realPid, string $field, array $incomingFieldArray = []): array
1937 {
1938 $workspaceId = $this->BE_USER->workspace;
1939 $helper = GeneralUtility::makeInstance(SlugHelper::class, $table, $field, $tcaFieldConf, $workspaceId);
1940 $fullRecord = array_replace_recursive($this->checkValue_currentRecord, $incomingFieldArray ?? []);
1941 // Generate a value if there is none, otherwise ensure that all characters are cleaned up
1942 if (empty($value)) {
1943 $value = $helper->generate($fullRecord, $realPid);
1944 } else {
1945 $value = $helper->sanitize($value);
1946 }
1947
1948 $languageId = (int)$fullRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1949 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
1950
1951 // In case a workspace is given, and the $realPid(!) still is negative
1952 // this is most probably triggered by versionizeRecord() and a raw record
1953 // copy - thus, uniqueness cannot be determined without having the
1954 // real information
1955 // @todo This is still not explicit, but probably should be
1956 if ($workspaceId > 0 && $realPid === -1
1957 && !MathUtility::canBeInterpretedAsInteger($id)
1958 ) {
1959 return ['value' => $value];
1960 }
1961
1962 if (in_array('uniqueInSite', $evalCodesArray, true)) {
1963 $value = $helper->buildSlugForUniqueInSite($value, $id, $realPid, $languageId);
1964 }
1965 if (in_array('uniqueInPid', $evalCodesArray, true)) {
1966 $value = $helper->buildSlugForUniqueInPid($value, $id, $realPid, $languageId);
1967 }
1968
1969 return ['value' => $value];
1970 }
1971
1972 /**
1973 * Evaluates 'check' type values.
1974 *
1975 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1976 * @param string $value The value to set.
1977 * @param array $tcaFieldConf Field configuration from TCA
1978 * @param string $table Table name
1979 * @param int $id UID of record
1980 * @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.
1981 * @param string $field Field name
1982 * @return array Modified $res array
1983 */
1984 protected function checkValueForCheck($res, $value, $tcaFieldConf, $table, $id, $realPid, $field)
1985 {
1986 $items = $tcaFieldConf['items'];
1987 if (!empty($tcaFieldConf['itemsProcFunc'])) {
1988 /** @var ItemProcessingService $processingService */
1989 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
1990 $items = $processingService->getProcessingItems(
1991 $table,
1992 $realPid,
1993 $field,
1994 $this->checkValue_currentRecord,
1995 $tcaFieldConf,
1996 $tcaFieldConf['items']
1997 );
1998 }
1999
2000 $itemC = 0;
2001 if ($items !== null) {
2002 $itemC = count($items);
2003 }
2004 if (!$itemC) {
2005 $itemC = 1;
2006 }
2007 $maxV = (2 ** $itemC) - 1;
2008 if ($value < 0) {
2009 // @todo: throw LogicException here? Negative values for checkbox items do not make sense and indicate a coding error.
2010 $value = 0;
2011 }
2012 if ($value > $maxV) {
2013 // @todo: This case is pretty ugly: If there is an itemsProcFunc registered, and if it returns a dynamic,
2014 // @todo: changing list of items, then it may happen that a value is transformed and vanished checkboxes
2015 // @todo: are permanently removed from the value.
2016 // @todo: Suggestion: Throw an exception instead? Maybe a specific, catchable exception that generates a
2017 // @todo: error message to the user - dynamic item sets via itemProcFunc on check would be a bad idea anyway.
2018 $value = $value & $maxV;
2019 }
2020 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
2021 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], true);
2022 $otherRecordsWithSameValue = [];
2023 $maxCheckedRecords = 0;
2024 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, true)) {
2025 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
2026 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
2027 }
2028 if (in_array('maximumRecordsChecked', $evalCodesArray, true)) {
2029 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
2030 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
2031 }
2032
2033 // there are more than enough records with value "1" in the DB
2034 // if so, set this value to "0" again
2035 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
2036 $value = 0;
2037 $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]);
2038 }
2039 }
2040 $res['value'] = $value;
2041 return $res;
2042 }
2043
2044 /**
2045 * Evaluates 'radio' type values.
2046 *
2047 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2048 * @param string $value The value to set.
2049 * @param array $tcaFieldConf Field configuration from TCA
2050 * @param string $table The table of the record
2051 * @param int $id The id of the record
2052 * @param int $pid The pid of the record
2053 * @param string $field The field to check
2054 * @return array Modified $res array
2055 */
2056 protected function checkValueForRadio($res, $value, $tcaFieldConf, $table, $id, $pid, $field)
2057 {
2058 if (is_array($tcaFieldConf['items'])) {
2059 foreach ($tcaFieldConf['items'] as $set) {
2060 if ((string)$set[1] === (string)$value) {
2061 $res['value'] = $value;
2062 break;
2063 }
2064 }
2065 }
2066
2067 // if no value was found and an itemsProcFunc is defined, check that for the value
2068 if ($tcaFieldConf['itemsProcFunc'] && empty($res['value'])) {
2069 $processingService = GeneralUtility::makeInstance(ItemProcessingService::class);
2070 $processedItems = $processingService->getProcessingItems(
2071 $table,
2072 $pid,
2073 $field,
2074 $this->checkValue_currentRecord,
2075 $tcaFieldConf,
2076 $tcaFieldConf['items']
2077 );
2078
2079 foreach ($processedItems as $set) {
2080 if ((string)$set[1] === (string)$value) {
2081 $res['value'] = $value;
2082 break;
2083 }
2084 }
2085 }
2086
2087 return $res;
2088 }
2089
2090 /**
2091 * Evaluates 'group' or 'select' type values.
2092 *
2093 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2094 * @param string|array $value The value to set.
2095 * @param array $tcaFieldConf Field configuration from TCA
2096 * @param string $table Table name
2097 * @param int $id UID of record
2098 * @param mixed $curValue Current value of the field
2099 * @param string $status 'update' or 'new' flag
2100 * @param string $recFID Field identifier [table:uid:field] for flexforms
2101 * @param array $uploadedFiles
2102 * @param string $field Field name
2103 * @return array Modified $res array
2104 */
2105 protected function checkValueForGroupSelect($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $recFID, $uploadedFiles, $field)
2106 {
2107 // Detecting if value sent is an array and if so, implode it around a comma:
2108 if (is_array($value)) {
2109 $value = implode(',', $value);
2110 }
2111 // 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.
2112 // Anyway, this should NOT disturb anything else:
2113 $value = $this->convNumEntityToByteValue($value);
2114 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
2115 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
2116 // If multiple is not set, remove duplicates:
2117 if (!$tcaFieldConf['multiple']) {
2118 $valueArray = array_unique($valueArray);
2119 }
2120 // If an exclusive key is found, discard all others:
2121 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['exclusiveKeys']) {
2122 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
2123 foreach ($valueArray as $index => $key) {
2124 if (in_array($key, $exclusiveKeys, true)) {
2125 $valueArray = [$index => $key];
2126 break;
2127 }
2128 }
2129 }
2130 // 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?)
2131 // 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!!
2132 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
2133 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
2134 if ($tcaFieldConf['type'] === 'select' && $tcaFieldConf['authMode']) {
2135 $preCount = count($valueArray);
2136 foreach ($valueArray as $index => $key) {
2137 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
2138 unset($valueArray[$index]);
2139 }
2140 }
2141 // 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.
2142 if ($preCount && empty($valueArray)) {
2143 return [];
2144 }
2145 }
2146 // For group types:
2147 if ($tcaFieldConf['type'] === 'group'
2148 && in_array($tcaFieldConf['internal_type'], ['file', 'file_reference'], true)) {
2149 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
2150 }
2151 // For select types which has a foreign table attached:
2152 $unsetResult = false;
2153 if (
2154 $tcaFieldConf['type'] === 'group' && $tcaFieldConf['internal_type'] === 'db'
2155 || $tcaFieldConf['type'] === 'select' && ($tcaFieldConf['foreign_table'] || isset($tcaFieldConf['special']) && $tcaFieldConf['special'] === 'languages')
2156 ) {
2157 // check, if there is a NEW... id in the value, that should be substituted later
2158 if (strpos($value, 'NEW') !== false) {
2159 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2160 $this->addNewValuesToRemapStackChildIds($valueArray);
2161 $this->remapStack[] = [
2162 'func' => 'checkValue_group_select_processDBdata',
2163 'args' => [$valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field],
2164 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5],
2165 'field' => $field
2166 ];
2167 $unsetResult = true;
2168 } else {
2169 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $tcaFieldConf['type'], $table, $field);
2170 }
2171 }
2172 if (!$unsetResult) {
2173 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
2174 $res['value'] = $this->castReferenceValue(implode(',', $newVal), $tcaFieldConf);
2175 } else {
2176 unset($res['value']);
2177 }
2178 return $res;
2179 }
2180
2181 /**
2182 * Applies the filter methods from a column's TCA configuration to a value array.
2183 *
2184 * @param array $tcaFieldConfiguration
2185 * @param array $values
2186 * @return array|mixed
2187 * @throws \RuntimeException
2188 */
2189 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values)
2190 {
2191 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
2192 return $values;
2193 }
2194 foreach ($tcaFieldConfiguration['filter'] as $filter) {
2195 if (empty($filter['userFunc'])) {
2196 continue;
2197 }
2198 $parameters = $filter['parameters'] ?: [];
2199 $parameters['values'] = $values;
2200 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
2201 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
2202 if (!is_array($values)) {
2203 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
2204 }
2205 }
2206 return $values;
2207 }
2208
2209 /**
2210 * Handling files for group/select function
2211 *
2212 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
2213 * @param array $tcaFieldConf Configuration array from TCA of the field
2214 * @param string $curValue Current value of the field
2215 * @param array $uploadedFileArray Array of uploaded files, if any
2216 * @param string $status 'update' or 'new' flag
2217 * @param string $table tablename of record
2218 * @param int $id UID of record
2219 * @param string $recFID Field identifier [table:uid:field] for flexforms
2220 * @return array Modified value array
2221 *
2222 * @throws \RuntimeException
2223 */
2224 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID)
2225 {
2226 // If file handling should NOT be bypassed, do processing:
2227 if (!$this->bypassFileHandling) {
2228 // If any files are uploaded, add them to value array
2229 // Numeric index means that there are multiple files
2230 if (isset($uploadedFileArray[0])) {
2231 $uploadedFiles = $uploadedFileArray;
2232 } else {
2233 // There is only one file
2234 $uploadedFiles = [$uploadedFileArray];
2235 }
2236 foreach ($uploadedFiles as $uploadedFileArray) {
2237 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
2238 $valueArray[] = $uploadedFileArray['tmp_name'];
2239 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
2240 }
2241 }
2242 // Creating fileFunc object.
2243 if (!$this->fileFunc) {
2244 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
2245 }
2246 // Setting permitted extensions.
2247 $this->fileFunc->setFileExtensionPermissions($tcaFieldConf['allowed'], $tcaFieldConf['disallowed'] ?: '*');
2248 }
2249 // If there is an upload folder defined:
2250 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] === 'file') {
2251 $currentFilesForHistory = null;
2252 // If filehandling should NOT be bypassed, do processing:
2253 if (!$this->bypassFileHandling) {
2254 // For logging..
2255 $propArr = $this->getRecordProperties($table, $id);
2256 // Get destination path:
2257 $dest = Environment::getPublicPath() . '/' . $tcaFieldConf['uploadfolder'];
2258 // If we are updating:
2259 if ($status === 'update') {
2260 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
2261 // 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!
2262 // 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_.
2263 // 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.
2264 // Illustration of the problem comes here:
2265 // 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.
2266 // 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.
2267 // 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.
2268 // 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.
2269 if ($this->autoVersioningUpdate === true) {
2270 foreach ($valueArray as $key => $theFile) {
2271 // If it is an already attached file...
2272 if ($theFile === PathUtility::basename($theFile)) {
2273 $valueArray[$key] = Environment::getPublicPath() . '/' . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
2274 }
2275 }
2276 }
2277 // Finding the CURRENT files listed, either from MM or from the current record.
2278 $theFileValues = [];
2279 // If MM relations for the files also!
2280 if ($tcaFieldConf['MM']) {
2281 $dbAnalysis = $this->createRelationHandlerInstance();
2282 /** @var RelationHandler $dbAnalysis */
2283 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
2284 foreach ($dbAnalysis->itemArray as $item) {
2285 if ($item['id']) {
2286 $theFileValues[] = $item['id'];
2287 }
2288 }
2289 } else {
2290 $theFileValues = GeneralUtility::trimExplode(',', $curValue, true);
2291 }
2292 $currentFilesForHistory = implode(',', $theFileValues);
2293 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
2294 if (!empty($theFileValues)) {
2295 // 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!)
2296 foreach ($valueArray as $key => $theFile) {
2297 if ($theFile && strpos(GeneralUtility::fixWindowsFilePath($theFile), '/') === false) {
2298 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
2299 }
2300 }
2301 // This array contains the filenames in the uploadfolder that should be deleted:
2302 foreach ($theFileValues as $key => $theFile) {
2303 $theFile = trim($theFile);
2304 if (@is_file($dest . '/' . $theFile)) {
2305 $this->removeFilesStore[] = $dest . '/' . $theFile;
2306 } elseif ($theFile) {
2307 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, [$dest . '/' . $theFile, $recFID], $propArr['event_pid']);
2308 }
2309 }
2310 }
2311 }
2312 // Traverse the submitted values:
2313 foreach ($valueArray as $key => $theFile) {
2314 // Init:
2315 $maxSize = (int)$tcaFieldConf['max_size'];
2316 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2317 $theDestFile = '';
2318 // a FAL file was added, now resolve the file object and get the absolute path
2319 // @todo in future versions this needs to be modified to handle FAL objects natively
2320 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2321 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2322 $theFile = $fileObject->getForLocalProcessing(false);
2323 }
2324 // NEW FILES? If the value contains '/' it indicates, that the file
2325 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
2326 if (strpos(GeneralUtility::fixWindowsFilePath($theFile), '/') !== false) {
2327 // Check various things before copying file:
2328 // File and destination must exist
2329 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2330 // Finding size.
2331 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2332 $fileSize = $uploadedFileArray['size'];
2333 } else {
2334 $fileSize = filesize($theFile);
2335 }
2336 // Check file size:
2337 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2338 // Prepare filename:
2339 $theEndFileName = $this->alternativeFileName[$theFile] ?? $theFile;
2340 $fI = GeneralUtility::split_fileref($theEndFileName);
2341 // Check for allowed extension:
2342 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2343 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2344 // If we have a unique destination filename, then write the file:
2345 if ($theDestFile) {
2346 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2347 // Hook for post-processing the upload action
2348 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] ?? [] as $className) {
2349 $hookObject = GeneralUtility::makeInstance($className);
2350 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2351 throw new \UnexpectedValueException($className . ' must implement interface ' . DataHandlerProcessUploadHookInterface::class, 1279962349);
2352 }
2353 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2354 }
2355 $this->copiedFileMap[$theFile] = $theDestFile;
2356 clearstatcache();
2357 if (!@is_file($theDestFile)) {
2358 $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']);
2359 }
2360 } else {
2361 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2362 }
2363 } else {
2364 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2365 }
2366 } else {
2367 $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']);
2368 }
2369 } else {
2370 $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']);
2371 }
2372 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2373 if (@is_file($theDestFile)) {
2374 $info = GeneralUtility::split_fileref($theDestFile);
2375 // The value is set to the new filename
2376 $valueArray[$key] = $info['file'];
2377 } else {
2378 // The value is set to the new filename
2379 unset($valueArray[$key]);
2380 }
2381 }
2382 }
2383 }
2384 // 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!
2385 if ($tcaFieldConf['MM']) {
2386 /** @var RelationHandler $dbAnalysis */
2387 $dbAnalysis = $this->createRelationHandlerInstance();
2388 // Dummy
2389 $dbAnalysis->tableArray['files'] = [];
2390 foreach ($valueArray as $key => $theFile) {
2391 // Explode files
2392 $dbAnalysis->itemArray[]['id'] = $theFile;
2393 }
2394 if ($status === 'update') {
2395 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2396 $newFiles = implode(',', $dbAnalysis->getValueArray());
2397 list(, , $recFieldName) = explode(':', $recFID);
2398 if ($currentFilesForHistory != $newFiles) {
2399 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2400 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2401 } else {
2402 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2403 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2404 }
2405 } else {
2406 $this->dbAnalysisStore[] = [$dbAnalysis, $tcaFieldConf['MM'], $id, 0];
2407 }
2408 $valueArray = $dbAnalysis->countItems();
2409 }
2410 } else {
2411 if (!empty($valueArray)) {
2412 // If filehandling should NOT be bypassed, do processing:
2413 if (!$this->bypassFileHandling) {
2414 // For logging..
2415 $propArr = $this->getRecordProperties($table, $id);
2416 foreach ($valueArray as &$theFile) {
2417 // FAL handling: it's a UID, thus it is resolved to the absolute path
2418 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2419 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2420 $theFile = $fileObject->getForLocalProcessing(false);
2421 }
2422 if ($this->alternativeFilePath[$theFile]) {
2423 // If alternative File Path is set for the file, then it was an import
2424 // don't import the file if it already exists
2425 if (@is_file(Environment::getPublicPath() . '/' . $this->alternativeFilePath[$theFile])) {
2426 $theFile = Environment::getPublicPath() . '/' . $this->alternativeFilePath[$theFile];
2427 } elseif (@is_file($theFile)) {
2428 $dest = PathUtility::dirname(Environment::getPublicPath() . '/' . $this->alternativeFilePath[$theFile]);
2429 if (!@is_dir($dest)) {
2430 GeneralUtility::mkdir_deep($dest);
2431 }
2432 // Init:
2433 $maxSize = (int)$tcaFieldConf['max_size'];
2434 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2435 $theDestFile = '';
2436 $fileSize = filesize($theFile);
2437 // Check file size:
2438 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2439 // Prepare filename:
2440 $theEndFileName = $this->alternativeFileName[$theFile] ?? $theFile;
2441 $fI = GeneralUtility::split_fileref($theEndFileName);
2442 // Check for allowed extension:
2443 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2444 $theDestFile = Environment::getPublicPath() . '/' . $this->alternativeFilePath[$theFile];
2445 // Write the file:
2446 if ($theDestFile) {
2447 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2448 $this->copiedFileMap[$theFile] = $theDestFile;
2449 clearstatcache();
2450 if (!@is_file($theDestFile)) {
2451 $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']);
2452 }
2453 } else {
2454 $this->log($table, $id, 5, 0, 1, 'Copying file \'%s\' failed!: No destination file (%s) possible!. (%s)', 11, [$theFile, $theDestFile, $recFID], $propArr['event_pid']);
2455 }
2456 } else {
2457 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, [$fI['fileext'], $recFID], $propArr['event_pid']);
2458 }
2459 } else {
2460 $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']);
2461 }
2462 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2463 if (@is_file($theDestFile)) {
2464 // The value is set to the new filename
2465 $theFile = $theDestFile;
2466 } else {
2467 // The value is set to the new filename
2468 unset($theFile);
2469 }
2470 }
2471 }
2472 if (!empty($theFile)) {
2473 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2474 if (GeneralUtility::isFirstPartOfStr($theFile, Environment::getPublicPath())) {
2475 $theFile = PathUtility::stripPathSitePrefix($theFile);
2476 }
2477 }
2478 }
2479 unset($theFile);
2480 }
2481 }
2482 }
2483 return $valueArray;
2484 }
2485
2486 /**
2487 * Evaluates 'flex' type values.
2488 *
2489 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2490 * @param string|array $value The value to set.
2491 * @param array $tcaFieldConf Field configuration from TCA
2492 * @param string $table Table name
2493 * @param int $id UID of record
2494 * @param mixed $curValue Current value of the field
2495 * @param string $status 'update' or 'new' flag
2496 * @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.
2497 * @param string $recFID Field identifier [table:uid:field] for flexforms
2498 * @param int $tscPID TSconfig PID
2499 * @param array $uploadedFiles Uploaded files for the field
2500 * @param string $field Field name
2501 * @return array Modified $res array
2502 */
2503 protected function checkValueForFlex($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $tscPID, $uploadedFiles, $field)
2504 {
2505 if (is_array($value)) {
2506 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2507 // Problem: when copying a page, flexform XML comes along in the array for the new record - but since $this->checkValue_currentRecord
2508 // does not have a uid or pid for that sake, the FlexFormTools->getDataStructureIdentifier() function returns no good DS. For new
2509 // records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
2510 $row = $this->checkValue_currentRecord;
2511 if ($status === 'new') {
2512 $row['pid'] = $realPid;
2513 }
2514
2515 $flexFormTools = GeneralUtility::makeInstance(FlexFormTools::class);
2516
2517 // Get data structure. The methods may throw various exceptions, with some of them being
2518 // ok in certain scenarios, for instance on new record rows. Those are ok to "eat" here
2519 // and substitute with a dummy DS.
2520 $dataStructureArray = ['sheets' => ['sDEF' => []]];
2521 try {
2522 $dataStructureIdentifier = $flexFormTools->getDataStructureIdentifier(
2523 ['config' => $tcaFieldConf],
2524 $table,
2525 $field,
2526 $row
2527 );
2528
2529 $dataStructureArray = $flexFormTools->parseDataStructureByIdentifier($dataStructureIdentifier);
2530 } catch (InvalidParentRowException $e) {
2531 } catch (InvalidParentRowLoopException $e) {
2532 } catch (InvalidParentRowRootException $e) {
2533 } catch (InvalidPointerFieldValueException $e) {
2534 } catch (InvalidIdentifierException $e) {
2535 }
2536
2537 // Get current value array:
2538 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : [];
2539 if (!is_array($currentValueArray)) {
2540 $currentValueArray = [];
2541 }
2542 // Remove all old meta for languages...
2543 // Evaluation of input values:
2544 $value['data'] = $this->checkValue_flex_procInData($value['data'] ?? [], $currentValueArray['data'] ?? [], $uploadedFiles['data'] ?? [], $dataStructureArray, [$table, $id, $curValue, $status, $realPid, $recFID, $tscPID]);
2545 // Create XML from input value:
2546 $xmlValue = $this->checkValue_flexArray2Xml($value, true);
2547
2548 // 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
2549 // (provided that the current value was already stored IN the charset that the new value is converted to).
2550 $arrValue = GeneralUtility::xml2array($xmlValue);
2551
2552 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] ?? [] as $className) {
2553 $hookObject = GeneralUtility::makeInstance($className);
2554 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2555 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2556 }
2557 }
2558
2559 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2560 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, true);
2561
2562 // Action commands (sorting order and removals of elements) for flexform sections,
2563 // see FormEngine for the use of this GP parameter
2564 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2565 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2566 $arrValue = GeneralUtility::xml2array($xmlValue);
2567 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2568 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, true);
2569 }
2570 // Create the value XML:
2571 $res['value'] = '';
2572 $res['value'] .= $xmlValue;
2573 } else {
2574 // Passthrough...:
2575 $res['value'] = $value;
2576 }
2577
2578 return $res;
2579 }
2580
2581 /**
2582 * Converts an array to FlexForm XML
2583 *
2584 * @param array $array Array with FlexForm data
2585 * @param bool $addPrologue If set, the XML prologue is returned as well.
2586 * @return string Input array converted to XML
2587 */
2588 public function checkValue_flexArray2Xml($array, $addPrologue = false)
2589 {
2590 /** @var FlexFormTools $flexObj */
2591 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2592 return $flexObj->flexArray2Xml($array, $addPrologue);
2593 }
2594
2595 /**
2596 * Actions for flex form element (move, delete)
2597 * allows to remove and move flexform sections
2598 *
2599 * @param array $valueArray by reference
2600 * @param array $actionCMDs
2601 */
2602 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs)
2603 {
2604 if (!is_array($valueArray) || !is_array($actionCMDs)) {
2605 return;
2606 }
2607
2608 foreach ($actionCMDs as $key => $value) {
2609 if ($key === '_ACTION') {
2610 // First, check if there are "commands":
2611 if (current($actionCMDs[$key]) === '') {
2612 continue;
2613 }
2614
2615 asort($actionCMDs[$key]);
2616 $newValueArray = [];
2617 foreach ($actionCMDs[$key] as $idx => $order) {
2618 // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost
2619 // files unless we act on this delete operation by traversing and deleting files that were referred to.
2620 if ($order !== 'DELETE') {
2621 $newValueArray[$idx] = $valueArray[$idx];
2622 }
2623 unset($valueArray[$idx]);
2624 }
2625 $valueArray += $newValueArray;
2626 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2627 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2628 }
2629 }
2630 }
2631
2632 /**
2633 * Evaluates 'inline' type values.
2634 * (partly copied from the select_group function on this issue)
2635 *
2636 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2637 * @param string $value The value to set.
2638 * @param array $tcaFieldConf Field configuration from TCA
2639 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2640 * @param string $field Field name
2641 * @param array $additionalData Additional data to be forwarded to sub-processors
2642 * @return array Modified $res array
2643 */
2644 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = null)
2645 {
2646 list($table, $id, , $status) = $PP;
2647 $this->checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, $additionalData);
2648 }
2649
2650 /**
2651 * Evaluates 'inline' type values.
2652 * (partly copied from the select_group function on this issue)
2653 *
2654 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2655 * @param string $value The value to set.
2656 * @param array $tcaFieldConf Field configuration from TCA
2657 * @param string $table Table name
2658 * @param int $id UID of record
2659 * @param string $status 'update' or 'new' flag
2660 * @param string $field Field name
2661 * @param array $additionalData Additional data to be forwarded to sub-processors
2662 * @return array|bool Modified $res array
2663 */
2664 public function checkValueForInline($res, $value, $tcaFieldConf, $table, $id, $status, $field, array $additionalData = null)
2665 {
2666 if (!$tcaFieldConf['foreign_table']) {
2667 // Fatal error, inline fields should always have a foreign_table defined
2668 return false;
2669 }
2670 // When values are sent they come as comma-separated values which are exploded by this function:
2671 $valueArray = GeneralUtility::trimExplode(',', $value);
2672 // Remove duplicates: (should not be needed)
2673 $valueArray = array_unique($valueArray);
2674 // Example for received data:
2675 // $value = 45,NEW4555fdf59d154,12,123
2676 // We need to decide whether we use the stack or can save the relation directly.
2677 if (!empty($value) && (strpos($value, 'NEW') !== false || !MathUtility::canBeInterpretedAsInteger($id))) {
2678 $this->remapStackRecords[$table][$id] = ['remapStackIndex' => count($this->remapStack)];
2679 $this->addNewValuesToRemapStackChildIds($valueArray);
2680 $this->remapStack[] = [
2681 'func' => 'checkValue_inline_processDBdata',
2682 'args' => [$valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData],
2683 'pos' => ['valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4],
2684 'additionalData' => $additionalData,
2685 'field' => $field,
2686 ];
2687 unset($res['value']);
2688 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2689 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2690 }
2691 return $res;
2692 }
2693
2694 /**
2695 * Checks if a fields has more items than defined via TCA in maxitems.
2696 * If there are more items than allowed, the item list is truncated to the defined number.
2697 *
2698 * @param array $tcaFieldConf Field configuration from TCA
2699 * @param array $valueArray Current value array of items
2700 * @return array The truncated value array of items
2701 */
2702 public function checkValue_checkMax($tcaFieldConf, $valueArray)
2703 {
2704 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function
2705 // calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check
2706 // before? Probably because we could not evaluate the validity of record uids etc... Hmm...
2707 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first,
2708 // if the field is actual used regarding the CType.
2709 $maxitems = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 99999;
2710 return array_slice($valueArray, 0, $maxitems);
2711 }
2712
2713 /*********************************************
2714 *
2715 * Helper functions for evaluation functions.
2716 *
2717 ********************************************/
2718 /**
2719 * Gets a unique value for $table/$id/$field based on $value
2720 *
2721 * @param string $table Table name
2722 * @param string $field Field name for which $value must be unique
2723 * @param string $value Value string.
2724 * @param int $id UID to filter out in the lookup (the record itself...)
2725 * @param int $newPid If set, the value will be unique for this PID
2726 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2727 */
2728 public function getUnique($table, $field, $value, $id, $newPid = 0)
2729 {
2730 // If the field is configured in TCA, proceed:
2731 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2732 $newValue = $value;
2733 $statement = $this->getUniqueCountStatement($newValue, $table, $field, (int)$id, (int)$newPid);
2734 // For as long as records with the test-value existing, try again (with incremented numbers appended)
2735 if ($statement->fetchColumn()) {
2736 for ($counter = 0; $counter <= 100; $counter++) {
2737 $newValue = $value . $counter;
2738 $statement->bindValue(1, $newValue);
2739 $statement->execute();
2740 if (!$statement->fetchColumn()) {
2741 break;
2742 }
2743 }
2744 }
2745 $value = $newValue;
2746 }
2747 return $value;
2748 }
2749
2750 /**
2751 * Gets the count of records for a unique field
2752 *
2753 * @param string $value The string value which should be unique
2754 * @param string $table Table name
2755 * @param string $field Field name for which $value must be unique
2756 * @param int $uid UID to filter out in the lookup (the record itself...)
2757 * @param int $pid If set, the value will be unique for this PID
2758 * @return \Doctrine\DBAL\Driver\Statement|int Return the prepared statement to check uniqueness
2759 */
2760 protected function getUniqueCountStatement(
2761 string $value,
2762 string $table,
2763 string $field,
2764 int $uid,
2765 int $pid
2766 ): Statement {
2767 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
2768 $this->addDeleteRestriction($queryBuilder->getRestrictions()->removeAll());
2769 $queryBuilder
2770 ->count('uid')
2771 ->from($table)
2772 ->where(
2773 $queryBuilder->expr()->eq($field, $queryBuilder->createPositionalParameter($value, \PDO::PARAM_STR)),
2774 $queryBuilder->expr()->neq('uid', $queryBuilder->createPositionalParameter($uid, \PDO::PARAM_INT))
2775 );
2776 if ($pid !== 0) {
2777 $queryBuilder->andWhere(
2778 $queryBuilder->expr()->eq('pid', $queryBuilder->createPositionalParameter($pid, \PDO::PARAM_INT))
2779 );
2780 } else {
2781 // pid>=0 for versioning
2782 $queryBuilder->andWhere(
2783 $queryBuilder->expr()->gte('pid', $queryBuilder->createPositionalParameter(0, \PDO::PARAM_INT))
2784 );
2785 }
2786
2787 return $queryBuilder->execute();
2788 }
2789
2790 /**
2791 * gets all records that have the same value in a field
2792 * excluding the given uid
2793 *
2794 * @param string $tableName Table name
2795 * @param int $uid UID to filter out in the lookup (the record itself...)
2796 * @param string $fieldName Field name for which $value must be unique
2797 * @param string $value Value string.
2798 * @param int $pageId If set, the value will be unique for this PID
2799 * @return array
2800 */
2801 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0)
2802 {
2803 $result = [];
2804 if (empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2805 return $result;
2806 }
2807
2808 $uid = (int)$uid;
2809 $pageId = (int)$pageId;
2810
2811 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
2812 $queryBuilder->getRestrictions()
2813 ->removeAll()
2814 ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
2815 ->add(GeneralUtility::makeInstance(BackendWorkspaceRestriction::class));
2816
2817 $queryBuilder->select('*')
2818 ->from($tableName)
2819 ->where(
2820 $queryBuilder->expr()->eq(
2821 $fieldName,
2822 $queryBuilder->createNamedParameter($value, \PDO::PARAM_STR)
2823 ),
2824 $queryBuilder->expr()->neq(
2825 'uid',
2826 $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
2827 )
2828 );
2829
2830 if ($pageId) {
2831 $queryBuilder->andWhere(
2832 $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pageId, \PDO::PARAM_INT))
2833 );
2834 } else {
2835 $queryBuilder->andWhere(
2836 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
2837 );
2838 }
2839
2840 $result = $queryBuilder->execute()->fetchAll();
2841
2842 return $result;
2843 }
2844
2845 /**
2846 * @param string $value The field value to be evaluated
2847 * @param array $evalArray Array of evaluations to traverse.
2848 * @param string $is_in The "is_in" value of the field configuration from TCA
2849 * @return array
2850 */
2851 public function checkValue_text_Eval($value, $evalArray, $is_in)
2852 {
2853 $res = [];
2854 $set = true;
2855 foreach ($evalArray as $func) {
2856 switch ($func) {
2857 case 'trim':
2858 $value = trim($value);
2859 break;
2860 case 'required':
2861 if (!$value) {
2862 $set = false;
2863 }
2864 break;
2865 default:
2866 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2867 if (class_exists($func)) {
2868 $evalObj = GeneralUtility::makeInstance($func);
2869 if (method_exists($evalObj, 'evaluateFieldValue')) {
2870 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2871 }
2872 }
2873 }
2874 }
2875 }
2876 if ($set) {
2877 $res['value'] = $value;
2878 }
2879 return $res;
2880 }
2881
2882 /**
2883 * Evaluation of 'input'-type values based on 'eval' list
2884 *
2885 * @param string $value Value to evaluate
2886 * @param array $evalArray Array of evaluations to traverse.
2887 * @param string $is_in Is-in string for 'is_in' evaluation
2888 * @param string $table Table name the eval is evaluated on
2889 * @return array Modified $value in key 'value' or empty array
2890 */
2891 public function checkValue_input_Eval($value, $evalArray, $is_in, string $table = ''): array
2892 {
2893 $res = [];
2894 $set = true;
2895 foreach ($evalArray as $func) {
2896 switch ($func) {
2897 case 'int':
2898 case 'year':
2899 $value = (int)$value;
2900 break;
2901 case 'time':
2902 case 'timesec':
2903 // If $value is a pure integer we have the number of seconds, we can store that directly
2904 if ($value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2905 // $value is an ISO 8601 date
2906 $value = (new \DateTime($value))->getTimestamp();
2907 }
2908 break;
2909 case 'date':
2910 case 'datetime':
2911 // If $value is a pure integer we have the number of seconds, we can store that directly
2912 if ($value !== null && $value !== '' && !MathUtility::canBeInterpretedAsInteger($value)) {
2913 // The value we receive from JS is an ISO 8601 date, which is always in UTC. (the JS code works like that, on purpose!)
2914 // For instance "1999-11-11T11:11:11Z"
2915 // Since the user actually specifies the time in the server's local time, we need to mangle this
2916 // to reflect the server TZ. So we make this 1999-11-11T11:11:11+0200 (assuming Europe/Vienna here)
2917 // In the database we store the date in UTC (1999-11-11T09:11:11Z), hence we take the timestamp of this converted value.
2918 // For achieving this we work with timestamps only (which are UTC) and simply adjust it for the
2919 // TZ difference.
2920 try {
2921 // Make the date from JS a timestamp
2922 $value = (new \DateTime($value))->getTimestamp();
2923 } catch (\Exception $e) {
2924 // set the default timezone value to achieve the value of 0 as a result
2925 $value = (int)date('Z', 0);
2926 }
2927
2928 // @todo this hacky part is problematic when it comes to times around DST switch! Add test to prove that this is broken.
2929 $value -= date('Z', $value);
2930 }
2931 break;
2932 case 'double2':
2933 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2934 $negative = $value[0] === '-';