* Added Karsten D.s patches for DBAL.
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tcemain.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2004 Kasper Skaarhoj (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 * $Id$
31 * Revised for TYPO3 3.6 August/2003 by Kasper Skaarhoj
32 *
33 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
34 */
35 /**
36 * [CLASS/FUNCTION INDEX of SCRIPT]
37 *
38 *
39 *
40 * 199: class t3lib_TCEmain
41 * 285: function start($data,$cmd,$altUserObject='')
42 * 318: function setMirror($mirror)
43 * 343: function setDefaultsFromUserTS($userTS)
44 * 366: function process_uploads($postFiles)
45 * 396: function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
46 *
47 * SECTION: PROCESSING DATA
48 * 432: function process_datamap()
49 * 625: function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
50 * 816: function checkModifyAccessList($table)
51 * 828: function isRecordInWebMount($table,$id)
52 * 842: function isInWebMount($pid)
53 * 859: function checkRecordUpdateAccess($table,$id)
54 * 884: function checkRecordInsertAccess($insertTable,$pid,$action=1)
55 * 920: function isTableAllowedForThisPage($page_uid, $checkTable)
56 * 955: function doesRecordExist($table,$id,$perms)
57 * 1017: function doesRecordExist_pageLookUp($id, $perms)
58 * 1043: function doesBranchExist($inList,$pid,$perms, $recurse)
59 * 1078: function pageInfo($id,$field)
60 * 1098: function recordInfo($table,$id,$fieldList)
61 * 1115: function getRecordProperties($table,$id)
62 * 1127: function getRecordPropertiesFromRow($table,$row)
63 * 1146: function setTSconfigPermissions($fieldArray,$TSConfig_p)
64 * 1162: function newFieldArray($table)
65 * 1193: function overrideFieldArray($table,$data)
66 * 1206: function assemblePermissions($string)
67 *
68 * SECTION: Evaluation of input values
69 * 1256: function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
70 * 1316: function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
71 * 1362: function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
72 * 1400: function checkValue_check($res,$value,$tcaFieldConf,$PP)
73 * 1423: function checkValue_radio($res,$value,$tcaFieldConf,$PP)
74 * 1449: function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
75 * 1549: function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
76 * 1702: function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
77 * 1760: function checkValue_flexArray2Xml($array)
78 * 1777: function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
79 *
80 * SECTION: Helper functions for evaluation functions.
81 * 1825: function getUnique($table,$field,$value,$id,$newPid=0)
82 * 1863: function checkValue_input_Eval($value,$evalArray,$is_in)
83 * 1951: function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)
84 * 1984: function checkValue_group_select_explodeSelectGroupValue($value)
85 * 2007: function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
86 * 2044: function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc='')
87 *
88 * SECTION: Storing data to Database Layer
89 * 2184: function updateDB($table,$id,$fieldArray)
90 * 2230: function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
91 * 2280: function insertDB($table,$id,$fieldArray,$newVersion=FALSE)
92 * 2338: function checkStoredRecord($table,$id,$fieldArray,$action)
93 * 2373: function dbAnalysisStoreExec()
94 * 2389: function removeRegisteredFiles()
95 * 2406: function clear_cache($table,$uid)
96 * 2502: function getPID($table,$uid)
97 *
98 * SECTION: PROCESSING COMMANDS
99 * 2545: function process_cmdmap()
100 * 2633: function moveRecord($table,$uid,$destPid)
101 * 2777: function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
102 * 2885: function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
103 * 2940: function insertNewCopyVersion($table,$fieldArray,$realPid)
104 * 2991: function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf)
105 * 3044: function copyRecord_localize($table,$uid,$language)
106 * 3103: function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
107 * 3131: function copyRecord_procFilesRefs($conf, $uid, $value)
108 * 3182: function copyPages($uid,$destPid)
109 * 3237: function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
110 * 3267: function versionizeRecord($table,$id,$label)
111 * 3319: function versionizePages($uid,$label)
112 * 3376: function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
113 * 3400: function version_swap($table,$id,$swapWith)
114 * 3514: function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
115 * 3535: function compileAdminTables()
116 * 3552: function fixUniqueInPid($table,$uid)
117 * 3588: function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
118 * 3613: function extFileFields ($table)
119 * 3639: function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
120 * 3668: function prependLabel($table)
121 * 3685: function resolvePid($table,$pid)
122 * 3703: function clearPrefixFromValue($table,$value)
123 * 3714: function remapListedDBRecords()
124 * 3797: function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
125 * 3823: function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)
126 * 3868: function extFileFunctions($table,$field,$filelist,$func)
127 * 3900: function deleteRecord($table,$uid, $noRecordCheck)
128 * 3958: function deletePages($uid)
129 * 4000: function deleteSpecificPage($uid)
130 * 4024: function noRecordsFromUnallowedTables($inList)
131 *
132 * SECTION: MISC FUNCTIONS
133 * 4086: function getSortNumber($table,$uid,$pid)
134 * 4151: function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
135 * 4180: function rmComma ($input)
136 * 4190: function convNumEntityToByteValue($input)
137 * 4212: function destPathFromUploadFolder ($folder)
138 * 4223: function destNotInsideSelf ($dest,$id)
139 * 4249: function getExcludeListArray()
140 * 4273: function doesPageHaveUnallowedTables($page_uid,$doktype)
141 * 4306: function deleteClause($table)
142 * 4322: function tableReadOnly($table)
143 * 4334: function tableAdminOnly($table)
144 * 4348: function getInterfacePagePositionID($uid)
145 * 4381: function isReferenceField($conf)
146 * 4391: function getTCEMAIN_TSconfig($tscPID)
147 * 4405: function getTableEntries($table,$TSconfig)
148 * 4419: function setHistory($table,$id,$logId)
149 * 4456: function clearHistory($table,$id,$keepEntries=10,$maxAgeSeconds=604800)
150 * 4504: function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=0,$data=array(),$event_pid=-1,$NEWid='')
151 * 4518: function printLogErrorMessages($redirect)
152 * 4580: function clear_cacheCmd($cacheCmd)
153 * 4640: function removeCacheFiles()
154 *
155 * TOTAL FUNCTIONS: 101
156 * (This index is automatically created/updated by the extension "extdeveval")
157 *
158 */
159
160
161
162
163 // *******************************
164 // Including necessary libraries
165 // *******************************
166 require_once (PATH_t3lib.'class.t3lib_loaddbgroup.php');
167 require_once (PATH_t3lib.'class.t3lib_parsehtml_proc.php');
168 require_once (PATH_t3lib.'class.t3lib_stdgraphic.php');
169 require_once (PATH_t3lib.'class.t3lib_basicfilefunc.php');
170
171
172
173
174
175
176
177
178
179
180
181
182
183 /**
184 * This is the TYPO3 Core Engine class for manipulation of the database
185 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
186 *
187 * Dependencies:
188 * - $GLOBALS['TCA'] must exist
189 * - $GLOBALS['LANG'] (languageobject) may be preferred, but not fatal.
190 *
191 * Note: Seems like many instances of array_merge() in this class are candidates for t3lib_div::array_merge() if integer-keys will some day make trouble...
192 *
193 * tce_db.php for further comments and SYNTAX! Also see document 'Inside TYPO3' for details.
194 *
195 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
196 * @package TYPO3
197 * @subpackage t3lib
198 */
199 class t3lib_TCEmain {
200 var $log_table = 'sys_log';
201
202 var $checkStoredRecords = 1; // 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
203 var $checkStoredRecords_loose=1; // If set, values '' and 0 will equal each other when the stored records are checked.
204 var $sortIntervals = 256; // The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
205
206 var $deleteTree = 0; // 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 delete ONLY if it has no branch
207 var $copyTree = 0; // int. 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
208 var $versionizeTree = 0; // int. If 0 then branch is NOT versionized. If 1 then pages on the 1st level is versionized. If 2 then pages on the second level is versionized ... and so on
209 var $neverHideAtCopy = 0; // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
210 var $reverseOrder=0; // boolean. If set, the dataarray is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
211 var $copyWhichTables = '*'; // 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)
212 var $stripslashes_values=1; // If set, 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!
213 var $storeLogMessages=1; // If set, 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.
214 var $enableLogging=1; // If set, actions are logged.
215
216 var $callBackObj; // Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
217
218 // var $history=1; // Bit-array: Bit0: History on/off. DEPENDS on checkSimilar to be set!
219 var $checkSimilar=1; // Boolean: If set, 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.
220 var $dontProcessTransformations=0; // Boolean: If set, then transformations are NOT performed on the input.
221 # var $disableRTE = 0; // Boolean: If set, the RTE is expected to have been disabled in the interface which submitted information. Thus transformations related to the RTE is not done.
222
223 var $pMap = Array( // Permission mapping
224 'show' => 1, // 1st bit
225 'edit' => 2, // 2nd bit
226 'delete' => 4, // 3rd bit
227 'new' => 8, // 4th bit
228 'editcontent' => 16 // 5th bit
229 );
230 var $defaultPermissions = array( // Can be overridden from $TYPO3_CONF_VARS
231 'user' => 'show,edit,delete,new,editcontent',
232 'group' => 'show,edit,new,editcontent',
233 'everybody' => ''
234 );
235
236
237 var $alternativeFileName=array(); // 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.
238 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.
239 var $defaultValues=array(); // You can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. You must set this externally.
240 var $overrideValues=array(); // 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!
241 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)
242
243 // *********
244 // internal
245 // *********
246 var $fileFunc; // May contain an object
247 var $last_log_id;
248 var $BE_USER; // The user-object the the script uses. If not set from outside, this is set to the current global $BE_USER.
249 var $userid; // will be set to uid of be_user executing this script
250 var $username; // will be set to username of be_user executing this script
251 var $admin; // will be set if user is admin
252 var $exclude_array; // the list of <table>-<fields> that cannot be edited. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
253
254 var $data = Array();
255 var $datamap = Array();
256 var $cmd = Array();
257 var $cmdmap = Array();
258 var $uploadedFileArray = array();
259
260 var $cachedTSconfig = array();
261 var $substNEWwithIDs = Array();
262 var $substNEWwithIDs_table = Array();
263 var $recUpdateAccessCache = Array(); // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
264 var $recInsertAccessCache = Array();
265 var $isRecordInWebMount_Cache=array();
266 var $isInWebMount_Cache=array();
267 var $pageCache = Array(); // Used for caching page records in pageInfo()
268 var $copyMappingArray = Array(); // Use by the copy action to track the ids of new pages so subpages are correctly inserted!
269 var $copyMappingArray_merged = Array(); // This array is the sum of all copying operations in this class
270 var $registerDBList=array();
271 var $dbAnalysisStore=array();
272 var $removeFilesStore=array();
273 var $copiedFileMap=array();
274
275 var $checkValue_currentRecord=array(); // Set to "currentRecord" during checking of values.
276
277
278 /**
279 * Initializing.
280 * For details, see 'TYPO3 Core API' document.
281 * This function does not start the processing of data, but merely initializes the object
282 *
283 * @param array Data to be modified or inserted in the database
284 * @param array Commands to copy, move, delete records.
285 * @param object An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
286 * @return void
287 */
288 function start($data,$cmd,$altUserObject='') {
289 // Initializing BE_USER
290 $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
291 $this->userid = $this->BE_USER->user['uid'];
292 $this->username = $this->BE_USER->user['username'];
293 $this->admin = $this->BE_USER->user['admin'];
294
295 // Initializing default permissions for pages
296 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
297 if (isset($defaultPermissions['user'])) {$this->defaultPermissions['user'] = $defaultPermissions['user'];}
298 if (isset($defaultPermissions['group'])) {$this->defaultPermissions['group'] = $defaultPermissions['group'];}
299 if (isset($defaultPermissions['everybody'])) {$this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];}
300
301 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
302 $this->exclude_array = ($this->admin) ? array() : $this->getExcludeListArray();
303
304 // Setting the data and cmd arrays
305 if (is_array($data)) {
306 reset($data);
307 $this->datamap = $data;
308 }
309 if (is_array($cmd)) {
310 reset($cmd);
311 $this->cmdmap = $cmd;
312 }
313 }
314
315 /**
316 * [Describe function...]
317 *
318 * @param array This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
319 * @return void
320 */
321 function setMirror($mirror) {
322 if (is_array($mirror)) {
323 reset($mirror);
324 while(list($table,$uid_array)=each($mirror)) {
325 if (isset($this->datamap[$table])) {
326 reset($uid_array);
327 while (list($id,$uidList) = each($uid_array)) {
328 if (isset($this->datamap[$table][$id])) {
329 $theIdsInArray = t3lib_div::trimExplode(',',$uidList,1);
330 while(list(,$copyToUid)=each($theIdsInArray)) {
331 $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
332 }
333 }
334 }
335 }
336 }
337 }
338 }
339
340 /**
341 * Initializes default values coming from User TSconfig
342 *
343 * @param array User TSconfig array
344 * @return void
345 */
346 function setDefaultsFromUserTS($userTS) {
347 global $TCA;
348 if (is_array($userTS)) {
349 foreach($userTS as $k => $v) {
350 $k = substr($k,0,-1);
351 if ($k && is_array($v) && isset($TCA[$k])) {
352 if (is_array($this->defaultValues[$k])) {
353 $this->defaultValues[$k] = array_merge($this->defaultValues[$k],$v);
354 } else {
355 $this->defaultValues[$k] = $v;
356 }
357 }
358 }
359 }
360 }
361
362 /**
363 * Processing of uploaded files.
364 * 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.
365 *
366 * @param array $_FILES array
367 * @return void
368 */
369 function process_uploads($postFiles) {
370 if (is_array($postFiles)) {
371 reset($postFiles);
372 $subA = current($postFiles);
373 if (is_array($subA)) {
374 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
375 // Initialize the uploadedFilesArray:
376 $this->uploadedFileArray=array();
377
378 // For each entry:
379 foreach($subA as $key => $values) {
380 $this->process_uploads_traverseArray($this->uploadedFileArray,$values,$key);
381 }
382 } else {
383 $this->uploadedFileArray=$subA;
384 }
385 }
386 }
387 }
388
389 /**
390 * Traverse the upload array if needed to rearrange values.
391 *
392 * @param array $this->uploadedFileArray passed by reference
393 * @param array Input array ($_FILES parts)
394 * @param string The current $_FILES array key to set on the outermost level.
395 * @return void
396 * @access private
397 * @see process_uploads()
398 */
399 function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet) {
400 if (is_array($inputArr)) {
401 foreach($inputArr as $key => $value) {
402 $this->process_uploads_traverseArray($outputArr[$key],$inputArr[$key],$keyToSet);
403 }
404 } else {
405 $outputArr[$keyToSet]=$inputArr;
406 }
407 }
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423 /*********************************************
424 *
425 * PROCESSING DATA
426 *
427 *********************************************/
428
429 /**
430 * Processing the data-array
431 * Call this function to process the data-array set by start()
432 *
433 * @return void
434 */
435 function process_datamap() {
436 global $TCA, $TYPO3_CONF_VARS;
437
438 // First prepare user defined objects (if any) for hooks which extend this function:
439 $hookObjectsArr = array();
440 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
441 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
442 $hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
443 }
444 }
445
446 // Organize tables so that the pages-table are always processed first. This is required if you want to make sure that content pointing to a new page will be created.
447 $orderOfTables = Array();
448 if (isset($this->datamap['pages'])) { // Set pages first.
449 $orderOfTables[]='pages';
450 }
451 reset($this->datamap);
452 while (list($table,) = each($this->datamap)) {
453 if ($table!='pages') {
454 $orderOfTables[]=$table;
455 }
456 }
457
458 // Process the tables...
459 foreach($orderOfTables as $table) {
460 /* Check if
461 - table is set in $TCA,
462 - table is NOT readOnly,
463 - the table is set with content in the data-array (if not, there's nothing to process...)
464 - permissions for tableaccess OK
465 */
466 $modifyAccessList = $this->checkModifyAccessList($table);
467 if (!$modifyAccessList) {
468 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
469 }
470 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList) {
471 if ($this->reverseOrder) {
472 $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
473 }
474
475 // For each record from the table, do:
476 // $id is the record uid, may be a string if new records...
477 // $incomingFieldArray is the array of fields
478 foreach($this->datamap[$table] as $id => $incomingFieldArray) {
479 if (is_array($incomingFieldArray)) {
480
481 // Hook: processDatamap_preProcessIncomingFieldArray
482 foreach($hookObjectsArr as $hookObj) {
483 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
484 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
485 }
486 }
487
488 // ******************************
489 // Checking access to the record
490 // ******************************
491 $recordAccess = 0;
492 $old_pid_value = '';
493 if (!t3lib_div::testInt($id)) { // Is it a new record? (Then Id is a string)
494 $fieldArray = $this->newFieldArray($table); // Get a fieldArray with default values
495 if (isset($incomingFieldArray['pid'])) { // A pid must be set for new records.
496 // $value = the pid
497 $pid_value = $incomingFieldArray['pid'];
498
499 // Checking and finding numerical pid, it may be a string-reference to another value
500 $OK = 1;
501 if (strstr($pid_value,'NEW')) { // If a NEW... id
502 if (substr($pid_value,0,1)=='-') {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
503 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.
504 $old_pid_value = $pid_value;
505 $pid_value=intval($negFlag*$this->substNEWwithIDs[$pid_value]);
506 } else {$OK = 0;} // If not found in the substArray we must stop the proces...
507 }
508 $pid_value = intval($pid_value);
509
510 // The $pid_value is now the numerical pid at this point
511 if ($OK) {
512 $sortRow = $TCA[$table]['ctrl']['sortby'];
513 if ($pid_value>=0) { // Points to a page on which to insert the element, possibly in the top of the page
514 if ($sortRow) { // If this table is sorted we better find the top sorting number
515 $fieldArray[$sortRow] = $this->getSortNumber($table,0,$pid_value);
516 }
517 $fieldArray['pid'] = $pid_value; // The numerical pid is inserted in the data array
518 } else { // points to another record before ifself
519 if ($sortRow) { // If this table is sorted we better find the top sorting number
520 $tempArray=$this->getSortNumber($table,0,$pid_value); // Because $pid_value is < 0, getSortNumber returns an array
521 $fieldArray['pid'] = $tempArray['pid'];
522 $fieldArray[$sortRow] = $tempArray['sortNumber'];
523 } else { // Here we fetch the PID of the record that we point to...
524 $tempdata = $this->recordInfo($table,abs($pid_value),'pid');
525 $fieldArray['pid']=$tempdata['pid'];
526 }
527 }
528 }
529 }
530 $theRealPid = $fieldArray['pid'];
531 // Now, check if we may insert records on this pid.
532 if ($theRealPid>=0) {
533 $recordAccess = $this->checkRecordInsertAccess($table,$theRealPid); // Checks if records can be inserted on this $pid.
534 } else {
535 debug('Internal ERROR: pid should not be less than zero!');
536 }
537 $status = 'new'; // Yes new record, change $record_status to 'insert'
538 } else { // Nope... $id is a number
539 $fieldArray = Array();
540 $recordAccess = $this->checkRecordUpdateAccess($table,$id);
541 if (!$recordAccess) {
542 $propArr = $this->getRecordProperties($table,$id);
543 $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']);
544 } else { // Next check of the record permissions (internals)
545 $recordAccess = $this->BE_USER->recordEditAccessInternals($table,$id);
546 if (!$recordAccess) {
547 $propArr = $this->getRecordProperties($table,$id);
548 $this->log($table,$id,2,0,1,"recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",2,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
549 } else { // Here we fetch the PID of the record that we point to...
550 $tempdata = $this->recordInfo($table,$id,'pid');
551 $theRealPid = $tempdata['pid'];
552 }
553 }
554 $status = 'update'; // the default is 'update'
555 }
556
557 // **************************************
558 // If access was granted above, proceed:
559 // **************************************
560 if ($recordAccess) {
561
562 list($tscPID) = t3lib_BEfunc::getTSCpid($table,$id,$old_pid_value ? $old_pid_value : $fieldArray['pid']); // Here the "pid" is sent IF NOT the old pid was a string pointing to a place in the subst-id array.
563 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
564 if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.'])) {
565 $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
566 }
567
568 $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
569
570 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
571
572 $fieldArray = $this->overrideFieldArray($table,$fieldArray); // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
573
574 // Setting system fields
575 if ($status=='new') {
576 if ($TCA[$table]['ctrl']['crdate']) {
577 $fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
578 }
579 if ($TCA[$table]['ctrl']['cruser_id']) {
580 $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
581 }
582 } elseif ($this->checkSimilar) { // Removing fields which are equal to the current value:
583 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
584 }
585 if ($TCA[$table]['ctrl']['tstamp']) {
586 $fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
587 }
588
589 // Hook: processDatamap_postProcessFieldArray
590 foreach($hookObjectsArr as $hookObj) {
591 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
592 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
593 }
594 }
595
596 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
597 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
598 if (is_array($fieldArray)) {
599 if ($status=='new') {
600 // if ($pid_value<0) {$fieldArray = $this->fixCopyAfterDuplFields($table,$id,abs($pid_value),0,$fieldArray);} // Out-commented 02-05-02: I couldn't understand WHY this is needed for NEW records. Obviously to proces records being copied? Problem is that the fields are not set anyways and the copying function should basically take care of this!
601 $this->insertDB($table,$id,$fieldArray,FALSE,$incomingFieldArray['uid']);
602 } else {
603 $this->updateDB($table,$id,$fieldArray);
604 }
605 }
606 } // if ($recordAccess) {
607 } // if (is_array($incomingFieldArray)) {
608 }
609 }
610 }
611 $this->dbAnalysisStoreExec();
612 $this->removeRegisteredFiles();
613 }
614
615 /**
616 * Filling in the field array
617 * $this->exclude_array is used to filter fields if needed.
618 *
619 * @param string Table name
620 * @param [type] $id: ...
621 * @param array Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
622 * @param array $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
623 * @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.
624 * @param string $status = 'new' or 'update'
625 * @param [type] $tscPID: ...
626 * @return [type] ...
627 */
628 function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID) {
629 global $TCA;
630
631 // Initialize:
632 t3lib_div::loadTCA($table);
633 unset($originalLanguageRecord);
634 unset($originalLanguage_diffStorage);
635 $diffStorageFlag = FALSE;
636
637 // Setting 'currentRecord' and 'checkValueRecord':
638 if (strstr($id,'NEW')) {
639 $currentRecord = $checkValueRecord = $fieldArray; // must have the 'current' array - not the values after processing below...
640
641 // IF $incomingFieldArray is an array, overlay it.
642 // 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...
643 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
644 $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
645 }
646 } else {
647 $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
648
649 // Get original language record if available:
650 if (is_array($currentRecord)
651 && $TCA[$table]['ctrl']['transOrigDiffSourceField']
652 && $TCA[$table]['ctrl']['languageField']
653 && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
654 && $TCA[$table]['ctrl']['transOrigPointerField']
655 && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0) {
656
657 $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
658 $originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
659 $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
660 }
661 }
662 $this->checkValue_currentRecord = $checkValueRecord;
663
664 /*
665 In the following all incoming value-fields are tested:
666 - Are the user allowed to change the field?
667 - Is the field uid/pid (which are already set)
668 - perms-fields for pages-table, then do special things...
669 - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
670
671 If everything is OK, the field is entered into $fieldArray[]
672 */
673 foreach($incomingFieldArray as $field => $fieldValue) {
674 if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) { // The field must be editable.
675
676 // Checking language:
677 $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);
678
679 if (!$languageDeny) {
680 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
681 if ($this->stripslashes_values) {
682 if (is_array($fieldValue)) {
683 t3lib_div::stripSlashesOnArray($fieldValue);
684 } else $fieldValue = stripslashes($fieldValue);
685 }
686
687 switch ($field) {
688 case 'uid':
689 case 'pid':
690 // Nothing happens, already set
691 break;
692 case 'perms_userid':
693 case 'perms_groupid':
694 case 'perms_user':
695 case 'perms_group':
696 case 'perms_everybody':
697 // Permissions can be edited by the owner or the administrator
698 if ($table=='pages' && ($this->admin || $status=='new' || $this->pageInfo($id,'perms_userid')==$this->userid) ) {
699 $value=intval($fieldValue);
700 switch($field) {
701 case 'perms_userid':
702 $fieldArray[$field]=$value;
703 break;
704 case 'perms_groupid':
705 $fieldArray[$field]=$value;
706 break;
707 default:
708 if ($value>=0 && $value<pow(2,5)) {
709 $fieldArray[$field]=$value;
710 }
711 break;
712 }
713 }
714 break;
715 case 't3ver_oid':
716 case 't3ver_id':
717 // t3ver_label is not here because it CAN be edited as a regular field!
718 break;
719 default:
720 if (isset($TCA[$table]['columns'][$field])) {
721 // Evaluating the value.
722 $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
723 if (isset($res['value'])) {
724 $fieldArray[$field]=$res['value'];
725
726 // Add the value of the original record to the diff-storage content:
727 if ($TCA[$table]['ctrl']['transOrigDiffSourceField']) {
728 $originalLanguage_diffStorage[$field] = $originalLanguageRecord[$field];
729 $diffStorageFlag = TRUE;
730 }
731 }
732 }
733
734
735 break;
736 }
737 } // Checking language.
738 } // Check exclude fields / disabled fields...
739 }
740
741 // Add diff-storage information:
742 if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']])) { // 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...
743 $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
744 }
745
746 // Checking for RTE-transformations of fields:
747 $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
748 $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
749 if (is_array($types_fieldConfig)) {
750 reset($types_fieldConfig);
751 while(list(,$vconf) = each($types_fieldConfig)) {
752 // Write file configuration:
753 $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray)); // inserted array_merge($currentRecord,$fieldArray) 170502
754
755 // RTE transformations:
756 if (!$this->dontProcessTransformations) {
757 if (isset($fieldArray[$vconf['field']])) {
758 // Look for transformation flag:
759 switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']]) {
760 case 'RTE':
761 $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
762 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
763
764 // Set alternative relative path for RTE images/links:
765 $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
766
767 // Get RTE object, draw form and set flag:
768 $RTEobj = &t3lib_BEfunc::RTEgetObj();
769 if (is_object($RTEobj)) {
770 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
771 } else {
772 debug('NO RTE OBJECT FOUND!');
773 }
774 break;
775 }
776 }
777 }
778
779 // Write file configuration:
780 if (is_array($eFile)) {
781 $mixedRec = array_merge($currentRecord,$fieldArray);
782 $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
783 $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
784 $parseHTML->init('','');
785
786 $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
787 $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
788
789 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, chr(10).$insertContent.chr(10), 1, 1);
790 t3lib_div::writeFile($eFile['editFile'],$SW_fileNewContent);
791
792 // Write status:
793 if (!strstr($id,'NEW') && $eFile['statusField']) {
794 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
795 $table,
796 'uid='.intval($id),
797 array(
798 $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
799 )
800 );
801 }
802 } elseif ($eFile && is_string($eFile)) {
803 $this->log($insertTable,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
804 }
805 }
806 }
807 // Return fieldArray
808 return $fieldArray;
809 }
810
811 /**
812 * Checking group modify_table access list
813 *
814 * Returns true if the user has general access to modify the $table
815 *
816 * @param [type] $table: ...
817 * @return [type] ...
818 */
819 function checkModifyAccessList($table) {
820 $res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData['tables_modify'],$table)));
821 return $res;
822 }
823
824 /**
825 * [Describe function...]
826 *
827 * @param [type] $table: ...
828 * @param [type] $id: ...
829 * @return [type] ...
830 */
831 function isRecordInWebMount($table,$id) {
832 if (!isset($this->isRecordInWebMount_Cache[$table.':'.$id])) {
833 $recP=$this->getRecordProperties($table,$id);
834 $this->isRecordInWebMount_Cache[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
835 }
836 return $this->isRecordInWebMount_Cache[$table.':'.$id];
837 }
838
839 /**
840 * [Describe function...]
841 *
842 * @param [type] $pid: ...
843 * @return [type] ...
844 */
845 function isInWebMount($pid) {
846 if (!isset($this->isInWebMount_Cache[$pid])) {
847 $this->isInWebMount_Cache[$pid]=$this->BE_USER->isInWebMount($pid);
848 }
849 //debug($this->isInWebMount_Cache);
850 return $this->isInWebMount_Cache[$pid];
851 }
852
853 /**
854 * Checks if user may update a certain record.
855 *
856 * Returns true if the user may update the record given by $table and $id
857 *
858 * @param [type] $table: ...
859 * @param [type] $id: ...
860 * @return [type] ...
861 */
862 function checkRecordUpdateAccess($table,$id) {
863 global $TCA;
864 $res = 0;
865 if ($TCA[$table] && intval($id)>0) {
866 if (isset($this->recUpdateAccessCache[$table][$id])) { // If information is cached, return it
867 return $this->recUpdateAccessCache[$table][$id];
868 // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
869 } elseif ($this->doesRecordExist($table,$id,'edit')) {
870 $res = 1;
871 }
872 $this->recUpdateAccessCache[$table][$id]=$res; // Cache the result
873 }
874 return $res;
875 }
876
877 /**
878 * Checks if user may insert a certain record.
879 *
880 * Returns true if the user may insert a record from table $insertTable on page $pid
881 *
882 * @param [type] $insertTable: ...
883 * @param [type] $pid: ...
884 * @param [type] $action: ...
885 * @return [type] ...
886 */
887 function checkRecordInsertAccess($insertTable,$pid,$action=1) {
888 global $TCA;
889 $res = 0;
890 $pid = intval($pid);
891 if ($pid>=0) {
892 if (isset($this->recInsertAccessCache[$insertTable][$pid])) { // If information is cached, return it
893 return $this->recInsertAccessCache[$insertTable][$pid];
894 } else {
895 // If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
896 if ( (!$pid && $this->admin) || $this->doesRecordExist('pages',$pid,($insertTable=='pages'?$this->pMap['new']:$this->pMap['editcontent'])) ) { // Check permissions
897 if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
898 $res = 1;
899 $this->recInsertAccessCache[$insertTable][$pid]=$res; // Cache the result
900 } else {
901 $propArr = $this->getRecordProperties('pages',$pid);
902 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert record on page '%s' (%s) where this table, %s, is not allowed",11,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
903 }
904 } else {
905 $propArr = $this->getRecordProperties('pages',$pid);
906 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert a record on page '%s' (%s) from table '%s' without permissions. Or non-existing page.",12,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
907 }
908 }
909 }
910 return $res;
911 }
912
913 /**
914 * Checks is a table is allowed on a certain page.
915 *
916 * $checkTable is the tablename
917 * $page_uid is the uid of the page to check
918 *
919 * @param [type] $page_uid: ...
920 * @param [type] $checkTable: ...
921 * @return [type] ...
922 */
923 function isTableAllowedForThisPage($page_uid, $checkTable) {
924 global $TCA, $PAGES_TYPES;
925 $page_uid = intval($page_uid);
926
927 // Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
928 if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages') {
929 return false;
930 }
931
932 // Check root-level
933 if (!$page_uid) {
934 if ($this->admin) {
935 return true;
936 }
937 } else {
938 // Check non-root-level
939 $doktype = $this->pageInfo($page_uid,'doktype');
940 $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
941 $allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
942 if (strstr($allowedTableList,'*') || in_array($checkTable,$allowedArray)) { // If all tables or the table is listed as a allowed type, return true
943 return true;
944 }
945 }
946 }
947
948 /**
949 * Checks if record exists
950 *
951 * Returns true if the record given by $table, $id and $perms
952 *
953 * @param string Record table name
954 * @param integer Record UID
955 * @param mixed Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array
956 * @return [type] ...
957 */
958 function doesRecordExist($table,$id,$perms) {
959 global $TCA;
960
961 $res = 0;
962 $id = intval($id);
963
964 // Processing the incoming $perms (from possible string to integer that can be AND'ed)
965 if (!t3lib_div::testInt($perms)) {
966 if ($table!='pages') {
967 switch($perms) {
968 case 'edit':
969 case 'delete':
970 case 'new':
971 $perms = 'editcontent'; // This holds it all in case the record is not page!!
972 break;
973 }
974 }
975 $perms = intval($this->pMap[$perms]);
976 } else {
977 $perms = intval($perms);
978 }
979
980 if (!$perms) {debug('Internal ERROR: no permissions to check for non-admin user.');}
981
982 // For all tables: Check if record exists:
983 // Notice: If $perms are 0 (zero) no perms-clause is added!
984 if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) || $this->admin)) {
985 if ($table != 'pages') {
986
987 // Find record without checking page:
988 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid', $table, 'uid='.intval($id).$this->deleteClause($table));
989 $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
990 t3lib_BEfunc::fixVersioningPid($table,$output);
991
992 // If record found, check page as well:
993 if (is_array($output)) {
994
995 // Looking up the page for record:
996 $mres = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
997 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
998
999 // Return true if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
1000 if (is_array($pageRec) || (!$output['pid'] && $this->admin)) {
1001 return TRUE;
1002 }
1003 }
1004 return FALSE;
1005 } else {
1006 $mres = $this->doesRecordExist_pageLookUp($id, $perms);
1007 return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
1008 }
1009 }
1010 }
1011
1012 /**
1013 * Looks up a page based on permissions.
1014 *
1015 * @param integer Page id
1016 * @param integer Permission integer
1017 * @return pointer MySQL result pointer (from exec_SELECTquery())
1018 * @access private
1019 * @see doesRecordExist()
1020 */
1021 function doesRecordExist_pageLookUp($id, $perms) {
1022 global $TCA;
1023
1024 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1025 'uid',
1026 'pages',
1027 'uid='.intval($id).
1028 $this->deleteClause('pages').
1029 ($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '').
1030 (!$this->admin && $TCA['pages']['ctrl']['editlock'] && ($perms & (2+4+16)) ? ' AND '.$TCA['pages']['ctrl']['editlock'].'=0':'') // admin users don't need check
1031 );
1032 }
1033
1034 /**
1035 * Checks if a whole branch of pages exists
1036 *
1037 * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
1038 * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
1039 * if $recurse is set, then the function will follow subpages. This MUST be set, if we need the idlist for deleting pages or else we get an incomplete list
1040 *
1041 * @param [type] $inList: ...
1042 * @param [type] $pid: ...
1043 * @param [type] $perms: ...
1044 * @param [type] $recurse: ...
1045 * @return [type] ...
1046 */
1047 function doesBranchExist($inList,$pid,$perms, $recurse) {
1048 global $TCA;
1049 $pid = intval($pid);
1050 $perms = intval($perms);
1051 if ($pid>=0) {
1052 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1053 'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
1054 'pages',
1055 'pid='.intval($pid).$this->deleteClause('pages'),
1056 '',
1057 'sorting'
1058 );
1059 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1060 if ($this->admin || $this->BE_USER->doesUserHaveAccess($row,$perms)) { // IF admin, then it's OK
1061 $inList.=$row['uid'].',';
1062 if ($recurse) { // Follow the subpages recursively...
1063 $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
1064 if ($inList == -1) {return -1;} // No permissions somewhere in the branch
1065 }
1066 } else {
1067 return -1; // No permissions
1068 }
1069 }
1070 }
1071 return $inList;
1072 }
1073
1074 /**
1075 * Returns the value of the $field from page $id
1076 * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performanceloss since it doesn't look up the same record twice!
1077 *
1078 * @param integer Page uid
1079 * @param string Field name for which to return value
1080 * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
1081 */
1082 function pageInfo($id,$field) {
1083 if (!isset($this->pageCache[$id])) {
1084 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
1085 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1086 $this->pageCache[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1087 }
1088 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1089 }
1090 return $this->pageCache[$id][$field];
1091 }
1092
1093 /**
1094 * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
1095 * NOTICE: No check for deleted or access!
1096 *
1097 * @param string Table name
1098 * @param integer UID of the record from $table
1099 * @param string Field list for the SELECT query, eg. "*" or "uid,pid,..."
1100 * @return mixed Returns the selected record on success, otherwise false.
1101 */
1102 function recordInfo($table,$id,$fieldList) {
1103 global $TCA;
1104 if (is_array($TCA[$table])) {
1105 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
1106 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1107 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1108 }
1109 }
1110 }
1111
1112 /**
1113 * Returns an array with record properties, like header and pid
1114 *
1115 * @param [type] $table: ...
1116 * @param [type] $id: ...
1117 * @return [type] ...
1118 */
1119 function getRecordProperties($table,$id) {
1120 $row = ($table=='pages' && !$id) ? array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
1121 t3lib_BEfunc::fixVersioningPid($table,$row);
1122 return $this->getRecordPropertiesFromRow($table,$row);
1123 }
1124
1125 /**
1126 * Returns an array with record properties, like header and pid, based on the row
1127 *
1128 * @param [type] $table: ...
1129 * @param [type] $row: ...
1130 * @return [type] ...
1131 */
1132 function getRecordPropertiesFromRow($table,$row) {
1133 global $TCA;
1134 if ($TCA[$table]) {
1135 $out = array(
1136 'header' => $row[$TCA[$table]['ctrl']['label']],
1137 'pid' => $row['pid'],
1138 'event_pid' => ($table=='pages'?$row['uid']:$row['pid'])
1139 );
1140 return $out;
1141 }
1142 }
1143
1144 /**
1145 * [Describe function...]
1146 *
1147 * @param [type] $fieldArray: ...
1148 * @param [type] $TSConfig_p: ...
1149 * @return [type] ...
1150 */
1151 function setTSconfigPermissions($fieldArray,$TSConfig_p) {
1152 if (strcmp($TSConfig_p['userid'],'')) $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
1153 if (strcmp($TSConfig_p['groupid'],'')) $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
1154 if (strcmp($TSConfig_p['user'],'')) $fieldArray['perms_user']=t3lib_div::testInt($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
1155 if (strcmp($TSConfig_p['group'],'')) $fieldArray['perms_group']=t3lib_div::testInt($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
1156 if (strcmp($TSConfig_p['everybody'],'')) $fieldArray['perms_everybody']=t3lib_div::testInt($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
1157
1158 return $fieldArray;
1159 }
1160
1161 /**
1162 * Returns a fieldArray with default values.
1163 *
1164 * @param [type] $table: ...
1165 * @return [type] ...
1166 */
1167 function newFieldArray($table) {
1168 global $TCA;
1169 t3lib_div::loadTCA($table);
1170 $fieldArray=Array();
1171 if (is_array($TCA[$table]['columns'])) {
1172 reset ($TCA[$table]['columns']);
1173 while (list($field,$content)=each($TCA[$table]['columns'])) {
1174 if (isset($this->defaultValues[$table][$field])) {
1175 $fieldArray[$field] = $this->defaultValues[$table][$field];
1176 } elseif (isset($content['config']['default'])) {
1177 $fieldArray[$field] = $content['config']['default'];
1178 }
1179 }
1180 }
1181 if ($table=='pages') { // Set default permissions for a page.
1182 $fieldArray['perms_userid'] = $this->userid;
1183 $fieldArray['perms_groupid'] = intval($this->BE_USER->firstMainGroup);
1184 $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions['user']);
1185 $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions['group']);
1186 $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions['everybody']);
1187 }
1188 return $fieldArray;
1189 }
1190
1191 /**
1192 * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
1193 *
1194 * @param [type] $table: ...
1195 * @param [type] $data: ...
1196 * @return [type] ...
1197 */
1198 function overrideFieldArray($table,$data) {
1199 if (is_array($this->overrideValues[$table])) {
1200 $data = array_merge($data,$this->overrideValues[$table]); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1201 }
1202 return $data;
1203 }
1204
1205 /**
1206 * Calculates the bitvalue of the permissions given in a string, comma-sep
1207 *
1208 * @param [type] $string: ...
1209 * @return [type] ...
1210 */
1211 function assemblePermissions($string) {
1212 $keyArr = t3lib_div::trimExplode(',',$string,1);
1213 $value=0;
1214 while(list(,$key)=each($keyArr)) {
1215 if ($key && isset($this->pMap[$key])) {
1216 $value |= $this->pMap[$key];
1217 }
1218 }
1219 return $value;
1220 }
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241 /*********************************************
1242 *
1243 * Evaluation of input values
1244 *
1245 ********************************************/
1246
1247 /**
1248 * Evaluates a value according to $table/$field settings.
1249 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1250 * 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() )
1251 *
1252 * @param string Table name
1253 * @param string Field name
1254 * @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.
1255 * @param string The record-uid, mainly - but not exclusively - used for logging
1256 * @param string 'update' or 'new' flag
1257 * @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.
1258 * @param integer $tscPID
1259 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1260 */
1261 function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID) {
1262 global $TCA, $PAGES_TYPES;
1263 t3lib_div::loadTCA($table);
1264
1265 $res = Array(); // result array
1266 $recFID = $table.':'.$id.':'.$field;
1267
1268 // Processing special case of field pages.doktype
1269 if ($table=='pages' && $field=='doktype') {
1270 // If the user may not use this specific doktype, we issue a warning
1271 if (! ($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'],$value))) {
1272 $propArr = $this->getRecordProperties($table,$id);
1273 $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']);
1274 return $res;
1275 };
1276 if ($status=='update') {
1277 // This checks if 1) we should check for disallowed tables and 2) the there are records from disallowed tables on the current page
1278 $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ? $PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
1279 if ($onlyAllowedTables) {
1280 $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
1281 if ($theWrongTables) {
1282 $propArr = $this->getRecordProperties($table,$id);
1283 $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']);
1284 return $res;
1285 }
1286 }
1287 }
1288 }
1289
1290 // Get current value:
1291 $curValueRec = $this->recordInfo($table,$id,$field);
1292 $curValue = $curValueRec[$field];
1293
1294 // Getting config for the field
1295 $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
1296
1297 // Preform processing:
1298 $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);
1299
1300 return $res;
1301 }
1302
1303 /**
1304 * Branches out evaluation of a field value based on its type as configured in TCA
1305 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1306 *
1307 * @param array The result array. The processed value (if any!) is set in the "value" key.
1308 * @param string The value to set.
1309 * @param array Field configuration from TCA
1310 * @param string Table name
1311 * @param integer Return UID
1312 * @param [type] $curValue: ...
1313 * @param [type] $status: ...
1314 * @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.
1315 * @param [type] $recFID: ...
1316 * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1317 * @param [type] $uploadedFiles: ...
1318 * @param [type] $tscPID: ...
1319 * @return array Returns the evaluated $value as key "value" in this array.
1320 */
1321 function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID) {
1322
1323 $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
1324
1325 switch ($tcaFieldConf['type']) {
1326 case 'text':
1327 case 'passthrough':
1328 case 'user':
1329 $res['value'] = $value;
1330 break;
1331 case 'input':
1332 $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
1333 break;
1334 case 'check':
1335 $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
1336 break;
1337 case 'radio':
1338 $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
1339 break;
1340 case 'group':
1341 case 'select':
1342 $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1343 break;
1344 case 'flex':
1345 if ($field) { // FlexForms are only allowed for real fields.
1346 $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1347 }
1348 break;
1349 default:
1350 #debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
1351 break;
1352 }
1353
1354 return $res;
1355 }
1356
1357 /**
1358 * Evaluate "input" type values.
1359 *
1360 * @param array The result array. The processed value (if any!) is set in the "value" key.
1361 * @param string The value to set.
1362 * @param array Field configuration from TCA
1363 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1364 * @param string Field name
1365 * @return array Modified $res array
1366 */
1367 function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='') {
1368 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1369
1370 // Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
1371 if (intval($tcaFieldConf['max'])>0) {$value = substr($value,0,intval($tcaFieldConf['max']));}
1372
1373 // Checking range of value:
1374 if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox']) { // If value is not set to the allowed checkbox-value then it is checked against the ranges
1375 if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper']) {$value=$tcaFieldConf['range']['upper'];}
1376 if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower']) {$value=$tcaFieldConf['range']['lower'];}
1377 }
1378
1379 // Process evaluation settings:
1380 $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
1381 $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
1382
1383 // Process UNIQUE settings:
1384 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...
1385 if ($res['value'] && in_array('uniqueInPid',$evalCodesArray)) {
1386 $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
1387 }
1388 if ($res['value'] && in_array('unique',$evalCodesArray)) {
1389 $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
1390 }
1391 }
1392
1393 return $res;
1394 }
1395
1396 /**
1397 * Evaluates 'check' type values.
1398 *
1399 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1400 * @param string The value to set.
1401 * @param array Field configuration from TCA
1402 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1403 * @return array Modified $res array
1404 */
1405 function checkValue_check($res,$value,$tcaFieldConf,$PP) {
1406 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1407
1408 $itemC = count($tcaFieldConf['items']);
1409 if (!$itemC) {$itemC=1;}
1410 $maxV = pow(2,$itemC);
1411
1412 if ($value<0) {$value=0;}
1413 if ($value>$maxV) {$value=$maxV;}
1414 $res['value'] = $value;
1415
1416 return $res;
1417 }
1418
1419 /**
1420 * Evaluates 'radio' type values.
1421 *
1422 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1423 * @param string The value to set.
1424 * @param array Field configuration from TCA
1425 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1426 * @return array Modified $res array
1427 */
1428 function checkValue_radio($res,$value,$tcaFieldConf,$PP) {
1429 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1430
1431 if (is_array($tcaFieldConf['items'])) {
1432 foreach($tcaFieldConf['items'] as $set) {
1433 if (!strcmp($set[1],$value)) {
1434 $res['value'] = $value;
1435 break;
1436 }
1437 }
1438 }
1439
1440 return $res;
1441 }
1442
1443 /**
1444 * Evaluates 'group' or 'select' type values.
1445 *
1446 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1447 * @param string The value to set.
1448 * @param array Field configuration from TCA
1449 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1450 * @param [type] $uploadedFiles: ...
1451 * @param string Field name
1452 * @return array Modified $res array
1453 */
1454 function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1455 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1456
1457 // Detecting if value send is an array and if so, implode it around a comma:
1458 if (is_array($value)) {
1459 $value = implode(',',$value);
1460 }
1461
1462 // 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.
1463 // Anyways, this should NOT disturb anything else:
1464 $value = $this->convNumEntityToByteValue($value);
1465
1466 // When values are send as group or select they come as comma-separated values which are exploded by this function:
1467 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1468
1469 // If not multiple is set, then remove duplicates:
1470 if (!$tcaFieldConf['multiple']) {
1471 $valueArray = array_unique($valueArray);
1472 }
1473
1474 // This could be a good spot for parsing the array through a validation-function which checks if the values are allright (except that database references are not in their final form - but that is the point, isn't it?)
1475 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1476
1477 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1478 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode']) {
1479 $preCount = count($valueArray);
1480 foreach($valueArray as $kk => $vv) {
1481 if (!$this->BE_USER->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode'])) {
1482 unset($valueArray[$kk]);
1483 }
1484 }
1485
1486 // 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.
1487 if ($preCount && !count($valueArray)) {
1488 return array();
1489 }
1490 }
1491
1492 // For group types:
1493 if ($tcaFieldConf['type']=='group') {
1494 switch($tcaFieldConf['internal_type']) {
1495 case 'file':
1496 $valueArray = $this->checkValue_group_select_file(
1497 $valueArray,
1498 $tcaFieldConf,
1499 $curValue,
1500 $uploadedFiles,
1501 $status,
1502 $table,
1503 $id,
1504 $recFID
1505 );
1506 break;
1507 case 'db':
1508 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group');
1509 break;
1510 }
1511 }
1512 // For select types which has a foreign table attached:
1513 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table']) {
1514 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select');
1515 }
1516
1517 // 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...
1518
1519 // Checking the number of items, that it is correct.
1520 // If files, there MUST NOT be too many files in the list at this point, so check that prior to this code.
1521 $valueArrayC = count($valueArray);
1522 $minI = isset($tcaFieldConf['minitems']) ? intval($tcaFieldConf['minitems']):0;
1523
1524 // 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.
1525 $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']):1;
1526 if ($valueArrayC > $maxI) {$valueArrayC=$maxI;} // Checking for not too many elements
1527
1528 // Dumping array to list
1529 $newVal=array();
1530 foreach($valueArray as $nextVal) {
1531 if ($valueArrayC==0) {break;}
1532 $valueArrayC--;
1533 $newVal[]=$nextVal;
1534 }
1535 $res['value'] = implode(',',$newVal);
1536
1537 return $res;
1538 }
1539
1540 /**
1541 * Handling files for group/select function
1542 *
1543 * @param [type] $valueArray: ...
1544 * @param [type] $tcaFieldConf: ...
1545 * @param [type] $curValue: ...
1546 * @param [type] $uploadedFileArray: ...
1547 * @param [type] $status: ...
1548 * @param [type] $table: ...
1549 * @param [type] $id: ...
1550 * @param [type] $recFID: ...
1551 * @return array Modified value array
1552 * @see checkValue_group_select()
1553 */
1554 function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID) {
1555
1556 // If any files are uploaded:
1557 if (is_array($uploadedFileArray) &&
1558 $uploadedFileArray['name'] &&
1559 strcmp($uploadedFileArray['tmp_name'],'none')) {
1560 $valueArray[]=$uploadedFileArray['tmp_name'];
1561 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1562 }
1563
1564 // Creating fileFunc object.
1565 if (!$this->fileFunc) {
1566 $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
1567 $this->include_filefunctions=1;
1568 }
1569 // Setting permitted extensions.
1570 $all_files = Array();
1571 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1572 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
1573 $all_files['ftpspace'] = $all_files['webspace'];
1574 $this->fileFunc->init('', $all_files);
1575
1576 // If there is an upload folder defined:
1577 if ($tcaFieldConf['uploadfolder']) {
1578 // For logging..
1579 $propArr = $this->getRecordProperties($table,$id);
1580
1581 // Get destrination path:
1582 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1583
1584 // If we are updating:
1585 if ($status=='update') {
1586
1587 // Finding the CURRENT files listed, either from MM or from the current record.
1588 $theFileValues=array();
1589 if ($tcaFieldConf['MM']) { // If MM relations for the files also!
1590 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1591 $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
1592 reset($dbAnalysis->itemArray);
1593 while (list($somekey,$someval)=each($dbAnalysis->itemArray)) {
1594 if ($someval['id']) {
1595 $theFileValues[]=$someval['id'];
1596 }
1597 }
1598 } else {
1599 $theFileValues=t3lib_div::trimExplode(',',$curValue,1);
1600 }
1601
1602 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1603 if (count($theFileValues)) {
1604 // 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!)
1605 foreach($valueArray as $key => $theFile) {
1606 if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
1607 $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues,$theFile);
1608 }
1609 }
1610
1611 // This array contains the filenames in the uploadfolder that should be deleted:
1612 foreach($theFileValues as $key => $theFile) {
1613 $theFile = trim($theFile);
1614 if (@is_file($dest.'/'.$theFile)) {
1615 $this->removeFilesStore[]=$dest.'/'.$theFile;
1616 } elseif ($theFile) {
1617 $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
1618 }
1619 }
1620 }
1621 }
1622
1623 // Traverse the submitted values:
1624 foreach($valueArray as $key => $theFile) {
1625 // 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)
1626 if (strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
1627 // Init:
1628 $maxSize = intval($tcaFieldConf['max_size']);
1629 $cmd='';
1630 $theDestFile=''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!! (Change: 22/12/2000)
1631
1632 // Check various things before copying file:
1633 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist
1634
1635 // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
1636 if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name']) {
1637 $fileSize = $uploadedFileArray['size'];
1638 } else {
1639 $fileSize = filesize($theFile);
1640 }
1641
1642 if (!$maxSize || $fileSize<=($maxSize*1024)) { // Check file size:
1643 // Prepare filename:
1644 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
1645 $fI = t3lib_div::split_fileref($theEndFileName);
1646
1647 // Check for allowed extension:
1648 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1649 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
1650
1651 // If we have a unique destination filename, then write the file:
1652 if ($theDestFile) {
1653 t3lib_div::upload_copy_move($theFile,$theDestFile);
1654 $this->copiedFileMap[$theFile] = $theDestFile;
1655 clearstatcache();
1656 if (!@is_file($theDestFile)) $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']);
1657 } else $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']);
1658 } else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
1659 } else $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']);
1660 } else $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']);
1661
1662 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1663 if (@is_file($theDestFile)) {
1664 $info = t3lib_div::split_fileref($theDestFile);
1665 $valueArray[$key]=$info['file']; // The value is set to the new filename
1666 } else {
1667 unset($valueArray[$key]); // The value is set to the new filename
1668 }
1669 }
1670 }
1671
1672 // 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!
1673 if ($tcaFieldConf['MM']) {
1674 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1675 $dbAnalysis->tableArray['files']=array(); // dummy
1676
1677 reset($valueArray);
1678 while (list($key,$theFile)=each($valueArray)) {
1679 // explode files
1680 $dbAnalysis->itemArray[]['id']=$theFile;
1681 }
1682 if ($status=='update') {
1683 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
1684 } else {
1685 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1686 }
1687 $cc=count($dbAnalysis->itemArray);
1688 $valueArray = array($cc);
1689 }
1690 }
1691
1692 return $valueArray;
1693 }
1694
1695 /**
1696 * Evaluates 'flex' type values.
1697 *
1698 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1699 * @param string The value to set.
1700 * @param array Field configuration from TCA
1701 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1702 * @param array Uploaded files for the field
1703 * @param array Current record array.
1704 * @param string Field name
1705 * @return array Modified $res array
1706 */
1707 function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1708 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1709
1710 if (is_array($value)) {
1711
1712 // Get current value array:
1713 $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table);
1714 #debug($this->checkValue_currentRecord);
1715 $currentValueArray = t3lib_div::xml2array($curValue);
1716 if (!is_array($currentValueArray)) $currentValueArray = array();
1717 if (is_array($currentValueArray['meta']['currentLangId'])) unset($currentValueArray['meta']['currentLangId']); // Remove all old meta for languages...
1718
1719 // Evaluation of input values:
1720 $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
1721
1722 // Create XML and convert charsets from input value:
1723 $xmlValue = $this->checkValue_flexArray2Xml($value);
1724
1725 // If we wanted to set UTF fixed:
1726 // $storeInCharset='utf-8';
1727 // $currentCharset=$GLOBALS['LANG']->charSet;
1728 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1729 $storeInCharset=$GLOBALS['LANG']->charSet;
1730
1731 // Merge them together IF they are both arrays:
1732 // 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).
1733 if (is_array($currentValueArray)) {
1734 $arrValue = t3lib_div::xml2array($xmlValue);
1735 $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
1736 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1737 }
1738
1739 // Temporary fix to delete elements:
1740 $deleteCMDs = t3lib_div::_GP('_DELETE_FLEX_FORMdata');
1741
1742 if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
1743 $arrValue = t3lib_div::xml2array($xmlValue);
1744 $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
1745 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1746 }
1747
1748 // Create the value XML:
1749 $res['value']='';
1750 $res['value'].='<?xml version="1.0" encoding="'.$storeInCharset.'" standalone="yes" ?>'.chr(10);
1751 $res['value'].=$xmlValue;
1752 } else { // Passthrough...:
1753 $res['value']=$value;
1754 }
1755
1756 return $res;
1757 }
1758
1759 /**
1760 * [Describe function...]
1761 *
1762 * @param [type] $array: ...
1763 * @return [type] ...
1764 */
1765 function checkValue_flexArray2Xml($array) {
1766 $output = t3lib_div::array2xml($array,'',0,'T3FlexForms',4,array('parentTagMap' => array(
1767 /* 'data' => 'sheets',
1768 'sheets' => 'language',
1769 'language' => 'fieldname',
1770 'el' => 'fieldname' */
1771 )));
1772 return $output;
1773 }
1774
1775 /**
1776 * [Describe function...]
1777 *
1778 * @param [type] $$valueArrayToRemoveFrom: ...
1779 * @param [type] $deleteCMDS: ...
1780 * @return [type] ...
1781 */
1782 function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS) {
1783 if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
1784 foreach($deleteCMDS as $key => $value) {
1785 if (is_array($deleteCMDS[$key])) {
1786 $this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
1787 } else {
1788 unset($valueArrayToRemoveFrom[$key]);
1789 }
1790 }
1791 }
1792 }
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813 /*********************************************
1814 *
1815 * Helper functions for evaluation functions.
1816 *
1817 ********************************************/
1818
1819
1820 /**
1821 * Gets a unique value for $table/$id/$field based on $value
1822 *
1823 * @param string Table name
1824 * @param string Field name for which $value must be unique
1825 * @param string Value string.
1826 * @param integer UID to filter out in the lookup (the record itself...)
1827 * @param integer If set, the value will be unique for this PID
1828 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
1829 */
1830 function getUnique($table,$field,$value,$id,$newPid=0) {
1831 global $TCA;
1832
1833 // Initialize:
1834 t3lib_div::loadTCA($table);
1835 $whereAdd='';
1836 $newValue='';
1837 if (intval($newPid)) { $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AND pid>=0'; } // "AND pid>=0" for versioning
1838 $whereAdd.=$this->deleteClause($table);
1839
1840 // If the field is configured in TCA, proceed:
1841 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
1842
1843 // Look for a record which might already have the value:
1844 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table).' AND uid!='.intval($id).$whereAdd);
1845 $counter = 0;
1846
1847 // For as long as records with the test-value existing, try again (with incremented numbers appended).
1848 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1849 $newValue = $value.$counter;
1850 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table).' AND uid!='.intval($id).$whereAdd);
1851 $counter++;
1852 if ($counter>100) { break; } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
1853 }
1854 // If the new value is there:
1855 $value = strlen($newValue) ? $newValue : $value;
1856 }
1857 return $value;
1858 }
1859
1860 /**
1861 * Evaluation of 'input'-type values based on 'eval' list
1862 *
1863 * @param string Value
1864 * @param array Array of evaluations to traverse.
1865 * @param string Is-in string
1866 * @return string Modified $value
1867 */
1868 function checkValue_input_Eval($value,$evalArray,$is_in) {
1869 $res = Array();
1870 $newValue = $value;
1871 $set = true;
1872
1873 foreach($evalArray as $func) {
1874 switch($func) {
1875 case 'int':
1876 case 'year':
1877 case 'date':
1878 case 'datetime':
1879 case 'time':
1880 case 'timesec':
1881 $value = intval($value);
1882 break;
1883 case 'double2':
1884 $theDec = 0;
1885 for ($a=strlen($value); $a>0; $a--) {
1886 if (substr($value,$a-1,1)=='.' || substr($value,$a-1,1)==',') {
1887 $theDec = substr($value,$a);
1888 $value = substr($value,0,$a-1);
1889 break;
1890 }
1891 }
1892 $theDec = ereg_replace('[^0-9]','',$theDec).'00';
1893 $value = intval(str_replace(' ','',$value)).'.'.substr($theDec,0,2);
1894 break;
1895 case 'md5':
1896 if (strlen($value)!=32){$set=false;}
1897 break;
1898 case 'trim':
1899 $value = trim($value);
1900 break;
1901 case 'upper':
1902 $value = strtoupper($value);
1903 # $value = strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÂÊÛÔÎÆØÅÄÖÜ'); // WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
1904 break;
1905 case 'lower':
1906 $value = strtolower($value);
1907 # $value = strtr($value, 'ÁÉÚÍÂÊÛÔÎÆØÅÄÖÜ', 'áéúíâêûôîæøåäöü'); // WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
1908 break;
1909 case 'required':
1910 if (!$value) {$set=0;}
1911 break;
1912 case 'is_in':
1913 $c=strlen($value);
1914 if ($c) {
1915 $newVal = '';
1916 for ($a=0;$a<$c;$a++) {
1917 $char = substr($value,$a,1);
1918 if (strstr($is_in,$char)) {
1919 $newVal.=$char;
1920 }
1921 }
1922 $value = $newVal;
1923 }
1924 break;
1925 case 'nospace':
1926 $value = str_replace(' ','',$value);
1927 break;
1928 case 'alpha':
1929 $value = ereg_replace('[^a-zA-Z]','',$value);
1930 break;
1931 case 'num':
1932 $value = ereg_replace('[^0-9]','',$value);
1933 break;
1934 case 'alphanum':
1935 $value = ereg_replace('[^a-zA-Z0-9]','',$value);
1936 break;
1937 case 'alphanum_x':
1938 $value = ereg_replace('[^a-zA-Z0-9_-]','',$value);
1939 break;
1940 }
1941 }
1942 if ($set) {$res['value'] = $value;}
1943 return $res;
1944 }
1945
1946 /**
1947 * Returns data for group/db and select fields
1948 *
1949 * @param array Current value array
1950 * @param array TCA field config
1951 * @param integer Record id, used for look-up of MM relations (local_uid)
1952 * @param string Status string ('update' or 'new')
1953 * @param string The type, either 'select' or 'group'
1954 * @return array Modified value array
1955 */
1956 function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type) {
1957 $tables = $type=='group'?$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
1958 $prep = $type=='group'?$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
1959
1960 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1961 $dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
1962 $dbAnalysis->start(implode(',',$valueArray),$tables);
1963
1964 if ($tcaFieldConf['MM']) {
1965 if ($status=='update') {
1966 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
1967 } else {
1968 $this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep); // This will be traversed later to execute the actions
1969 }
1970 $cc=count($dbAnalysis->itemArray);
1971 $valueArray = array($cc);
1972 } else {
1973 $valueArray = $dbAnalysis->getValueArray($prep);
1974 if ($type=='select' && $prep) {
1975 $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
1976 }
1977 }
1978
1979 // Here we should se if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
1980 return $valueArray;
1981 }
1982
1983 /**
1984 * Explodes the $value, which is a list of files/uids (group select)
1985 *
1986 * @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.
1987 * @return array The value array.
1988 */
1989 function checkValue_group_select_explodeSelectGroupValue($value) {
1990 $valueArray = t3lib_div::trimExplode(',',$value,1);
1991 reset($valueArray);
1992 while(list($key,$newVal)=each($valueArray)) {
1993 $temp=explode('|',$newVal,2);
1994 $valueArray[$key] = str_replace(',','',str_replace('|','',rawurldecode($temp[0])));
1995 }
1996 return $valueArray;
1997 }
1998
1999 /**
2000 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2001 * See checkValue_flex_procInData_travDS() for more details.
2002 *
2003 * @param array The 'data' part of the INPUT flexform data
2004 * @param array The 'data' part of the CURRENT flexform data
2005 * @param array The uploaded files for the 'data' part of the INPUT flexform data
2006 * @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.
2007 * @param array A set of parameters to pass through for the calling of the evaluation functions
2008 * @param string Optional call back function, see checkValue_flex_procInData_travDS()
2009 * @return array The modified 'data' part.
2010 * @see checkValue_flex_procInData_travDS()
2011 */
2012 function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='') {
2013 #debug(array($dataPart,$dataPart_current,$dataStructArray));
2014 if (is_array($dataPart)) {
2015 foreach($dataPart as $sKey => $sheetDef) {
2016 list ($dataStruct,$actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sKey);
2017 #debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
2018 if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef)) {
2019 foreach($sheetDef as $lKey => $lData) {
2020 $this->checkValue_flex_procInData_travDS(
2021 $dataPart[$sKey][$lKey],
2022 $dataPart_current[$sKey][$lKey],
2023 $uploadedFiles[$sKey][$lKey],
2024 $dataStruct['ROOT']['el'],
2025 $pParams,
2026 $callBackFunc,
2027 $sKey.'/'.$lKey.'/'
2028 );
2029 }
2030 }
2031 }
2032 }
2033
2034 return $dataPart;
2035 }
2036
2037 /**
2038 * Processing of the sheet/language data array
2039 * 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.
2040 *
2041 * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2042 * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2043 * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2044 * @param array Data structure which fits the data array
2045 * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
2046 * @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.
2047 * @return void
2048 * @see checkValue_flex_procInData()
2049 */
2050 function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath) {
2051 if (is_array($DSelements)) {
2052
2053 // For each DS element:
2054 foreach($DSelements as $key => $dsConf) {
2055
2056 // Array/Section:
2057 if ($DSelements[$key]['type']=='array') {
2058 if (is_array($dataValues[$key]['el'])) {
2059 if ($DSelements[$key]['section']) {
2060 foreach($dataValues[$key]['el'] as $ik => $el) {
2061 $theKey = key($el);
2062 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2063 $this->checkValue_flex_procInData_travDS(
2064 $dataValues[$key]['el'][$ik][$theKey]['el'],
2065 $dataValues_current[$key]['el'][$ik][$theKey]['el'],
2066 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2067 $DSelements[$key]['el'][$theKey]['el'],
2068 $pParams,
2069 $callBackFunc,
2070 $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
2071 );
2072 }
2073 }
2074 } else {
2075 if (!isset($dataValues[$key]['el'])) $dataValues[$key]['el']=array();
2076 $this->checkValue_flex_procInData_travDS(
2077 $dataValues[$key]['el'],
2078 $dataValues_current[$key]['el'],
2079 $uploadedFiles[$key]['el'],
2080 $DSelements[$key]['el'],
2081 $pParams,
2082 $callBackFunc,
2083 $structurePath.$key.'/el/'
2084 );
2085 }
2086 }
2087 } else {
2088 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2089 foreach($dataValues[$key] as $vKey => $data) {
2090
2091 if ($callBackFunc) {
2092 if (is_object($this->callBackObj)) {
2093 $res = $this->callBackObj->$callBackFunc(
2094 $pParams,
2095 $dsConf['TCEforms']['config'],
2096 $dataValues[$key][$vKey],
2097 $dataValues_current[$key][$vKey],
2098 $uploadedFiles[$key][$vKey],
2099 $structurePath.$key.'/'.$vKey.'/'
2100 );
2101 } else {
2102 $res = $this->$callBackFunc(
2103 $pParams,
2104 $dsConf['TCEforms']['config'],
2105 $dataValues[$key][$vKey],
2106 $dataValues_current[$key][$vKey],
2107 $uploadedFiles[$key][$vKey]
2108 );
2109 }
2110 } else { // Default
2111 list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
2112
2113 $res = $this->checkValue_SW(
2114 array(),
2115 $dataValues[$key][$vKey],
2116 $dsConf['TCEforms']['config'],
2117 $CVtable,
2118 $CVid,
2119 $dataValues_current[$key][$vKey],
2120 $CVstatus,
2121 $CVrealPid,
2122 $CVrecFID,
2123 '',
2124 $uploadedFiles[$key][$vKey],
2125 array(),
2126 $CVtscPID
2127 );
2128
2129 // Look for RTE transformation of field:
2130 if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations) {
2131
2132 // Unsetting trigger field - we absolutely don't want that into the data storage!
2133 unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
2134
2135 if (isset($res['value'])) {
2136
2137 // Calculating/Retrieving some values here:
2138 list(,,$recFieldName) = explode(':', $CVrecFID);
2139 $theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable,$this->checkValue_currentRecord);
2140 $specConf = t3lib_BEfunc::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
2141
2142 // Find, thisConfig:
2143 $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($CVtscPID));
2144 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
2145
2146 // Get RTE object, draw form and set flag:
2147 $RTEobj = &t3lib_BEfunc::RTEgetObj();
2148 if (is_object($RTEobj)) {
2149 $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord,$specConf,$thisConfig,'',$CVrealPid);
2150 } else {
2151 debug('NO RTE OBJECT FOUND!');
2152 }
2153 }
2154 }
2155 }
2156
2157 // Adding the value:
2158 if (isset($res['value'])) {
2159 $dataValues[$key][$vKey] = $res['value'];
2160 }
2161 }
2162 }
2163 }
2164 }
2165 }
2166 }
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187 /*********************************************
2188 *
2189 * Storing data to Database Layer
2190 *
2191 ********************************************/
2192
2193
2194 /**
2195 * Update database record
2196 * Does not check permissions but expects them to be verified on beforehand
2197 *
2198 * @param string Record table name
2199 * @param integer Record uid
2200 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
2201 * @return void
2202 */
2203 function updateDB($table,$id,$fieldArray) {
2204 global $TCA;
2205
2206 if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id)) {
2207 unset($fieldArray['uid']); // Do NOT update the UID field, ever!
2208
2209 if (count($fieldArray)) {
2210
2211 // Execute the UPDATE query:
2212 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
2213
2214 // If succees, do...:
2215 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2216 if ($this->checkStoredRecords) {
2217 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
2218 }
2219
2220 // Set log entry:
2221 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2222 $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
2223
2224 // Set History data:
2225 $this->setHistory($table,$id,$theLogId);
2226
2227 // Clear cache for relavant pages:
2228 $this->clear_cache($table,$id);
2229
2230 // Unset the pageCache for the id if table was page.
2231 if ($table=='pages') unset($this->pageCache[$id]);
2232 } else {
2233 $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2234 }
2235 }
2236 }
2237 }
2238
2239 /**
2240 * Compares the incoming field array with the current record and unsets all fields which are the same.
2241 * If the returned array is empty, then the record should not be updated!
2242 * $fieldArray must be an array.
2243 *
2244 * @param string Record table name
2245 * @param integer Record uid
2246 * @param array Array of field=>value pairs intended to be inserted into the database. All keys with values matching exactly the current value will be unset!
2247 * @return array Returns $fieldArray
2248 */
2249 function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray) {
2250
2251 // Fetch the original record:
2252 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2253 $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2254
2255 // If the current record exists (which it should...), begin comparison:
2256 if (is_array($currentRecord)) {
2257
2258 // Read all field types:
2259 $c = 0;
2260 $cRecTypes = array();
2261 foreach($currentRecord as $col => $val) {
2262 // DBAL
2263 # $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($table,$col);
2264 $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
2265 $c++;
2266 }
2267 #debug($cRecTypes);
2268
2269 // Free result:
2270 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2271
2272 // Unset the fields which are similar:
2273 foreach($fieldArray as $col => $val) {
2274 if (
2275 #!isset($currentRecord[$col]) || // Unset fields which were NOT found in the current record! [Uncommented because NULL fields will not return an entry in the array!]
2276 !strcmp($val,$currentRecord[$col]) || // Unset fields which matched exactly.
2277 ($cRecTypes[$col]=='int' && $currentRecord[$col]==0 && !strcmp($val,'')) // Now, a situation where TYPO3 tries to put an empty string into an integer field, we should not strcmp the integer-zero and '', but rather accept them to be similar.
2278 ) {
2279 unset($fieldArray[$col]);
2280 } else {
2281 $this->historyRecords[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
2282 $this->historyRecords[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
2283 }
2284 }
2285 } else { // If the current record does not exist this is an error anyways and we just return an empty array here.
2286 $fieldArray = array();
2287 }
2288
2289 return $fieldArray;
2290 }
2291
2292 /**
2293 * Insert into database
2294 * Does not check permissions but expects them to be verified on beforehand
2295 *
2296 * @param string Record table name
2297 * @param string "NEW...." uid string
2298 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done. "pid" must point to the destination of the record!
2299 * @param boolean Set to true if new version is created.
2300 * @param integer Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
2301 * @return void
2302 */
2303 function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0) {
2304 global $TCA;
2305
2306 if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid'])) {
2307 unset($fieldArray['uid']); // Do NOT insert the UID field, ever!
2308
2309 if (count($fieldArray)) {
2310
2311 // Check for "suggestedUid".
2312 // This feature is used by the import functionality to force a new record to have a certain UID value.
2313 // This is only recommended for use when the destination server is a passive mirrow of another server.
2314 // As a security measure this feature is available only for Admin Users (for now)
2315 $suggestedUid = intval($suggestedUid);
2316 if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table.':'.$suggestedUid]) {
2317 // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
2318 if ($this->suggestedInsertUids[$table.':'.$suggestedUid]==='DELETE') {
2319 // DELETE:
2320 $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($suggestedUid));
2321 }
2322 $fieldArray['uid'] = $suggestedUid;
2323 }
2324
2325 // Execute the INSERT query:
2326 $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
2327
2328 // If succees, do...:
2329 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2330
2331 // Set mapping for NEW... -> real uid:
2332 $NEW_id = $id; // the NEW_id now holds the 'NEW....' -id
2333 $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
2334 $this->substNEWwithIDs[$NEW_id] = $id;
2335 $this->substNEWwithIDs_table[$NEW_id] = $table;
2336
2337 // Checking the record is properly saved and writing to log
2338 if ($this->checkStoredRecords) {
2339 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
2340 }
2341
2342 if ($newVersion) {
2343 $this->log($table,$id,1,0,0,"New version created of table '%s', uid '%s'",10,array($table,$fieldArray['t3ver_oid']),$newRow['pid'],$NEW_id);
2344 } else {
2345 // Set log entry:
2346 if ($table=='pages') {
2347 $thePositionID = $this->getInterfacePagePositionID($id);
2348 } else {
2349 $thePositionID = 0;
2350 }
2351 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2352 $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
2353 $this->log($table,$id,1,$thePositionID,0,"Record '%s' (%s) was inserted on page '%s' (%s)",10,array($propArr['header'],$table.':'.$id,$page_propArr['header'],$newRow['pid']),$newRow['pid'],$NEW_id);
2354
2355 // Clear cache for relavant pages:
2356 $this->clear_cache($table,$id);
2357 }
2358 } else {
2359 $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2360 }
2361 }
2362 }
2363 }
2364
2365 /**
2366 * Checking stored record to see if the written values are properly updated.
2367 *
2368 * @param string Record table name
2369 * @param integer Record uid
2370 * @param array Array of field=>value pairs to insert/update
2371 * @param string Action, for logging only.
2372 * @return array Selected row
2373 * @see insertDB(), updateDB()
2374 */
2375 function checkStoredRecord($table,$id,$fieldArray,$action) {
2376 global $TCA;
2377
2378 $id = intval($id);
2379 if (is_array($TCA[$table]) && $id) {
2380 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2381 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2382 // Traverse arrow of values that was inserted into the database and compare with the actually stored value:
2383 $errorString = array();
2384 foreach($fieldArray as $key => $value) {
2385 if ($this->checkStoredRecords_loose && !$value && !$row[$key]) {
2386 // Nothing...
2387 } elseif (strcmp($value,$row[$key])) {
2388 // DEBUGGING KFISH
2389 // debug(array("$value != ".$row[$key]));
2390 $errorString[] = $key;
2391 }
2392 }
2393
2394 // Set log message if there were fields with unmatching values:
2395 if (count($errorString)) {
2396 $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
2397 }
2398
2399 // Return selected rows:
2400 return $row;
2401 }
2402 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2403 }
2404 }
2405
2406 /**
2407 * Executing dbAnalysisStore
2408 *
2409 * @return [type] ...
2410 */
2411 function dbAnalysisStoreExec() {
2412 reset($this->dbAnalysisStore);
2413 while(list($k,$v)=each($this->dbAnalysisStore)) {
2414 $id = $this->substNEWwithIDs[$v[2]];
2415 if ($id) {
2416 $v[2] = $id;
2417 $v[0]->writeMM($v[1],$v[2],$v[3]);
2418 }
2419 }
2420 }
2421
2422 /**
2423 * Executing dbAnalysisStore
2424 *
2425 * @return [type] ...
2426 */
2427 function removeRegisteredFiles() {
2428 reset($this->removeFilesStore);
2429 while(list($k,$v)=each($this->removeFilesStore)) {
2430 unlink($v);
2431 // debug($v,1);
2432 }
2433 }
2434
2435 /**
2436 * Clearing the cache based on a page being updated
2437 * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
2438 * Else just clear the cache for the parent page of the record.
2439 *
2440 * @param string Table name of record that was just updated.
2441 * @param integer UID of updated / inserted record
2442 * @return void
2443 */
2444 function clear_cache($table,$uid) {
2445 global $TCA, $TYPO3_CONF_VARS;
2446
2447 $uid = intval($uid);
2448 if (is_array($TCA[$table]) && $uid > 0) {
2449
2450 // Get Page TSconfig relavant:
2451 list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
2452 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2453
2454 if (!$TSConfig['clearCache_disable']) {
2455
2456 // If table is "pages":
2457 if (t3lib_extMgm::isLoaded('cms')) {
2458 $list_cache = array();
2459 if ($table=='pages') {
2460
2461 // Builds list of pages on the SAME level as this page (siblings)
2462 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2463 'A.pid AS pid, B.uid AS uid',
2464 'pages A, pages B',
2465 'A.uid='.intval($uid).' AND B.pid=A.pid AND B.deleted=0'
2466 );
2467
2468 $pid_tmp = 0;
2469 while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2470 $list_cache[] = $row_tmp['uid'];
2471 $pid_tmp = $row_tmp['pid'];
2472
2473 // Add children as well:
2474 if ($TSConfig['clearCache_pageSiblingChildren']) {
2475 $res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2476 'uid',
2477 'pages',
2478 'pid='.intval($row_tmp['uid']).' AND deleted=0'
2479 );
2480 while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2)) {
2481 $list_cache[] = $row_tmp2['uid'];
2482 }
2483 }
2484 }
2485
2486 // Finally, add the parent page as well:
2487 $list_cache[] = $pid_tmp;
2488
2489 // Add grand-parent as well:
2490 if ($TSConfig['clearCache_pageGrandParent']) {
2491 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2492 'pid',
2493 'pages',
2494 'uid='.intval($pid_tmp)
2495 );
2496 if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2497 $list_cache[] = $row_tmp['pid'];
2498 }
2499 }
2500 } else { // For other tables than "pages", delete cache for the records "parent page".
2501 $list_cache[] = intval($this->getPID($table,$uid));
2502 }
2503
2504 // Call pre-processing function for clearing of cache for page ids:
2505 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'])) {
2506 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName) {
2507 $_params = array('pageIdArray' => &$list_cache, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()');
2508 // Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
2509 t3lib_div::callUserFunction($funcName,$_params,$this);
2510 }
2511 }
2512
2513 // Delete cache for selected pages:
2514 if (is_array($list_cache)) {
2515 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2516 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2517 }
2518 }
2519 }
2520
2521 // Clear cache for pages entered in TSconfig:
2522 if ($TSConfig['clearCacheCmd']) {
2523 $Commands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
2524 $Commands = array_unique($Commands);
2525 foreach($Commands as $cmdPart) {
2526 $this->clear_cacheCmd($cmdPart);
2527 }
2528 }
2529
2530 // Call post processing function for clear-cache:
2531 global $TYPO3_CONF_VARS;
2532 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
2533 $_params = array('table' => $table,'uid' => $uid,'uid_page' => $uid_page,'TSConfig' => $TSConfig);
2534 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
2535 t3lib_div::callUserFunction($_funcRef,$_params,$this);
2536 }
2537 }
2538 }
2539 }
2540
2541 /**
2542 * Returns the pid of a record from $table with $uid
2543 *
2544 * @param string Table name
2545 * @param integer Record uid
2546 * @return integer PID value (unless the record did not exist in which case FALSE)
2547 */
2548 function getPID($table,$uid) {
2549 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
2550 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2551 return $row['pid'];
2552 }
2553 }
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579 /*********************************************
2580 *
2581 * PROCESSING COMMANDS
2582 *
2583 ********************************************/
2584
2585 /**
2586 * Processing the cmd-array
2587 * See "TYPO3 Core API" for a description of the options.
2588 *
2589 * @return void
2590 */
2591 function process_cmdmap() {
2592 global $TCA;
2593
2594 // Traverse command map:
2595 reset ($this->cmdmap);
2596 while (list($table,) = each($this->cmdmap)) {
2597
2598 // Check if the table may be modified!
2599 $modifyAccessList = $this->checkModifyAccessList($table);
2600 if (!$modifyAccessList) {
2601 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
2602 }
2603
2604 // Check basic permissions and circumstances:
2605 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap[$table]) && $modifyAccessList) {
2606
2607 // Traverse the command map:
2608 foreach($this->cmdmap[$table] as $id => $incomingCmdArray) {
2609 if (is_array($incomingCmdArray)) { // have found a command.
2610
2611 // Get command and value (notice, only one command is observed at a time!):
2612 reset($incomingCmdArray);
2613 $command = key($incomingCmdArray);
2614 $value = current($incomingCmdArray);
2615
2616 // Init copyMapping array:
2617 $this->copyMappingArray = Array(); // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
2618
2619 // Branch, based on command
2620 switch ($command) {
2621 case 'move':
2622 $this->moveRecord($table,$id,$value);
2623 break;
2624 case 'copy':
2625 if ($table == 'pages') {
2626 $this->copyPages($id,$value);
2627 } else {
2628 $this->copyRecord($table,$id,$value,1);
2629 }
2630 break;
2631 case 'localize':
2632 $this->copyRecord_localize($table,$id,$value);
2633 break;
2634 case 'version':
2635 switch ((string)$value['action']) {
2636 case 'new':
2637 $this->versionizeTree = t3lib_div::intInRange($value['treeLevels'],-1,4); // Max 4 levels of versioning...
2638 if ($table == 'pages' && $this->versionizeTree>=0) {
2639 $this->versionizePages($id,$value['label']);
2640 } else {
2641 $this->versionizeRecord($table,$id,$value['label']);
2642 }
2643 break;
2644 case 'swap':
2645 $this->version_swap($table,$id,$value['swapWith'],$value['swapContent']);
2646 break;
2647 }
2648 break;
2649 case 'delete':
2650 if ($table == 'pages') {
2651 $this->deletePages($id);
2652 } else {
2653 $this->deleteRecord($table,$id, 0);
2654 }
2655 break;
2656 }
2657 // Merging the copy-array info together for remapping purposes.
2658 $this->copyMappingArray_merged= t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged,$this->copyMappingArray);
2659 }
2660 }
2661 }
2662 }
2663
2664 #debug($this->copyMappingArray_merged,'$this->copyMappingArray_merged');
2665 #debug($this->registerDBList,'$this->registerDBList');
2666
2667 // Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
2668 $this->remapListedDBRecords();
2669 }
2670
2671 /**
2672 * Moving records
2673 *
2674 * @param string Table name to move
2675 * @param integer Record uid to move
2676 * @param integer Position to move to: $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
2677 * @return void
2678 */
2679 function moveRecord($table,$uid,$destPid) {
2680 global $TCA;
2681
2682 // Initialize:
2683 $sortRow = $TCA[$table]['ctrl']['sortby'];
2684 $destPid = intval($destPid);
2685 $origDestPid = $destPid;
2686
2687 if ($TCA[$table]) {
2688 $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
2689 $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving.
2690
2691 // Finding out, if the record may be moved from where it is. If the record is a non-page, then it depends on edit-permissions.
2692 // If the record is a page, then there are two options: If the page is moved within itself, (same pid) it's edit-perms of the pid. If moved to another place then its both delete-perms of the pid and new-page perms on the destination.
2693 if ($table!='pages' || $resolvedPid==$propArr['pid']) {
2694 $mayMoveAccess = $this->checkRecordUpdateAccess($table,$uid); // Edit rights for the record...
2695 } else {
2696 $mayMoveAccess = $this->doesRecordExist($table,$uid,'delete');
2697 }
2698
2699 // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new), unless the pages is moved on the same pid, then edit-rights are checked
2700 if ($table!='pages' || $resolvedPid!=$propArr['pid']) {
2701 $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4); // Edit rights for the record...
2702 } else {
2703 $mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
2704 }
2705
2706 // Checking if the pid is negativ, but no sorting row is defined. In that case, find the correct pid. Basically this check make the error message 4-13 meaning less... But you can always remove this check if you prefer the error instead of a no-good action (which is to move the record to its own page...)
2707 if ($destPid<0 && !$sortRow) {
2708 $destPid = $resolvedPid;
2709 }
2710
2711 // Timestamp field:
2712 $updateFields = array();
2713 if ($TCA[$table]['ctrl']['tstamp']) {
2714 $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
2715 }
2716
2717 // If moving is allowed, begin the processing:
2718 if ($mayMoveAccess) {
2719 if ($destPid>=0) { // insert as first element on page (where uid = $destPid)
2720 if ($mayInsertAccess) {
2721 if ($table!='pages' || $this->destNotInsideSelf ($destPid,$uid)) {
2722 $this->clear_cache($table,$uid); // clear cache before moving
2723
2724 $updateFields['pid'] = $destPid; // Setting PID
2725
2726 // table is sorted by 'sortby'
2727 if ($sortRow) {
2728 $sortNumber = $this->getSortNumber($table,$uid,$destPid);
2729 $updateFields[$sortRow] = $sortNumber;
2730 }
2731
2732 // Create query for update:
2733 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2734
2735 // Logging...
2736 $newPropArr = $this->getRecordProperties($table,$uid);
2737 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2738 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2739
2740 if ($destPid!=$propArr['pid']) {
2741 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
2742 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2743 } else {
2744 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2745 }
2746 $this->clear_cache($table,$uid); // clear cache after moving
2747 $this->fixUniqueInPid($table,$uid);
2748 // fixCopyAfterDuplFields
2749 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);} // origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
2750 } else {
2751 $destPropArr = $this->getRecordProperties('pages',$destPid);
2752 $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
2753 }
2754 }
2755 } else { // Put after another record
2756 if ($sortRow) { // table is being sorted
2757 $sortInfo = $this->getSortNumber($table,$uid,$destPid);
2758 $destPid = $sortInfo['pid']; // Setting the destPid to the new pid of the record.
2759 if (is_array($sortInfo)) { // If not an array, there was an error (which is already logged)
2760 if ($mayInsertAccess) {
2761 if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid)) {
2762 $this->clear_cache($table,$uid); // clear cache before moving
2763
2764 // We now update the pid and sortnumber
2765 $updateFields['pid'] = $destPid;
2766 $updateFields[$sortRow] = $sortInfo['sortNumber'];
2767 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2768
2769 // Logging...
2770 if ($table=='pages') {
2771 $thePositionID = $this->getInterfacePagePositionID($uid);
2772 } else {
2773 $thePositionID = 0;
2774 }
2775 $this->log($table,$uid,4,$thePositionID,0,'');
2776
2777 // Logging...
2778 $newPropArr = $this->getRecordProperties($table,$uid);
2779 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2780 if ($destPid!=$propArr['pid']) {
2781 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2782 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
2783 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2784 } else {
2785 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2786 }
2787
2788 // clear cache after moving
2789 $this->clear_cache($table,$uid);
2790
2791 // fixUniqueInPid
2792 $this->fixUniqueInPid($table,$uid);
2793
2794 // fixCopyAfterDuplFields
2795 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
2796 } else {
2797 $destPropArr = $this->getRecordProperties('pages',$destPid);
2798 $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
2799 }
2800 }
2801 }
2802 } else {
2803 $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after another record, although the table has no sorting row.",13,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
2804 }
2805 }
2806 } else {
2807 $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
2808 }
2809 }
2810 }
2811
2812 /**
2813 * Copying records
2814 *
2815 * @param string Element table
2816 * @param integer Element UID
2817 * @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
2818 * @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
2819 * @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!
2820 * @param string Commalist of fields to exclude from the copy process (might get default values)
2821 * @return void
2822 */
2823 function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='') {
2824 global $TCA;
2825
2826 $uid = intval($uid);
2827 if ($TCA[$table] && $uid) {
2828 t3lib_div::loadTCA($table);
2829 if ($this->doesRecordExist($table,$uid,'show')) { // This checks if the record can be selected which is all that a copy action requires.
2830 $data = Array();
2831
2832 $nonFields = array_unique(t3lib_div::trimExplode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,t3ver_oid,t3ver_id,t3ver_label,'.$excludeFields,1));
2833
2834 $row = $this->recordInfo($table,$uid,'*');
2835 if (is_array($row)) {
2836
2837 // Initializing:
2838 $theNewID = uniqid('NEW');
2839 $enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ? $TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
2840 $headerField = $TCA[$table]['ctrl']['label'];
2841
2842 // Getting default data:
2843 $defaultData = $this->newFieldArray($table);
2844
2845 // Getting "copy-after" fields if applicable:
2846 // origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
2847 $copyAfterFields = $destPid<0 ? $this->fixCopyAfterDuplFields($table,$uid,abs($destPid),0) : array();
2848
2849 // Page TSconfig related:
2850 $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...
2851 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2852 $tE = $this->getTableEntries($table,$TSConfig);
2853
2854 // Traverse ALL fields of the selected record:
2855 foreach($row as $field => $value) {
2856 if (!in_array($field,$nonFields)) {
2857
2858 // Get TCA configuration for the field:
2859 $conf = $TCA[$table]['columns'][$field]['config'];
2860
2861 // Preparation/Processing of the value:
2862 if ($field=='pid') { // "pid" is hardcoded of course:
2863 $value = $destPid;
2864 } elseif (isset($overrideValues[$field])) { // Override value...
2865 $value = $overrideValues[$field];
2866 } elseif (isset($copyAfterFields[$field])) { // Copy-after value if available:
2867 $value = $copyAfterFields[$field];
2868 } elseif ($TCA[$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div::inList($TCA[$table]['ctrl']['setToDefaultOnCopy'],$field)) { // Revert to default for some fields:
2869 $value = $defaultData[$field];
2870 } else {
2871 // Hide at copy may override:
2872 if ($first && $field==$enableField && $TCA[$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy']) {
2873 $value=1;
2874 }
2875 // Prepend label on copy:
2876 if ($first && $field==$headerField && $TCA[$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
2877 $value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
2878 }
2879 // Processing based on the TCA config field type (files, references, flexforms...)
2880 $value = $this->copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf);
2881 }
2882
2883 // Add value to array.
2884 $data[$table][$theNewID][$field] = $value;
2885 }
2886
2887 // Overriding values:
2888 if ($TCA[$table]['ctrl']['editlock']) {
2889 $data[$table][$theNewID][$TCA[$table]['ctrl']['editlock']] = 0;
2890 }
2891 }
2892
2893 // Do the copy by simply submitting the array through TCEmain:
2894 $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
2895 $c