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