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