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