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