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