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