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