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