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