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