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