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