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