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