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