[BUGFIX] Use "user_auth" index for DataHandler:printLogErrorMessages
[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 = NULL;
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 if ($theTypeString === NULL) {
1471 $theTypeString = BackendUtility::getTCAtypeValue($table, $currentRecord);
1472 }
1473 $RTEsetup = $this->BE_USER->getTSConfig('RTE', BackendUtility::getPagesTSconfig($tscPID));
1474 $thisConfig = BackendUtility::RTEsetup($RTEsetup['properties'], $table, $vconf['field'], $theTypeString);
1475 // Get RTE object, draw form and set flag:
1476 $RTEobj = BackendUtility::RTEgetObj();
1477 if (is_object($RTEobj)) {
1478 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db', $fieldArray[$vconf['field']], $table, $vconf['field'], $currentRecord, $vconf['spec'], $thisConfig, '', $currentRecord['pid']);
1479 } else {
1480 debug('NO RTE OBJECT FOUND!');
1481 }
1482 break;
1483 }
1484 }
1485 }
1486 }
1487 }
1488 // Return fieldArray
1489 return $fieldArray;
1490 }
1491
1492 /*********************************************
1493 *
1494 * Evaluation of input values
1495 *
1496 ********************************************/
1497 /**
1498 * Evaluates a value according to $table/$field settings.
1499 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1500 * 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() )
1501 *
1502 * @param string $table Table name
1503 * @param string $field Field name
1504 * @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.
1505 * @param string $id The record-uid, mainly - but not exclusively - used for logging
1506 * @param string $status 'update' or 'new' flag
1507 * @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.
1508 * @param int $tscPID tscPID
1509 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1510 */
1511 public function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID) {
1512 // Result array
1513 $res = array();
1514 // Processing special case of field pages.doktype
1515 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1516 // If the user may not use this specific doktype, we issue a warning
1517 if (!($this->admin || GeneralUtility::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
1518 $propArr = $this->getRecordProperties($table, $id);
1519 $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']);
1520 return $res;
1521 }
1522 if ($status == 'update') {
1523 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1524 $onlyAllowedTables = isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']) ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'] : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables'];
1525 if ($onlyAllowedTables) {
1526 $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
1527 if ($theWrongTables) {
1528 $propArr = $this->getRecordProperties($table, $id);
1529 $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']);
1530 return $res;
1531 }
1532 }
1533 }
1534 }
1535 $curValue = NULL;
1536 if ((int)$id !== 0) {
1537 // Get current value:
1538 $curValueRec = $this->recordInfo($table, $id, $field);
1539 if (isset($curValueRec[$field])) {
1540 $curValue = $curValueRec[$field];
1541 }
1542 }
1543 // Getting config for the field
1544 $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
1545 $recFID = $table . ':' . $id . ':' . $field;
1546 // Preform processing:
1547 $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
1548 return $res;
1549 }
1550
1551 /**
1552 * Branches out evaluation of a field value based on its type as configured in $GLOBALS['TCA']
1553 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1554 *
1555 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1556 * @param string $value The value to set.
1557 * @param array $tcaFieldConf Field configuration from $GLOBALS['TCA']
1558 * @param string $table Table name
1559 * @param int $id UID of record
1560 * @param mixed $curValue Current value of the field
1561 * @param string $status 'update' or 'new' flag
1562 * @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.
1563 * @param string $recFID Field identifier [table:uid:field] for flexforms
1564 * @param string $field Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1565 * @param array $uploadedFiles
1566 * @param int $tscPID TSconfig PID
1567 * @param array $additionalData Additional data to be forwarded to sub-processors
1568 * @return array Returns the evaluated $value as key "value" in this array.
1569 */
1570 public function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID, array $additionalData = NULL) {
1571 // Convert to NULL value if defined in TCA
1572 if ($value === NULL && !empty($tcaFieldConf['eval']) && GeneralUtility::inList($tcaFieldConf['eval'], 'null')) {
1573 $res = array('value' => NULL);
1574 return $res;
1575 }
1576
1577 $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
1578 switch ($tcaFieldConf['type']) {
1579 case 'text':
1580 $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
1581 break;
1582 case 'passthrough':
1583
1584 case 'user':
1585 $res['value'] = $value;
1586 break;
1587 case 'input':
1588 $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
1589 break;
1590 case 'check':
1591 $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP, $field);
1592 break;
1593 case 'radio':
1594 $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
1595 break;
1596 case 'group':
1597
1598 case 'select':
1599 $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1600 break;
1601 case 'inline':
1602 $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, $additionalData);
1603 break;
1604 case 'flex':
1605 // FlexForms are only allowed for real fields.
1606 if ($field) {
1607 $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
1608 }
1609 break;
1610 default:
1611 // Do nothing
1612 }
1613 return $res;
1614 }
1615
1616 /**
1617 * Evaluate "text" type values.
1618 *
1619 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1620 * @param string $value The value to set.
1621 * @param array $tcaFieldConf Field configuration from TCA
1622 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1623 * @param string $field Field name
1624 * @return array Modified $res array
1625 */
1626 public function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
1627 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1628 $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1629 return $res;
1630 }
1631
1632 /**
1633 * Evaluate "input" type values.
1634 *
1635 * @param array $res The result array. The processed value (if any!) is set in the "value" key.
1636 * @param string $value The value to set.
1637 * @param array $tcaFieldConf Field configuration from TCA
1638 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1639 * @param string $field Field name
1640 * @return array Modified $res array
1641 */
1642 public function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
1643 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1644 // Handle native date/time fields
1645 $isDateOrDateTimeField = FALSE;
1646 if (isset($tcaFieldConf['dbType']) && ($tcaFieldConf['dbType'] === 'date' || $tcaFieldConf['dbType'] === 'datetime')) {
1647 $isDateOrDateTimeField = TRUE;
1648 $dateTimeFormats = $this->databaseConnection->getDateTimeFormats($table);
1649 // Convert the date/time into a timestamp for the sake of the checks
1650 $emptyValue = $dateTimeFormats[$tcaFieldConf['dbType']]['empty'];
1651 $format = $dateTimeFormats[$tcaFieldConf['dbType']]['format'];
1652 // At this point in the processing, the timestamps are still based on UTC
1653 $timeZone = new \DateTimeZone('UTC');
1654 $dateTime = \DateTime::createFromFormat('!' . $format, $value, $timeZone);
1655 $value = $value === $emptyValue ? 0 : $dateTime->getTimestamp();
1656 }
1657 // Secures the string-length to be less than max.
1658 if ((int)$tcaFieldConf['max'] > 0) {
1659 $value = $GLOBALS['LANG']->csConvObj->substr($GLOBALS['LANG']->charSet, $value, 0, (int)$tcaFieldConf['max']);
1660 }
1661 // Checking range of value:
1662 if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && (int)$value !== (int)$tcaFieldConf['default']) {
1663 if (isset($tcaFieldConf['range']['upper']) && (int)$value > (int)$tcaFieldConf['range']['upper']) {
1664 $value = $tcaFieldConf['range']['upper'];
1665 }
1666 if (isset($tcaFieldConf['range']['lower']) && (int)$value < (int)$tcaFieldConf['range']['lower']) {
1667 $value = $tcaFieldConf['range']['lower'];
1668 }
1669 }
1670 // Process evaluation settings:
1671 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1672 $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
1673 // Process UNIQUE settings:
1674 // 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...
1675 if ($field && $realPid >= 0) {
1676 if ($res['value'] && in_array('uniqueInPid', $evalCodesArray, TRUE)) {
1677 $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
1678 }
1679 if ($res['value'] && in_array('unique', $evalCodesArray, TRUE)) {
1680 $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
1681 }
1682 }
1683 // Handle native date/time fields
1684 if ($isDateOrDateTimeField) {
1685 // Convert the timestamp back to a date/time
1686 $res['value'] = $res['value'] ? date($format, $res['value']) : $emptyValue;
1687 }
1688 return $res;
1689 }
1690
1691 /**
1692 * Evaluates 'check' type values.
1693 *
1694 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1695 * @param string $value The value to set.
1696 * @param array $tcaFieldConf Field configuration from TCA
1697 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1698 * @param string $field Field name
1699 * @return array Modified $res array
1700 */
1701 public function checkValue_check($res, $value, $tcaFieldConf, $PP, $field = '') {
1702 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1703 $itemC = count($tcaFieldConf['items']);
1704 if (!$itemC) {
1705 $itemC = 1;
1706 }
1707 $maxV = pow(2, $itemC) - 1;
1708 if ($value < 0) {
1709 $value = 0;
1710 }
1711 if ($value > $maxV) {
1712 $value = $maxV;
1713 }
1714 if ($field && $realPid >= 0 && $value > 0 && !empty($tcaFieldConf['eval'])) {
1715 $evalCodesArray = GeneralUtility::trimExplode(',', $tcaFieldConf['eval'], TRUE);
1716 $otherRecordsWithSameValue = array();
1717 $maxCheckedRecords = 0;
1718 if (in_array('maximumRecordsCheckedInPid', $evalCodesArray, TRUE)) {
1719 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value, $realPid);
1720 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsCheckedInPid'];
1721 }
1722 if (in_array('maximumRecordsChecked', $evalCodesArray, TRUE)) {
1723 $otherRecordsWithSameValue = $this->getRecordsWithSameValue($table, $id, $field, $value);
1724 $maxCheckedRecords = (int)$tcaFieldConf['validation']['maximumRecordsChecked'];
1725 }
1726
1727 // there are more than enough records with value "1" in the DB
1728 // if so, set this value to "0" again
1729 if ($maxCheckedRecords && count($otherRecordsWithSameValue) >= $maxCheckedRecords) {
1730 $value = 0;
1731 $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));
1732 }
1733 }
1734 $res['value'] = $value;
1735 return $res;
1736 }
1737
1738 /**
1739 * Evaluates 'radio' type values.
1740 *
1741 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1742 * @param string $value The value to set.
1743 * @param array $tcaFieldConf Field configuration from TCA
1744 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1745 * @return array Modified $res array
1746 */
1747 public function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
1748 if (is_array($tcaFieldConf['items'])) {
1749 foreach ($tcaFieldConf['items'] as $set) {
1750 if ((string)$set[1] === (string)$value) {
1751 $res['value'] = $value;
1752 break;
1753 }
1754 }
1755 }
1756 return $res;
1757 }
1758
1759 /**
1760 * Evaluates 'group' or 'select' type values.
1761 *
1762 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
1763 * @param string $value The value to set.
1764 * @param array $tcaFieldConf Field configuration from TCA
1765 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1766 * @param array $uploadedFiles
1767 * @param string $field Field name
1768 * @return array Modified $res array
1769 */
1770 public function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
1771 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
1772 // Detecting if value sent is an array and if so, implode it around a comma:
1773 if (is_array($value)) {
1774 $value = implode(',', $value);
1775 }
1776 // 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.
1777 // Anyway, this should NOT disturb anything else:
1778 $value = $this->convNumEntityToByteValue($value);
1779 // When values are sent as group or select they come as comma-separated values which are exploded by this function:
1780 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1781 // If multiple is not set, remove duplicates:
1782 if (!$tcaFieldConf['multiple']) {
1783 $valueArray = array_unique($valueArray);
1784 }
1785 // If an exclusive key is found, discard all others:
1786 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
1787 $exclusiveKeys = GeneralUtility::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
1788 foreach ($valueArray as $index => $key) {
1789 if (in_array($key, $exclusiveKeys, TRUE)) {
1790 $valueArray = array($index => $key);
1791 break;
1792 }
1793 }
1794 }
1795 // 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?)
1796 // 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!!
1797 $valueArray = $this->applyFiltersToValues($tcaFieldConf, $valueArray);
1798 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1799 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
1800 $preCount = count($valueArray);
1801 foreach ($valueArray as $index => $key) {
1802 if (!$this->BE_USER->checkAuthMode($table, $field, $key, $tcaFieldConf['authMode'])) {
1803 unset($valueArray[$index]);
1804 }
1805 }
1806 // 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.
1807 if ($preCount && !count($valueArray)) {
1808 return array();
1809 }
1810 }
1811 // For group types:
1812 if ($tcaFieldConf['type'] == 'group') {
1813 switch ($tcaFieldConf['internal_type']) {
1814 case 'file_reference':
1815
1816 case 'file':
1817 $valueArray = $this->checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFiles, $status, $table, $id, $recFID);
1818 break;
1819 case 'db':
1820 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
1821 break;
1822 }
1823 }
1824 // For select types which has a foreign table attached:
1825 if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
1826 // check, if there is a NEW... id in the value, that should be substituted later
1827 if (strpos($value, 'NEW') !== FALSE) {
1828 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
1829 $this->addNewValuesToRemapStackChildIds($valueArray);
1830 $this->remapStack[] = array(
1831 'func' => 'checkValue_group_select_processDBdata',
1832 'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
1833 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
1834 'field' => $field
1835 );
1836 $unsetResult = TRUE;
1837 } else {
1838 $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
1839 }
1840 }
1841 if (!$unsetResult) {
1842 $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
1843 $res['value'] = implode(',', $newVal);
1844 } else {
1845 unset($res['value']);
1846 }
1847 return $res;
1848 }
1849
1850 /**
1851 * Applies the filter methods from a column's TCA configuration to a value array.
1852 *
1853 * @param array $tcaFieldConfiguration
1854 * @param array $values
1855 * @return array|mixed
1856 * @throws \RuntimeException
1857 */
1858 protected function applyFiltersToValues(array $tcaFieldConfiguration, array $values) {
1859 if (empty($tcaFieldConfiguration['filter']) || !is_array($tcaFieldConfiguration['filter'])) {
1860 return $values;
1861 }
1862 foreach ($tcaFieldConfiguration['filter'] as $filter) {
1863 if (empty($filter['userFunc'])) {
1864 continue;
1865 }
1866 $parameters = $filter['parameters'] ?: array();
1867 $parameters['values'] = $values;
1868 $parameters['tcaFieldConfig'] = $tcaFieldConfiguration;
1869 $values = GeneralUtility::callUserFunction($filter['userFunc'], $parameters, $this);
1870 if (!is_array($values)) {
1871 throw new \RuntimeException('Failed calling filter userFunc.', 1336051942);
1872 }
1873 }
1874 return $values;
1875 }
1876
1877 /**
1878 * Handling files for group/select function
1879 *
1880 * @param array $valueArray Array of incoming file references. Keys are numeric, values are files (basically, this is the exploded list of incoming files)
1881 * @param array $tcaFieldConf Configuration array from TCA of the field
1882 * @param string $curValue Current value of the field
1883 * @param array $uploadedFileArray Array of uploaded files, if any
1884 * @param string $status Status ("update" or ?)
1885 * @param string $table tablename of record
1886 * @param int $id UID of record
1887 * @param string $recFID Field identifier ([table:uid:field:....more for flexforms?]
1888 * @return array Modified value array
1889 * @see checkValue_group_select()
1890 */
1891 public function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
1892 // If file handling should NOT be bypassed, do processing:
1893 if (!$this->bypassFileHandling) {
1894 // If any files are uploaded, add them to value array
1895 // Numeric index means that there are multiple files
1896 if (isset($uploadedFileArray[0])) {
1897 $uploadedFiles = $uploadedFileArray;
1898 } else {
1899 // There is only one file
1900 $uploadedFiles = array($uploadedFileArray);
1901 }
1902 foreach ($uploadedFiles as $uploadedFileArray) {
1903 if (!empty($uploadedFileArray['name']) && $uploadedFileArray['tmp_name'] !== 'none') {
1904 $valueArray[] = $uploadedFileArray['tmp_name'];
1905 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1906 }
1907 }
1908 // Creating fileFunc object.
1909 if (!$this->fileFunc) {
1910 $this->fileFunc = GeneralUtility::makeInstance(BasicFileUtility::class);
1911 $this->include_filefunctions = 1;
1912 }
1913 // Setting permitted extensions.
1914 $all_files = array();
1915 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1916 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?: '*';
1917 $all_files['ftpspace'] = $all_files['webspace'];
1918 $this->fileFunc->init('', $all_files);
1919 }
1920 // If there is an upload folder defined:
1921 if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
1922 // If filehandling should NOT be bypassed, do processing:
1923 if (!$this->bypassFileHandling) {
1924 // For logging..
1925 $propArr = $this->getRecordProperties($table, $id);
1926 // Get destrination path:
1927 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1928 // If we are updating:
1929 if ($status == 'update') {
1930 // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
1931 // 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!
1932 // 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_.
1933 // 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.
1934 // Illustration of the problem comes here:
1935 // 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.
1936 // 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.
1937 // 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.
1938 // 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.
1939 if ($this->autoVersioningUpdate === TRUE) {
1940 foreach ($valueArray as $key => $theFile) {
1941 // If it is an already attached file...
1942 if ($theFile === basename($theFile)) {
1943 $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
1944 }
1945 }
1946 }
1947 // Finding the CURRENT files listed, either from MM or from the current record.
1948 $theFileValues = array();
1949 // If MM relations for the files also!
1950 if ($tcaFieldConf['MM']) {
1951 $dbAnalysis = $this->createRelationHandlerInstance();
1952 /** @var $dbAnalysis RelationHandler */
1953 $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
1954 foreach ($dbAnalysis->itemArray as $item) {
1955 if ($item['id']) {
1956 $theFileValues[] = $item['id'];
1957 }
1958 }
1959 } else {
1960 $theFileValues = GeneralUtility::trimExplode(',', $curValue, TRUE);
1961 }
1962 $currentFilesForHistory = implode(',', $theFileValues);
1963 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1964 if (count($theFileValues)) {
1965 // 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!)
1966 foreach ($valueArray as $key => $theFile) {
1967 if ($theFile && !strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
1968 $theFileValues = ArrayUtility::removeArrayEntryByValue($theFileValues, $theFile);
1969 }
1970 }
1971 // This array contains the filenames in the uploadfolder that should be deleted:
1972 foreach ($theFileValues as $key => $theFile) {
1973 $theFile = trim($theFile);
1974 if (@is_file(($dest . '/' . $theFile))) {
1975 $this->removeFilesStore[] = $dest . '/' . $theFile;
1976 } elseif ($theFile) {
1977 $this->log($table, $id, 5, 0, 1, 'Could not delete file \'%s\' (does not exist). (%s)', 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
1978 }
1979 }
1980 }
1981 }
1982 // Traverse the submitted values:
1983 foreach ($valueArray as $key => $theFile) {
1984 // Init:
1985 $maxSize = (int)$tcaFieldConf['max_size'];
1986 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
1987 $theDestFile = '';
1988 // a FAL file was added, now resolve the file object and get the absolute path
1989 // @todo in future versions this needs to be modified to handle FAL objects natively
1990 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
1991 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
1992 $theFile = $fileObject->getForLocalProcessing(FALSE);
1993 }
1994 // NEW FILES? If the value contains '/' it indicates, that the file
1995 // is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1996 if (strstr(GeneralUtility::fixWindowsFilePath($theFile), '/')) {
1997 // Check various things before copying file:
1998 // File and destination must exist
1999 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) {
2000 // Finding size.
2001 if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
2002 $fileSize = $uploadedFileArray['size'];
2003 } else {
2004 $fileSize = filesize($theFile);
2005 }
2006 // Check file size:
2007 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2008 // Prepare filename:
2009 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2010 $fI = GeneralUtility::split_fileref($theEndFileName);
2011 // Check for allowed extension:
2012 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2013 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
2014 // If we have a unique destination filename, then write the file:
2015 if ($theDestFile) {
2016 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2017 // Hook for post-processing the upload action
2018 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
2019 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
2020 $hookObject = GeneralUtility::getUserObj($classRef);
2021 if (!$hookObject instanceof DataHandlerProcessUploadHookInterface) {
2022 throw new \UnexpectedValueException('$hookObject must implement interface TYPO3\\CMS\\Core\\DataHandling\\DataHandlerProcessUploadHookInterface', 1279962349);
2023 }
2024 $hookObject->processUpload_postProcessAction($theDestFile, $this);
2025 }
2026 }
2027 $this->copiedFileMap[$theFile] = $theDestFile;
2028 clearstatcache();
2029 if (!@is_file($theDestFile)) {
2030 $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']);
2031 }
2032 } else {
2033 $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']);
2034 }
2035 } else {
2036 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2037 }
2038 } else {
2039 $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']);
2040 }
2041 } else {
2042 $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']);
2043 }
2044 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2045 if (@is_file($theDestFile)) {
2046 $info = GeneralUtility::split_fileref($theDestFile);
2047 // The value is set to the new filename
2048 $valueArray[$key] = $info['file'];
2049 } else {
2050 // The value is set to the new filename
2051 unset($valueArray[$key]);
2052 }
2053 }
2054 }
2055 }
2056 // 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!
2057 if ($tcaFieldConf['MM']) {
2058 /** @var $dbAnalysis RelationHandler */
2059 $dbAnalysis = $this->createRelationHandlerInstance();
2060 // Dummy
2061 $dbAnalysis->tableArray['files'] = array();
2062 foreach ($valueArray as $key => $theFile) {
2063 // Explode files
2064 $dbAnalysis->itemArray[]['id'] = $theFile;
2065 }
2066 if ($status == 'update') {
2067 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
2068 $newFiles = implode(',', $dbAnalysis->getValueArray());
2069 list(, , $recFieldName) = explode(':', $recFID);
2070 if ($currentFilesForHistory != $newFiles) {
2071 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
2072 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
2073 } else {
2074 $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
2075 $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
2076 }
2077 } else {
2078 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);
2079 }
2080 $valueArray = $dbAnalysis->countItems();
2081 }
2082 } else {
2083 if (count($valueArray)) {
2084 // If filehandling should NOT be bypassed, do processing:
2085 if (!$this->bypassFileHandling) {
2086 // For logging..
2087 $propArr = $this->getRecordProperties($table, $id);
2088 foreach ($valueArray as &$theFile) {
2089 // FAL handling: it's a UID, thus it is resolved to the absolute path
2090 if (!empty($theFile) && MathUtility::canBeInterpretedAsInteger($theFile)) {
2091 $fileObject = ResourceFactory::getInstance()->getFileObject($theFile);
2092 $theFile = $fileObject->getForLocalProcessing(FALSE);
2093 }
2094 if ($this->alternativeFilePath[$theFile]) {
2095 // If alternative File Path is set for the file, then it was an import
2096 // don't import the file if it already exists
2097 if (@is_file((PATH_site . $this->alternativeFilePath[$theFile]))) {
2098 $theFile = PATH_site . $this->alternativeFilePath[$theFile];
2099 } elseif (@is_file($theFile)) {
2100 $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
2101 if (!@is_dir($dest)) {
2102 GeneralUtility::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
2103 }
2104 // Init:
2105 $maxSize = (int)$tcaFieldConf['max_size'];
2106 // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
2107 $theDestFile = '';
2108 $fileSize = filesize($theFile);
2109 // Check file size:
2110 if (!$maxSize || $fileSize <= $maxSize * 1024) {
2111 // Prepare filename:
2112 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
2113 $fI = GeneralUtility::split_fileref($theEndFileName);
2114 // Check for allowed extension:
2115 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
2116 $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
2117 // Write the file:
2118 if ($theDestFile) {
2119 GeneralUtility::upload_copy_move($theFile, $theDestFile);
2120 $this->copiedFileMap[$theFile] = $theDestFile;
2121 clearstatcache();
2122 if (!@is_file($theDestFile)) {
2123 $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']);
2124 }
2125 } else {
2126 $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']);
2127 }
2128 } else {
2129 $this->log($table, $id, 5, 0, 1, 'File extension \'%s\' not allowed. (%s)', 12, array($fI['fileext'], $recFID), $propArr['event_pid']);
2130 }
2131 } else {
2132 $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']);
2133 }
2134 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
2135 if (@is_file($theDestFile)) {
2136 // The value is set to the new filename
2137 $theFile = $theDestFile;
2138 } else {
2139 // The value is set to the new filename
2140 unset($theFile);
2141 }
2142 }
2143 }
2144 $theFile = GeneralUtility::fixWindowsFilePath($theFile);
2145 if (GeneralUtility::isFirstPartOfStr($theFile, PATH_site)) {
2146 $theFile = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($theFile);
2147 }
2148 }
2149 unset($theFile);
2150 }
2151 }
2152 }
2153 return $valueArray;
2154 }
2155
2156 /**
2157 * Evaluates 'flex' type values.
2158 *
2159 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2160 * @param string $value The value to set.
2161 * @param array $tcaFieldConf Field configuration from TCA
2162 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2163 * @param array $uploadedFiles Uploaded files for the field
2164 * @param string $field Field name
2165 * @return array Modified $res array
2166 */
2167 public function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
2168 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2169
2170 if (is_array($value)) {
2171 // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
2172 // 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
2173 // 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.
2174 // Only active when larger than zero.
2175 $newRecordPidValue = $status == 'new' ? $realPid : 0;
2176 // Get current value array:
2177 $dataStructArray = BackendUtility::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, $field, TRUE, $newRecordPidValue);
2178 $currentValueArray = (string)$curValue !== '' ? GeneralUtility::xml2array($curValue) : array();
2179 if (!is_array($currentValueArray)) {
2180 $currentValueArray = array();
2181 }
2182 if (is_array($currentValueArray['meta']['currentLangId'])) {
2183 unset($currentValueArray['meta']['currentLangId']);
2184 }
2185 // Remove all old meta for languages...
2186 // Evaluation of input values:
2187 $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
2188 // Create XML from input value:
2189 $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
2190
2191 // 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
2192 // (provided that the current value was already stored IN the charset that the new value is converted to).
2193 $arrValue = GeneralUtility::xml2array($xmlValue);
2194
2195 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'])) {
2196 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkFlexFormValue'] as $classRef) {
2197 $hookObject = GeneralUtility::getUserObj($classRef);
2198 if (method_exists($hookObject, 'checkFlexFormValue_beforeMerge')) {
2199 $hookObject->checkFlexFormValue_beforeMerge($this, $currentValueArray, $arrValue);
2200 }
2201 }
2202 }
2203
2204 ArrayUtility::mergeRecursiveWithOverrule($currentValueArray, $arrValue);
2205 $xmlValue = $this->checkValue_flexArray2Xml($currentValueArray, TRUE);
2206
2207 // Action commands (sorting order and removals of elements) for flexform sections,
2208 // see FormEngine for the use of this GP parameter
2209 $actionCMDs = GeneralUtility::_GP('_ACTION_FLEX_FORMdata');
2210 if (is_array($actionCMDs[$table][$id][$field]['data'])) {
2211 $arrValue = GeneralUtility::xml2array($xmlValue);
2212 $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
2213 $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
2214 }
2215 // Create the value XML:
2216 $res['value'] = '';
2217 $res['value'] .= $xmlValue;
2218 } else {
2219 // Passthrough...:
2220 $res['value'] = $value;
2221 }
2222
2223 return $res;
2224 }
2225
2226 /**
2227 * Converts an array to FlexForm XML
2228 *
2229 * @param array $array Array with FlexForm data
2230 * @param bool $addPrologue If set, the XML prologue is returned as well.
2231 * @return string Input array converted to XML
2232 */
2233 public function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
2234 /** @var $flexObj FlexFormTools */
2235 $flexObj = GeneralUtility::makeInstance(FlexFormTools::class);
2236 return $flexObj->flexArray2Xml($array, $addPrologue);
2237 }
2238
2239 /**
2240 * Actions for flex form element (move, delete)
2241 * allows to remove and move flexform sections
2242 *
2243 * @param array $valueArray by reference
2244 * @param array $actionCMDs
2245 */
2246 protected function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
2247 if (is_array($valueArray) && is_array($actionCMDs)) {
2248 foreach ($actionCMDs as $key => $value) {
2249 if ($key == '_ACTION') {
2250 // First, check if there are "commands":
2251 if (current($actionCMDs[$key]) !== '') {
2252 asort($actionCMDs[$key]);
2253 $newValueArray = array();
2254 foreach ($actionCMDs[$key] as $idx => $order) {
2255 if (substr($idx, 0, 3) == 'ID-') {
2256 $idx = $this->newIndexMap[$idx];
2257 }
2258 // 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.
2259 if ($order != 'DELETE') {
2260 $newValueArray[$idx] = $valueArray[$idx];
2261 }
2262 unset($valueArray[$idx]);
2263 }
2264 $valueArray = $valueArray + $newValueArray;
2265 }
2266 } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
2267 $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
2268 }
2269 }
2270 }
2271 }
2272
2273 /**
2274 * Evaluates 'inline' type values.
2275 * (partly copied from the select_group function on this issue)
2276 *
2277 * @param array $res The result array. The processed value (if any!) is set in the 'value' key.
2278 * @param string $value The value to set.
2279 * @param array $tcaFieldConf Field configuration from TCA
2280 * @param array $PP Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
2281 * @param string $field Field name
2282 * @param array $additionalData Additional data to be forwarded to sub-processors
2283 * @return array Modified $res array
2284 */
2285 public function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field, array $additionalData = NULL) {
2286 list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
2287 if (!$tcaFieldConf['foreign_table']) {
2288 // Fatal error, inline fields should always have a foreign_table defined
2289 return FALSE;
2290 }
2291 // When values are sent they come as comma-separated values which are exploded by this function:
2292 $valueArray = GeneralUtility::trimExplode(',', $value);
2293 // Remove duplicates: (should not be needed)
2294 $valueArray = array_unique($valueArray);
2295 // Example for received data:
2296 // $value = 45,NEW4555fdf59d154,12,123
2297 // We need to decide whether we use the stack or can save the relation directly.
2298 if (strpos($value, 'NEW') !== FALSE || !MathUtility::canBeInterpretedAsInteger($id)) {
2299 $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
2300 $this->addNewValuesToRemapStackChildIds($valueArray);
2301 $this->remapStack[] = array(
2302 'func' => 'checkValue_inline_processDBdata',
2303 'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData),
2304 'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
2305 'additionalData' => $additionalData,
2306 'field' => $field,
2307 );
2308 unset($res['value']);
2309 } elseif ($value || MathUtility::canBeInterpretedAsInteger($id)) {
2310 $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field, $additionalData);
2311 }
2312 return $res;
2313 }
2314
2315 /**
2316 * Checks if a fields has more items than defined via TCA in maxitems.
2317 * If there are more items than allowd, the item list is truncated to the defined number.
2318 *
2319 * @param array $tcaFieldConf Field configuration from TCA
2320 * @param array $valueArray Current value array of items
2321 * @return array The truncated value array of items
2322 */
2323 public function checkValue_checkMax($tcaFieldConf, $valueArray) {
2324 // 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...
2325 $valueArrayC = count($valueArray);
2326 // 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.
2327 $maxI = isset($tcaFieldConf['maxitems']) ? (int)$tcaFieldConf['maxitems'] : 1;
2328 if ($valueArrayC > $maxI) {
2329 $valueArrayC = $maxI;
2330 }
2331 // Checking for not too many elements
2332 // Dumping array to list
2333 $newVal = array();
2334 foreach ($valueArray as $nextVal) {
2335 if ($valueArrayC == 0) {
2336 break;
2337 }
2338 $valueArrayC--;
2339 $newVal[] = $nextVal;
2340 }
2341 return $newVal;
2342 }
2343
2344 /*********************************************
2345 *
2346 * Helper functions for evaluation functions.
2347 *
2348 ********************************************/
2349 /**
2350 * Gets a unique value for $table/$id/$field based on $value
2351 *
2352 * @param string $table Table name
2353 * @param string $field Field name for which $value must be unique
2354 * @param string $value Value string.
2355 * @param int $id UID to filter out in the lookup (the record itself...)
2356 * @param int $newPid If set, the value will be unique for this PID
2357 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
2358 */
2359 public function getUnique($table, $field, $value, $id, $newPid = 0) {
2360 // Initialize:
2361 $whereAdd = '';
2362 $newValue = '';
2363 if ((int)$newPid) {
2364 $whereAdd .= ' AND pid=' . (int)$newPid;
2365 } else {
2366 $whereAdd .= ' AND pid>=0';
2367 }
2368 // "AND pid>=0" for versioning
2369 $whereAdd .= $this->deleteClause($table);
2370 // If the field is configured in TCA, proceed:
2371 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
2372 // Look for a record which might already have the value:
2373 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($value, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2374 $counter = 0;
2375 // For as long as records with the test-value existing, try again (with incremented numbers appended).
2376 while ($this->databaseConnection->sql_num_rows($res)) {
2377 $newValue = $value . $counter;
2378 $res = $this->databaseConnection->exec_SELECTquery('uid', $table, $field . '=' . $this->databaseConnection->fullQuoteStr($newValue, $table) . ' AND uid<>' . (int)$id . $whereAdd);
2379 $counter++;
2380 if ($counter > 100) {
2381 break;
2382 }
2383 }
2384 $this->databaseConnection->sql_free_result($res);
2385 // If the new value is there:
2386 $value = $newValue !== '' ? $newValue : $value;
2387 }
2388 return $value;
2389 }
2390
2391 /**
2392 * gets all records that have the same value in a field
2393 * excluding the given uid
2394 *
2395 * @param string $tableName Table name
2396 * @param int $uid UID to filter out in the lookup (the record itself...)
2397 * @param string $fieldName Field name for which $value must be unique
2398 * @param string $value Value string.
2399 * @param int $pageId If set, the value will be unique for this PID
2400 * @return array
2401 */
2402 public function getRecordsWithSameValue($tableName, $uid, $fieldName, $value, $pageId = 0) {
2403 $result = array();
2404 if (!empty($GLOBALS['TCA'][$tableName]['columns'][$fieldName])) {
2405
2406 $uid = (int)$uid;
2407 $pageId = (int)$pageId;
2408 $whereStatement = ' AND uid <> ' . $uid . ' AND ' . ($pageId ? 'pid = ' . $pageId : 'pid >= 0');
2409 $result = BackendUtility::getRecordsByField($tableName, $fieldName, $value, $whereStatement);
2410 }
2411 return $result;
2412 }
2413
2414 /**
2415 * @param string $value The field value to be evaluated
2416 * @param array $evalArray Array of evaluations to traverse.
2417 * @param string $is_in The "is_in" value of the field configuration from TCA
2418 * @return array
2419 */
2420 public function checkValue_text_Eval($value, $evalArray, $is_in) {
2421 $res = array();
2422 $set = TRUE;
2423 foreach ($evalArray as $func) {
2424 switch ($func) {
2425 case 'trim':
2426 $value = trim($value);
2427 break;
2428 case 'required':
2429 if (!$value) {
2430 $set = FALSE;
2431 }
2432 break;
2433 default:
2434 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2435 break;
2436 }
2437 $evalObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2438 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2439 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2440 }
2441 }
2442 }
2443 if ($set) {
2444 $res['value'] = $value;
2445 }
2446 return $res;
2447 }
2448
2449 /**
2450 * Evaluation of 'input'-type values based on 'eval' list
2451 *
2452 * @param string $value Value to evaluate
2453 * @param array $evalArray Array of evaluations to traverse.
2454 * @param string $is_in Is-in string for 'is_in' evaluation
2455 * @return array Modified $value in key 'value' or empty array
2456 */
2457 public function checkValue_input_Eval($value, $evalArray, $is_in) {
2458 $res = array();
2459 $set = TRUE;
2460 foreach ($evalArray as $func) {
2461 switch ($func) {
2462 case 'int':
2463 case 'year':
2464 case 'time':
2465 case 'timesec':
2466 $value = (int)$value;
2467 break;
2468 case 'date':
2469 case 'datetime':
2470 $value = (int)$value;
2471 if ($value > 0 && !$this->dontProcessTransformations) {
2472 $value -= date('Z', $value);
2473 }
2474 break;
2475 case 'double2':
2476 $value = preg_replace('/[^0-9,\\.-]/', '', $value);
2477 $negative = $value[0] === '-';
2478 $value = strtr($value, array(',' => '.', '-' => ''));
2479 if (strpos($value, '.') === FALSE) {
2480 $value .= '.0';
2481 }
2482 $valueArray = explode('.', $value);
2483 $dec = array_pop($valueArray);
2484 $value = join('', $valueArray) . '.' . $dec;
2485 if ($negative) {
2486 $value *= -1;
2487 }
2488 $value = number_format($value, 2, '.', '');
2489 break;
2490 case 'md5':
2491 if (strlen($value) != 32) {
2492 $set = FALSE;
2493 }
2494 break;
2495 case 'trim':
2496 $value = trim($value);
2497 break;
2498 case 'upper':
2499 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toUpper');
2500 break;
2501 case 'lower':
2502 $value = $GLOBALS['LANG']->csConvObj->conv_case($GLOBALS['LANG']->charSet, $value, 'toLower');
2503 break;
2504 case 'required':
2505 if (!isset($value) || $value === '') {
2506 $set = FALSE;
2507 }
2508 break;
2509 case 'is_in':
2510 $c = strlen($value);
2511 if ($c) {
2512 $newVal = '';
2513 for ($a = 0; $a < $c; $a++) {
2514 $char = substr($value, $a, 1);
2515 if (strpos($is_in, $char) !== FALSE) {
2516 $newVal .= $char;
2517 }
2518 }
2519 $value = $newVal;
2520 }
2521 break;
2522 case 'nospace':
2523 $value = str_replace(' ', '', $value);
2524 break;
2525 case 'alpha':
2526 $value = preg_replace('/[^a-zA-Z]/', '', $value);
2527 break;
2528 case 'num':
2529 $value = preg_replace('/[^0-9]/', '', $value);
2530 break;
2531 case 'alphanum':
2532 $value = preg_replace('/[^a-zA-Z0-9]/', '', $value);
2533 break;
2534 case 'alphanum_x':
2535 $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value);
2536 break;
2537 case 'domainname':
2538 if (!preg_match('/^[a-z0-9.\\-]*$/i', $value)) {
2539 $value = GeneralUtility::idnaEncode($value);
2540 }
2541 break;
2542 case 'email':
2543 $this->checkValue_input_ValidateEmail($value, $set);
2544 break;
2545 default:
2546 if (empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func])) {
2547 break;
2548 }
2549 $evalObj = GeneralUtility::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func] . ':&' . $func);
2550 if (is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue')) {
2551 $value = $evalObj->evaluateFieldValue($value, $is_in, $set);
2552 }
2553 }
2554 }
2555 if ($set) {
2556 $res['value'] = $value;
2557 }
2558 return $res;
2559 }
2560
2561 /**
2562 * If $value is not a valid e-mail address,
2563 * $set will be set to false and a flash error
2564 * message will be added
2565 *
2566 * @param string $value Value to evaluate
2567 * @param bool $set TRUE if an update should be done
2568 * @throws \InvalidArgumentException
2569 * @throws \TYPO3\CMS\Core\Exception
2570 * @return void
2571 */
2572 protected function checkValue_input_ValidateEmail($value, &$set) {
2573 if (GeneralUtility::validEmail($value)) {
2574 return;
2575 }
2576
2577 $set = FALSE;
2578 /** @var FlashMessage $message */
2579 $message = GeneralUtility::makeInstance(FlashMessage::class,
2580 sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:error.invalidEmail'), $value),
2581 '', // header is optional
2582 FlashMessage::ERROR,
2583 TRUE // whether message should be stored in session
2584 );
2585 /** @var $flashMessageService FlashMessageService */
2586 $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
2587 $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
2588 }
2589
2590 /**
2591 * Returns data for group/db and select fields
2592 *
2593 * @param array $valueArray Current value array
2594 * @param array $tcaFieldConf TCA field config
2595 * @param int $id Record id, used for look-up of MM relations (local_uid)
2596 * @param string $status Status string ('update' or 'new')
2597 * @param string $type The type, either 'select', 'group' or 'inline'
2598 * @param string $currentTable Table name, needs to be passed to \TYPO3\CMS\Core\Database\RelationHandler
2599 * @param string $currentField field name, needs to be set for writing to sys_history
2600 * @return array Modified value array
2601 */
2602 public function checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, $type, $currentTable, $currentField) {
2603 $tables = $type == 'group' ? $tcaFieldConf['allowed'] : $tcaFieldConf['foreign_table'] . ',' . $tcaFieldConf['neg_foreign_table'];
2604 $prep = $type == 'group' ? $tcaFieldConf['prepend_tname'] : $tcaFieldConf['neg_foreign_table'];
2605 $newRelations = implode(',', $valueArray);
2606 /** @var $dbAnalysis RelationHandler */
2607 $dbAnalysis = $this->createRelationHandlerInstance();
2608 $dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2609 $dbAnalysis->start($newRelations, $tables, '', 0, $currentTable, $tcaFieldConf);
2610 if ($tcaFieldConf['MM']) {
2611 if ($status == 'update') {
2612 /** @var $oldRelations_dbAnalysis RelationHandler */
2613 $oldRelations_dbAnalysis = $this->createRelationHandlerInstance();
2614 $oldRelations_dbAnalysis->registerNonTableValues = $tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2615 // Db analysis with $id will initialize with the existing relations
2616 $oldRelations_dbAnalysis->start('', $tables, $tcaFieldConf['MM'], $id, $currentTable, $tcaFieldConf);
2617 $oldRelations = implode(',', $oldRelations_dbAnalysis->getValueArray());
2618 $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, $prep);
2619 if ($oldRelations != $newRelations) {
2620 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = $oldRelations;
2621 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = $newRelations;
2622 } else {
2623 $this->mmHistoryRecords[$currentTable . ':' . $id]['oldRecord'][$currentField] = '';
2624 $this->mmHistoryRecords[$currentTable . ':' . $id]['newRecord'][$currentField] = '';
2625 }
2626 } else {
2627 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, $prep, $currentTable);
2628 }
2629 $valueArray = $dbAnalysis->countItems();
2630 } else {
2631 $valueArray = $dbAnalysis->getValueArray($prep);
2632 if ($type == 'select' && $prep) {
2633 $valueArray = $dbAnalysis->convertPosNeg($valueArray, $tcaFieldConf['foreign_table'], $tcaFieldConf['neg_foreign_table']);
2634 }
2635 }
2636 // 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.
2637 return $valueArray;
2638 }
2639
2640 /**
2641 * Explodes the $value, which is a list of files/uids (group select)
2642 *
2643 * @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.
2644 * @return array The value array.
2645 */
2646 public function checkValue_group_select_explodeSelectGroupValue($value) {
2647 $valueArray = GeneralUtility::trimExplode(',', $value, TRUE);
2648 foreach ($valueArray as &$newVal) {
2649 $temp = explode('|', $newVal, 2);
2650 $newVal = str_replace(',', '', str_replace('|', '', rawurldecode($temp[0])));
2651 }
2652 unset($newVal);
2653 return $valueArray;
2654 }
2655
2656 /**
2657 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2658 * See checkValue_flex_procInData_travDS() for more details.
2659 * 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
2660 *
2661 * @param array $dataPart The 'data' part of the INPUT flexform data
2662 * @param array $dataPart_current The 'data' part of the CURRENT flexform data
2663 * @param array $uploadedFiles The uploaded files for the 'data' part of the INPUT flexform data
2664 * @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.
2665 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions
2666 * @param string $callBackFunc Optional call back function, see checkValue_flex_procInData_travDS() DEPRECATED, use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools instead for traversal!
2667 * @return array The modified 'data' part.
2668 * @see checkValue_flex_procInData_travDS()
2669 */
2670 public function checkValue_flex_procInData($dataPart, $dataPart_current, $uploadedFiles, $dataStructArray, $pParams, $callBackFunc = '') {
2671 if (is_array($dataPart)) {
2672 foreach ($dataPart as $sKey => $sheetDef) {
2673 list($dataStruct, $actualSheet) = GeneralUtility::resolveSheetDefInDS($dataStructArray, $sKey);
2674 if (is_array($dataStruct) && $actualSheet == $sKey && is_array($sheetDef)) {
2675 foreach ($sheetDef as $lKey => $lData) {
2676 $this->checkValue_flex_procInData_travDS($dataPart[$sKey][$lKey], $dataPart_current[$sKey][$lKey], $uploadedFiles[$sKey][$lKey], $dataStruct['ROOT']['el'], $pParams, $callBackFunc, $sKey . '/' . $lKey . '/');
2677 }
2678 }
2679 }
2680 }
2681 return $dataPart;
2682 }
2683
2684 /**
2685 * Processing of the sheet/language data array
2686 * 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.
2687 *
2688 * @param array $dataValues New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2689 * @param array $dataValues_current Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2690 * @param array $uploadedFiles Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2691 * @param array $DSelements Data structure which fits the data array
2692 * @param array $pParams A set of parameters to pass through for the calling of the evaluation functions / call back function
2693 * @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.
2694 * @param string $structurePath
2695 * @return void
2696 * @see checkValue_flex_procInData()
2697 */
2698 public function checkValue_flex_procInData_travDS(&$dataValues, $dataValues_current, $uploadedFiles, $DSelements, $pParams, $callBackFunc, $structurePath) {
2699 if (is_array($DSelements)) {
2700 // For each DS element:
2701 foreach ($DSelements as $key => $dsConf) {
2702 // Array/Section:
2703 if ($DSelements[$key]['type'] == 'array') {
2704 if (is_array($dataValues[$key]['el'])) {
2705 if ($DSelements[$key]['section']) {
2706 $newIndexCounter = 0;
2707 foreach ($dataValues[$key]['el'] as $ik => $el) {
2708 if (is_array($el)) {
2709 if (!is_array($dataValues_current[$key]['el'])) {
2710 $dataValues_current[$key]['el'] = array();
2711 }
2712 $theKey = key($el);
2713 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2714 $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/');
2715 // 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:
2716 // The fact that the order changes is not important since order is controlled by a separately submitted index.
2717 if (substr($ik, 0, 3) == 'ID-') {
2718 $newIndexCounter++;
2719 // Set mapping index
2720 $this->newIndexMap[$ik] = (is_array($dataValues_current[$key]['el']) && count($dataValues_current[$key]['el']) ? max(array_keys($dataValues_current[$key]['el'])) : 0) + $newIndexCounter;
2721 // Transfer values
2722 $dataValues[$key]['el'][$this->newIndexMap[$ik]] = $dataValues[$key]['el'][$ik];
2723 // Unset original
2724 unset($dataValues[$key]['el'][$ik]);
2725 }
2726 }
2727 }