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