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