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