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