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