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