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