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