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