[CLEANUP] Make use of possible imports and remove unused ones
[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 $recFID = $table . ':' . $id . ':' . $field;
1507 // Processing special case of field pages.doktype
1508 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1509 // If the user may not use this specific doktype, we issue a warning
1510 if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1511 $propArr = $this->getRecordProperties($table, $id);
1512 $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']);
1513 return $res;
1514 }
1515 if ($status == 'update') {
1516 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1517 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1518 if ($onlyAllowedTables) {
1519 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1520 if ($theWrongTables) {
1521 $propArr = $this->getRecordProperties($table, $id);
1522 $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']);
1523 return $res;
1524 }
1525 }
1526 }
1527 }
1528 // Get current value:
1529 $curValueRec = $this->recordInfo($table, $id, $field);
1530 $curValue = $curValueRec[$field];
1531 // Getting config for the field
1532 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1533 // Preform processing:
1534 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1535 return $res;
1536 }
1537
1538 /**
1539 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1540 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1541 *
1542 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1543 * @param string $value The value to set.
1544 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1545 * @param string $table Table name
1546 * @param int $id UID of record
1547 * @param mixed $curValue Current value of the field
1548 * @param string $status 'update' or 'new' flag
1549 * @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.
1550 * @param string $recFID Field identifier [table:uid:field] for flexforms
1551 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1552 * @param array $uploadedFiles
1553 * @param int $tscPID TSconfig PID
1554 * @param array $additionalData Additional data to be forwarded to sub-processors
1555 * @return array Returns the evaluated $value as key "value" in this array.
1556 */
1557 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = NULL) {
1558 // Convert to NULL value if defined in TCA
1559 if ($value === NULL && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1560 $res = array('value' => NULL);
1561 return $res;
1562 }
1563
1564 $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
1565 switch ($tcaFieldConf['type']) {
1566 case 'text':
1567 $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
1568 break;
1569 case 'passthrough':
1570
1571 case 'user':
1572 $res['value'] = $value;
1573 break;
1574 case 'input':
1575 $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
1576 break;
1577 case 'check':
1578 $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP, $field);
1579 break;
1580 case 'radio':
1581 $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
1582 break;
1583 case 'group':
1584
1585 case 'select':
1586 $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1587 break;
1588 case 'inline':
1589 $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, $additionalData);
1590 break;
1591 case 'flex':
1592 // FlexForms are only allowed for real fields.
1593 if ($field) {
1594 $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1595 }
1596 break;
1597 default:
1598 // Do nothing
1599 }
1600 return $res;
1601 }
1602
1603 /**
1604 * Evaluate "text" type values.
1605 *
1606 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1607 * @param string $value The value to set.
1608 * @param array $tcaFieldConf Field configuration from TCA
1609 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1610 * @param string $field Field name
1611 * @return array Modified $res array
1612 */
1613 public function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1614 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1615 $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1616 return $res;
1617 }
1618
1619 /**
1620 * Evaluate "input" type values.
1621 *
1622 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1623 * @param string $value The value to set.
1624 * @param array $tcaFieldConf Field configuration from TCA
1625 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1626 * @param string $field Field name
1627 * @return array Modified $res array
1628 */
1629 public function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1630 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1631 // Handle native date/time fields
1632 $isDateOrDateTimeField = FALSE;
1633 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' || $tcaFieldConf['dbType'] === 'datetime')) {
1634 $isDateOrDateTimeField = TRUE;
1635 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1636 // Convert the date/time into a timestamp for the sake of the checks
1637 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1638 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1639 // At this point in the processing, the timestamps are still based on UTC
1640 $timeZone = new \DateTimeZone('UTC');
1641 $dateTime = \DateTime::createFromFormat('!' . $format, $value, $timeZone);
1642 $value = $value === $emptyValue ? 0 : $dateTime->getTimestamp();
1643 }
1644 // Secures the string-length to be less than max.
1645 if ((int)$tcaFieldConf['max'] > 0) {
1646 $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, $value, 0, (int)$tcaFieldConf['max']);
1647 }
1648 // Checking range of value:
1649 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1650 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1651 $value = $tcaFieldConf['range']['upper'];
1652 }
1653 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1654 $value = $tcaFieldConf['range']['lower'];
1655 }
1656 }
1657 // Process evaluation settings:
1658 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1659 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1660 // Process UNIQUE settings:
1661 // 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...
1662 if ($field && $realPid >= 0) {
1663 if ($res['value'] && in_array('uniqueInPid', $evalCodesArray, TRUE)) {
1664 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1665 }
1666 if ($res['value'] && in_array('unique', $evalCodesArray, TRUE)) {
1667 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1668 }
1669 }
1670 // Handle native date/time fields
1671 if ($isDateOrDateTimeField) {
1672 // Convert the timestamp back to a date/time
1673 $res['value'] = $res['value'] ? date($format, $res['value']) : $emptyValue;
1674 }
1675 return $res;
1676 }
1677
1678 /**
1679 * Evaluates 'check' type values.
1680 *
1681 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1682 * @param string $value The value to set.
1683 * @param array $tcaFieldConf Field configuration from TCA
1684 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1685 * @param string $field Field name
1686 * @return array Modified $res array
1687 */
1688 public function checkValue_check($res, $value, $tcaFieldConf, $PP, $field = '') {
1689 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1690 $itemC = count($tcaFieldConf['items']);
1691 if (!$itemC) {
1692 $itemC = 1;
1693 }
1694 $maxV = pow(2, $itemC) - 1;
1695 if ($value < 0) {
1696 $value = 0;
1697 }
1698 if ($value > $maxV) {
1699 $value = $maxV;
1700 }
1701 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1702 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1703 $otherRecordsWithSameValue = array();
1704 $maxCheckedRecords = 0;
1705 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, TRUE)) {
1706 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1707 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1708 }
1709 if (in_array('maximumRecordsChecked', $evalCodesArray, TRUE)) {
1710 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1711 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1712 }
1713
1714 // there are more than enough records with value "1" in the DB
1715 // if so, set this value to "0" again
1716 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1717 $value = 0;
1718 $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));
1719 }
1720 }
1721 $res['value'] = $value;
1722 return $res;
1723 }
1724
1725 /**
1726 * Evaluates 'radio' type values.
1727 *
1728 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1729 * @param string $value The value to set.
1730 * @param array $tcaFieldConf Field configuration from TCA
1731 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1732 * @return array Modified $res array
1733 */
1734 public function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1735 if (is_array($tcaFieldConf['items'])) {
1736 foreach ($tcaFieldConf['items'] as $set) {
1737 if ((string)$set[1] === (string)$value) {
1738 $res['value'] = $value;
1739 break;
1740 }
1741 }
1742 }
1743 return $res;
1744 }
1745
1746 /**
1747 * Evaluates 'group' or 'select' type values.
1748 *
1749 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1750 * @param string $value The value to set.
1751 * @param array $tcaFieldConf Field configuration from TCA
1752 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1753 * @param array $uploadedFiles
1754 * @param string $field Field name
1755 * @return array Modified $res array
1756 */
1757 public function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1758 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1759 // Detecting if value sent is an array and if so, implode it around a comma:
1760 if (is_array($value)) {
1761 $value = implode(',', $value);
1762 }
1763 // 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.
1764 // Anyway, this should NOT disturb anything else:
1765 $value = $this->convNumEntityToByteValue($value);
1766 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1767 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1768 // If multiple is not set, remove duplicates:
1769 if (!$tcaFieldConf['multiple']) {
1770 $valueArray = array_unique($valueArray);
1771 }
1772 // If an exclusive key is found, discard all others:
1773 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1774 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1775 foreach ($valueArray as $index => $key) {
1776 if (in_array($key, $exclusiveKeys, TRUE)) {
1777 $valueArray = array($index => $key);
1778 break;
1779 }
1780 }
1781 }
1782 // 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?)
1783 // 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!!
1784 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1785 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1786 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1787 $preCount = count($valueArray);
1788 foreach ($valueArray as $index => $key) {
1789 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1790 unset($valueArray[$index]);
1791 }
1792 }
1793 // 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.
1794 if ($preCount && !count($valueArray)) {
1795 return array();
1796 }
1797 }
1798 // For group types:
1799 if ($tcaFieldConf['type'] == 'group') {
1800 switch ($tcaFieldConf['internal_type']) {
1801 case 'file_reference':
1802
1803 case 'file':
1804 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
1805 break;
1806 case 'db':
1807 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
1808 break;
1809 }
1810 }
1811 // For select types which has a foreign table attached:
1812 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
1813 // check, if there is a NEW... id in the value, that should be substituted later
1814 if (strpos($value, 'NEW') !== FALSE) {
1815 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
1816 $this->addNewValuesToRemapStackChildIds($valueArray);
1817 $this->remapStack[] = array(
1818 'func' => 'checkValue_group_select_processDBdata',
1819 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
1820 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
1821 'field' => $field
1822 );
1823 $unsetResult = TRUE;
1824 } else {
1825 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
1826 }
1827 }
1828 if (!$unsetResult) {
1829 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
1830 $res['value'] = implode(',', $newVal);
1831 } else {
1832 unset($res['value']);
1833 }
1834 return $res;
1835 }
1836
1837 /**
1838 * Applies the filter methods from a column's TCA configuration to a value array.
1839 *
1840 * @param array $tcaFieldConfiguration
1841 * @param array $values
1842 * @return array|mixed
1843 * @throws \RuntimeException
1844 */
1845 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values) {
1846 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
1847 return $values;
1848 }
1849 foreach ($tcaFieldConfiguration['filter'] as $filter) {
1850 if (empty($filter['userFunc'])) {
1851 continue;
1852 }
1853 $parameters = $filter['parameters'] ?: array();
1854 $parameters['values'] = $values;
1855 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
1856 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
1857 if (!is_array($values)) {
1858 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
1859 }
1860 }
1861 return $values;
1862 }
1863
1864 /**
1865 * Handling files for group/select function
1866 *
1867 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
1868 * @param array $tcaFieldConf Configuration array from TCA of the field
1869 * @param string $curValue Current value of the field
1870 * @param array $uploadedFileArray Array of uploaded files, if any
1871 * @param string $status Status ("update" or ?)
1872 * @param string $table tablename of record
1873 * @param int $id UID of record
1874 * @param string $recFID Field identifier ([table:uid:field:....more for flexforms?]
1875 * @return array Modified value array
1876 * @see checkValue_group_select()
1877 */
1878 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
1879 // If file handling should NOT be bypassed, do processing:
1880 if (!$this->bypassFileHandling) {
1881 // If any files are uploaded, add them to value array
1882 // Numeric index means that there are multiple files
1883 if (isset($uploadedFileArray[0])) {
1884 $uploadedFiles = $uploadedFileArray;
1885 } else {
1886 // There is only one file
1887 $uploadedFiles = array($uploadedFileArray);
1888 }
1889 foreach ($uploadedFiles as $uploadedFileArray) {
1890 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
1891 $valueArray[] = $uploadedFileArray['tmp_name'];
1892 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1893 }
1894 }
1895 // Creating fileFunc object.
1896 if (!$this->fileFunc) {
1897 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
1898 $this->include_filefunctions = 1;
1899 }
1900 // Setting permitted extensions.
1901 $all_files = array();
1902 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1903 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
1904 $all_files['ftpspace'] = $all_files['webspace'];
1905 $this->fileFunc->init('', $all_files);
1906 }
1907 // If there is an upload folder defined:
1908 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
1909 // If filehandling should NOT be bypassed, do processing:
1910 if (!$this->bypassFileHandling) {
1911 // For logging..
1912 $propArr = $this->getRecordProperties($table, $id);
1913 // Get destrination path:
1914 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1915 // If we are updating:
1916 if ($status == 'update') {
1917 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
1918 // 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!
1919 // 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_.
1920 // 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.
1921 // Illustration of the problem comes here:
1922 // 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.
1923 // 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.
1924 // 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.
1925 // 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.
1926 if ($this->autoVersioningUpdate === TRUE) {
1927 foreach ($valueArray as $key => $theFile) {
1928 // If it is an already attached file...
1929 if ($theFile === basename($theFile)) {
1930 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
1931 }
1932 }
1933 }
1934 // Finding the CURRENT files listed, either from MM or from the current record.
1935 $theFileValues = array();
1936 // If MM relations for the files also!
1937 if ($tcaFieldConf['MM']) {
1938 $dbAnalysis = $this->createRelationHandlerInstance();
1939 /** @var $dbAnalysis RelationHandler */
1940 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
1941 foreach ($dbAnalysis->itemArray as $item) {
1942 if ($item['id']) {
1943 $theFileValues[] = $item['id'];
1944 }
1945 }
1946 } else {
1947 $theFileValues = GeneralUtility::trimExplode(',', $curValue, TRUE);
1948 }
1949 $currentFilesForHistory = implode(',', $theFileValues);
1950 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1951 if (count($theFileValues)) {
1952 // 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!)
1953 foreach ($valueArray as $key => $theFile) {
1954 if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
1955 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
1956 }
1957 }
1958 // This array contains the filenames in the uploadfolder that should be deleted:
1959 foreach ($theFileValues as $key => $theFile) {
1960 $theFile = trim($theFile);
1961 if (@is_file(($dest . '/' . $theFile))) {
1962 $this->removeFilesStore[] = $dest . '/' . $theFile;
1963 } elseif ($theFile) {
1964 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
1965 }
1966 }
1967 }
1968 }
1969 // Traverse the submitted values:
1970 foreach ($valueArray as $key => $theFile) {
1971 // Init:
1972 $maxSize = (int)$tcaFieldConf['max_size'];
1973 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1974 $theDestFile = '';
1975 // a FAL file was added, now resolve the file object and get the absolute path
1976 // @todo in future versions this needs to be modified to handle FAL objects natively
1977 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
1978 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
1979 $theFile = $fileObject->getForLocalProcessing(FALSE);
1980 }
1981 // NEW FILES? If the value contains '/' it indicates, that the file
1982 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1983 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
1984 // Check various things before copying file:
1985 // File and destination must exist
1986 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
1987 // Finding size.
1988 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
1989 $fileSize = $uploadedFileArray['size'];
1990 } else {
1991 $fileSize = filesize($theFile);
1992 }
1993 // Check file size:
1994 if (!$maxSize || $fileSize <= $maxSize * 1024) {
1995 // Prepare filename:
1996 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
1997 $fI = GeneralUtility::split_fileref($theEndFileName);
1998 // Check for allowed extension:
1999 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2000 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2001 // If we have a unique destination filename, then write the file:
2002 if ($theDestFile) {
2003 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2004 // Hook for post-processing the upload action
2005 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2006 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2007 $hookObject = GeneralUtility::getUserObj($classRef);
2008 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2009 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
2010 }
2011 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2012 }
2013 }
2014 $this->copiedFileMap[$theFile] = $theDestFile;
2015 clearstatcache();
2016 if (!@is_file($theDestFile)) {
2017 $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']);
2018 }
2019 } else {
2020 $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']);
2021 }
2022 } else {
2023 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2024 }
2025 } else {
2026 $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']);
2027 }
2028 } else {
2029 $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']);
2030 }
2031 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2032 if (@is_file($theDestFile)) {
2033 $info = GeneralUtility::split_fileref($theDestFile);
2034 // The value is set to the new filename
2035 $valueArray[$key] = $info['file'];
2036 } else {
2037 // The value is set to the new filename
2038 unset($valueArray[$key]);
2039 }
2040 }
2041 }
2042 }
2043 // 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!
2044 if ($tcaFieldConf['MM']) {
2045 /** @var $dbAnalysis RelationHandler */
2046 $dbAnalysis = $this->createRelationHandlerInstance();
2047 // Dummy
2048 $dbAnalysis->tableArray['files'] = array();
2049 foreach ($valueArray as $key => $theFile) {
2050 // Explode files
2051 $dbAnalysis->itemArray[]['id'] = $theFile;
2052 }
2053 if ($status == 'update') {
2054 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2055 $newFiles = implode(',', $dbAnalysis->getValueArray());
2056 list(, , $recFieldName) = explode(':', $recFID);
2057 if ($currentFilesForHistory != $newFiles) {
2058 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2059 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2060 } else {
2061 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2062 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2063 }
2064 } else {
2065 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
2066 }
2067 $valueArray = $dbAnalysis->countItems();
2068 }
2069 } else {
2070 if (count($valueArray)) {
2071 // If filehandling should NOT be bypassed, do processing:
2072 if (!$this->bypassFileHandling) {
2073 // For logging..
2074 $propArr = $this->getRecordProperties($table, $id);
2075 foreach ($valueArray as &$theFile) {
2076 // FAL handling: it's a UID, thus it is resolved to the absolute path
2077 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2078 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2079 $theFile = $fileObject->getForLocalProcessing(FALSE);
2080 }
2081 if ($this->alternativeFilePath[$theFile]) {
2082 // If alternative File Path is set for the file, then it was an import
2083 // don't import the file if it already exists
2084 if (@is_file((PATH_site . $this->alternativeFilePath[$theFile]))) {
2085 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2086 } elseif (@is_file($theFile)) {
2087 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2088 if (!@is_dir($dest)) {
2089 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
2090 }
2091 // Init:
2092 $maxSize = (int)$tcaFieldConf['max_size'];
2093 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2094 $theDestFile = '';
2095 $fileSize = filesize($theFile);
2096 // Check file size:
2097 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2098 // Prepare filename:
2099 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2100 $fI = GeneralUtility::split_fileref($theEndFileName);
2101 // Check for allowed extension:
2102 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2103 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2104 // Write the file:
2105 if ($theDestFile) {
2106 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2107 $this->copiedFileMap[$theFile] = $theDestFile;
2108 clearstatcache();
2109 if (!@is_file($theDestFile)) {
2110 $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']);
2111 }
2112 } else {
2113 $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']);
2114 }
2115 } else {
2116 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2117 }
2118 } else {
2119 $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']);
2120 }
2121 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2122 if (@is_file($theDestFile)) {
2123 // The value is set to the new filename
2124 $theFile = $theDestFile;
2125 } else {
2126 // The value is set to the new filename
2127 unset($theFile);
2128 }
2129 }
2130 }
2131 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2132 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2133 $theFile = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($theFile);
2134 }
2135 }
2136 unset($theFile);
2137 }
2138 }
2139 }
2140 return $valueArray;
2141 }
2142
2143 /**
2144 * Evaluates 'flex' type values.
2145 *
2146 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2147 * @param string $value The value to set.
2148 * @param array $tcaFieldConf Field configuration from TCA
2149 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2150 * @param array $uploadedFiles Uploaded files for the field
2151 * @param string $field Field name
2152 * @return array Modified $res array
2153 */
2154 public function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
2155 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2156
2157 if (is_array($value)) {
2158 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2159 // 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
2160 // 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.
2161 // Only active when larger than zero.
2162 $newRecordPidValue = $status == 'new' ? $realPid : 0;
2163 // Get current value array:
2164 $dataStructArray = BackendUtility::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, $field, TRUE, $newRecordPidValue);
2165 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : array();
2166 if (!is_array($currentValueArray)) {
2167 $currentValueArray = array();
2168 }
2169 if (is_array($currentValueArray['meta']['currentLangId'])) {
2170 unset($currentValueArray['meta']['currentLangId']);
2171 }
2172 // Remove all old meta for languages...
2173 // Evaluation of input values:
2174 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
2175 // Create XML from input value:
2176 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
2177
2178 // 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
2179 // (provided that the current value was already stored IN the charset that the new value is converted to).
2180 $arrValue = GeneralUtility::xml2array($xmlValue);
2181
2182 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2183 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2184 $hookObject = GeneralUtility::getUserObj($classRef);
2185 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2186 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2187 }
2188 }
2189 }
2190
2191 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2192 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, TRUE);
2193
2194 // Action commands (sorting order and removals of elements) for flexform sections,
2195 // see FormEngine for the use of this GP parameter
2196 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2197 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2198 $arrValue = GeneralUtility::xml2array($xmlValue);
2199 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2200 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
2201 }
2202 // Create the value XML:
2203 $res['value'] = '';
2204 $res['value'] .= $xmlValue;
2205 } else {
2206 // Passthrough...:
2207 $res['value'] = $value;
2208 }
2209
2210 return $res;
2211 }
2212
2213 /**
2214 * Converts an array to FlexForm XML
2215 *
2216 * @param array $array Array with FlexForm data
2217 * @param bool $addPrologue If set, the XML prologue is returned as well.
2218 * @return string Input array converted to XML
2219 */
2220 public function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
2221 /** @var $flexObj FlexFormTools */
2222 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2223 return $flexObj->flexArray2Xml($array, $addPrologue);
2224 }
2225
2226 /**
2227 * Actions for flex form element (move, delete)
2228 * allows to remove and move flexform sections
2229 *
2230 * @param array $valueArray by reference
2231 * @param array $actionCMDs
2232 */
2233 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
2234 if (is_array($valueArray) && is_array($actionCMDs)) {
2235 foreach ($actionCMDs as $key => $value) {
2236 if ($key == '_ACTION') {
2237 // First, check if there are "commands":
2238 if (current($actionCMDs[$key]) !== '') {
2239 asort($actionCMDs[$key]);
2240 $newValueArray = array();
2241 foreach ($actionCMDs[$key] as $idx => $order) {
2242 if (substr($idx, 0, 3) == 'ID-') {
2243 $idx = $this->newIndexMap[$idx];
2244 }
2245 // 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.
2246 if ($order != 'DELETE') {
2247 $newValueArray[$idx] = $valueArray[$idx];
2248 }
2249 unset($valueArray[$idx]);
2250 }
2251 $valueArray = $valueArray + $newValueArray;
2252 }
2253 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2254 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2255 }
2256 }
2257 }
2258 }
2259
2260 /**
2261 * Evaluates 'inline' type values.
2262 * (partly copied from the select_group function on this issue)
2263 *
2264 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2265 * @param string $value The value to set.
2266 * @param array $tcaFieldConf Field configuration from TCA
2267 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2268 * @param string $field Field name
2269 * @param array $additionalData Additional data to be forwarded to sub-processors
2270 * @return array Modified $res array
2271 */
2272 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = NULL) {
2273 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2274 if (!$tcaFieldConf['foreign_table']) {
2275 // Fatal error, inline fields should always have a foreign_table defined
2276 return FALSE;
2277 }
2278 // When values are sent they come as comma-separated values which are exploded by this function:
2279 $valueArray = GeneralUtility::trimExplode(',', $value);
2280 // Remove duplicates: (should not be needed)
2281 $valueArray = array_unique($valueArray);
2282 // Example for received data:
2283 // $value = 45,NEW4555fdf59d154,12,123
2284 // We need to decide whether we use the stack or can save the relation directly.
2285 if (strpos($value, 'NEW') !== FALSE || !MathUtility::canBeInterpretedAsInteger($id)) {
2286 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2287 $this->addNewValuesToRemapStackChildIds($valueArray);
2288 $this->remapStack[] = array(
2289 'func' => 'checkValue_inline_processDBdata',
2290 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData),
2291 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
2292 'additionalData' => $additionalData,
2293 'field' => $field,
2294 );
2295 unset($res['value']);
2296 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2297 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2298 }
2299 return $res;
2300 }
2301
2302 /**
2303 * Checks if a fields has more items than defined via TCA in maxitems.
2304 * If there are more items than allowd, the item list is truncated to the defined number.
2305 *
2306 * @param array $tcaFieldConf Field configuration from TCA
2307 * @param array $valueArray Current value array of items
2308 * @return array The truncated value array of items
2309 */
2310 public function checkValue_checkMax($tcaFieldConf, $valueArray) {
2311 // 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...
2312 $valueArrayC = count($valueArray);
2313 // 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.
2314 $maxI = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 1;
2315 if ($valueArrayC > $maxI) {
2316 $valueArrayC = $maxI;
2317 }
2318 // Checking for not too many elements
2319 // Dumping array to list
2320 $newVal = array();
2321 foreach ($valueArray as $nextVal) {
2322 if ($valueArrayC == 0) {
2323 break;
2324 }
2325 $valueArrayC--;
2326 $newVal[] = $nextVal;
2327 }
2328 return $newVal;
2329 }
2330
2331 /*********************************************
2332 *
2333 * Helper functions for evaluation functions.
2334 *
2335 ********************************************/
2336 /**
2337 * Gets a unique value for $table/$id/$field based on $value
2338 *
2339 * @param string $table Table name
2340 * @param string $field Field name for which $value must be unique
2341 * @param string $value Value string.
2342 * @param int $id UID to filter out in the lookup (the record itself...)
2343 * @param int $newPid If set, the value will be unique for this PID
2344 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2345 */
2346 public function getUnique($table, $field, $value, $id, $newPid = 0) {
2347 // Initialize:
2348 $whereAdd = '';
2349 $newValue = '';
2350 if ((int)$newPid) {
2351 $whereAdd .= ' AND pid=' . (int)$newPid;
2352 } else {
2353 $whereAdd .= ' AND pid>=0';
2354 }
2355 // "AND pid>=0" for versioning
2356 $whereAdd .= $this->deleteClause($table);
2357 // If the field is configured in TCA, proceed:
2358 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2359 // Look for a record which might already have the value:
2360 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($value, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2361 $counter = 0;
2362 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2363 while ($this->databaseConnection->sql_num_rows($res)) {
2364 $newValue = $value . $counter;
2365 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($newValue, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2366 $counter++;
2367 if ($counter > 100) {
2368 break;
2369 }
2370 }
2371 $this->databaseConnection->sql_free_result($res);
2372 // If the new value is there:
2373 $value = $newValue !== '' ? $newValue : $value;
2374 }
2375 return $value;
2376 }
2377
2378 /**
2379 * gets all records that have the same value in a field
2380 * excluding the given uid
2381 *
2382 * @param string $tableName Table name
2383 * @param int $uid UID to filter out in the lookup (the record itself...)
2384 * @param string $fieldName Field name for which $value must be unique
2385 * @param string $value Value string.
2386 * @param int $pageId If set, the value will be unique for this PID
2387 * @return array
2388 */
2389 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0) {
2390 $result = array();
2391 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2392
2393 $uid = (int)$uid;
2394 $pageId = (int)$pageId;
2395 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ? 'pid = ' . $pageId : 'pid >= 0');
2396 $result = BackendUtility::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2397 }
2398 return $result;
2399 }
2400
2401 /**
2402 * @param string $value The field value to be evaluated
2403 * @param array $evalArray Array of evaluations to traverse.
2404 * @param string $is_in The "is_in" value of the field configuration from TCA
2405 * @return array
2406 */
2407 public function checkValue_text_Eval($value, $evalArray, $is_in) {
2408 $res = array();
2409 $set = TRUE;
2410 foreach ($evalArray as $func) {
2411 switch ($func) {
2412 case 'trim':
2413 $value = trim($value);
2414 break;
2415 case 'required':
2416 if (!$value) {
2417 $set = FALSE;
2418 }
2419 break;
2420 default:
2421 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2422 break;
2423 }
2424 $evalObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2425 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2426 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2427 }
2428 }
2429 }
2430 if ($set) {
2431 $res['value'] = $value;
2432 }
2433 return $res;
2434 }
2435
2436 /**
2437 * Evaluation of 'input'-type values based on 'eval' list
2438 *
2439 * @param string $value Value to evaluate
2440 * @param array $evalArray Array of evaluations to traverse.
2441 * @param string $is_in Is-in string for 'is_in' evaluation
2442 * @return array Modified $value in key 'value' or empty array
2443 */
2444 public function checkValue_input_Eval($value, $evalArray, $is_in) {
2445 $res = array();
2446 $set = TRUE;
2447 foreach ($evalArray as $func) {
2448 switch ($func) {
2449 case 'int':
2450 case 'year':
2451 case 'time':
2452 case 'timesec':
2453 $value = (int)$value;
2454 break;
2455 case 'date':
2456 case 'datetime':
2457 $value = (int)$value;
2458 if ($value > 0 && !$this->dontProcessTransformations) {
2459 $value -= date('Z', $value);
2460 }
2461 break;
2462 case 'double2':
2463 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2464 $negative = $value[0] === '-';
2465 $value = strtr($value, array(',' => '.', '-' => ''));
2466 if (strpos($value, '.') === FALSE) {
2467 $value .= '.0';
2468 }
2469 $valueArray = explode('.', $value);
2470 $dec = array_pop($valueArray);
2471 $value = join('', $valueArray) . '.' . $dec;
2472 if ($negative) {
2473 $value *= -1;
2474 }
2475 $value = number_format($value, 2, '.', '');
2476 break;
2477 case 'md5':
2478 if (strlen($value) != 32) {
2479 $set = FALSE;
2480 }
2481 break;
2482 case 'trim':
2483 $value = trim($value);
2484 break;
2485 case 'upper':
2486 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
2487 break;
2488 case 'lower':
2489 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
2490 break;
2491 case 'required':
2492 if (!isset($value) || $value === '') {
2493 $set = FALSE;
2494 }
2495 break;
2496 case 'is_in':
2497 $c = strlen($value);
2498 if ($c) {
2499 $newVal = '';
2500 for ($a = 0; $a < $c; $a++) {
2501 $char = substr($value, $a, 1);
2502 if (strpos($is_in, $char) !== FALSE) {
2503 $newVal .= $char;
2504 }
2505 }
2506 $value = $newVal;
2507 }
2508 break;
2509 case 'nospace':
2510 $value = str_replace(' ', '', $value);
2511 break;
2512 case 'alpha':
2513 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2514 break;
2515 case 'num':
2516 $value = preg_replace('/[^0-9]/', '', $value);
2517 break;
2518 case 'alphanum':
2519 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2520 break;
2521 case 'alphanum_x':
2522 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2523 break;
2524 case 'domainname':
2525 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2526 $value = GeneralUtility::idnaEncode($value);
2527 }
2528 break;
2529 case 'email':
2530 $this->checkValue_input_ValidateEmail($value, $set);
2531 break;
2532 default:
2533 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2534 break;
2535 }
2536 $evalObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2537 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2538 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2539 }
2540 }
2541 }
2542 if ($set) {
2543 $res['value'] = $value;
2544 }
2545 return $res;
2546 }
2547
2548 /**
2549 * If $value is not a valid e-mail address,
2550 * $set will be set to false and a flash error
2551 * message will be added
2552 *
2553 * @param string $value Value to evaluate
2554 * @param bool $set TRUE if an update should be done
2555 * @throws \InvalidArgumentException
2556 * @throws \TYPO3\CMS\Core\Exception
2557 * @return void
2558 */
2559 protected function checkValue_input_ValidateEmail($value, &$set) {
2560 if (GeneralUtility::validEmail($value)) {
2561 return;
2562 }
2563
2564 $set = FALSE;
2565 /** @var FlashMessage $message */
2566 $message = GeneralUtility::makeInstance(FlashMessage::class,
2567 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:error.invalidEmail'), $value),
2568 '', // header is optional
2569 FlashMessage::ERROR,
2570 TRUE // whether message should be stored in session
2571 );
2572 /** @var $flashMessageService FlashMessageService */
2573 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2574 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2575 }
2576
2577 /**
2578 * Returns data for group/db and select fields
2579 *
2580 * @param array $valueArray Current value array
2581 * @param array $tcaFieldConf TCA field config
2582 * @param int $id Record id, used for look-up of MM relations (local_uid)
2583 * @param string $status Status string ('update' or 'new')
2584 * @param string $type The type, either 'select', 'group' or 'inline'
2585 * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2586 * @param string $currentField field name, needs to be set for writing to sys_history
2587 * @return array Modified value array
2588 */
2589 public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
2590 $tables = $type == 'group' ? $tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'] . ',' . $tcaFieldConf['neg_foreign_table'];
2591 $prep = $type == 'group' ? $tcaFieldConf['prepend_tname'] : $tcaFieldConf['neg_foreign_table'];
2592 $newRelations = implode(',', $valueArray);
2593 /** @var $dbAnalysis RelationHandler */
2594 $dbAnalysis = $this->createRelationHandlerInstance();
2595 $dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2596 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2597 if ($tcaFieldConf['MM']) {
2598 if ($status == 'update') {
2599 /** @var $oldRelations_dbAnalysis RelationHandler */
2600 $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2601 $oldRelations_dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2602 // Db analysis with $id will initialize with the existing relations
2603 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2604 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2605 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2606 if ($oldRelations != $newRelations) {
2607 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2608 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2609 } else {
2610 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2611 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2612 }
2613 } else {
2614 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable);
2615 }
2616 $valueArray = $dbAnalysis->countItems();
2617 } else {
2618 $valueArray = $dbAnalysis->getValueArray($prep);
2619 if ($type == 'select' && $prep) {
2620 $valueArray = $dbAnalysis->convertPosNeg($valueArray, $tcaFieldConf['foreign_table'], $tcaFieldConf['neg_foreign_table']);
2621 }
2622 }
2623 // 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.
2624 return $valueArray;
2625 }
2626
2627 /**
2628 * Explodes the $value, which is a list of files/uids (group select)
2629 *
2630 * @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.
2631 * @return array The value array.
2632 */
2633 public function checkValue_group_select_explodeSelectGroupValue($value) {
2634 $valueArray = GeneralUtility::trimExplode(',', $value, TRUE);
2635 foreach ($valueArray as &$newVal) {
2636 $temp = explode('|', $newVal, 2);
2637 $newVal = str_replace(',', '', str_replace('|', '', rawurldecode($temp[0])));
2638 }
2639 unset($newVal);
2640 return $valueArray;
2641 }
2642
2643 /**
2644 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2645 * See checkValue_flex_procInData_travDS() for more details.
2646 * 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
2647 *
2648 * @param array $dataPart The 'data' part of the INPUT flexform data
2649 * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2650 * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2651 * @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.
2652 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2653 * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS() DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2654 * @return array The modified 'data' part.
2655 * @see checkValue_flex_procInData_travDS()
2656 */
2657 public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructArray, $pParams, $callBackFunc = '') {
2658 if (is_array($dataPart)) {
2659 foreach ($dataPart as $sKey => $sheetDef) {
2660 list($dataStruct, $actualSheet) = GeneralUtility::resolveSheetDefInDS($dataStructArray, $sKey);
2661 if (is_array($dataStruct) && $actualSheet == $sKey && is_array($sheetDef)) {
2662 foreach ($sheetDef as $lKey => $lData) {
2663 $this->checkValue_flex_procInData_travDS($dataPart[$sKey][$lKey], $dataPart_current[$sKey][$lKey], $uploadedFiles[$sKey][$lKey], $dataStruct['ROOT']['el'], $pParams, $callBackFunc, $sKey . '/' . $lKey . '/');
2664 }
2665 }
2666 }
2667 }
2668 return $dataPart;
2669 }
2670
2671 /**
2672 * Processing of the sheet/language data array
2673 * 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.
2674 *
2675 * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2676 * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2677 * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2678 * @param array $DSelements Data structure which fits the data array
2679 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2680 * @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.
2681 * @param string $structurePath
2682 * @return void
2683 * @see checkValue_flex_procInData()
2684 */
2685 public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath) {
2686 if (is_array($DSelements)) {
2687 // For each DS element:
2688 foreach ($DSelements as $key => $dsConf) {
2689 // Array/Section:
2690 if ($DSelements[$key]['type'] == 'array') {
2691 if (is_array($dataValues[$key]['el'])) {
2692 if ($DSelements[$key]['section']) {
2693 $newIndexCounter = 0;
2694 foreach ($dataValues[$key]['el'] as $ik => $el) {
2695 if (is_array($el)) {
2696 if (!is_array($dataValues_current[$key]['el'])) {
2697 $dataValues_current[$key]['el'] = array();
2698 }
2699 $theKey = key($el);
2700 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2701 $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/');
2702 // 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:
2703 // The fact that the order changes is not important since order is controlled by a separately submitted index.
2704 if (substr($ik, 0, 3) == 'ID-') {
2705 $newIndexCounter++;
2706 // Set mapping index
2707 $this->newIndexMap[$ik] = (is_array($dataValues_current[$key]['el']) && count($dataValues_current[$key]['el']) ? max(array_keys($dataValues_current[$key]['el'])) : 0) + $newIndexCounter;
2708 // Transfer values
2709 $dataValues[$key]['el'][$this->newIndexMap[$ik]] = $dataValues[$key]['el'][$ik];
2710 // Unset original
2711 unset($dataValues[$key]['el'][$ik]);
2712 }
2713 }
2714 }
2715 }
2716 } else {
2717 if (!isset($dataValues[$key]['el'])) {
2718 $dataValues[$key]['el'] = array();
2719 }
2720 $this->checkValue_flex_procInData_travDS($dataValues[$key]['el'], $dataValues_current[$key]['el'], $uploadedFiles[$key]['el'], $DSelements[$key]['el'], $pParams, $callBackFunc, $structurePath . $key . '/el/');
2721 }
2722 }
2723 } else {
2724 if (is_array($dsC