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