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