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