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