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