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