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