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