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