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