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