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