b0a4739a56a312aa617dc8b3fcfd1953cf985eeb
[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 } // if ($recordAccess) {
607 } // if (is_array($incomingFieldArray)) {
608 }
609 }
610 }
611 $this->dbAnalysisStoreExec();
612 $this->removeRegisteredFiles();
613 }
614
615 /**
616 * Filling in the field array
617 * $this->exclude_array is used to filter fields if needed.
618 *
619 * @param string Table name
620 * @param [type] $id: ...
621 * @param array Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
622 * @param array $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
623 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
624 * @param string $status = 'new' or 'update'
625 * @param [type] $tscPID: ...
626 * @return [type] ...
627 */
628 function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID) {
629 global $TCA;
630
631 // Initialize:
632 t3lib_div::loadTCA($table);
633 unset($originalLanguageRecord);
634 unset($originalLanguage_diffStorage);
635 $diffStorageFlag = FALSE;
636
637 // Setting 'currentRecord' and 'checkValueRecord':
638 if (strstr($id,'NEW')) {
639 $currentRecord = $checkValueRecord = $fieldArray; // must have the 'current' array - not the values after processing below...
640
641 // IF $incomingFieldArray is an array, overlay it.
642 // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
643 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
644 $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
645 }
646 } else {
647 $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
648
649 // Get original language record if available:
650 if (is_array($currentRecord)
651 && $TCA[$table]['ctrl']['transOrigDiffSourceField']
652 && $TCA[$table]['ctrl']['languageField']
653 && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
654 && $TCA[$table]['ctrl']['transOrigPointerField']
655 && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0) {
656
657 $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
658 $originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
659 $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
660 }
661 }
662 $this->checkValue_currentRecord = $checkValueRecord;
663
664 /*
665 In the following all incoming value-fields are tested:
666 - Are the user allowed to change the field?
667 - Is the field uid/pid (which are already set)
668 - perms-fields for pages-table, then do special things...
669 - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
670
671 If everything is OK, the field is entered into $fieldArray[]
672 */
673 foreach($incomingFieldArray as $field => $fieldValue) {
674 if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) { // The field must be editable.
675
676 // Checking language:
677 $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);
678
679 if (!$languageDeny) {
680 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
681 if ($this->stripslashes_values) {
682 if (is_array($fieldValue)) {
683 t3lib_div::stripSlashesOnArray($fieldValue);
684 } else $fieldValue = stripslashes($fieldValue);
685 }
686
687 switch ($field) {
688 case 'uid':
689 case 'pid':
690 // Nothing happens, already set
691 break;
692 case 'perms_userid':
693 case 'perms_groupid':
694 case 'perms_user':
695 case 'perms_group':
696 case 'perms_everybody':
697 // Permissions can be edited by the owner or the administrator
698 if ($table=='pages' && ($this->admin || $status=='new' || $this->pageInfo($id,'perms_userid')==$this->userid) ) {
699 $value=intval($fieldValue);
700 switch($field) {
701 case 'perms_userid':
702 $fieldArray[$field]=$value;
703 break;
704 case 'perms_groupid':
705 $fieldArray[$field]=$value;
706 break;
707 default:
708 if ($value>=0 && $value<pow(2,5)) {
709 $fieldArray[$field]=$value;
710 }
711 break;
712 }
713 }
714 break;
715 case 't3ver_oid':
716 case 't3ver_id':
717 // t3ver_label is not here because it CAN be edited as a regular field!
718 break;
719 default:
720 if (isset($TCA[$table]['columns'][$field])) {
721 // Evaluating the value.
722 $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
723 if (isset($res['value'])) {
724 $fieldArray[$field]=$res['value'];
725
726 // Add the value of the original record to the diff-storage content:
727 if ($TCA[$table]['ctrl']['transOrigDiffSourceField']) {
728 $originalLanguage_diffStorage[$field] = $originalLanguageRecord[$field];
729 $diffStorageFlag = TRUE;
730 }
731 }
732 }
733
734
735 break;
736 }
737 } // Checking language.
738 } // Check exclude fields / disabled fields...
739 }
740
741 // Add diff-storage information:
742 if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']])) { // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
743 $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
744 }
745
746 // Checking for RTE-transformations of fields:
747 $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
748 $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
749 if (is_array($types_fieldConfig)) {
750 reset($types_fieldConfig);
751 while(list(,$vconf) = each($types_fieldConfig)) {
752 // Write file configuration:
753 $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray)); // inserted array_merge($currentRecord,$fieldArray) 170502
754
755 // RTE transformations:
756 if (!$this->dontProcessTransformations) {
757 if (isset($fieldArray[$vconf['field']])) {
758 // Look for transformation flag:
759 switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']]) {
760 case 'RTE':
761 $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
762 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
763
764 // Set alternative relative path for RTE images/links:
765 $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
766
767 // Get RTE object, draw form and set flag:
768 $RTEobj = &t3lib_BEfunc::RTEgetObj();
769 if (is_object($RTEobj)) {
770 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
771 } else {
772 debug('NO RTE OBJECT FOUND!');
773 }
774 break;
775 }
776 }
777 }
778
779 // Write file configuration:
780 if (is_array($eFile)) {
781 $mixedRec = array_merge($currentRecord,$fieldArray);
782 $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
783 $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
784 $parseHTML->init('','');
785
786 $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
787 $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
788
789 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, chr(10).$insertContent.chr(10), 1, 1);
790 t3lib_div::writeFile($eFile['editFile'],$SW_fileNewContent);
791
792 // Write status:
793 if (!strstr($id,'NEW') && $eFile['statusField']) {
794 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
795 $table,
796 'uid='.intval($id),
797 array(
798 $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
799 )
800 );
801 }
802 } elseif ($eFile && is_string($eFile)) {
803 $this->log($insertTable,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
804 }
805 }
806 }
807 // Return fieldArray
808 return $fieldArray;
809 }
810
811 /**
812 * Checking group modify_table access list
813 *
814 * Returns true if the user has general access to modify the $table
815 *
816 * @param [type] $table: ...
817 * @return [type] ...
818 */
819 function checkModifyAccessList($table) {
820 $res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData['tables_modify'],$table)));
821 return $res;
822 }
823
824 /**
825 * [Describe function...]
826 *
827 * @param [type] $table: ...
828 * @param [type] $id: ...
829 * @return [type] ...
830 */
831 function isRecordInWebMount($table,$id) {
832 if (!isset($this->isRecordInWebMount_Cache[$table.':'.$id])) {
833 $recP=$this->getRecordProperties($table,$id);
834 $this->isRecordInWebMount_Cache[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
835 }
836 return $this->isRecordInWebMount_Cache[$table.':'.$id];
837 }
838
839 /**
840 * [Describe function...]
841 *
842 * @param [type] $pid: ...
843 * @return [type] ...
844 */
845 function isInWebMount($pid) {
846 if (!isset($this->isInWebMount_Cache[$pid])) {
847 $this->isInWebMount_Cache[$pid]=$this->BE_USER->isInWebMount($pid);
848 }
849 //debug($this->isInWebMount_Cache);
850 return $this->isInWebMount_Cache[$pid];
851 }
852
853 /**
854 * Checks if user may update a certain record.
855 *
856 * Returns true if the user may update the record given by $table and $id
857 *
858 * @param [type] $table: ...
859 * @param [type] $id: ...
860 * @return [type] ...
861 */
862 function checkRecordUpdateAccess($table,$id) {
863 global $TCA;
864 $res = 0;
865 if ($TCA[$table] && intval($id)>0) {
866 if (isset($this->recUpdateAccessCache[$table][$id])) { // If information is cached, return it
867 return $this->recUpdateAccessCache[$table][$id];
868 // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
869 } elseif ($this->doesRecordExist($table,$id,'edit')) {
870 $res = 1;
871 }
872 $this->recUpdateAccessCache[$table][$id]=$res; // Cache the result
873 }
874 return $res;
875 }
876
877 /**
878 * Checks if user may insert a certain record.
879 *
880 * Returns true if the user may insert a record from table $insertTable on page $pid
881 *
882 * @param [type] $insertTable: ...
883 * @param [type] $pid: ...
884 * @param [type] $action: ...
885 * @return [type] ...
886 */
887 function checkRecordInsertAccess($insertTable,$pid,$action=1) {
888 global $TCA;
889 $res = 0;
890 $pid = intval($pid);
891 if ($pid>=0) {
892 if (isset($this->recInsertAccessCache[$insertTable][$pid])) { // If information is cached, return it
893 return $this->recInsertAccessCache[$insertTable][$pid];
894 } else {
895 // If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
896 if ( (!$pid && $this->admin) || $this->doesRecordExist('pages',$pid,($insertTable=='pages'?$this->pMap['new']:$this->pMap['editcontent'])) ) { // Check permissions
897 if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
898 $res = 1;
899 $this->recInsertAccessCache[$insertTable][$pid]=$res; // Cache the result
900 } else {
901 $propArr = $this->getRecordProperties('pages',$pid);
902 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert record on page '%s' (%s) where this table, %s, is not allowed",11,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
903 }
904 } else {
905 $propArr = $this->getRecordProperties('pages',$pid);
906 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert a record on page '%s' (%s) from table '%s' without permissions. Or non-existing page.",12,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
907 }
908 }
909 }
910 return $res;
911 }
912
913 /**
914 * Checks is a table is allowed on a certain page.
915 *
916 * $checkTable is the tablename
917 * $page_uid is the uid of the page to check
918 *
919 * @param [type] $page_uid: ...
920 * @param [type] $checkTable: ...
921 * @return [type] ...
922 */
923 function isTableAllowedForThisPage($page_uid, $checkTable) {
924 global $TCA, $PAGES_TYPES;
925 $page_uid = intval($page_uid);
926
927 // Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
928 if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages') {
929 return false;
930 }
931
932 // Check root-level
933 if (!$page_uid) {
934 if ($this->admin) {
935 return true;
936 }
937 } else {
938 // Check non-root-level
939 $doktype = $this->pageInfo($page_uid,'doktype');
940 $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
941 $allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
942 if (strstr($allowedTableList,'*') || in_array($checkTable,$allowedArray)) { // If all tables or the table is listed as a allowed type, return true
943 return true;
944 }
945 }
946 }
947
948 /**
949 * Checks if record exists
950 *
951 * Returns true if the record given by $table, $id and $perms
952 *
953 * @param string Record table name
954 * @param integer Record UID
955 * @param mixed Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array
956 * @return [type] ...
957 */
958 function doesRecordExist($table,$id,$perms) {
959 global $TCA;
960
961 $res = 0;
962 $id = intval($id);
963
964 // Processing the incoming $perms (from possible string to integer that can be AND'ed)
965 if (!t3lib_div::testInt($perms)) {
966 if ($table!='pages') {
967 switch($perms) {
968 case 'edit':
969 case 'delete':
970 case 'new':
971 $perms = 'editcontent'; // This holds it all in case the record is not page!!
972 break;
973 }
974 }
975 $perms = intval($this->pMap[$perms]);
976 } else {
977 $perms = intval($perms);
978 }
979
980 if (!$perms) {debug('Internal ERROR: no permissions to check for non-admin user.');}
981
982 // For all tables: Check if record exists:
983 // Notice: If $perms are 0 (zero) no perms-clause is added!
984 if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) || $this->admin)) {
985 if ($table != 'pages') {
986
987 // Find record without checking page:
988 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid', $table, 'uid='.intval($id).$this->deleteClause($table));
989 $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
990 t3lib_BEfunc::fixVersioningPid($table,$output);
991
992 // If record found, check page as well:
993 if (is_array($output)) {
994
995 // Looking up the page for record:
996 $mres = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
997 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
998
999 // Return true if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
1000 if (is_array($pageRec) || (!$output['pid'] && $this->admin)) {
1001 return TRUE;
1002 }
1003 }
1004 return FALSE;
1005 } else {
1006 $mres = $this->doesRecordExist_pageLookUp($id, $perms);
1007 return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
1008 }
1009 }
1010 }
1011
1012 /**
1013 * Looks up a page based on permissions.
1014 *
1015 * @param integer Page id
1016 * @param integer Permission integer
1017 * @return pointer MySQL result pointer (from exec_SELECTquery())
1018 * @access private
1019 * @see doesRecordExist()
1020 */
1021 function doesRecordExist_pageLookUp($id, $perms) {
1022 global $TCA;
1023
1024 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1025 'uid',
1026 'pages',
1027 'uid='.intval($id).
1028 $this->deleteClause('pages').
1029 ($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '').
1030 (!$this->admin && $TCA['pages']['ctrl']['editlock'] && ($perms & (2+4+16)) ? ' AND '.$TCA['pages']['ctrl']['editlock'].'=0':'') // admin users don't need check
1031 );
1032 }
1033
1034 /**
1035 * Checks if a whole branch of pages exists
1036 *
1037 * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
1038 * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
1039 * if $recurse is set, then the function will follow subpages. This MUST be set, if we need the idlist for deleting pages or else we get an incomplete list
1040 *
1041 * @param [type] $inList: ...
1042 * @param [type] $pid: ...
1043 * @param [type] $perms: ...
1044 * @param [type] $recurse: ...
1045 * @return [type] ...
1046 */
1047 function doesBranchExist($inList,$pid,$perms, $recurse) {
1048 global $TCA;
1049 $pid = intval($pid);
1050 $perms = intval($perms);
1051 if ($pid>=0) {
1052 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1053 'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
1054 'pages',
1055 'pid='.intval($pid).$this->deleteClause('pages'),
1056 '',
1057 'sorting'
1058 );
1059 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1060 if ($this->admin || $this->BE_USER->doesUserHaveAccess($row,$perms)) { // IF admin, then it's OK
1061 $inList.=$row['uid'].',';
1062 if ($recurse) { // Follow the subpages recursively...
1063 $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
1064 if ($inList == -1) {return -1;} // No permissions somewhere in the branch
1065 }
1066 } else {
1067 return -1; // No permissions
1068 }
1069 }
1070 }
1071 return $inList;
1072 }
1073
1074 /**
1075 * Returns the value of the $field from page $id
1076 * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performanceloss since it doesn't look up the same record twice!
1077 *
1078 * @param integer Page uid
1079 * @param string Field name for which to return value
1080 * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
1081 */
1082 function pageInfo($id,$field) {
1083 if (!isset($this->pageCache[$id])) {
1084 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
1085 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1086 $this->pageCache[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1087 }
1088 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1089 }
1090 return $this->pageCache[$id][$field];
1091 }
1092
1093 /**
1094 * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
1095 * NOTICE: No check for deleted or access!
1096 *
1097 * @param string Table name
1098 * @param integer UID of the record from $table
1099 * @param string Field list for the SELECT query, eg. "*" or "uid,pid,..."
1100 * @return mixed Returns the selected record on success, otherwise false.
1101 */
1102 function recordInfo($table,$id,$fieldList) {
1103 global $TCA;
1104 if (is_array($TCA[$table])) {
1105 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
1106 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1107 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1108 }
1109 }
1110 }
1111
1112 /**
1113 * Returns an array with record properties, like header and pid
1114 *
1115 * @param [type] $table: ...
1116 * @param [type] $id: ...
1117 * @return [type] ...
1118 */
1119 function getRecordProperties($table,$id) {
1120 $row = ($table=='pages' && !$id) ? array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
1121 t3lib_BEfunc::fixVersioningPid($table,$row);
1122 return $this->getRecordPropertiesFromRow($table,$row);
1123 }
1124
1125 /**
1126 * Returns an array with record properties, like header and pid, based on the row
1127 *
1128 * @param [type] $table: ...
1129 * @param [type] $row: ...
1130 * @return [type] ...
1131 */
1132 function getRecordPropertiesFromRow($table,$row) {
1133 global $TCA;
1134 if ($TCA[$table]) {
1135 $out = array(
1136 'header' => $row[$TCA[$table]['ctrl']['label']],
1137 'pid' => $row['pid'],
1138 'event_pid' => ($table=='pages'?$row['uid']:$row['pid'])
1139 );
1140 return $out;
1141 }
1142 }
1143
1144 /**
1145 * [Describe function...]
1146 *
1147 * @param [type] $fieldArray: ...
1148 * @param [type] $TSConfig_p: ...
1149 * @return [type] ...
1150 */
1151 function setTSconfigPermissions($fieldArray,$TSConfig_p) {
1152 if (strcmp($TSConfig_p['userid'],'')) $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
1153 if (strcmp($TSConfig_p['groupid'],'')) $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
1154 if (strcmp($TSConfig_p['user'],'')) $fieldArray['perms_user']=t3lib_div::testInt($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
1155 if (strcmp($TSConfig_p['group'],'')) $fieldArray['perms_group']=t3lib_div::testInt($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
1156 if (strcmp($TSConfig_p['everybody'],'')) $fieldArray['perms_everybody']=t3lib_div::testInt($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
1157
1158 return $fieldArray;
1159 }
1160
1161 /**
1162 * Returns a fieldArray with default values.
1163 *
1164 * @param [type] $table: ...
1165 * @return [type] ...
1166 */
1167 function newFieldArray($table) {
1168 global $TCA;
1169 t3lib_div::loadTCA($table);
1170 $fieldArray=Array();
1171 if (is_array($TCA[$table]['columns'])) {
1172 reset ($TCA[$table]['columns']);
1173 while (list($field,$content)=each($TCA[$table]['columns'])) {
1174 if (isset($this->defaultValues[$table][$field])) {
1175 $fieldArray[$field] = $this->defaultValues[$table][$field];
1176 } elseif (isset($content['config']['default'])) {
1177 $fieldArray[$field] = $content['config']['default'];
1178 }
1179 }
1180 }
1181 if ($table=='pages') { // Set default permissions for a page.
1182 $fieldArray['perms_userid'] = $this->userid;
1183 $fieldArray['perms_groupid'] = intval($this->BE_USER->firstMainGroup);
1184 $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions['user']);
1185 $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions['group']);
1186 $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions['everybody']);
1187 }
1188 return $fieldArray;
1189 }
1190
1191 /**
1192 * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
1193 *
1194 * @param [type] $table: ...
1195 * @param [type] $data: ...
1196 * @return [type] ...
1197 */
1198 function overrideFieldArray($table,$data) {
1199 if (is_array($this->overrideValues[$table])) {
1200 $data = array_merge($data,$this->overrideValues[$table]); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1201 }
1202 return $data;
1203 }
1204
1205 /**
1206 * Calculates the bitvalue of the permissions given in a string, comma-sep
1207 *
1208 * @param [type] $string: ...
1209 * @return [type] ...
1210 */
1211 function assemblePermissions($string) {
1212 $keyArr = t3lib_div::trimExplode(',',$string,1);
1213 $value=0;
1214 while(list(,$key)=each($keyArr)) {
1215 if ($key && isset($this->pMap[$key])) {
1216 $value |= $this->pMap[$key];
1217 }
1218 }
1219 return $value;
1220 }
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241 /*********************************************
1242 *
1243 * Evaluation of input values
1244 *
1245 ********************************************/
1246
1247 /**
1248 * Evaluates a value according to $table/$field settings.
1249 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1250 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
1251 *
1252 * @param string Table name
1253 * @param string Field name
1254 * @param string Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1255 * @param string The record-uid, mainly - but not exclusively - used for logging
1256 * @param string 'update' or 'new' flag
1257 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1258 * @param integer $tscPID
1259 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1260 */
1261 function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID) {
1262 global $TCA, $PAGES_TYPES;
1263 t3lib_div::loadTCA($table);
1264
1265 $res = Array(); // result array
1266 $recFID = $table.':'.$id.':'.$field;
1267
1268 // Processing special case of field pages.doktype
1269 if ($table=='pages' && $field=='doktype') {
1270 // If the user may not use this specific doktype, we issue a warning
1271 if (! ($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'],$value))) {
1272 $propArr = $this->getRecordProperties($table,$id);
1273 $this->log($table,$id,5,0,1,"You cannot change the 'doktype' of page '%s' to the desired value.",1,array($propArr['header']),$propArr['event_pid']);
1274 return $res;
1275 };
1276 if ($status=='update') {
1277 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1278 $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ? $PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
1279 if ($onlyAllowedTables) {
1280 $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
1281 if ($theWrongTables) {
1282 $propArr = $this->getRecordProperties($table,$id);
1283 $this->log($table,$id,5,0,1,"'doktype' of page '%s' could not be changed because the page contains records from disallowed tables; %s",2,array($propArr['header'],$theWrongTables),$propArr['event_pid']);
1284 return $res;
1285 }
1286 }
1287 }
1288 }
1289
1290 // Get current value:
1291 $curValueRec = $this->recordInfo($table,$id,$field);
1292 $curValue = $curValueRec[$field];
1293
1294 // Getting config for the field
1295 $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
1296
1297 // Preform processing:
1298 $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);
1299
1300 return $res;
1301 }
1302
1303 /**
1304 * Branches out evaluation of a field value based on its type as configured in TCA
1305 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1306 *
1307 * @param array The result array. The processed value (if any!) is set in the "value" key.
1308 * @param string The value to set.
1309 * @param array Field configuration from TCA
1310 * @param string Table name
1311 * @param integer Return UID
1312 * @param [type] $curValue: ...
1313 * @param [type] $status: ...
1314 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1315 * @param [type] $recFID: ...
1316 * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1317 * @param [type] $uploadedFiles: ...
1318 * @param [type] $tscPID: ...
1319 * @return array Returns the evaluated $value as key "value" in this array.
1320 */
1321 function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID) {
1322
1323 $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
1324
1325 switch ($tcaFieldConf['type']) {
1326 case 'text':
1327 case 'passthrough':
1328 case 'user':
1329 $res['value'] = $value;
1330 break;
1331 case 'input':
1332 $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
1333 break;
1334 case 'check':
1335 $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
1336 break;
1337 case 'radio':
1338 $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
1339 break;
1340 case 'group':
1341 case 'select':
1342 $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1343 break;
1344 case 'flex':
1345 if ($field) { // FlexForms are only allowed for real fields.
1346 $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1347 }
1348 break;
1349 default:
1350 #debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
1351 break;
1352 }
1353
1354 return $res;
1355 }
1356
1357 /**
1358 * Evaluate "input" type values.
1359 *
1360 * @param array The result array. The processed value (if any!) is set in the "value" key.
1361 * @param string The value to set.
1362 * @param array Field configuration from TCA
1363 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1364 * @param string Field name
1365 * @return array Modified $res array
1366 */
1367 function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='') {
1368 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1369
1370 // Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
1371 if (intval($tcaFieldConf['max'])>0) {$value = substr($value,0,intval($tcaFieldConf['max']));}
1372
1373 // Checking range of value:
1374 if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox']) { // If value is not set to the allowed checkbox-value then it is checked against the ranges
1375 if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper']) {$value=$tcaFieldConf['range']['upper'];}
1376 if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower']) {$value=$tcaFieldConf['range']['lower'];}
1377 }
1378
1379 // Process evaluation settings:
1380 $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
1381 $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
1382
1383 // Process UNIQUE settings:
1384 if ($field && $realPid>=0) { // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
1385 if ($res['value'] && in_array('uniqueInPid',$evalCodesArray)) {
1386 $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
1387 }
1388 if ($res['value'] && in_array('unique',$evalCodesArray)) {
1389 $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
1390 }
1391 }
1392
1393 return $res;
1394 }
1395
1396 /**
1397 * Evaluates 'check' type values.
1398 *
1399 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1400 * @param string The value to set.
1401 * @param array Field configuration from TCA
1402 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1403 * @return array Modified $res array
1404 */
1405 function checkValue_check($res,$value,$tcaFieldConf,$PP) {
1406 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1407
1408 $itemC = count($tcaFieldConf['items']);
1409 if (!$itemC) {$itemC=1;}
1410 $maxV = pow(2,$itemC);
1411
1412 if ($value<0) {$value=0;}
1413 if ($value>$maxV) {$value=$maxV;}
1414 $res['value'] = $value;
1415
1416 return $res;
1417 }
1418
1419 /**
1420 * Evaluates 'radio' type values.
1421 *
1422 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1423 * @param string The value to set.
1424 * @param array Field configuration from TCA
1425 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1426 * @return array Modified $res array
1427 */
1428 function checkValue_radio($res,$value,$tcaFieldConf,$PP) {
1429 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1430
1431 if (is_array($tcaFieldConf['items'])) {
1432 foreach($tcaFieldConf['items'] as $set) {
1433 if (!strcmp($set[1],$value)) {
1434 $res['value'] = $value;
1435 break;
1436 }
1437 }
1438 }
1439
1440 return $res;
1441 }
1442
1443 /**
1444 * Evaluates 'group' or 'select' type values.
1445 *
1446 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1447 * @param string The value to set.
1448 * @param array Field configuration from TCA
1449 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1450 * @param [type] $uploadedFiles: ...
1451 * @param string Field name
1452 * @return array Modified $res array
1453 */
1454 function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1455 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1456
1457 // Detecting if value send is an array and if so, implode it around a comma:
1458 if (is_array($value)) {
1459 $value = implode(',',$value);
1460 }
1461
1462 // This converts all occurencies of '&#123;' to the byte 123 in the string - this is needed in very rare cases where filenames with special characters (like æøå, umlaud etc) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
1463 // Anyways, this should NOT disturb anything else:
1464 $value = $this->convNumEntityToByteValue($value);
1465
1466 // When values are send as group or select they come as comma-separated values which are exploded by this function:
1467 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1468
1469 // If not multiple is set, then remove duplicates:
1470 if (!$tcaFieldConf['multiple']) {
1471 $valueArray = array_unique($valueArray);
1472 }
1473
1474 // This could be a good spot for parsing the array through a validation-function which checks if the values are allright (except that database references are not in their final form - but that is the point, isn't it?)
1475 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1476
1477 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1478 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode']) {
1479 $preCount = count($valueArray);
1480 foreach($valueArray as $kk => $vv) {
1481 if (!$this->BE_USER->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode'])) {
1482 unset($valueArray[$kk]);
1483 }
1484 }
1485
1486 // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
1487 if ($preCount && !count($valueArray)) {
1488 return array();
1489 }
1490 }
1491
1492 // For group types:
1493 if ($tcaFieldConf['type']=='group') {
1494 switch($tcaFieldConf['internal_type']) {
1495 case 'file':
1496 $valueArray = $this->checkValue_group_select_file(
1497 $valueArray,
1498 $tcaFieldConf,
1499 $curValue,
1500 $uploadedFiles,
1501 $status,
1502 $table,
1503 $id,
1504 $recFID
1505 );
1506 break;
1507 case 'db':
1508 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group');
1509 break;
1510 }
1511 }
1512 // For select types which has a foreign table attached:
1513 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table']) {
1514 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select');
1515 }
1516
1517 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
1518
1519 // Checking the number of items, that it is correct.
1520 // If files, there MUST NOT be too many files in the list at this point, so check that prior to this code.
1521 $valueArrayC = count($valueArray);
1522 $minI = isset($tcaFieldConf['minitems']) ? intval($tcaFieldConf['minitems']):0;
1523
1524 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
1525 $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']):1;
1526 if ($valueArrayC > $maxI) {$valueArrayC=$maxI;} // Checking for not too many elements
1527
1528 // Dumping array to list
1529 $newVal=array();
1530 foreach($valueArray as $nextVal) {
1531 if ($valueArrayC==0) {break;}
1532 $valueArrayC--;
1533 $newVal[]=$nextVal;
1534 }
1535 $res['value'] = implode(',',$newVal);
1536
1537 return $res;
1538 }
1539
1540 /**
1541 * Handling files for group/select function
1542 *
1543 * @param [type] $valueArray: ...
1544 * @param [type] $tcaFieldConf: ...
1545 * @param [type] $curValue: ...
1546 * @param [type] $uploadedFileArray: ...
1547 * @param [type] $status: ...
1548 * @param [type] $table: ...
1549 * @param [type] $id: ...
1550 * @param [type] $recFID: ...
1551 * @return array Modified value array
1552 * @see checkValue_group_select()
1553 */
1554 function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID) {
1555
1556 // If any files are uploaded:
1557 if (is_array($uploadedFileArray) &&
1558 $uploadedFileArray['name'] &&
1559 strcmp($uploadedFileArray['tmp_name'],'none')) {
1560 $valueArray[]=$uploadedFileArray['tmp_name'];
1561 $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1562 }
1563
1564 // Creating fileFunc object.
1565 if (!$this->fileFunc) {
1566 $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
1567 $this->include_filefunctions=1;
1568 }
1569 // Setting permitted extensions.
1570 $all_files = Array();
1571 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1572 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
1573 $all_files['ftpspace'] = $all_files['webspace'];
1574 $this->fileFunc->init('', $all_files);
1575
1576 // If there is an upload folder defined:
1577 if ($tcaFieldConf['uploadfolder']) {
1578 // For logging..
1579 $propArr = $this->getRecordProperties($table,$id);
1580
1581 // Get destrination path:
1582 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1583
1584 // If we are updating:
1585 if ($status=='update') {
1586
1587 // Finding the CURRENT files listed, either from MM or from the current record.
1588 $theFileValues=array();
1589 if ($tcaFieldConf['MM']) { // If MM relations for the files also!
1590 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1591 $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
1592 reset($dbAnalysis->itemArray);
1593 while (list($somekey,$someval)=each($dbAnalysis->itemArray)) {
1594 if ($someval['id']) {
1595 $theFileValues[]=$someval['id'];
1596 }
1597 }
1598 } else {
1599 $theFileValues=t3lib_div::trimExplode(',',$curValue,1);
1600 }
1601
1602 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1603 if (count($theFileValues)) {
1604 // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
1605 foreach($valueArray as $key => $theFile) {
1606 if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
1607 $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues,$theFile);
1608 }
1609 }
1610
1611 // This array contains the filenames in the uploadfolder that should be deleted:
1612 foreach($theFileValues as $key => $theFile) {
1613 $theFile = trim($theFile);
1614 if (@is_file($dest.'/'.$theFile)) {
1615 $this->removeFilesStore[]=$dest.'/'.$theFile;
1616 } elseif ($theFile) {
1617 $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
1618 }
1619 }
1620 }
1621 }
1622
1623 // Traverse the submitted values:
1624 foreach($valueArray as $key => $theFile) {
1625 // NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1626 if (strstr(t3lib_div::fixWindowsFilePath($theFile),'/')) {
1627 // Init:
1628 $maxSize = intval($tcaFieldConf['max_size']);
1629 $cmd='';
1630 $theDestFile=''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!! (Change: 22/12/2000)
1631
1632 // Check various things before copying file:
1633 if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist
1634
1635 // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
1636 if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name']) {
1637 $fileSize = $uploadedFileArray['size'];
1638 } else {
1639 $fileSize = filesize($theFile);
1640 }
1641
1642 if (!$maxSize || $fileSize<=($maxSize*1024)) { // Check file size:
1643 // Prepare filename:
1644 $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
1645 $fI = t3lib_div::split_fileref($theEndFileName);
1646
1647 // Check for allowed extension:
1648 if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1649 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
1650
1651 // If we have a unique destination filename, then write the file:
1652 if ($theDestFile) {
1653 t3lib_div::upload_copy_move($theFile,$theDestFile);
1654 $this->copiedFileMap[$theFile] = $theDestFile;
1655 clearstatcache();
1656 if (!@is_file($theDestFile)) $this->log($table,$id,5,0,1,"Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)",16,array($theFile, dirname($theDestFile), $recFID),$propArr['event_pid']);
1657 } else $this->log($table,$id,5,0,1,"Copying file '%s' failed!: No destination file (%s) possible!. (%s)",11,array($theFile, $theDestFile, $recFID),$propArr['event_pid']);
1658 } else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
1659 } else $this->log($table,$id,5,0,1,"Filesize (%s) of file '%s' exceeds limit (%s). (%s)",13,array(t3lib_div::formatSize($fileSize),$theFile,t3lib_div::formatSize($maxSize*1024),$recFID),$propArr['event_pid']);
1660 } else $this->log($table,$id,5,0,1,'The destination (%s) or the source file (%s) does not exist. (%s)',14,array($dest, $theFile, $recFID),$propArr['event_pid']);
1661
1662 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1663 if (@is_file($theDestFile)) {
1664 $info = t3lib_div::split_fileref($theDestFile);
1665 $valueArray[$key]=$info['file']; // The value is set to the new filename
1666 } else {
1667 unset($valueArray[$key]); // The value is set to the new filename
1668 }
1669 }
1670 }
1671
1672 // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
1673 if ($tcaFieldConf['MM']) {
1674 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
1675 $dbAnalysis->tableArray['files']=array(); // dummy
1676
1677 reset($valueArray);
1678 while (list($key,$theFile)=each($valueArray)) {
1679 // explode files
1680 $dbAnalysis->itemArray[]['id']=$theFile;
1681 }
1682 if ($status=='update') {
1683 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
1684 } else {
1685 $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1686 }
1687 $cc=count($dbAnalysis->itemArray);
1688 $valueArray = array($cc);
1689 }
1690 }
1691
1692 return $valueArray;
1693 }
1694
1695 /**
1696 * Evaluates 'flex' type values.
1697 *
1698 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1699 * @param string The value to set.
1700 * @param array Field configuration from TCA
1701 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1702 * @param array Uploaded files for the field
1703 * @param array Current record array.
1704 * @param string Field name
1705 * @return array Modified $res array
1706 */
1707 function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1708 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1709
1710 if (is_array($value)) {
1711
1712 // Get current value array:
1713 $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table);
1714 #debug($this->checkValue_currentRecord);
1715 $currentValueArray = t3lib_div::xml2array($curValue);
1716 if (!is_array($currentValueArray)) $currentValueArray = array();
1717 if (is_array($currentValueArray['meta']['currentLangId'])) unset($currentValueArray['meta']['currentLangId']); // Remove all old meta for languages...
1718
1719 // Evaluation of input values:
1720 $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
1721
1722 // Create XML and convert charsets from input value:
1723 $xmlValue = $this->checkValue_flexArray2Xml($value);
1724
1725 // If we wanted to set UTF fixed:
1726 // $storeInCharset='utf-8';
1727 // $currentCharset=$GLOBALS['LANG']->charSet;
1728 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1729 $storeInCharset=$GLOBALS['LANG']->charSet;
1730
1731 // Merge them together IF they are both arrays:
1732 // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same (provided that the current value was already stored IN the charset that the new value is converted to).
1733 if (is_array($currentValueArray)) {
1734 $arrValue = t3lib_div::xml2array($xmlValue);
1735 $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
1736 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1737 }
1738
1739 // Temporary fix to delete flex form elements:
1740 $deleteCMDs = t3lib_div::_GP('_DELETE_FLEX_FORMdata');
1741 if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
1742 $arrValue = t3lib_div::xml2array($xmlValue);
1743 $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
1744 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1745 }
1746
1747 // Temporary fix to move flex form elements up:
1748 $moveCMDs = t3lib_div::_GP('_MOVEUP_FLEX_FORMdata');
1749 if (is_array($moveCMDs[$table][$id][$field]['data'])) {
1750 $arrValue = t3lib_div::xml2array($xmlValue);
1751 $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'up');
1752 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1753 }
1754
1755 // Temporary fix to move flex form elements down:
1756 $moveCMDs = t3lib_div::_GP('_MOVEDOWN_FLEX_FORMdata');
1757 if (is_array($moveCMDs[$table][$id][$field]['data'])) {
1758 $arrValue = t3lib_div::xml2array($xmlValue);
1759 $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'down');
1760 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1761 }
1762
1763 // Create the value XML:
1764 $res['value']='';
1765 $res['value'].='<?xml version="1.0" encoding="'.$storeInCharset.'" standalone="yes" ?>'.chr(10);
1766 $res['value'].=$xmlValue;
1767 } else { // Passthrough...:
1768 $res['value']=$value;
1769 }
1770
1771 return $res;
1772 }
1773
1774 /**
1775 * [Describe function...]
1776 *
1777 * @param [type] $array: ...
1778 * @return [type] ...
1779 */
1780 function checkValue_flexArray2Xml($array) {
1781 $output = t3lib_div::array2xml($array,'',0,'T3FlexForms',4,array('parentTagMap' => array(
1782 /* 'data' => 'sheets',
1783 'sheets' => 'language',
1784 'language' => 'fieldname',
1785 'el' => 'fieldname' */
1786 )));
1787 return $output;
1788 }
1789
1790 /**
1791 * Deletes a flex form element
1792 *
1793 * @param array &$valueArrayToRemoveFrom: by reference
1794 * @param [type] $deleteCMDS: ... *
1795 * @return void
1796 */
1797 function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS) {
1798 if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
1799 foreach($deleteCMDS as $key => $value) {
1800 if (is_array($deleteCMDS[$key])) {
1801 $this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
1802 } else {
1803 unset($valueArrayToRemoveFrom[$key]);
1804 }
1805 }
1806 }
1807 }
1808
1809 /**
1810 * Deletes a flex form element
1811 *
1812 * @param array &$valueArrayToMoveIn: by reference
1813 * @param [type] $moveCMDS: ... *
1814 * @param string $direction: 'up' or 'down'
1815 * @return void
1816 * TODO: Like _DELETE_FLEX_FORMdata, this is only a temporary solution!
1817 */
1818 function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction) {
1819 if (is_array($valueArrayToMoveIn) && is_array($moveCMDS)) {
1820
1821 // Only execute the first move command:
1822 list ($key, $value) = each ($moveCMDS);
1823
1824 if (is_array($moveCMDS[$key])) {
1825 $this->_MOVE_FLEX_FORMdata($valueArrayToMoveIn[$key],$moveCMDS[$key], $direction);
1826 } else {
1827 switch ($direction) {
1828 case 'up':
1829 if ($key > 1) {
1830 $tmpArr = $valueArrayToMoveIn[$key];
1831 $valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key-1];
1832 $valueArrayToMoveIn[$key-1] = $tmpArr;
1833 }
1834 break;
1835 case 'down':
1836 if ($key < count($valueArrayToMoveIn)) {
1837 $tmpArr = $valueArrayToMoveIn[$key];
1838 $valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key+1];
1839 $valueArrayToMoveIn[$key+1] = $tmpArr;
1840 }
1841 break;
1842 }
1843 }
1844 }
1845 }
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864 /*********************************************
1865 *
1866 * Helper functions for evaluation functions.
1867 *
1868 ********************************************/
1869
1870
1871 /**
1872 * Gets a unique value for $table/$id/$field based on $value
1873 *
1874 * @param string Table name
1875 * @param string Field name for which $value must be unique
1876 * @param string Value string.
1877 * @param integer UID to filter out in the lookup (the record itself...)
1878 * @param integer If set, the value will be unique for this PID
1879 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
1880 */
1881 function getUnique($table,$field,$value,$id,$newPid=0) {
1882 global $TCA;
1883
1884 // Initialize:
1885 t3lib_div::loadTCA($table);
1886 $whereAdd='';
1887 $newValue='';
1888 if (intval($newPid)) { $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AND pid>=0'; } // "AND pid>=0" for versioning
1889 $whereAdd.=$this->deleteClause($table);
1890
1891 // If the field is configured in TCA, proceed:
1892 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
1893
1894 // Look for a record which might already have the value:
1895 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table).' AND uid!='.intval($id).$whereAdd);
1896 $counter = 0;
1897
1898 // For as long as records with the test-value existing, try again (with incremented numbers appended).
1899 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1900 $newValue = $value.$counter;
1901 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table).' AND uid!='.intval($id).$whereAdd);
1902 $counter++;
1903 if ($counter>100) { break; } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
1904 }
1905 // If the new value is there:
1906 $value = strlen($newValue) ? $newValue : $value;
1907 }
1908 return $value;
1909 }
1910
1911 /**
1912 * Evaluation of 'input'-type values based on 'eval' list
1913 *
1914 * @param string Value
1915 * @param array Array of evaluations to traverse.
1916 * @param string Is-in string
1917 * @return string Modified $value
1918 */
1919 function checkValue_input_Eval($value,$evalArray,$is_in) {
1920 $res = Array();
1921 $newValue = $value;
1922 $set = true;
1923
1924 foreach($evalArray as $func) {
1925 switch($func) {
1926 case 'int':
1927 case 'year':
1928 case 'date':
1929 case 'datetime':
1930 case 'time':
1931 case 'timesec':
1932 $value = intval($value);
1933 break;
1934 case 'double2':
1935 $theDec = 0;
1936 for ($a=strlen($value); $a>0; $a--) {
1937 if (substr($value,$a-1,1)=='.' || substr($value,$a-1,1)==',') {
1938 $theDec = substr($value,$a);
1939 $value = substr($value,0,$a-1);
1940 break;
1941 }
1942 }
1943 $theDec = ereg_replace('[^0-9]','',$theDec).'00';
1944 $value = intval(str_replace(' ','',$value)).'.'.substr($theDec,0,2);
1945 break;
1946 case 'md5':
1947 if (strlen($value)!=32){$set=false;}
1948 break;
1949 case 'trim':
1950 $value = trim($value);
1951 break;
1952 case 'upper':
1953 $value = strtoupper($value);
1954 # $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.
1955 break;
1956 case 'lower':
1957 $value = strtolower($value);
1958 # $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.
1959 break;
1960 case 'required':
1961 if (!$value) {$set=0;}
1962 break;
1963 case 'is_in':
1964 $c=strlen($value);
1965 if ($c) {
1966 $newVal = '';
1967 for ($a=0;$a<$c;$a++) {
1968 $char = substr($value,$a,1);
1969 if (strstr($is_in,$char)) {
1970 $newVal.=$char;
1971 }
1972 }
1973 $value = $newVal;
1974 }
1975 break;
1976 case 'nospace':
1977 $value = str_replace(' ','',$value);
1978 break;
1979 case 'alpha':
1980 $value = ereg_replace('[^a-zA-Z]','',$value);
1981 break;
1982 case 'num':
1983 $value = ereg_replace('[^0-9]','',$value);
1984 break;
1985 case 'alphanum':
1986 $value = ereg_replace('[^a-zA-Z0-9]','',$value);
1987 break;
1988 case 'alphanum_x':
1989 $value = ereg_replace('[^a-zA-Z0-9_-]','',$value);
1990 break;
1991 }
1992 }
1993 if ($set) {$res['value'] = $value;}
1994 return $res;
1995 }
1996
1997 /**
1998 * Returns data for group/db and select fields
1999 *
2000 * @param array Current value array
2001 * @param array TCA field config
2002 * @param integer Record id, used for look-up of MM relations (local_uid)
2003 * @param string Status string ('update' or 'new')
2004 * @param string The type, either 'select' or 'group'
2005 * @return array Modified value array
2006 */
2007 function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type) {
2008 $tables = $type=='group'?$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
2009 $prep = $type=='group'?$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
2010
2011 $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
2012 $dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
2013 $dbAnalysis->start(implode(',',$valueArray),$tables);
2014
2015 if ($tcaFieldConf['MM']) {
2016 if ($status=='update') {
2017 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
2018 } else {
2019 $this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep); // This will be traversed later to execute the actions
2020 }
2021 $cc=count($dbAnalysis->itemArray);
2022 $valueArray = array($cc);
2023 } else {
2024 $valueArray = $dbAnalysis->getValueArray($prep);
2025 if ($type=='select' && $prep) {
2026 $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
2027 }
2028 }
2029
2030 // 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.
2031 return $valueArray;
2032 }
2033
2034 /**
2035 * Explodes the $value, which is a list of files/uids (group select)
2036 *
2037 * @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.
2038 * @return array The value array.
2039 */
2040 function checkValue_group_select_explodeSelectGroupValue($value) {
2041 $valueArray = t3lib_div::trimExplode(',',$value,1);
2042 reset($valueArray);
2043 while(list($key,$newVal)=each($valueArray)) {
2044 $temp=explode('|',$newVal,2);
2045 $valueArray[$key] = str_replace(',','',str_replace('|','',rawurldecode($temp[0])));
2046 }
2047 return $valueArray;
2048 }
2049
2050 /**
2051 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2052 * See checkValue_flex_procInData_travDS() for more details.
2053 *
2054 * @param array The 'data' part of the INPUT flexform data
2055 * @param array The 'data' part of the CURRENT flexform data
2056 * @param array The uploaded files for the 'data' part of the INPUT flexform data
2057 * @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.
2058 * @param array A set of parameters to pass through for the calling of the evaluation functions
2059 * @param string Optional call back function, see checkValue_flex_procInData_travDS()
2060 * @return array The modified 'data' part.
2061 * @see checkValue_flex_procInData_travDS()
2062 */
2063 function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='') {
2064 #debug(array($dataPart,$dataPart_current,$dataStructArray));
2065 if (is_array($dataPart)) {
2066 foreach($dataPart as $sKey => $sheetDef) {
2067 list ($dataStruct,$actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sKey);
2068 #debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
2069 if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef)) {
2070 foreach($sheetDef as $lKey => $lData) {
2071 $this->checkValue_flex_procInData_travDS(
2072 $dataPart[$sKey][$lKey],
2073 $dataPart_current[$sKey][$lKey],
2074 $uploadedFiles[$sKey][$lKey],
2075 $dataStruct['ROOT']['el'],
2076 $pParams,
2077 $callBackFunc,
2078 $sKey.'/'.$lKey.'/'
2079 );
2080 }
2081 }
2082 }
2083 }
2084
2085 return $dataPart;
2086 }
2087
2088 /**
2089 * Processing of the sheet/language data array
2090 * 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.
2091 *
2092 * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2093 * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2094 * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2095 * @param array Data structure which fits the data array
2096 * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
2097 * @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.
2098 * @param [type] $structurePath: ...
2099 * @return void
2100 * @see checkValue_flex_procInData()
2101 */
2102 function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath) {
2103 if (is_array($DSelements)) {
2104
2105 // For each DS element:
2106 foreach($DSelements as $key => $dsConf) {
2107
2108 // Array/Section:
2109 if ($DSelements[$key]['type']=='array') {
2110 if (is_array($dataValues[$key]['el'])) {
2111 if ($DSelements[$key]['section']) {
2112 foreach($dataValues[$key]['el'] as $ik => $el) {
2113 $theKey = key($el);
2114 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2115 $this->checkValue_flex_procInData_travDS(
2116 $dataValues[$key]['el'][$ik][$theKey]['el'],
2117 $dataValues_current[$key]['el'][$ik][$theKey]['el'],
2118 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2119 $DSelements[$key]['el'][$theKey]['el'],
2120 $pParams,
2121 $callBackFunc,
2122 $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
2123 );
2124 }
2125 }
2126 } else {
2127 if (!isset($dataValues[$key]['el'])) $dataValues[$key]['el']=array();
2128 $this->checkValue_flex_procInData_travDS(
2129 $dataValues[$key]['el'],
2130 $dataValues_current[$key]['el'],
2131 $uploadedFiles[$key]['el'],
2132 $DSelements[$key]['el'],
2133 $pParams,
2134 $callBackFunc,
2135 $structurePath.$key.'/el/'
2136 );
2137 }
2138 }
2139 } else {
2140 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2141 foreach($dataValues[$key] as $vKey => $data) {
2142
2143 if ($callBackFunc) {
2144 if (is_object($this->callBackObj)) {
2145 $res = $this->callBackObj->$callBackFunc(
2146 $pParams,
2147 $dsConf['TCEforms']['config'],
2148 $dataValues[$key][$vKey],
2149 $dataValues_current[$key][$vKey],
2150 $uploadedFiles[$key][$vKey],
2151 $structurePath.$key.'/'.$vKey.'/'
2152 );
2153 } else {
2154 $res = $this->$callBackFunc(
2155 $pParams,
2156 $dsConf['TCEforms']['config'],
2157 $dataValues[$key][$vKey],
2158 $dataValues_current[$key][$vKey],
2159 $uploadedFiles[$key][$vKey]
2160 );
2161 }
2162 } else { // Default
2163 list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
2164
2165 $res = $this->checkValue_SW(
2166 array(),
2167 $dataValues[$key][$vKey],
2168 $dsConf['TCEforms']['config'],
2169 $CVtable,
2170 $CVid,
2171 $dataValues_current[$key][$vKey],
2172 $CVstatus,
2173 $CVrealPid,
2174 $CVrecFID,
2175 '',
2176 $uploadedFiles[$key][$vKey],
2177 array(),
2178 $CVtscPID
2179 );
2180
2181 // Look for RTE transformation of field:
2182 if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations) {
2183
2184 // Unsetting trigger field - we absolutely don't want that into the data storage!
2185 unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
2186
2187 if (isset($res['value'])) {
2188
2189 // Calculating/Retrieving some values here:
2190 list(,,$recFieldName) = explode(':', $CVrecFID);
2191 $theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable,$this->checkValue_currentRecord);
2192 $specConf = t3lib_BEfunc::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
2193
2194 // Find, thisConfig:
2195 $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($CVtscPID));
2196 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
2197
2198 // Get RTE object, draw form and set flag:
2199 $RTEobj = &t3lib_BEfunc::RTEgetObj();
2200 if (is_object($RTEobj)) {
2201 $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord,$specConf,$thisConfig,'',$CVrealPid);
2202 } else {
2203 debug('NO RTE OBJECT FOUND!');
2204 }
2205 }
2206 }
2207 }
2208
2209 // Adding the value:
2210 if (isset($res['value'])) {
2211 $dataValues[$key][$vKey] = $res['value'];
2212 }
2213 }
2214 }
2215 }
2216 }
2217 }
2218 }
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239 /*********************************************
2240 *
2241 * Storing data to Database Layer
2242 *
2243 ********************************************/
2244
2245
2246 /**
2247 * Update database record
2248 * Does not check permissions but expects them to be verified on beforehand
2249 *
2250 * @param string Record table name
2251 * @param integer Record uid
2252 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
2253 * @return void
2254 */
2255 function updateDB($table,$id,$fieldArray) {
2256 global $TCA;
2257
2258 if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id)) {
2259 unset($fieldArray['uid']); // Do NOT update the UID field, ever!
2260
2261 if (count($fieldArray)) {
2262
2263 // Execute the UPDATE query:
2264 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
2265
2266 // If succees, do...:
2267 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2268 if ($this->checkStoredRecords) {
2269 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
2270 }
2271
2272 // Set log entry:
2273 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2274 $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
2275
2276 // Set History data:
2277 $this->setHistory($table,$id,$theLogId);
2278
2279 // Clear cache for relavant pages:
2280 $this->clear_cache($table,$id);
2281
2282 // Unset the pageCache for the id if table was page.
2283 if ($table=='pages') unset($this->pageCache[$id]);
2284 } else {
2285 $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2286 }
2287 }
2288 }
2289 }
2290
2291 /**
2292 * Compares the incoming field array with the current record and unsets all fields which are the same.
2293 * If the returned array is empty, then the record should not be updated!
2294 * $fieldArray must be an array.
2295 *
2296 * @param string Record table name
2297 * @param integer Record uid
2298 * @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!
2299 * @return array Returns $fieldArray
2300 */
2301 function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray) {
2302
2303 // Fetch the original record:
2304 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2305 $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2306
2307 // If the current record exists (which it should...), begin comparison:
2308 if (is_array($currentRecord)) {
2309
2310 // Read all field types:
2311 $c = 0;
2312 $cRecTypes = array();
2313 foreach($currentRecord as $col => $val) {
2314 // DBAL
2315 # $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($table,$col);
2316 $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
2317 $c++;
2318 }
2319 #debug($cRecTypes);
2320
2321 // Free result:
2322 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2323
2324 // Unset the fields which are similar:
2325 foreach($fieldArray as $col => $val) {
2326 if (
2327 #!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!]
2328 !strcmp($val,$currentRecord[$col]) || // Unset fields which matched exactly.
2329 ($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.
2330 ) {
2331 unset($fieldArray[$col]);
2332 } else {
2333 $this->historyRecords[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
2334 $this->historyRecords[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
2335 }
2336 }
2337 } else { // If the current record does not exist this is an error anyways and we just return an empty array here.
2338 $fieldArray = array();
2339 }
2340
2341 return $fieldArray;
2342 }
2343
2344 /**
2345 * Insert into database
2346 * Does not check permissions but expects them to be verified on beforehand
2347 *
2348 * @param string Record table name
2349 * @param string "NEW...." uid string
2350 * @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!
2351 * @param boolean Set to true if new version is created.
2352 * @param integer Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
2353 * @return void
2354 */
2355 function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0) {
2356 global $TCA;
2357
2358 if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid'])) {
2359 unset($fieldArray['uid']); // Do NOT insert the UID field, ever!
2360
2361 if (count($fieldArray)) {
2362
2363 // Check for "suggestedUid".
2364 // This feature is used by the import functionality to force a new record to have a certain UID value.
2365 // This is only recommended for use when the destination server is a passive mirrow of another server.
2366 // As a security measure this feature is available only for Admin Users (for now)
2367 $suggestedUid = intval($suggestedUid);
2368 if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table.':'.$suggestedUid]) {
2369 // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
2370 if ($this->suggestedInsertUids[$table.':'.$suggestedUid]==='DELETE') {
2371 // DELETE:
2372 $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($suggestedUid));
2373 }
2374 $fieldArray['uid'] = $suggestedUid;
2375 }
2376
2377 // Execute the INSERT query:
2378 $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
2379
2380 // If succees, do...:
2381 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2382
2383 // Set mapping for NEW... -> real uid:
2384 $NEW_id = $id; // the NEW_id now holds the 'NEW....' -id
2385 $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
2386 $this->substNEWwithIDs[$NEW_id] = $id;
2387 $this->substNEWwithIDs_table[$NEW_id] = $table;
2388
2389 // Checking the record is properly saved and writing to log
2390 if ($this->checkStoredRecords) {
2391 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
2392 }
2393
2394 if ($newVersion) {
2395 $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);
2396 } else {
2397 // Set log entry:
2398 if ($table=='pages') {
2399 $thePositionID = $this->getInterfacePagePositionID($id);
2400 } else {
2401 $thePositionID = 0;
2402 }
2403 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2404 $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
2405 $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);
2406
2407 // Clear cache for relavant pages:
2408 $this->clear_cache($table,$id);
2409 }
2410 } else {
2411 $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2412 }
2413 }
2414 }
2415 }
2416
2417 /**
2418 * Checking stored record to see if the written values are properly updated.
2419 *
2420 * @param string Record table name
2421 * @param integer Record uid
2422 * @param array Array of field=>value pairs to insert/update
2423 * @param string Action, for logging only.
2424 * @return array Selected row
2425 * @see insertDB(), updateDB()
2426 */
2427 function checkStoredRecord($table,$id,$fieldArray,$action) {
2428 global $TCA;
2429
2430 $id = intval($id);
2431 if (is_array($TCA[$table]) && $id) {
2432 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2433 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2434 // Traverse array of values that was inserted into the database and compare with the actually stored value:
2435 $errorString = array();
2436 foreach($fieldArray as $key => $value) {
2437 if ($this->checkStoredRecords_loose && !$value && !$row[$key]) {
2438 // Nothing...
2439 } elseif (strcmp($value,$row[$key])) {
2440 // DEBUGGING KFISH
2441 // debug(array("$value != ".$row[$key]));
2442 $errorString[] = $key;
2443 }
2444 }
2445
2446 // Set log message if there were fields with unmatching values:
2447 if (count($errorString)) {
2448 $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
2449 }
2450
2451 // Return selected rows:
2452 return $row;
2453 }
2454 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2455 }
2456 }
2457
2458 /**
2459 * Executing dbAnalysisStore
2460 *
2461 * @return [type] ...
2462 */
2463 function dbAnalysisStoreExec() {
2464 reset($this->dbAnalysisStore);
2465 while(list($k,$v)=each($this->dbAnalysisStore)) {
2466 $id = $this->substNEWwithIDs[$v[2]];
2467 if ($id) {
2468 $v[2] = $id;
2469 $v[0]->writeMM($v[1],$v[2],$v[3]);
2470 }
2471 }
2472 }
2473
2474 /**
2475 * Executing dbAnalysisStore
2476 *
2477 * @return [type] ...
2478 */
2479 function removeRegisteredFiles() {
2480 reset($this->removeFilesStore);
2481 while(list($k,$v)=each($this->removeFilesStore)) {
2482 unlink($v);
2483 // debug($v,1);
2484 }
2485 }
2486
2487 /**
2488 * Clearing the cache based on a page being updated
2489 * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
2490 * Else just clear the cache for the parent page of the record.
2491 *
2492 * @param string Table name of record that was just updated.
2493 * @param integer UID of updated / inserted record
2494 * @return void
2495 */
2496 function clear_cache($table,$uid) {
2497 global $TCA, $TYPO3_CONF_VARS;
2498
2499 $uid = intval($uid);
2500 if (is_array($TCA[$table]) && $uid > 0) {
2501
2502 // Get Page TSconfig relavant:
2503 list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
2504 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2505
2506 if (!$TSConfig['clearCache_disable']) {
2507
2508 // If table is "pages":
2509 if (t3lib_extMgm::isLoaded('cms')) {
2510 $list_cache = array();
2511 if ($table=='pages') {
2512
2513 // Builds list of pages on the SAME level as this page (siblings)
2514 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2515 'A.pid AS pid, B.uid AS uid',
2516 'pages A, pages B',
2517 'A.uid='.intval($uid).' AND B.pid=A.pid AND B.deleted=0'
2518 );
2519
2520 $pid_tmp = 0;
2521 while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2522 $list_cache[] = $row_tmp['uid'];
2523 $pid_tmp = $row_tmp['pid'];
2524
2525 // Add children as well:
2526 if ($TSConfig['clearCache_pageSiblingChildren']) {
2527 $res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2528 'uid',
2529 'pages',
2530 'pid='.intval($row_tmp['uid']).' AND deleted=0'
2531 );
2532 while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2)) {
2533 $list_cache[] = $row_tmp2['uid'];
2534 }
2535 }
2536 }
2537
2538 // Finally, add the parent page as well:
2539 $list_cache[] = $pid_tmp;
2540
2541 // Add grand-parent as well:
2542 if ($TSConfig['clearCache_pageGrandParent']) {
2543 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2544 'pid',
2545 'pages',
2546 'uid='.intval($pid_tmp)
2547 );
2548 if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2549 $list_cache[] = $row_tmp['pid'];
2550 }
2551 }
2552 } else { // For other tables than "pages", delete cache for the records "parent page".
2553 $list_cache[] = intval($this->getPID($table,$uid));
2554 }
2555
2556 // Call pre-processing function for clearing of cache for page ids:
2557 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'])) {
2558 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName) {
2559 $_params = array('pageIdArray' => &$list_cache, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()');
2560 // Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
2561 t3lib_div::callUserFunction($funcName,$_params,$this);
2562 }
2563 }
2564
2565 // Delete cache for selected pages:
2566 if (is_array($list_cache)) {
2567 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2568 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2569 }
2570 }
2571 }
2572
2573 // Clear cache for pages entered in TSconfig:
2574 if ($TSConfig['clearCacheCmd']) {
2575 $Commands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
2576 $Commands = array_unique($Commands);
2577 foreach($Commands as $cmdPart) {
2578 $this->clear_cacheCmd($cmdPart);
2579 }
2580 }
2581
2582 // Call post processing function for clear-cache:
2583 global $TYPO3_CONF_VARS;
2584 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
2585 $_params = array('table' => $table,'uid' => $uid,'uid_page' => $uid_page,'TSConfig' => $TSConfig);
2586 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
2587 t3lib_div::callUserFunction($_funcRef,$_params,$this);
2588 }
2589 }
2590 }
2591 }
2592
2593 /**
2594 * Returns the pid of a record from $table with $uid
2595 *
2596 * @param string Table name
2597 * @param integer Record uid
2598 * @return integer PID value (unless the record did not exist in which case FALSE)
2599 */
2600 function getPID($table,$uid) {
2601 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
2602 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2603 return $row['pid'];
2604 }
2605 }
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631 /*********************************************
2632 *
2633 * PROCESSING COMMANDS
2634 *
2635 ********************************************/
2636
2637 /**
2638 * Processing the cmd-array
2639 * See "TYPO3 Core API" for a description of the options.
2640 *
2641 * @return void
2642 */
2643 function process_cmdmap() {
2644 global $TCA;
2645
2646 // Traverse command map:
2647 reset ($this->cmdmap);
2648 while (list($table,) = each($this->cmdmap)) {
2649
2650 // Check if the table may be modified!
2651 $modifyAccessList = $this->checkModifyAccessList($table);
2652 if (!$modifyAccessList) {
2653 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
2654 }
2655
2656 // Check basic permissions and circumstances:
2657 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap[$table]) && $modifyAccessList) {
2658
2659 // Traverse the command map:
2660 foreach($this->cmdmap[$table] as $id => $incomingCmdArray) {
2661 if (is_array($incomingCmdArray)) { // have found a command.
2662
2663 // Get command and value (notice, only one command is observed at a time!):
2664 reset($incomingCmdArray);
2665 $command = key($incomingCmdArray);
2666 $value = current($incomingCmdArray);
2667
2668 // Init copyMapping array:
2669 $this->copyMappingArray = Array(); // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
2670
2671 // Branch, based on command
2672 switch ($command) {
2673 case 'move':
2674 $this->moveRecord($table,$id,$value);
2675 break;
2676 case 'copy':
2677 if ($table == 'pages') {
2678 $this->copyPages($id,$value);
2679 } else {
2680 $this->copyRecord($table,$id,$value,1);
2681 }
2682 break;
2683 case 'localize':
2684 $this->copyRecord_localize($table,$id,$value);
2685 break;
2686 case 'version':
2687 switch ((string)$value['action']) {
2688 case 'new':
2689 $this->versionizeTree = t3lib_div::intInRange($value['treeLevels'],-1,4); // Max 4 levels of versioning...
2690 if ($table == 'pages' && $this->versionizeTree>=0) {
2691 $this->versionizePages($id,$value['label']);
2692 } else {
2693 $this->versionizeRecord($table,$id,$value['label']);
2694 }
2695 break;
2696 case 'swap':
2697 $this->version_swap($table,$id,$value['swapWith'],$value['swapContent']);
2698 break;
2699 }
2700 break;
2701 case 'delete':
2702 if ($table == 'pages') {
2703 $this->deletePages($id);
2704 } else {
2705 $this->deleteRecord($table,$id, 0);
2706 }
2707 break;
2708 }
2709 // Merging the copy-array info together for remapping purposes.
2710 $this->copyMappingArray_merged= t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged,$this->copyMappingArray);
2711 }
2712 }
2713 }
2714 }
2715
2716 #debug($this->copyMappingArray_merged,'$this->copyMappingArray_merged');
2717 #debug($this->registerDBList,'$this->registerDBList');
2718
2719 // Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
2720 $this->remapListedDBRecords();
2721 }
2722
2723 /**
2724 * Moving records
2725 *
2726 * @param string Table name to move
2727 * @param integer Record uid to move
2728 * @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
2729 * @return void
2730 */
2731 function moveRecord($table,$uid,$destPid) {
2732 global $TCA;
2733
2734 // Initialize:
2735 $sortRow = $TCA[$table]['ctrl']['sortby'];
2736 $destPid = intval($destPid);
2737 $origDestPid = $destPid;
2738
2739 if ($TCA[$table]) {
2740 $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
2741 $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving.
2742
2743 // 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.
2744 // 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.
2745 if ($table!='pages' || $resolvedPid==$propArr['pid']) {
2746 $mayMoveAccess = $this->checkRecordUpdateAccess($table,$uid); // Edit rights for the record...
2747 } else {
2748 $mayMoveAccess = $this->doesRecordExist($table,$uid,'delete');
2749 }
2750
2751 // 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
2752 if ($table!='pages' || $resolvedPid!=$propArr['pid']) {
2753 $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4); // Edit rights for the record...
2754 } else {
2755 $mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
2756 }
2757
2758 // 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...)
2759 if ($destPid<0 && !$sortRow) {
2760 $destPid = $resolvedPid;
2761 }
2762
2763 // Timestamp field:
2764 $updateFields = array();
2765 if ($TCA[$table]['ctrl']['tstamp']) {
2766 $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
2767 }
2768
2769 // If moving is allowed, begin the processing:
2770 if ($mayMoveAccess) {
2771 if ($destPid>=0) { // insert as first element on page (where uid = $destPid)
2772 if ($mayInsertAccess) {
2773 if ($table!='pages' || $this->destNotInsideSelf ($destPid,$uid)) {
2774 $this->clear_cache($table,$uid); // clear cache before moving
2775
2776 $updateFields['pid'] = $destPid; // Setting PID
2777
2778 // table is sorted by 'sortby'
2779 if ($sortRow) {
2780 $sortNumber = $this->getSortNumber($table,$uid,$destPid);
2781 $updateFields[$sortRow] = $sortNumber;
2782 }
2783
2784 // Create query for update:
2785 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2786
2787 // Logging...
2788 $newPropArr = $this->getRecordProperties($table,$uid);
2789 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2790 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2791
2792 if ($destPid!=$propArr['pid']) {
2793 $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
2794 $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
2795 } else {
2796 $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
2797 }
2798 $this->clear_cache($table,$uid); // clear cache after moving
2799 $this->fixUniqueInPid($table,$uid);
2800 // fixCopyAfterDuplFields
2801 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.
2802 } else {
2803 $destPropArr = $this->getRecordProperties('pages',$destPid);
2804 $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']);
2805 }
2806 }
2807 } else { // Put after another record
2808 if ($sortRow) { // table is being sorted
2809 $sortInfo = $this->getSortNumber($table,$uid,$destPid);
2810 $destPid = $sortInfo['pid']; // Setting the destPid to the new pid of the record.
2811 if (is_array($sortInfo)) { // If not an array, there was an error (which is already logged)
2812 if ($mayInsertAccess) {
2813 if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid)) {
2814 $this->clear_cache($table,$uid); // clear cache before moving
2815
2816 // We now update the pid and sortnumber
2817 $updateFields['pid'] = $destPid;
2818 $updateFields[$sortRow] = $sortInfo['sortNumber'];
2819 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2820
2821 // Logging...
2822 if ($table=='pages') {
2823 $thePositionID = $this->getInterfacePagePositionID($uid);
2824 } else {
2825 $thePositionID = 0;
2826 }
2827 $this->log($table,$uid,4,$thePositionID,0,'');
2828
2829 // Logging...
2830 $newPropArr = $this->getRecordProperties($table,$uid);
2831 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2832 if ($destPid!=$propArr['pid']) {
2833 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2834 $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
2835 $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
2836 } else {
2837 $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
2838 }
2839
2840 // clear cache after moving
2841 $this->clear_cache($table,$uid);
2842
2843 // fixUniqueInPid
2844 $this->fixUniqueInPid($table,$uid);
2845
2846 // fixCopyAfterDuplFields
2847 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
2848 } else {
2849 $destPropArr = $this->getRecordProperties('pages',$destPid);
2850 $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']);
2851 }
2852 }
2853 }
2854 } else {
2855 $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']);
2856 }
2857 }
2858 } else {
2859 $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']);
2860 }
2861 }
2862 }
2863
2864 /**
2865 * Copying records
2866 *
2867 * @param string Element table
2868 * @param integer Element UID
2869 * @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
2870 * @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
2871 * @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!
2872 * @param string Commalist of fields to exclude from the copy process (might get default values)
2873 * @return void
2874 */
2875 function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='') {
2876 global $TCA;
2877
2878 $uid = intval($uid);
2879 if ($TCA[$table] && $uid) {
2880 t3lib_div::loadTCA($table);
2881 if ($this->doesRecordExist($table,$uid,'show')) { // This checks if the record can be selected which is all that a copy action requires.
2882 $data = Array();
2883
2884 $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));
2885
2886 $row = $this->recordInfo($table,$uid,'*');
2887 if (is_array($row)) {
2888
2889 // Initializing:
2890 $theNewID = uniqid('NEW');
2891 $enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ? $TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
2892 $headerField = $TCA[$table]['ctrl']['label'];
2893
2894 // Getting default data:
2895 $defaultData = $this->newFieldArray($table);
2896
2897 // Getting "copy-after" fields if applicable:
2898 // 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.