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