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