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