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