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