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