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