2 /***************************************************************
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains the TYPO3 Core Engine
31 * Revised for TYPO3 3.6 August/2003 by Kasper Skaarhoj
33 * @author Kasper Skaarhoj <kasper@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
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)
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)
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)
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='')
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)
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)
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()
146 * TOTAL FUNCTIONS: 92
147 * (This index is automatically created/updated by the extension "extdeveval")
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');
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.
179 * - $GLOBALS['TCA'] must exist
180 * - $GLOBALS['LANG'] (languageobject) may be preferred, but not fatal.
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...
184 * tce_db.php for further comments and SYNTAX! Also see document 'Inside TYPO3' for details.
186 * @author Kasper Skaarhoj <kasper@typo3.com>
190 class t3lib_TCEmain
{
191 var $log_table = 'sys_log';
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
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.
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.
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
218 var $defaultPermissions = array( // Can be overridden from $TYPO3_CONF_VARS
219 'user' => 'show,edit,delete,new,editcontent',
220 'group' => 'show,edit,new,editcontent',
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!
233 var $fileFunc; // May contain an object
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.
242 var $datamap = Array();
244 var $cmdmap = Array();
245 var $uploadedFileArray = array();
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();
262 var $checkValue_currentRecord=array(); // Set to "currentRecord" during checking of values.
267 * For details, see 'TYPO3 Core API' document.
268 * This function does not start the processing of data, but merely initializes the object
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']
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'];
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'];}
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();
291 // Setting the data and cmd arrays
292 if (is_array($data)) {
294 $this->datamap
= $data;
296 if (is_array($cmd)) {
298 $this->cmdmap
= $cmd;
303 * [Describe function...]
305 * @param array This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
308 function setMirror($mirror) {
309 if (is_array($mirror)) {
311 while(list($table,$uid_array)=each($mirror)) {
312 if (isset($this->datamap
[$table])) {
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];
328 * Initializes default values coming from User TSconfig
330 * @param array User TSconfig array
333 function setDefaultsFromUserTS($userTS) {
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);
342 $this->defaultValues
[$k] = $v;
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.
353 * @param array HTTP_POST_FILES array
356 function process_uploads($postFiles) {
357 if (is_array($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();
366 foreach($subA as $key => $values) {
367 $this->process_uploads_traverseArray($this->uploadedFileArray
,$values,$key);
370 $this->uploadedFileArray
=$subA;
377 * Traverse the upload array if needed to rearrange values.
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.
384 * @see process_uploads()
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);
392 $outputArr[$keyToSet]=$inputArr;
410 /*********************************************
414 *********************************************/
417 * Processing the data-array
418 * Call this function to process the data-array set by start()
422 function process_datamap() {
424 reset ($this->datamap
);
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';
431 while (list($table,) = each($this->datamap
)) {
432 if ($table!='pages') {
433 $orderOfTables[]=$table;
436 // Process the tables...
437 reset($orderOfTables);
438 while (list(,$table) = each($orderOfTables)) { // Have found table
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
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));
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);
453 reset ($this->datamap
[$table]);
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)) {
461 // ******************************
462 // Checking access to the record
463 // ******************************
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.
470 $pid_value = $incomingFieldArray['pid'];
472 // Checking and finding numerical pid, it may be a string-reference to another value
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...
481 $pid_value = intval($pid_value);
483 // The $pid_value is now the numerical pid at this point
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);
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'];
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.
508 debug('Internal ERROR: pid should not be less than zero!');
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'];
521 $status='update'; // the default is 'update'
524 // **************************************
525 // If access was granted above, proceed:
526 // **************************************
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);
532 if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.'])) {
533 $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
536 //debug(array($table,$tscPID));
538 $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
539 $fieldArray = $this->overrideFieldArray($table,$fieldArray);
541 // Setting system fields
542 if ($status=='new') {
543 if ($TCA[$table]['ctrl']['crdate']) {
544 $fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
546 if ($TCA[$table]['ctrl']['cruser_id']) {
547 $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid
;
549 } elseif ($this->checkSimilar
) {
550 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
552 if ($TCA[$table]['ctrl']['tstamp']) {
553 $fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
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);
561 $this->updateDB($table,$id,$fieldArray);
563 } // if ($recordAccess) {
564 } // if (is_array($incomingFieldArray)) {
568 $this->dbAnalysisStoreExec();
569 $this->removeRegisteredFiles();
573 * Filling in the field array
574 * $this->exclude_array is used to filter fields if needed.
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: ...
585 function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID) {
588 t3lib_div
::loadTCA($table);
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...
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);
600 $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
602 $this->checkValue_currentRecord
= $checkValueRecord;
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
611 If everything is OK, the field is entered into $fieldArray[]
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.
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);
627 // Nothing happens, already set
630 case 'perms_groupid':
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);
639 $fieldArray[$field]=$value;
641 case 'perms_groupid':
642 $fieldArray[$field]=$value;
645 if ($value>=0 && $value<pow(2,5)) {
646 $fieldArray[$field]=$value;
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'];
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
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']]) {
680 $RTEsetup = $this->BE_USER
->getTSConfig('RTE',t3lib_BEfunc
::getPagesTSconfig($tscPID));
681 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
683 // Set alternative relative path for RTE images/links:
684 $RTErelPath = is_array($eFile) ?
dirname($eFile['relEditFile']) : '';
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']);
691 debug('NO RTE OBJECT FOUND!');
697 // These transformations has been removed and the one above inserted; content is now transformed if a flag is sent with the field, typ. "_TRANSFORM_".[fieldname] = "RTE"
698 // This is more safe, doesn't require us to calculate if a transformation has to be done and finally; it is now possible to use RTEs in FlexForms as well!
700 if ($vconf['spec']['richtext'] && !$this->disableRTE) {
701 // Cross transformation?
702 $this->crossRTEtransformation=0; // Crosstransformation is, when a record is saved, the CType has changed and the other type might also use the RTE - then the transformation of THAT rte is used instead. This is usefull only if we know the TBE interface did it, because in that interface the CType value changes the interface and allows extended options in RTE without first saving the type-shift.
703 if ($this->crossRTEtransformation) {
704 $next_types_fieldConfig=t3lib_BEfunc::getTCAtypes($table,array_merge($currentRecord,$fieldArray),1);
705 if ($next_types_fieldConfig[$vconf['field']]['spec']['richtext']) { // RTE must be enabled for the fields
706 $vconf['spec'] = $next_types_fieldConfig[$vconf['field']]['spec'];
707 $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,array_merge($currentRecord,$fieldArray));
710 //debug($theTypeString);
712 if ($vconf['spec']['rte_transform']) {
713 $p=t3lib_BEfunc::getSpecConfParametersFromArray($vconf['spec']['rte_transform']['parameters']);
714 if ($p['mode']) { // There must be a mode set for transformation
715 if (isset($fieldArray[$vconf['field']])) {
718 $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
719 $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
720 if (!$thisConfig['disabled'] && (!$p['flag'] || !$currentRecord[$p['flag']]) && $this->BE_USER->isRTE()) { // ... and any disable flag should not be set!
721 $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
722 $parseHTML->init($table.':'.$vconf['field'],$currentRecord['pid']);
723 if (is_array($eFile)) {$parseHTML->setRelPath(dirname($eFile['relEditFile']));}
724 $fieldArray[$vconf['field']]=$parseHTML->RTE_transform($fieldArray[$vconf['field']],$vconf['spec'],'db',$thisConfig);
734 // Write file configuration:
735 if (is_array($eFile)) {
736 $mixedRec = array_merge($currentRecord,$fieldArray);
737 $SW_fileContent = t3lib_div
::getUrl($eFile['editFile']);
738 $parseHTML = t3lib_div
::makeInstance('t3lib_parsehtml_proc');
739 $parseHTML->init('','');
741 $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ?
trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
742 $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
744 $SW_fileNewContent = $parseHTML->substituteSubpart(
747 chr(10).$insertContent.chr(10),
749 t3lib_div
::writeFile($eFile['editFile'],$SW_fileNewContent);
752 if (!strstr($id,'NEW') && $eFile['statusField']) {
753 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
757 $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
761 } elseif ($eFile && is_string($eFile)) {
762 $this->log($insertTable,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
771 * Checking group modify_table access list
773 * Returns true if the user has general access to modify the $table
775 * @param [type] $table: ...
778 function checkModifyAccessList($table) {
779 $res = ($this->admin ||
(!$this->tableAdminOnly($table) && t3lib_div
::inList($this->BE_USER
->groupData
['tables_modify'],$table)));
784 * [Describe function...]
786 * @param [type] $table: ...
787 * @param [type] $id: ...
790 function isRecordInWebMount($table,$id) {
791 if (!isset($this->isRecordInWebMount_Cache
[$table.':'.$id])) {
792 $recP=$this->getRecordProperties($table,$id);
793 $this->isRecordInWebMount_Cache
[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
795 return $this->isRecordInWebMount_Cache
[$table.':'.$id];
799 * [Describe function...]
801 * @param [type] $pid: ...
804 function isInWebMount($pid) {
805 if (!isset($this->isInWebMount_Cache
[$pid])) {
806 $this->isInWebMount_Cache
[$pid]=$this->BE_USER
->isInWebMount($pid);
808 //debug($this->isInWebMount_Cache);
809 return $this->isInWebMount_Cache
[$pid];
813 * Checks if user may update a certain record.
815 * Returns true if the user may update the record given by $table and $id
817 * @param [type] $table: ...
818 * @param [type] $id: ...
821 function checkRecordUpdateAccess($table,$id) {
824 if ($TCA[$table] && intval($id)>0) {
825 if (isset($this->recUpdateAccessCache
[$table][$id])) { // If information is cached, return it
826 return $this->recUpdateAccessCache
[$table][$id];
827 // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
828 } elseif ($this->doesRecordExist($table,$id,'edit')) {
831 $this->recUpdateAccessCache
[$table][$id]=$res; // Cache the result
837 * Checks if user may insert a certain record.
839 * Returns true if the user may insert a record from table $insertTable on page $pid
841 * @param [type] $insertTable: ...
842 * @param [type] $pid: ...
843 * @param [type] $action: ...
846 function checkRecordInsertAccess($insertTable,$pid,$action=1) {
851 if (isset($this->recInsertAccessCache
[$insertTable][$pid])) { // If information is cached, return it
852 return $this->recInsertAccessCache
[$insertTable][$pid];
854 // 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
855 if ( (!$pid && $this->admin
) ||
$this->doesRecordExist('pages',$pid,($insertTable=='pages'?
$this->pMap
['new']:$this->pMap
['editcontent'])) ) { // Check permissions
856 if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
858 $this->recInsertAccessCache
[$insertTable][$pid]=$res; // Cache the result
860 $propArr = $this->getRecordProperties('pages',$pid);
861 $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']);
864 $propArr = $this->getRecordProperties('pages',$pid);
865 $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']);
873 * Checks is a table is allowed on a certain page.
875 * $checkTable is the tablename
876 * $page_uid is the uid of the page to check
878 * @param [type] $page_uid: ...
879 * @param [type] $checkTable: ...
882 function isTableAllowedForThisPage($page_uid, $checkTable) {
883 global $TCA, $PAGES_TYPES;
884 $page_uid = intval($page_uid);
886 // 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.
887 if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages') {
897 // Check non-root-level
898 $doktype = $this->pageInfo($page_uid,'doktype');
899 $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ?
$PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
900 $allowedArray = t3lib_div
::trimExplode(',',$allowedTableList,1);
901 if (strstr($allowedTableList,'*') ||
in_array($checkTable,$allowedArray)) { // If all tables or the table is listed as a allowed type, return true
908 * Checks if record exists
910 * Returns true if the record given by $table, $id and $perms
912 * @param string Record table name
913 * @param integer Record UID
914 * @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
917 function doesRecordExist($table,$id,$perms) {
923 // Processing the incoming $perms (from possible string to integer that can be AND'ed)
924 if (!t3lib_div
::testInt($perms)) {
925 if ($table!='pages') {
930 $perms = 'editcontent'; // This holds it all in case the record is not page!!
934 $perms = intval($this->pMap
[$perms]);
936 $perms = intval($perms);
939 if (!$perms) {debug('Internal ERROR: no permissions to check for non-admin user.');}
941 // For all tables: Check if record exists:
942 // Notice: If $perms are 0 (zero) no perms-clause is added!
943 if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) ||
$this->admin
)) {
944 if ($table != 'pages') {
946 // Find record without checking page:
947 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($id).$this->deleteClause($table));
948 $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
950 // If record found, check page as well:
951 if (is_array($output)) {
953 // Looking up the page for record:
954 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
957 'uid='.intval($output['pid']).
958 $this->deleteClause('pages').
959 ($perms && !$this->admin ?
' AND '.$this->BE_USER
->getPagePermsClause($perms) : '') // admin users don't need check
961 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
963 // 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):
964 if (is_array($pageRec) ||
(!$output['pid'] && $this->admin
)) {
970 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
973 $table.'.pid=pages.uid && '.$table.'.uid='.intval($id).
974 $this->deleteClause('pages').
975 ($perms && !$this->admin ? " AND ".$this->BE_USER->getPagePermsClause($perms) : '') // admin users don't need check
977 if ($GLOBALS['TYPO3_DB']->sql_num_rows($mres)) {
980 if ($this->admin) { // admin may do stuff on records in the root
981 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'uid='.intval($id).$this->deleteClause($table));
982 return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
987 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
991 $this->deleteClause('pages').
992 ($perms && !$this->admin ?
' AND '.$this->BE_USER
->getPagePermsClause($perms) : '') // admin users don't need check
994 return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
1000 * Checks if a whole branch of pages exists
1002 * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
1003 * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
1004 * 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
1006 * @param [type] $inList: ...
1007 * @param [type] $pid: ...
1008 * @param [type] $perms: ...
1009 * @param [type] $recurse: ...
1010 * @return [type] ...
1012 function doesBranchExist($inList,$pid,$perms, $recurse) {
1014 $pid = intval($pid);
1015 $perms = intval($perms);
1017 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1018 'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
1020 'pid='.intval($pid).$this->deleteClause('pages'),
1024 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1025 if ($this->admin ||
$this->BE_USER
->doesUserHaveAccess($row,$perms)) { // IF admin, then it's OK
1026 $inList.=$row['uid'].',';
1027 if ($recurse) { // Follow the subpages recursively...
1028 $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
1029 if ($inList == -1) {return -1;} // No permissions somewhere in the branch
1032 return -1; // No permissions
1040 * Returns the value of the $field from page $id
1041 * 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!
1043 * @param integer Page uid
1044 * @param string Field name for which to return value
1045 * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
1047 function pageInfo($id,$field) {
1048 if (!isset($this->pageCache
[$id])) {
1049 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
1050 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1051 $this->pageCache
[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1053 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1055 return $this->pageCache
[$id][$field];
1059 * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
1060 * NOTICE: No check for deleted or access!
1062 * @param string Table name
1063 * @param integer UID of the record from $table
1064 * @param string Field list for the SELECT query, eg. "*" or "uid,pid,..."
1065 * @return mixed Returns the selected record on success, otherwise false.
1067 function recordInfo($table,$id,$fieldList) {
1069 if (is_array($TCA[$table])) {
1070 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
1071 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1072 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1078 * Returns an array with record properties, like header and pid
1080 * @param [type] $table: ...
1081 * @param [type] $id: ...
1082 * @return [type] ...
1084 function getRecordProperties($table,$id) {
1085 $row = ($table=='pages' && !$id) ?
array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
1086 return $this->getRecordPropertiesFromRow($table,$row);
1090 * Returns an array with record properties, like header and pid, based on the row
1092 * @param [type] $table: ...
1093 * @param [type] $row: ...
1094 * @return [type] ...
1096 function getRecordPropertiesFromRow($table,$row) {
1100 'header' => $row[$TCA[$table]['ctrl']['label']],
1101 'pid' => $row['pid'],
1102 'event_pid' => ($table=='pages'?
$row['uid']:$row['pid'])
1109 * [Describe function...]
1111 * @param [type] $fieldArray: ...
1112 * @param [type] $TSConfig_p: ...
1113 * @return [type] ...
1115 function setTSconfigPermissions($fieldArray,$TSConfig_p) {
1116 if (strcmp($TSConfig_p['userid'],'')) $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
1117 if (strcmp($TSConfig_p['groupid'],'')) $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
1118 if (strcmp($TSConfig_p['user'],'')) $fieldArray['perms_user']=t3lib_div
::testInt($TSConfig_p['user']) ?
$TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
1119 if (strcmp($TSConfig_p['group'],'')) $fieldArray['perms_group']=t3lib_div
::testInt($TSConfig_p['group']) ?
$TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
1120 if (strcmp($TSConfig_p['everybody'],'')) $fieldArray['perms_everybody']=t3lib_div
::testInt($TSConfig_p['everybody']) ?
$TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
1126 * Returns a fieldArray with default values.
1128 * @param [type] $table: ...
1129 * @return [type] ...
1131 function newFieldArray($table) {
1133 t3lib_div
::loadTCA($table);
1134 $fieldArray=Array();
1135 if (is_array($TCA[$table]['columns'])) {
1136 reset ($TCA[$table]['columns']);
1137 while (list($field,$content)=each($TCA[$table]['columns'])) {
1138 if (isset($this->defaultValues
[$table][$field])) {
1139 $fieldArray[$field] = $this->defaultValues
[$table][$field];
1140 } elseif (isset($content['config']['default'])) {
1141 $fieldArray[$field] = $content['config']['default'];
1145 if ($table=='pages') { // Set default permissions for a page.
1146 $fieldArray['perms_userid'] = $this->userid
;
1147 $fieldArray['perms_groupid'] = intval($this->BE_USER
->firstMainGroup
);
1148 $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions
['user']);
1149 $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions
['group']);
1150 $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions
['everybody']);
1156 * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
1158 * @param [type] $table: ...
1159 * @param [type] $data: ...
1160 * @return [type] ...
1162 function overrideFieldArray($table,$data) {
1163 if (is_array($this->overrideValues
[$table])) {
1164 $data = array_merge($data,$this->overrideValues
[$table]); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1170 * Calculates the bitvalue of the permissions given in a string, comma-sep
1172 * @param [type] $string: ...
1173 * @return [type] ...
1175 function assemblePermissions($string) {
1176 $keyArr = t3lib_div
::trimExplode(',',$string,1);
1178 while(list(,$key)=each($keyArr)) {
1179 if ($key && isset($this->pMap
[$key])) {
1180 $value |
= $this->pMap
[$key];
1205 /*********************************************
1207 * Evaluation of input values
1209 ********************************************/
1212 * Evaluates a value according to $table/$field settings.
1213 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1214 * 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() )
1216 * @param string Table name
1217 * @param string Field name
1218 * @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.
1219 * @param string The record-uid, mainly - but not exclusively - used for logging
1220 * @param string 'update' or 'new' flag
1221 * @param [type] $realPid: ...
1222 * @param integer $tscPID
1223 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1225 function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID) {
1226 global $TCA, $PAGES_TYPES;
1227 t3lib_div
::loadTCA($table);
1229 $res = Array(); // result array
1230 $recFID = $table.':'.$id.':'.$field;
1232 // Processing special case of field pages.doktype
1233 if ($table=='pages' && $field=='doktype') {
1234 // If the user may not use this specific doktype, we issue a warning
1235 if (! ($this->admin || t3lib_div
::inList($this->BE_USER
->groupData
['pagetypes_select'],$value))) {
1236 $propArr = $this->getRecordProperties($table,$id);
1237 $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']);
1240 if ($status=='update') {
1241 // This checks if 1) we should check for disallowed tables and 2) the there are records from disallowed tables on the current page
1242 $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ?
$PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
1243 if ($onlyAllowedTables) {
1244 $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
1245 if ($theWrongTables) {
1246 $propArr = $this->getRecordProperties($table,$id);
1247 $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']);
1254 // Get current value:
1255 $curValueRec = $this->recordInfo($table,$id,$field);
1256 $curValue = $curValueRec[$field];
1258 // Getting config for the field
1259 $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
1261 // Preform processing:
1262 $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray
[$table][$id][$field],$tscPID);
1268 * Branches out evaluation of a field value based on its type as configured in TCA
1269 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1271 * @param array The result array. The processed value (if any!) is set in the "value" key.
1272 * @param string The value to set.
1273 * @param array Field configuration from TCA
1274 * @param string Table name
1275 * @param integer Return UID
1276 * @param [type] $curValue: ...
1277 * @param [type] $status: ...
1278 * @param [type] $realPid: ...
1279 * @param [type] $recFID: ...
1280 * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1281 * @param [type] $uploadedFiles: ...
1282 * @param [type] $tscPID: ...
1283 * @return array Returns the evaluated $value as key "value" in this array.
1285 function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID) {
1287 $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
1289 switch ($tcaFieldConf['type']) {
1292 $res['value'] = $value;
1295 $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
1298 $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
1301 $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
1305 $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles);
1308 if ($field) { // FlexForms are only allowed for real fields.
1309 $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1318 * Evaluate "input" type values.
1320 * @param array The result array. The processed value (if any!) is set in the "value" key.
1321 * @param string The value to set.
1322 * @param array Field configuration from TCA
1323 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1324 * @param string Field name
1325 * @return array Modified $res array
1327 function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='') {
1328 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1330 // Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
1331 if (intval($tcaFieldConf['max'])>0) {$value = substr($value,0,intval($tcaFieldConf['max']));}
1333 // Checking range of value:
1334 if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox']) { // If value is not set to the allowed checkbox-value then it is checked against the ranges
1335 if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper']) {$value=$tcaFieldConf['range']['upper'];}
1336 if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower']) {$value=$tcaFieldConf['range']['lower'];}
1339 // Process evaluation settings:
1340 $evalCodesArray = t3lib_div
::trimExplode(',',$tcaFieldConf['eval'],1);
1341 $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
1343 // Process UNIQUE settings:
1344 if ($field) { // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields!
1345 if ($res['value'] && in_array('uniqueInPid',$evalCodesArray)) {
1346 $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
1348 if ($res['value'] && in_array('unique',$evalCodesArray)) {
1349 $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
1357 * Evaluates 'check' type values.
1359 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1360 * @param string The value to set.
1361 * @param array Field configuration from TCA
1362 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1363 * @return array Modified $res array
1365 function checkValue_check($res,$value,$tcaFieldConf,$PP) {
1366 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1368 $itemC = count($tcaFieldConf['items']);
1369 if (!$itemC) {$itemC=1;}
1370 $maxV = pow(2,$itemC);
1372 if ($value<0) {$value=0;}
1373 if ($value>$maxV) {$value=$maxV;}
1374 $res['value'] = $value;
1380 * Evaluates 'radio' type values.
1382 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1383 * @param string The value to set.
1384 * @param array Field configuration from TCA
1385 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1386 * @return array Modified $res array
1388 function checkValue_radio($res,$value,$tcaFieldConf,$PP) {
1389 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1391 if (is_array($tcaFieldConf['items'])) {
1392 foreach($tcaFieldConf['items'] as $set) {
1393 if (!strcmp($set[1],$value)) {
1394 $res['value'] = $value;
1404 * Evaluates 'group' or 'select' type values.
1406 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1407 * @param string The value to set.
1408 * @param array Field configuration from TCA
1409 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1410 * @param [type] $uploadedFiles: ...
1411 * @return array Modified $res array
1413 function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles) {
1414 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1416 // This converts all occurencies of '{' 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.
1417 // Anyways, this should NOT disturb anything else:
1418 $value = $this->convNumEntityToByteValue($value);
1420 // When values are send as group or select they come as comma-separated values which are exploded by this function:
1421 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1423 // If not multiple is set, then remove duplicates:
1424 if (!$tcaFieldConf['multiple']) {
1425 $valueArray = array_unique($valueArray);
1428 // This could be a good spot for parsing the array through a validation-function which checks if the values are allright
1429 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1434 if ($tcaFieldConf['type']=='group') {
1435 switch($tcaFieldConf['internal_type']) {
1437 $valueArray = $this->checkValue_group_select_file(
1449 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group');
1453 // For select types which has a foreign table attached:
1454 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table']) {
1455 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select');
1460 // Checking the number of items, that it is correct.
1461 // If files, there MUST NOT be too many files in the list at this point, so check that prior to this code.
1462 $valueArrayC = count($valueArray);
1463 $minI = isset($tcaFieldConf['minitems']) ?
intval($tcaFieldConf['minitems']):0;
1465 // 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.
1466 $maxI = isset($tcaFieldConf['maxitems']) ?
intval($tcaFieldConf['maxitems']):1;
1467 if ($valueArrayC > $maxI) {$valueArrayC=$maxI;} // Checking for not too many elements
1469 // Dumping array to list
1471 foreach($valueArray as $nextVal) {
1472 if ($valueArrayC==0) {break;}
1476 $res['value']=implode(',',$newVal);
1482 * Handling files for group/select function
1484 * @param [type] $valueArray: ...
1485 * @param [type] $tcaFieldConf: ...
1486 * @param [type] $curValue: ...
1487 * @param [type] $uploadedFileArray: ...
1488 * @param [type] $status: ...
1489 * @param [type] $table: ...
1490 * @param [type] $id: ...
1491 * @param [type] $recFID: ...
1492 * @return array Modified value array
1493 * @see checkValue_group_select()
1495 function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID) {
1497 // If any files are uploaded:
1498 if (is_array($uploadedFileArray) &&
1499 $uploadedFileArray['name'] &&
1500 strcmp($uploadedFileArray['tmp_name'],'none')) {
1501 $valueArray[]=$uploadedFileArray['tmp_name'];
1502 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1505 // Creating fileFunc object.
1506 if (!$this->fileFunc
) {
1507 $this->fileFunc
= t3lib_div
::makeInstance('t3lib_basicFileFunctions');
1508 $this->include_filefunctions
=1;
1510 // Setting permitted extensions.
1511 $all_files = Array();
1512 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1513 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?
$tcaFieldConf['disallowed'] : '*';
1514 $all_files['ftpspace'] = $all_files['webspace'];
1515 $this->fileFunc
->init('', $all_files);
1517 // If there is an upload folder defined:
1518 if ($tcaFieldConf['uploadfolder']) {
1520 $propArr = $this->getRecordProperties($table,$id);
1522 // Get destrination path:
1523 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1525 // If we are updating:
1526 if ($status=='update') {
1528 // Finding the CURRENT files listed, either from MM or from the current record.
1529 $theFileValues=array();
1530 if ($tcaFieldConf['MM']) { // If MM relations for the files also!
1531 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1532 $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
1533 reset($dbAnalysis->itemArray
);
1534 while (list($somekey,$someval)=each($dbAnalysis->itemArray
)) {
1535 if ($someval['id']) {
1536 $theFileValues[]=$someval['id'];
1540 $theFileValues=t3lib_div
::trimExplode(',',$curValue,1);
1543 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1544 if (count($theFileValues)) {
1545 // 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!)
1546 foreach($valueArray as $key => $theFile) {
1547 if ($theFile && !strstr(t3lib_div
::fixWindowsFilePath($theFile),'/')) {
1548 $theFileValues = t3lib_div
::removeArrayEntryByValue($theFileValues,$theFile);
1552 // This array contains the filenames in the uploadfolder that should be deleted:
1553 foreach($theFileValues as $key => $theFile) {
1554 $theFile = trim($theFile);
1555 if (@is_file
($dest.'/'.$theFile)) {
1556 $this->removeFilesStore
[]=$dest.'/'.$theFile;
1557 } elseif ($theFile) {
1558 $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
1564 // Traverse the submitted values:
1565 foreach($valueArray as $key => $theFile) {
1566 // 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)
1567 if (strstr(t3lib_div
::fixWindowsFilePath($theFile),'/')) {
1569 $maxSize = intval($tcaFieldConf['max_size']);
1571 $theDestFile=''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!! (Change: 22/12/2000)
1573 // Check various things before copying file:
1574 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) { // File and destination must exist
1576 // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
1577 if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name']) {
1578 $fileSize = $uploadedFileArray['size'];
1580 $fileSize = filesize($theFile);
1583 if (!$maxSize ||
$fileSize<=($maxSize*1024)) { // Check file size:
1584 // Prepare filename:
1585 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
1586 $fI = t3lib_div
::split_fileref($theEndFileName);
1588 // Check for allowed extension:
1589 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1590 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
1592 // If we have a unique destination filename, then write the file:
1594 t3lib_div
::upload_copy_move($theFile,$theDestFile);
1595 $this->copiedFileMap
[$theFile]=$theDestFile;
1597 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']);
1598 } 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']);
1599 } else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
1600 } 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']);
1601 } 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']);
1603 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1604 if (@is_file
($theDestFile)) {
1605 $info = t3lib_div
::split_fileref($theDestFile);
1606 $valueArray[$key]=$info['file']; // The value is set to the new filename
1608 unset($valueArray[$key]); // The value is set to the new filename
1613 // 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!
1614 if ($tcaFieldConf['MM']) {
1615 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1616 $dbAnalysis->tableArray
['files']=array(); // dummy
1619 while (list($key,$theFile)=each($valueArray)) {
1621 $dbAnalysis->itemArray
[]['id']=$theFile;
1623 if ($status=='update') {
1624 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
1626 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1628 $cc=count($dbAnalysis->itemArray
);
1629 $valueArray = array($cc);
1637 * Evaluates 'flex' type values.
1639 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1640 * @param string The value to set.
1641 * @param array Field configuration from TCA
1642 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1643 * @param array Uploaded files for the field
1644 * @param array Current record array.
1645 * @param string Field name
1646 * @return array Modified $res array
1648 function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1649 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1651 if (is_array($value)) {
1653 // Get current value array:
1654 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord
,$table);
1655 #debug($this->checkValue_currentRecord);
1656 $currentValueArray = t3lib_div
::xml2array($curValue);
1657 if (!is_array($currentValueArray)) $currentValueArray = array();
1658 if (is_array($currentValueArray['meta']['currentLangId'])) unset($currentValueArray['meta']['currentLangId']); // Remove all old meta for languages...
1660 // Evaluation of input values:
1661 $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
1663 // Create XML and convert charsets from input value:
1664 $xmlValue = $this->checkValue_flexArray2Xml($value);
1666 // If we wanted to set UTF fixed:
1667 // $storeInCharset='utf-8';
1668 // $currentCharset=$GLOBALS['LANG']->charSet;
1669 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1670 $storeInCharset=$GLOBALS['LANG']->charSet
;
1672 // Merge them together IF they are both arrays:
1673 // 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).
1674 if (is_array($currentValueArray)) {
1675 $arrValue = t3lib_div
::xml2array($xmlValue);
1676 $arrValue = t3lib_div
::array_merge_recursive_overrule($currentValueArray,$arrValue);
1677 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1680 // Temporary fix to delete elements:
1681 $deleteCMDs = t3lib_div
::_GP('_DELETE_FLEX_FORMdata');
1683 if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
1684 $arrValue = t3lib_div
::xml2array($xmlValue);
1685 $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
1686 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1689 // Create the value XML:
1691 $res['value'].='<?xml version="1.0" encoding="'.$storeInCharset.'" standalone="yes" ?>'.chr(10);
1692 $res['value'].=$xmlValue;
1693 } else { // Passthrough...:
1694 $res['value']=$value;
1701 * [Describe function...]
1703 * @param [type] $array: ...
1704 * @return [type] ...
1706 function checkValue_flexArray2Xml($array) {
1707 $output = t3lib_div
::array2xml($array,'',0,'T3FlexForms',4,array('parentTagMap' => array(
1708 /* 'data' => 'sheets',
1709 'sheets' => 'language',
1710 'language' => 'fieldname',
1711 'el' => 'fieldname' */
1717 * [Describe function...]
1719 * @param [type] $$valueArrayToRemoveFrom: ...
1720 * @param [type] $deleteCMDS: ...
1721 * @return [type] ...
1723 function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS) {
1724 if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
1725 foreach($deleteCMDS as $key => $value) {
1726 if (is_array($deleteCMDS[$key])) {
1727 $this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
1729 unset($valueArrayToRemoveFrom[$key]);
1754 /*********************************************
1756 * Helper functions for evaluation functions.
1758 ********************************************/
1762 * Gets a unique value for $table/$id/$field based on $value
1764 * @param string Table name
1765 * @param string Field name for which $value must be unique
1766 * @param string Value string.
1767 * @param integer UID to filter out in the lookup (the record itself...)
1768 * @param integer If set, the value will be unique for this PID
1769 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
1771 function getUnique($table,$field,$value,$id,$newPid=0) {
1775 t3lib_div
::loadTCA($table);
1778 if (intval($newPid)) { $whereAdd.=' AND pid='.intval($newPid); }
1779 $whereAdd.=$this->deleteClause($table);
1781 // If the field is configured in TCA, proceed:
1782 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
1784 // Look for a record which might already have the value:
1785 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'="'.$GLOBALS['TYPO3_DB']->quoteStr($value, $table).'" AND uid!='.intval($id).$whereAdd);
1788 // For as long as records with the test-value existing, try again (with incremented numbers appended).
1789 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1790 $newValue = $value.$counter;
1791 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'="'.$GLOBALS['TYPO3_DB']->quoteStr($newValue, $table).'" AND uid!='.intval($id).$whereAdd);
1793 if ($counter>100) { break; } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
1795 // If the new value is there:
1796 $value = strlen($newValue) ?
$newValue : $value;
1802 * Evaluation of 'input'-type values based on 'eval' list
1804 * @param string Value
1805 * @param array Array of evaluations to traverse.
1806 * @param string Is-in string
1807 * @return string Modified $value
1809 function checkValue_input_Eval($value,$evalArray,$is_in) {
1814 foreach($evalArray as $func) {
1822 $value = intval($value);
1826 for ($a=strlen($value); $a>0; $a--) {
1827 if (substr($value,$a-1,1)=='.' ||
substr($value,$a-1,1)==',') {
1828 $theDec = substr($value,$a);
1829 $value = substr($value,0,$a-1);
1833 $theDec = ereg_replace('[^0-9]','',$theDec).'00';
1834 $value = intval(str_replace(' ','',$value)).'.'.substr($theDec,0,2);
1837 if (strlen($value)!=32){$set=false
;}
1840 $value = trim($value);
1843 $value = strtoupper($value);
1844 # $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.
1847 $value = strtolower($value);
1848 # $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.
1851 if (!$value) {$set=0;}
1857 for ($a=0;$a<$c;$a++
) {
1858 $char = substr($value,$a,1);
1859 if (strstr($is_in,$char)) {
1867 $value = str_replace(' ','',$value);
1870 $value = ereg_replace('[^a-zA-Z]','',$value);
1873 $value = ereg_replace('[^0-9]','',$value);
1876 $value = ereg_replace('[^a-zA-Z0-9]','',$value);
1879 $value = ereg_replace('[^a-zA-Z0-9_-]','',$value);
1883 if ($set) {$res['value'] = $value;}
1888 * Returns data for group/db and select fields
1890 * @param array Current value array
1891 * @param array TCA field config
1892 * @param integer Record id, used for look-up of MM relations (local_uid)
1893 * @param string Status string ('update' or 'new')
1894 * @param string The type, either 'select' or 'group'
1895 * @return array Modified value array
1897 function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type) {
1898 $tables = $type=='group'?
$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
1899 $prep = $type=='group'?
$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
1901 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1902 $dbAnalysis->registerNonTableValues
=$tcaFieldConf['allowNonIdValues'] ?
1 : 0;
1903 $dbAnalysis->start(implode($valueArray,','),$tables);
1905 if ($tcaFieldConf['MM']) {
1906 if ($status=='update') {
1907 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
1909 $this->dbAnalysisStore
[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep); // This will be traversed later to execute the actions
1911 $cc=count($dbAnalysis->itemArray
);
1912 $valueArray = array($cc);
1914 $valueArray = $dbAnalysis->getValueArray($prep);
1915 if ($type=='select' && $prep) {
1916 $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
1920 // 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.
1925 * Explodes the $value, which is a list of files/uids (group select)
1927 * @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.
1928 * @return array The value array.
1930 function checkValue_group_select_explodeSelectGroupValue($value) {
1931 $valueArray = t3lib_div
::trimExplode(',',$value,1);
1933 while(list($key,$newVal)=each($valueArray)) {
1934 $temp=explode('|',$newVal,2);
1935 $valueArray[$key] = str_replace(',','',str_replace('|','',rawurldecode($temp[0])));
1941 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
1942 * See checkValue_flex_procInData_travDS() for more details.
1944 * @param array The 'data' part of the INPUT flexform data
1945 * @param array The 'data' part of the CURRENT flexform data
1946 * @param array The uploaded files for the 'data' part of the INPUT flexform data
1947 * @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.
1948 * @param array A set of parameters to pass through for the calling of the evaluation functions
1949 * @param string Optional call back function, see checkValue_flex_procInData_travDS()
1950 * @return array The modified 'data' part.
1951 * @see checkValue_flex_procInData_travDS()
1953 function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='') {
1954 #debug(array($dataPart,$dataPart_current,$dataStructArray));
1955 if (is_array($dataPart)) {
1956 foreach($dataPart as $sKey => $sheetDef) {
1957 list ($dataStruct,$actualSheet) = t3lib_div
::resolveSheetDefInDS($dataStructArray,$sKey);
1958 #debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
1959 if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef)) {
1960 foreach($sheetDef as $lKey => $lData) {
1961 $this->checkValue_flex_procInData_travDS(
1962 $dataPart[$sKey][$lKey],
1963 $dataPart_current[$sKey][$lKey],
1964 $uploadedFiles[$sKey][$lKey],
1965 $dataStruct['ROOT']['el'],
1978 * Processing of the sheet/language data array
1979 * 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.
1981 * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
1982 * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
1983 * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
1984 * @param array Data structure which fits the data array
1985 * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
1986 * @param string Call back function, default is checkValue_SW().
1988 * @see checkValue_flex_procInData()
1990 function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc='') {
1991 if (is_array($DSelements)) {
1993 // For each DS element:
1994 foreach($DSelements as $key => $dsConf) {
1997 if ($DSelements[$key]['type']=='array') {
1998 if (is_array($dataValues[$key]['el'])) {
1999 if ($DSelements[$key]['section']) {
2000 foreach($dataValues[$key]['el'] as $ik => $el) {
2002 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2003 $this->checkValue_flex_procInData_travDS(
2004 $dataValues[$key]['el'][$ik][$theKey]['el'],
2005 $dataValues_current[$key]['el'][$ik][$theKey]['el'],
2006 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2007 $DSelements[$key]['el'][$theKey]['el'],
2014 if (!isset($dataValues[$key]['el'])) $dataValues[$key]['el']=array();
2015 $this->checkValue_flex_procInData_travDS(
2016 $dataValues[$key]['el'],
2017 $dataValues_current[$key]['el'],
2018 $uploadedFiles[$key]['el'],
2019 $DSelements[$key]['el'],
2026 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2027 foreach($dataValues[$key] as $vKey => $data) {
2029 if ($callBackFunc) {
2030 $res = $this->$callBackFunc(
2032 $dsConf['TCEforms']['config'],
2033 $dataValues[$key][$vKey],
2034 $dataValues_current[$key][$vKey],
2035 $uploadedFiles[$key][$vKey]
2038 list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
2040 $res = $this->checkValue_SW(
2042 $dataValues[$key][$vKey],
2043 $dsConf['TCEforms']['config'],
2046 $dataValues_current[$key][$vKey],
2051 $uploadedFiles[$key][$vKey],
2056 // Look for RTE transformation of field:
2057 if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations
) {
2059 // Unsetting trigger field - we absolutely don't want that into the data storage!
2060 unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
2062 if (isset($res['value'])) {
2064 // Calculating/Retrieving some values here:
2065 list(,,$recFieldName) = explode(':', $CVrecFID);
2066 $theTypeString = t3lib_BEfunc
::getTCAtypeValue($CVtable,$this->checkValue_currentRecord
);
2067 $specConf = t3lib_BEfunc
::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
2069 // Find, thisConfig:
2070 $RTEsetup = $this->BE_USER
->getTSConfig('RTE',t3lib_BEfunc
::getPagesTSconfig($CVtscPID));
2071 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
2073 // Get RTE object, draw form and set flag:
2074 $RTEobj = &t3lib_BEfunc
::RTEgetObj();
2075 if (is_object($RTEobj)) {
2076 $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord
,$specConf,$thisConfig,'',$CVrealPid);
2078 debug('NO RTE OBJECT FOUND!');
2084 // Adding the value:
2085 if (isset($res['value'])) {
2086 $dataValues[$key][$vKey] = $res['value'];
2114 /*********************************************
2116 * Storing data to Database Layer
2118 ********************************************/
2122 * Update database record
2123 * Does not check permissions but expects them to be verified on beforehand
2125 * @param string Record table name
2126 * @param integer Record uid
2127 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
2130 function updateDB($table,$id,$fieldArray) {
2133 if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id)) {
2134 unset($fieldArray['uid']); // Do NOT update the UID field, ever!
2136 if (count($fieldArray)) {
2138 // Execute the UPDATE query:
2139 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
2141 // If succees, do...:
2142 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2143 if ($this->checkStoredRecords
) {
2144 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
2148 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2149 $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
2151 // Set History data:
2152 $this->setHistory($table,$id,$theLogId);
2154 // Clear cache for relavant pages:
2155 $this->clear_cache($table,$id);
2157 // Unset the pageCache for the id if table was page.
2158 if ($table=='pages') unset($this->pageCache
[$id]);
2160 $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2167 * Compares the incoming field array with the current record and unsets all fields which are the same.
2168 * If the returned array is empty, then the record should not be updated!
2169 * $fieldArray must be an array.
2171 * @param string Record table name
2172 * @param integer Record uid
2173 * @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!
2174 * @return array Returns $fieldArray
2176 function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray) {
2178 // Fetch the original record:
2179 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2180 $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2182 // If the current record exists (which it should...), begin comparison:
2183 if (is_array($currentRecord)) {
2185 // Read all field types:
2187 $cRecTypes = array();
2188 foreach($currentRecord as $col => $val) {
2189 $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
2194 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2196 // Unset the fields which are similar:
2197 foreach($fieldArray as $col => $val) {
2199 #!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!]
2200 !strcmp($val,$currentRecord[$col]) ||
// Unset fields which matched exactly.
2201 ($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.
2203 unset($fieldArray[$col]);
2205 $this->historyRecords
[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
2206 $this->historyRecords
[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
2209 } else { // If the current record does not exist this is an error anyways and we just return an empty array here.
2210 $fieldArray = array();
2217 * Insert into database
2218 * Does not check permissions but expects them to be verified on beforehand
2220 * @param string Record table name
2221 * @param string "NEW...." uid string
2222 * @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!
2225 function insertDB($table,$id,$fieldArray) {
2228 if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid'])) {
2229 unset($fieldArray['uid']); // Do NOT insert the UID field, ever!
2231 if (count($fieldArray)) {
2233 // Execute the INSERT query:
2234 $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
2236 // If succees, do...:
2237 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2239 // Set mapping for NEW... -> real uid:
2240 $NEW_id = $id; // the NEW_id now holds the 'NEW....' -id
2241 $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
2242 $this->substNEWwithIDs
[$NEW_id] = $id;
2243 $this->substNEWwithIDs_table
[$NEW_id] = $table;
2245 // Checking the record is properly saved and writing to log
2246 if ($this->checkStoredRecords
) {
2247 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
2251 if ($table=='pages') {
2252 $thePositionID = $this->getInterfacePagePositionID($id);
2256 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2257 $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
2258 $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);
2260 // Clear cache for relavant pages:
2261 $this->clear_cache($table,$id);
2263 $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2270 * Checking stored record to see if the written values are properly updated.
2272 * @param string Record table name
2273 * @param integer Record uid
2274 * @param array Array of field=>value pairs to insert/update
2275 * @param string Action, for logging only.
2276 * @return array Selected row
2277 * @see insertDB(), updateDB()
2279 function checkStoredRecord($table,$id,$fieldArray,$action) {
2283 if (is_array($TCA[$table]) && $id) {
2284 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2285 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2287 // Traverse arrow of values that was inserted into the database and compare with the actually stored value:
2288 $errorString = array();
2289 foreach($fieldArray as $key => $value) {
2290 if ($this->checkStoredRecords_loose
&& !$value && !$row[$key]) {
2292 } elseif (strcmp($value,$row[$key])) {
2293 $errorString[] = $key;
2297 // Set log message if there were fields with unmatching values:
2298 if (count($errorString)) {
2299 $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
2302 // Return selected rows:
2305 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2310 * Executing dbAnalysisStore
2312 * @return [type] ...
2314 function dbAnalysisStoreExec() {
2315 reset($this->dbAnalysisStore
);
2316 while(list($k,$v)=each($this->dbAnalysisStore
)) {
2317 $id = $this->substNEWwithIDs
[$v[2]];
2320 $v[0]->writeMM($v[1],$v[2],$v[3]);
2326 * Executing dbAnalysisStore
2328 * @return [type] ...
2330 function removeRegisteredFiles() {
2331 reset($this->removeFilesStore
);
2332 while(list($k,$v)=each($this->removeFilesStore
)) {
2339 * Clearing the cache based on a page being updated
2340 * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
2341 * Else just clear the cache for the parent page of the record.
2343 * @param string Table name of record that was just updated.
2344 * @param integer UID of updated / inserted record
2347 function clear_cache($table,$uid) {
2350 $uid = intval($uid);
2351 if (is_array($TCA[$table]) && $uid > 0) {
2353 // Get Page TSconfig relavant:
2354 list($tscPID) = t3lib_BEfunc
::getTSCpid($table,$uid,'');
2355 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2357 // If table is "pages":
2358 if (t3lib_extMgm
::isLoaded('cms')) {
2359 if ($table=='pages') {
2361 // Builds list of pages on the SAME level as this page (siblings)
2362 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2363 'A.pid AS pid, B.uid AS uid',
2364 'pages AS A, pages AS B',
2365 'A.uid='.intval($uid).' AND B.pid=A.pid AND B.deleted=0'
2368 $list_cache = array();
2370 while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2371 $list_cache[] = $row_tmp['uid'];
2372 $pid_tmp = $row_tmp['pid'];
2374 // Add children as well:
2375 if ($TSConfig['clearCache_pageSiblingChildren']) {
2376 $res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2379 'pid='.intval($row_tmp['uid']).' AND deleted=0'
2381 while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2)) {
2382 $list_cache[] = $row_tmp2['uid'];
2387 // Finally, add the parent page as well:
2388 $list_cache[] = $pid_tmp;
2390 // Add grand-parent as well:
2391 if ($TSConfig['clearCache_pageGrandParent']) {
2392 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2395 'uid='.intval($pid_tmp)
2397 if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2398 $list_cache[] = $row_tmp['pid'];
2402 // Delete cache for selected pages:
2403 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2404 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2405 } else { // For other tables than "pages", delete cache for the records "parent page".
2406 $uid_page = $this->getPID($table,$uid);
2408 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id='.intval($uid_page));
2409 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id='.intval($uid_page));
2414 // Clear cache for pages entered in TSconfig:
2415 if ($TSConfig['clearCacheCmd']) {
2416 $Commands = t3lib_div
::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
2417 $Commands = array_unique($Commands);
2418 foreach($Commands as $cmdPart) {
2419 $this->clear_cacheCmd($cmdPart);
2423 // Call post processing function for clear-cache:
2424 global $TYPO3_CONF_VARS;
2425 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
2426 $_params = array('table' => $table,'uid' => $uid,'uid_page' => $uid_page);
2427 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
2428 t3lib_div
::callUserFunction($_funcRef,$_params,$this);
2435 * Returns the pid of a record from $table with $uid
2437 * @param string Table name
2438 * @param integer Record uid
2439 * @return integer PID value (unless the record did not exist in which case FALSE)
2441 function getPID($table,$uid) {
2442 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
2443 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2472 /*********************************************
2474 * Processing Commands
2476 ********************************************/
2479 * Processing the cmd-array
2483 function process_cmdmap() {
2485 #debug($this->cmdmap);
2486 reset ($this->cmdmap
);
2487 while (list($table,) = each($this->cmdmap
)) {
2488 $modifyAccessList = $this->checkModifyAccessList($table);
2489 if (!$modifyAccessList) {
2490 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
2492 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap
[$table]) && $modifyAccessList) { // Is table from $TCA and
2494 reset ($this->cmdmap
[$table]);
2495 while (list($id,$incomingCmdArray) = each($this->cmdmap
[$table])) { // Har fundet en tabel
2496 if (is_array($incomingCmdArray)) { // Har fundet et ID-nummer
2497 reset($incomingCmdArray);
2498 $command = key($incomingCmdArray);
2499 $value = current($incomingCmdArray);
2502 $this->moveRecord($table,$id,$value);
2505 $this->copyMappingArray
= Array(); // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
2506 if ($table == 'pages') {
2507 $this->copyPages($id,$value);
2509 $this->copyRecord($table,$id,$value,1);
2510 #debug(array($table,$id,$value));
2512 // Merging the copy-array info together for remapping purposes.
2513 $this->copyMappingArray_merged
= t3lib_div
::array_merge_recursive_overrule($this->copyMappingArray_merged
,$this->copyMappingArray
);
2516 if ($table == 'pages') {
2517 $this->deletePages($id);
2519 $this->deleteRecord($table,$id, 0);
2527 $this->remapListedDBRecords();
2533 * $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
2535 * @param [type] $table: ...
2536 * @param [type] $uid: ...
2537 * @param [type] $destPid: ...
2538 * @return [type] ...
2540 function moveRecord($table,$uid,$destPid) {
2543 $sortRow = $TCA[$table]['ctrl']['sortby'];
2544 $destPid = intval($destPid);
2545 $origDestPid = $destPid;
2547 $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
2548 $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving.
2550 // 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.
2551 // 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.
2552 if ($table!='pages' ||
$resolvedPid==$propArr['pid']) {
2553 $mayMoveAccess=$this->checkRecordUpdateAccess($table,$uid); // Edit rights for the record...
2555 $mayMoveAccess=$this->doesRecordExist($table,$uid,'delete');
2558 // 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
2559 if ($table!='pages' ||
$resolvedPid!=$propArr['pid']) {
2560 $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4); // Edit rights for the record...
2562 $mayInsertAccess=$this->checkRecordUpdateAccess($table,$uid);
2565 // 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...)
2566 if ($destPid<0 && !$sortRow) {
2567 $destPid = $resolvedPid;
2571 $updateFields = array();
2572 if ($TCA[$table]['ctrl']['tstamp']) {
2573 $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
2576 if ($mayMoveAccess) {
2577 if ($destPid>=0) { // insert as first element on page (where uid = $destPid)
2578 if ($mayInsertAccess) {
2579 if ($table!='pages' ||
$this->destNotInsideSelf ($destPid,$uid)) {
2580 $this->clear_cache($table,$uid); // clear cache before moving
2582 $updateFields['pid'] = $destPid; // Setting PID
2584 // table is sorted by 'sortby'
2586 $sortNumber = $this->getSortNumber($table,$uid,$destPid);
2587 $updateFields[$sortRow] = $sortNumber;
2590 // Create query for update:
2591 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2594 $newPropArr = $this->getRecordProperties($table,$uid);
2595 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2596 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2598 if ($destPid!=$propArr['pid']) {
2599 $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
2600 $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
2602 $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
2604 $this->clear_cache($table,$uid); // clear cache after moving
2605 $this->fixUniqueInPid($table,$uid);
2606 // fixCopyAfterDuplFields
2607 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.
2609 $destPropArr = $this->getRecordProperties('pages',$destPid);
2610 $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']);
2613 } else { // Put after another record
2614 if ($sortRow) { // table is being sorted
2615 $sortInfo = $this->getSortNumber($table,$uid,$destPid);
2616 $destPid = $sortInfo['pid']; // Setting the destPid to the new pid of the record.
2617 if (is_array($sortInfo)) { // If not an array, there was an error (which is already logged)
2618 if ($mayInsertAccess) {
2619 if ($table!='pages' ||
$this->destNotInsideSelf ($destPid,$uid)) {
2620 $this->clear_cache($table,$uid); // clear cache before moving
2622 $updateFields['pid'] = $destPid;
2623 $updateFields[$sortRow] = $sortInfo['sortNumber'];
2625 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields); // We now update the pid and sortnumber
2628 if ($table=='pages') {
2629 $thePositionID = $this->getInterfacePagePositionID($uid);
2634 $this->log($table,$uid,4,$thePositionID,0,'');
2636 $newPropArr = $this->getRecordProperties($table,$uid);
2637 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2638 if ($destPid!=$propArr['pid']) {
2639 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2640 $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
2641 $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
2643 $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
2645 $this->clear_cache($table,$uid); // clear cache after moving
2647 $this->fixUniqueInPid($table,$uid);
2648 // fixCopyAfterDuplFields
2649 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
2651 $destPropArr = $this->getRecordProperties('pages',$destPid);
2652 $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']);
2657 $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']);
2661 $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']);
2669 * $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
2670 * $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
2672 * @param [type] $table: ...
2673 * @param [type] $uid: ...
2674 * @param [type] $destPid: ...
2675 * @param [type] $first: ...
2676 * @return [type] ...
2678 function copyRecord($table,$uid,$destPid,$first=0) {
2680 $uid = intval($uid);
2681 if ($TCA[$table] && $uid) {
2682 t3lib_div
::loadTCA($table);
2683 if ($this->doesRecordExist($table,$uid,'show')) {
2685 $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody');
2686 $row = $this->recordInfo($table,$uid,'*');
2687 if (is_array($row)) {
2688 $theNewID = uniqid('NEW');
2689 // $fileFieldArr = $this->extFileFields($table); // Fetches all fields that holds references to files
2690 $enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ?
$TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
2691 $headerField = $TCA[$table]['ctrl']['label'];
2692 $defaultData = $this->newFieldArray($table);
2694 $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...
2695 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2696 $tE = $this->getTableEntries($table,$TSConfig);
2697 //debug(array($table,$destPid,$TSConfig));
2700 while (list($field,$value)=each($row)) {
2701 if (!in_array($field,$nonFields)) {
2702 $conf = $TCA[$table]['columns'][$field]['config'];
2704 if ($field=='pid') {
2708 if ($TCA[$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div
::inList($TCA[$table]['ctrl']['setToDefaultOnCopy'],$field)) {
2709 $value = $defaultData[$field];
2711 if ($first && $field==$enableField && $TCA[$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy
&& !$tE['disableHideAtCopy']) {
2714 if ($first && $field==$headerField && $TCA[$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy']) {
2715 $value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
2718 // 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)
2719 $value = $this->copyRecord_procFilesRefs($conf, $uid, $value);
2721 // Register if there are references to take care of (no change to value):
2722 if ($this->isReferenceField($conf)) {
2723 $allowedTables = $conf['type']=='group' ?
$conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
2724 $prependName = $conf['type']=='group' ?
$conf['prepend_tname'] : $conf['neg_foreign_table'];
2726 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2727 $dbAnalysis->start('',$allowedTables,$conf['MM'],$uid);
2728 $value = implode(',',$dbAnalysis->getValueArray($prependName));
2730 if ($value) { // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
2731 $this->registerDBList
[$table][$uid][$field] = $value;
2735 // 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())
2736 if ($conf['type']=='flex') {
2738 // Get current value array:
2739 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($conf, $row, $table);
2740 $currentValueArray = t3lib_div
::xml2array($value);
2742 // Traversing the XML structure, processing files:
2743 if (is_array($currentValueArray)) {
2744 $currentValueArray['data'] = $this->checkValue_flex_procInData(
2745 $currentValueArray['data'],
2746 array(), // Not used.
2747 array(), // Not used.
2749 array($table,$uid,$field), // Parameters.
2750 'copyRecord_flexFormCallBack'
2752 $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.
2757 // Add value to array.
2758 # $value=addSlashes($value); // Added 15-03-00, Remove 11-02-04 (see below)
2759 $data[$table][$theNewID][$field]=$value;
2763 // Added 02-05-02 to set the fields correctly for copied records...
2764 if ($destPid<0 && is_array($data[$table][$theNewID])) {
2765 $copyAfterFields = $this->fixCopyAfterDuplFields($table,$uid,abs($destPid),0);
2766 $data[$table][$theNewID] = array_merge($data[$table][$theNewID],$copyAfterFields);
2767 //debug($data[$table][$theNewID]);
2768 } // 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.
2772 //debug($data[$table][$theNewID]);
2773 #debug($data,'COPY RECORD:');
2774 $copyTCE = t3lib_div
::makeInstance('t3lib_TCEmain');
2775 $copyTCE->stripslashes_values
=0; // Added 11-02-04
2776 $copyTCE->copyTree
= $this->copyTree
;
2777 $copyTCE->cachedTSconfig
= $this->cachedTSconfig
; // Copy forth the cached TSconfig
2778 $copyTCE->dontProcessTransformations
=1; // Transformations should NOT be carried out during copy
2779 // $copyTCE->enableLogging = $table=='pages'?1:0; // If enabled the list-view does not update...
2781 $copyTCE->start($data,'',$this->BE_USER
);
2782 $copyTCE->process_datamap();
2784 $theNewSQLID = $copyTCE->substNEWwithIDs
[$theNewID];
2786 $this->copyMappingArray
[$table][$uid] = $theNewSQLID;
2788 $this->cachedTSconfig
= $copyTCE->cachedTSconfig
; // Copy back the cached TSconfig
2791 $this->log($table,$uid,3,0,1,'Attempt to copy record that did not exist!');
2794 $this->log($table,$uid,3,0,1,'Attempt to copy record without permission');
2800 * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
2802 * @param array Array of parameters in num-indexes: table, uid, field
2803 * @param array TCA field configuration (from Data Structure XML)
2804 * @param string The value of the flexForm field
2805 * @param string Not used.
2806 * @param string Not used.
2807 * @return array Result array with key "value" containing the value of the processing.
2808 * @see copyRecord(), checkValue_flex_procInData_travDS()
2810 function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2) {
2812 // Extract parameters:
2813 list($table, $uid, $field) = $pParams;
2815 // Process references and files, currently that means only the files, prepending absolute paths:
2816 $dataValue = $this->copyRecord_procFilesRefs($dsConf, $uid, $dataValue);
2818 // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
2819 if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
2820 $this->registerDBList
[$table][$uid][$field] = 'FlexForm_reference';
2824 return array('value' => $dataValue);
2828 * Modifying a field value for any situation regarding files/references:
2829 * For attached files: take current filenames and prepend absolute paths so they get copied.
2830 * For DB references: Nothing done.
2832 * @param array TCE field config
2833 * @param integer Record UID
2834 * @param string Field value (eg. list of files)
2835 * @return string The (possibly modified) value
2836 * @see copyRecord(), copyRecord_flexFormCallBack()
2838 function copyRecord_procFilesRefs($conf, $uid, $value) {
2840 // Prepend absolute paths to files:
2841 if ($conf['type']=='group' && $conf['internal_type']=='file') {
2843 // Get an array with files as values:
2845 $theFileValues = array();
2847 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2848 $dbAnalysis->start('', 'files', $conf['MM'], $uid);
2850 foreach($dbAnalysis->itemArray
as $somekey => $someval) {
2851 if ($someval['id']) {
2852 $theFileValues[] = $someval['id'];
2856 $theFileValues = t3lib_div
::trimExplode(',',$value,1);
2859 // Traverse this array of files:
2860 $uploadFolder = $conf['uploadfolder'];
2861 $dest = $this->destPathFromUploadFolder($uploadFolder);
2862 $newValue = array();
2864 foreach($theFileValues as $file) {
2866 $realFile = $dest.'/'.trim($file);
2867 if (@is_file
($realFile)) {
2868 $newValue[] = $realFile;
2873 // 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...)
2874 $value = implode(',',$newValue);
2877 // Return the new value:
2883 * Main function for copying pages.
2885 * @param integer Page UID to copy
2886 * @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
2889 function copyPages($uid,$destPid) {
2890 $uid = intval($uid);
2891 $destPid = intval($destPid);
2893 // Finding list of tables to copy.
2894 $copyTablesArray = $this->admin ?
$this->compileAdminTables() : explode(',',$this->BE_USER
->groupData
['tables_modify']); // These are the tables, the user may modify
2895 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
2896 foreach($copyTablesArray as $k => $table) {
2897 if (!$table ||
!t3lib_div
::inList($this->copyWhichTables
.',pages',$table)) { // pages are always going...
2898 unset($copyTablesArray[$k]);
2902 $copyTablesArray = array_unique($copyTablesArray);
2904 // Begin to copy pages if we're allowed to:
2905 if ($this->admin ||
in_array('pages',$copyTablesArray)) {
2907 // Copy this page we're on. And set first-flag!
2908 $this->copySpecificPage($uid,$destPid,$copyTablesArray,1);
2909 $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
2911 // If we're going to copy recursively...:
2912 if ($theNewRootID && $this->copyTree
) {
2914 // Get ALL subpages to copy:
2915 $CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($this->copyTree
), $theNewRootID);
2917 // Now copying the subpages:
2918 foreach($CPtable as $thePageUid => $thePagePid) {
2919 $newPid = $this->copyMappingArray
['pages'][$thePagePid];
2920 if (isset($newPid)) {
2921 $this->copySpecificPage($thePageUid,$newPid,$copyTablesArray);
2923 $this->log('pages',$uid,5,0,1,'Something went wrong during copying branch');