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