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