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