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