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