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