2 /***************************************************************
5 * (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@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 <kasperYYYY@typo3.com>
36 * [CLASS/FUNCTION INDEX of SCRIPT]
40 * 199: class t3lib_TCEmain
41 * 288: function start($data,$cmd,$altUserObject='')
42 * 321: function setMirror($mirror)
43 * 346: function setDefaultsFromUserTS($userTS)
44 * 369: function process_uploads($postFiles)
45 * 399: function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
47 * SECTION: PROCESSING DATA
48 * 435: function process_datamap()
49 * 628: function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
50 * 819: function checkModifyAccessList($table)
51 * 831: function isRecordInWebMount($table,$id)
52 * 845: function isInWebMount($pid)
53 * 862: function checkRecordUpdateAccess($table,$id)
54 * 887: function checkRecordInsertAccess($insertTable,$pid,$action=1)
55 * 923: function isTableAllowedForThisPage($page_uid, $checkTable)
56 * 958: function doesRecordExist($table,$id,$perms)
57 * 1021: function doesRecordExist_pageLookUp($id, $perms)
58 * 1047: function doesBranchExist($inList,$pid,$perms, $recurse)
59 * 1082: function pageInfo($id,$field)
60 * 1102: function recordInfo($table,$id,$fieldList)
61 * 1119: function getRecordProperties($table,$id)
62 * 1132: function getRecordPropertiesFromRow($table,$row)
63 * 1151: function setTSconfigPermissions($fieldArray,$TSConfig_p)
64 * 1167: function newFieldArray($table)
65 * 1198: function overrideFieldArray($table,$data)
66 * 1211: function assemblePermissions($string)
68 * SECTION: Evaluation of input values
69 * 1261: function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
70 * 1321: function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
71 * 1367: function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
72 * 1405: function checkValue_check($res,$value,$tcaFieldConf,$PP)
73 * 1428: function checkValue_radio($res,$value,$tcaFieldConf,$PP)
74 * 1454: function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
75 * 1554: function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
76 * 1707: function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
77 * 1765: function checkValue_flexArray2Xml($array)
78 * 1782: function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
80 * SECTION: Helper functions for evaluation functions.
81 * 1830: function getUnique($table,$field,$value,$id,$newPid=0)
82 * 1868: function checkValue_input_Eval($value,$evalArray,$is_in)
83 * 1956: function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)
84 * 1989: function checkValue_group_select_explodeSelectGroupValue($value)
85 * 2012: function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
86 * 2051: function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)
88 * SECTION: Storing data to Database Layer
89 * 2204: function updateDB($table,$id,$fieldArray)
90 * 2250: function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
91 * 2304: function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0)
92 * 2376: function checkStoredRecord($table,$id,$fieldArray,$action)
93 * 2412: function dbAnalysisStoreExec()
94 * 2428: function removeRegisteredFiles()
95 * 2445: function clear_cache($table,$uid)
96 * 2549: function getPID($table,$uid)
98 * SECTION: PROCESSING COMMANDS
99 * 2592: function process_cmdmap()
100 * 2680: function moveRecord($table,$uid,$destPid)
101 * 2824: function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
102 * 2933: function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
103 * 2989: function insertNewCopyVersion($table,$fieldArray,$realPid)
104 * 3040: function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf)
105 * 3093: function copyRecord_localize($table,$uid,$language)
106 * 3152: function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
107 * 3180: function copyRecord_procFilesRefs($conf, $uid, $value)
108 * 3231: function copyPages($uid,$destPid)
109 * 3286: function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
110 * 3316: function versionizeRecord($table,$id,$label)
111 * 3369: function versionizePages($uid,$label)
112 * 3426: function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
113 * 3451: function version_swap($table,$id,$swapWith,$swapContent)
114 * 3575: function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
115 * 3596: function compileAdminTables()
116 * 3613: function fixUniqueInPid($table,$uid)
117 * 3649: function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
118 * 3674: function extFileFields ($table)
119 * 3700: function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
120 * 3729: function prependLabel($table)
121 * 3746: function resolvePid($table,$pid)
122 * 3764: function clearPrefixFromValue($table,$value)
123 * 3775: function remapListedDBRecords()
124 * 3858: function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
125 * 3884: function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)
126 * 3929: function extFileFunctions($table,$field,$filelist,$func)
127 * 3961: function deleteRecord($table,$uid, $noRecordCheck)
128 * 4019: function deletePages($uid)
129 * 4061: function deleteSpecificPage($uid)
130 * 4085: function noRecordsFromUnallowedTables($inList)
132 * SECTION: MISC FUNCTIONS
133 * 4147: function getSortNumber($table,$uid,$pid)
134 * 4212: function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
135 * 4241: function rmComma ($input)
136 * 4251: function convNumEntityToByteValue($input)
137 * 4273: function destPathFromUploadFolder ($folder)
138 * 4284: function destNotInsideSelf ($dest,$id)
139 * 4310: function getExcludeListArray()
140 * 4334: function doesPageHaveUnallowedTables($page_uid,$doktype)
141 * 4367: function deleteClause($table)
142 * 4383: function tableReadOnly($table)
143 * 4395: function tableAdminOnly($table)
144 * 4409: function getInterfacePagePositionID($uid)
145 * 4442: function isReferenceField($conf)
146 * 4452: function getTCEMAIN_TSconfig($tscPID)
147 * 4466: function getTableEntries($table,$TSconfig)
148 * 4480: function setHistory($table,$id,$logId)
149 * 4517: function clearHistory($table,$id,$keepEntries=10,$maxAgeSeconds=604800)
150 * 4565: function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=0,$data=array(),$event_pid=-1,$NEWid='')
151 * 4579: function printLogErrorMessages($redirect)
152 * 4641: function clear_cacheCmd($cacheCmd)
153 * 4717: function removeCacheFiles()
155 * TOTAL FUNCTIONS: 101
156 * (This index is automatically created/updated by the extension "extdeveval")
163 // *******************************
164 // Including necessary libraries
165 // *******************************
166 require_once (PATH_t3lib
.'class.t3lib_loaddbgroup.php');
167 require_once (PATH_t3lib
.'class.t3lib_parsehtml_proc.php');
168 require_once (PATH_t3lib
.'class.t3lib_stdgraphic.php');
169 require_once (PATH_t3lib
.'class.t3lib_basicfilefunc.php');
184 * This is the TYPO3 Core Engine class for manipulation of the database
185 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
188 * - $GLOBALS['TCA'] must exist
189 * - $GLOBALS['LANG'] (languageobject) may be preferred, but not fatal.
191 * Note: Seems like many instances of array_merge() in this class are candidates for t3lib_div::array_merge() if integer-keys will some day make trouble...
193 * tce_db.php for further comments and SYNTAX! Also see document 'Inside TYPO3' for details.
195 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
199 class t3lib_TCEmain
{
200 var $log_table = 'sys_log';
202 var $checkStoredRecords = 1; // This will read the record after having updated or inserted it. If anything is not properly submitted an error is written to the log. This feature consumes extra time by selecting records
203 var $checkStoredRecords_loose=1; // If set, values '' and 0 will equal each other when the stored records are checked.
204 var $sortIntervals = 256; // The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
206 var $deleteTree = 0; // Boolean. If this is set, then a page is deleted by deleting the whole branch under it (user must have deletepermissions to it all). If not set, then the page is delete ONLY if it has no branch
207 var $copyTree = 0; // int. If 0 then branch is NOT copied. If 1 then pages on the 1st level is copied. If 2 then pages on the second level is copied ... and so on
208 var $versionizeTree = 0; // int. If 0 then branch is NOT versionized. If 1 then pages on the 1st level is versionized. If 2 then pages on the second level is versionized ... and so on
209 var $neverHideAtCopy = 0; // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
210 var $reverseOrder=0; // boolean. If set, the dataarray is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
211 var $copyWhichTables = '*'; // This list of tables decides which tables will be copied. If empty then none will. If '*' then all will (that the user has permission to of course)
212 var $stripslashes_values=1; // If set, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an unescaped data array instead. This switch may totally disappear in future versions of this class!
213 var $storeLogMessages=1; // If set, the default log-messages will be stored. This should not be necessary if the locallang-file for the log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
214 var $enableLogging=1; // If set, actions are logged.
216 var $callBackObj; // Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
218 // var $history=1; // Bit-array: Bit0: History on/off. DEPENDS on checkSimilar to be set!
219 var $checkSimilar=1; // Boolean: If set, only fields which are different from the database values are saved! In fact, if a whole input array is similar, it's not saved then.
220 var $dontProcessTransformations=0; // Boolean: If set, then transformations are NOT performed on the input.
221 # var $disableRTE = 0; // Boolean: If set, the RTE is expected to have been disabled in the interface which submitted information. Thus transformations related to the RTE is not done.
223 var $pMap = Array( // Permission mapping
224 'show' => 1, // 1st bit
225 'edit' => 2, // 2nd bit
226 'delete' => 4, // 3rd bit
227 'new' => 8, // 4th bit
228 'editcontent' => 16 // 5th bit
230 var $defaultPermissions = array( // Can be overridden from $TYPO3_CONF_VARS
231 'user' => 'show,edit,delete,new,editcontent',
232 'group' => 'show,edit,new,editcontent',
237 var $alternativeFileName=array(); // Use this array to force another name onto a file. Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field, then 'my_file.txt' will be used as the name instead.
238 var $data_disableFields=array(); // If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated. You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1. Then an empty checkbox will disable the field.
239 var $defaultValues=array(); // You can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. You must set this externally.
240 var $overrideValues=array(); // You can set this array on the form $overrideValues[$table][$field] = $value to override the incoming data. You must set this externally. You must make sure the fields in this array are also found in the table, because it's not checked. All columns can be set by this array!
241 var $suggestedInsertUids=array(); // Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be true, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)
246 var $fileFunc; // May contain an object
248 var $BE_USER; // The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
249 var $userid; // will be set to uid of be_user executing this script
250 var $username; // will be set to username of be_user executing this script
251 var $admin; // will be set if user is admin
252 var $exclude_array; // the list of <table>-<fields> that cannot be edited. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
255 var $datamap = Array();
257 var $cmdmap = Array();
258 var $uploadedFileArray = array();
260 var $cachedTSconfig = array();
261 var $substNEWwithIDs = Array();
262 var $substNEWwithIDs_table = Array();
263 var $recUpdateAccessCache = Array(); // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
264 var $recInsertAccessCache = Array();
265 var $isRecordInWebMount_Cache=array();
266 var $isInWebMount_Cache=array();
267 var $pageCache = Array(); // Used for caching page records in pageInfo()
268 var $copyMappingArray = Array(); // Use by the copy action to track the ids of new pages so subpages are correctly inserted!
269 var $copyMappingArray_merged = Array(); // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
270 var $registerDBList=array();
271 var $dbAnalysisStore=array();
272 var $removeFilesStore=array();
273 var $copiedFileMap=array();
275 var $checkValue_currentRecord=array(); // Set to "currentRecord" during checking of values.
280 * For details, see 'TYPO3 Core API' document.
281 * This function does not start the processing of data, but merely initializes the object
283 * @param array Data to be modified or inserted in the database
284 * @param array Commands to copy, move, delete records.
285 * @param object An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
288 function start($data,$cmd,$altUserObject='') {
289 // Initializing BE_USER
290 $this->BE_USER
= is_object($altUserObject) ?
$altUserObject : $GLOBALS['BE_USER'];
291 $this->userid
= $this->BE_USER
->user
['uid'];
292 $this->username
= $this->BE_USER
->user
['username'];
293 $this->admin
= $this->BE_USER
->user
['admin'];
295 // Initializing default permissions for pages
296 $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
297 if (isset($defaultPermissions['user'])) {$this->defaultPermissions
['user'] = $defaultPermissions['user'];}
298 if (isset($defaultPermissions['group'])) {$this->defaultPermissions
['group'] = $defaultPermissions['group'];}
299 if (isset($defaultPermissions['everybody'])) {$this->defaultPermissions
['everybody'] = $defaultPermissions['everybody'];}
301 // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
302 $this->exclude_array
= ($this->admin
) ?
array() : $this->getExcludeListArray();
304 // Setting the data and cmd arrays
305 if (is_array($data)) {
307 $this->datamap
= $data;
309 if (is_array($cmd)) {
311 $this->cmdmap
= $cmd;
316 * [Describe function...]
318 * @param array This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
321 function setMirror($mirror) {
322 if (is_array($mirror)) {
324 while(list($table,$uid_array)=each($mirror)) {
325 if (isset($this->datamap
[$table])) {
327 while (list($id,$uidList) = each($uid_array)) {
328 if (isset($this->datamap
[$table][$id])) {
329 $theIdsInArray = t3lib_div
::trimExplode(',',$uidList,1);
330 while(list(,$copyToUid)=each($theIdsInArray)) {
331 $this->datamap
[$table][$copyToUid] = $this->datamap
[$table][$id];
341 * Initializes default values coming from User TSconfig
343 * @param array User TSconfig array
346 function setDefaultsFromUserTS($userTS) {
348 if (is_array($userTS)) {
349 foreach($userTS as $k => $v) {
350 $k = substr($k,0,-1);
351 if ($k && is_array($v) && isset($TCA[$k])) {
352 if (is_array($this->defaultValues
[$k])) {
353 $this->defaultValues
[$k] = array_merge($this->defaultValues
[$k],$v);
355 $this->defaultValues
[$k] = $v;
363 * Processing of uploaded files.
364 * It turns out that some versions of PHP arranges submitted data for files different if sent in an array. This function will unify this so the internal array $this->uploadedFileArray will always contain files arranged in the same structure.
366 * @param array $_FILES array
369 function process_uploads($postFiles) {
370 if (is_array($postFiles)) {
372 $subA = current($postFiles);
373 if (is_array($subA)) {
374 if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
375 // Initialize the uploadedFilesArray:
376 $this->uploadedFileArray
=array();
379 foreach($subA as $key => $values) {
380 $this->process_uploads_traverseArray($this->uploadedFileArray
,$values,$key);
383 $this->uploadedFileArray
=$subA;
390 * Traverse the upload array if needed to rearrange values.
392 * @param array $this->uploadedFileArray passed by reference
393 * @param array Input array ($_FILES parts)
394 * @param string The current $_FILES array key to set on the outermost level.
397 * @see process_uploads()
399 function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet) {
400 if (is_array($inputArr)) {
401 foreach($inputArr as $key => $value) {
402 $this->process_uploads_traverseArray($outputArr[$key],$inputArr[$key],$keyToSet);
405 $outputArr[$keyToSet]=$inputArr;
423 /*********************************************
427 *********************************************/
430 * Processing the data-array
431 * Call this function to process the data-array set by start()
435 function process_datamap() {
436 global $TCA, $TYPO3_CONF_VARS;
438 // First prepare user defined objects (if any) for hooks which extend this function:
439 $hookObjectsArr = array();
440 if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
441 foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
442 $hookObjectsArr[] = &t3lib_div
::getUserObj($classRef);
446 // Organize tables so that the pages-table are always processed first. This is required if you want to make sure that content pointing to a new page will be created.
447 $orderOfTables = Array();
448 if (isset($this->datamap
['pages'])) { // Set pages first.
449 $orderOfTables[]='pages';
451 reset($this->datamap
);
452 while (list($table,) = each($this->datamap
)) {
453 if ($table!='pages') {
454 $orderOfTables[]=$table;
458 // Process the tables...
459 foreach($orderOfTables as $table) {
461 - table is set in $TCA,
462 - table is NOT readOnly,
463 - the table is set with content in the data-array (if not, there's nothing to process...)
464 - permissions for tableaccess OK
466 $modifyAccessList = $this->checkModifyAccessList($table);
467 if (!$modifyAccessList) {
468 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
470 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->datamap
[$table]) && $modifyAccessList) {
471 if ($this->reverseOrder
) {
472 $this->datamap
[$table] = array_reverse($this->datamap
[$table], 1);
475 // For each record from the table, do:
476 // $id is the record uid, may be a string if new records...
477 // $incomingFieldArray is the array of fields
478 foreach($this->datamap
[$table] as $id => $incomingFieldArray) {
479 if (is_array($incomingFieldArray)) {
481 // Hook: processDatamap_preProcessIncomingFieldArray
482 foreach($hookObjectsArr as $hookObj) {
483 if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
484 $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
488 // ******************************
489 // Checking access to the record
490 // ******************************
493 if (!t3lib_div
::testInt($id)) { // Is it a new record? (Then Id is a string)
494 $fieldArray = $this->newFieldArray($table); // Get a fieldArray with default values
495 if (isset($incomingFieldArray['pid'])) { // A pid must be set for new records.
497 $pid_value = $incomingFieldArray['pid'];
499 // Checking and finding numerical pid, it may be a string-reference to another value
501 if (strstr($pid_value,'NEW')) { // If a NEW... id
502 if (substr($pid_value,0,1)=='-') {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
503 if (isset($this->substNEWwithIDs
[$pid_value])) { // Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
504 $old_pid_value = $pid_value;
505 $pid_value=intval($negFlag*$this->substNEWwithIDs
[$pid_value]);
506 } else {$OK = 0;} // If not found in the substArray we must stop the proces...
508 $pid_value = intval($pid_value);
510 // The $pid_value is now the numerical pid at this point
512 $sortRow = $TCA[$table]['ctrl']['sortby'];
513 if ($pid_value>=0) { // Points to a page on which to insert the element, possibly in the top of the page
514 if ($sortRow) { // If this table is sorted we better find the top sorting number
515 $fieldArray[$sortRow] = $this->getSortNumber($table,0,$pid_value);
517 $fieldArray['pid'] = $pid_value; // The numerical pid is inserted in the data array
518 } else { // points to another record before ifself
519 if ($sortRow) { // If this table is sorted we better find the top sorting number
520 $tempArray=$this->getSortNumber($table,0,$pid_value); // Because $pid_value is < 0, getSortNumber returns an array
521 $fieldArray['pid'] = $tempArray['pid'];
522 $fieldArray[$sortRow] = $tempArray['sortNumber'];
523 } else { // Here we fetch the PID of the record that we point to...
524 $tempdata = $this->recordInfo($table,abs($pid_value),'pid');
525 $fieldArray['pid']=$tempdata['pid'];
530 $theRealPid = $fieldArray['pid'];
531 // Now, check if we may insert records on this pid.
532 if ($theRealPid>=0) {
533 $recordAccess = $this->checkRecordInsertAccess($table,$theRealPid); // Checks if records can be inserted on this $pid.
535 debug('Internal ERROR: pid should not be less than zero!');
537 $status = 'new'; // Yes new record, change $record_status to 'insert'
538 } else { // Nope... $id is a number
539 $fieldArray = Array();
540 $recordAccess = $this->checkRecordUpdateAccess($table,$id);
541 if (!$recordAccess) {
542 $propArr = $this->getRecordProperties($table,$id);
543 $this->log($table,$id,2,0,1,"Attempt to modify record '%s' (%s) without permission. Or non-existing page.",2,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
544 } else { // Next check of the record permissions (internals)
545 $recordAccess = $this->BE_USER
->recordEditAccessInternals($table,$id);
546 if (!$recordAccess) {
547 $propArr = $this->getRecordProperties($table,$id);
548 $this->log($table,$id,2,0,1,"recordEditAccessInternals() check failed. [".$this->BE_USER
->errorMsg
."]",2,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
549 } else { // Here we fetch the PID of the record that we point to...
550 $tempdata = $this->recordInfo($table,$id,'pid');
551 $theRealPid = $tempdata['pid'];
554 $status = 'update'; // the default is 'update'
557 // **************************************
558 // If access was granted above, proceed:
559 // **************************************
562 list($tscPID) = t3lib_BEfunc
::getTSCpid($table,$id,$old_pid_value ?
$old_pid_value : $fieldArray['pid']); // Here the "pid" is sent IF NOT the old pid was a string pointing to a place in the subst-id array.
563 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
564 if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.'])) {
565 $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
568 $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
570 // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
572 $fieldArray = $this->overrideFieldArray($table,$fieldArray); // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
574 // Setting system fields
575 if ($status=='new') {
576 if ($TCA[$table]['ctrl']['crdate']) {
577 $fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
579 if ($TCA[$table]['ctrl']['cruser_id']) {
580 $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid
;
582 } elseif ($this->checkSimilar
) { // Removing fields which are equal to the current value:
583 $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
585 if ($TCA[$table]['ctrl']['tstamp']) {
586 $fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
589 // Hook: processDatamap_postProcessFieldArray
590 foreach($hookObjectsArr as $hookObj) {
591 if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
592 $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
596 // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
597 // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
598 if (is_array($fieldArray)) {
599 if ($status=='new') {
600 // if ($pid_value<0) {$fieldArray = $this->fixCopyAfterDuplFields($table,$id,abs($pid_value),0,$fieldArray);} // Out-commented 02-05-02: I couldn't understand WHY this is needed for NEW records. Obviously to proces records being copied? Problem is that the fields are not set anyways and the copying function should basically take care of this!
601 $this->insertDB($table,$id,$fieldArray,FALSE,$incomingFieldArray['uid']);
603 $this->updateDB($table,$id,$fieldArray);
607 // Hook: processDatamap_afterDatabaseOperations
608 foreach($hookObjectsArr as $hookObj) {
609 if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
610 $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
613 } // if ($recordAccess) {
614 } // if (is_array($incomingFieldArray)) {
618 $this->dbAnalysisStoreExec();
619 $this->removeRegisteredFiles();
623 * Filling in the field array
624 * $this->exclude_array is used to filter fields if needed.
626 * @param string Table name
627 * @param [type] $id: ...
628 * @param array Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
629 * @param array $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
630 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
631 * @param string $status = 'new' or 'update'
632 * @param [type] $tscPID: ...
635 function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID) {
639 t3lib_div
::loadTCA($table);
640 unset($originalLanguageRecord);
641 unset($originalLanguage_diffStorage);
642 $diffStorageFlag = FALSE;
644 // Setting 'currentRecord' and 'checkValueRecord':
645 if (strstr($id,'NEW')) {
646 $currentRecord = $checkValueRecord = $fieldArray; // must have the 'current' array - not the values after processing below...
648 // IF $incomingFieldArray is an array, overlay it.
649 // The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
650 if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
651 $checkValueRecord = t3lib_div
::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
654 $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
656 // Get original language record if available:
657 if (is_array($currentRecord)
658 && $TCA[$table]['ctrl']['transOrigDiffSourceField']
659 && $TCA[$table]['ctrl']['languageField']
660 && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
661 && $TCA[$table]['ctrl']['transOrigPointerField']
662 && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0) {
664 $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ?
$TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
665 $originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
666 $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
669 $this->checkValue_currentRecord
= $checkValueRecord;
672 In the following all incoming value-fields are tested:
673 - Are the user allowed to change the field?
674 - Is the field uid/pid (which are already set)
675 - perms-fields for pages-table, then do special things...
676 - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
678 If everything is OK, the field is entered into $fieldArray[]
680 foreach($incomingFieldArray as $field => $fieldValue) {
681 if (!in_array($table.'-'.$field, $this->exclude_array
) && !$this->data_disableFields
[$table][$id][$field]) { // The field must be editable.
683 // Checking language:
684 $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER
->checkLanguageAccess($fieldValue);
686 if (!$languageDeny) {
687 // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
688 if ($this->stripslashes_values
) {
689 if (is_array($fieldValue)) {
690 t3lib_div
::stripSlashesOnArray($fieldValue);
691 } else $fieldValue = stripslashes($fieldValue);
697 // Nothing happens, already set
700 case 'perms_groupid':
703 case 'perms_everybody':
704 // Permissions can be edited by the owner or the administrator
705 if ($table=='pages' && ($this->admin ||
$status=='new' ||
$this->pageInfo($id,'perms_userid')==$this->userid
) ) {
706 $value=intval($fieldValue);
709 $fieldArray[$field]=$value;
711 case 'perms_groupid':
712 $fieldArray[$field]=$value;
715 if ($value>=0 && $value<pow(2,5)) {
716 $fieldArray[$field]=$value;
724 // t3ver_label is not here because it CAN be edited as a regular field!
727 if (isset($TCA[$table]['columns'][$field])) {
728 // Evaluating the value.
729 $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
730 if (isset($res['value'])) {
731 $fieldArray[$field]=$res['value'];
733 // Add the value of the original record to the diff-storage content:
734 if ($TCA[$table]['ctrl']['transOrigDiffSourceField']) {
735 $originalLanguage_diffStorage[$field] = $originalLanguageRecord[$field];
736 $diffStorageFlag = TRUE;
744 } // Checking language.
745 } // Check exclude fields / disabled fields...
748 // Add diff-storage information:
749 if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']])) { // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
750 $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
753 // Checking for RTE-transformations of fields:
754 $types_fieldConfig = t3lib_BEfunc
::getTCAtypes($table,$currentRecord);
755 $theTypeString = t3lib_BEfunc
::getTCAtypeValue($table,$currentRecord);
756 if (is_array($types_fieldConfig)) {
757 reset($types_fieldConfig);
758 while(list(,$vconf) = each($types_fieldConfig)) {
759 // Write file configuration:
760 $eFile = t3lib_parsehtml_proc
::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray)); // inserted array_merge($currentRecord,$fieldArray) 170502
762 // RTE transformations:
763 if (!$this->dontProcessTransformations
) {
764 if (isset($fieldArray[$vconf['field']])) {
765 // Look for transformation flag:
766 switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']]) {
768 $RTEsetup = $this->BE_USER
->getTSConfig('RTE',t3lib_BEfunc
::getPagesTSconfig($tscPID));
769 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
771 // Set alternative relative path for RTE images/links:
772 $RTErelPath = is_array($eFile) ?
dirname($eFile['relEditFile']) : '';
774 // Get RTE object, draw form and set flag:
775 $RTEobj = &t3lib_BEfunc
::RTEgetObj();
776 if (is_object($RTEobj)) {
777 $fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
779 debug('NO RTE OBJECT FOUND!');
786 // Write file configuration:
787 if (is_array($eFile)) {
788 $mixedRec = array_merge($currentRecord,$fieldArray);
789 $SW_fileContent = t3lib_div
::getUrl($eFile['editFile']);
790 $parseHTML = t3lib_div
::makeInstance('t3lib_parsehtml_proc');
791 $parseHTML->init('','');
793 $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ?
trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
794 $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]); // must replace the marker if present in content!
796 $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, chr(10).$insertContent.chr(10), 1, 1);
797 t3lib_div
::writeFile($eFile['editFile'],$SW_fileNewContent);
800 if (!strstr($id,'NEW') && $eFile['statusField']) {
801 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
805 $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
809 } elseif ($eFile && is_string($eFile)) {
810 $this->log($insertTable,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
819 * Checking group modify_table access list
821 * Returns true if the user has general access to modify the $table
823 * @param [type] $table: ...
826 function checkModifyAccessList($table) {
827 $res = ($this->admin ||
(!$this->tableAdminOnly($table) && t3lib_div
::inList($this->BE_USER
->groupData
['tables_modify'],$table)));
832 * [Describe function...]
834 * @param [type] $table: ...
835 * @param [type] $id: ...
838 function isRecordInWebMount($table,$id) {
839 if (!isset($this->isRecordInWebMount_Cache
[$table.':'.$id])) {
840 $recP=$this->getRecordProperties($table,$id);
841 $this->isRecordInWebMount_Cache
[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
843 return $this->isRecordInWebMount_Cache
[$table.':'.$id];
847 * [Describe function...]
849 * @param [type] $pid: ...
852 function isInWebMount($pid) {
853 if (!isset($this->isInWebMount_Cache
[$pid])) {
854 $this->isInWebMount_Cache
[$pid]=$this->BE_USER
->isInWebMount($pid);
856 //debug($this->isInWebMount_Cache);
857 return $this->isInWebMount_Cache
[$pid];
861 * Checks if user may update a certain record.
863 * Returns true if the user may update the record given by $table and $id
865 * @param [type] $table: ...
866 * @param [type] $id: ...
869 function checkRecordUpdateAccess($table,$id) {
872 if ($TCA[$table] && intval($id)>0) {
873 if (isset($this->recUpdateAccessCache
[$table][$id])) { // If information is cached, return it
874 return $this->recUpdateAccessCache
[$table][$id];
875 // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
876 } elseif ($this->doesRecordExist($table,$id,'edit')) {
879 $this->recUpdateAccessCache
[$table][$id]=$res; // Cache the result
885 * Checks if user may insert a certain record.
887 * Returns true if the user may insert a record from table $insertTable on page $pid
889 * @param [type] $insertTable: ...
890 * @param [type] $pid: ...
891 * @param [type] $action: ...
894 function checkRecordInsertAccess($insertTable,$pid,$action=1) {
899 if (isset($this->recInsertAccessCache
[$insertTable][$pid])) { // If information is cached, return it
900 return $this->recInsertAccessCache
[$insertTable][$pid];
902 // If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
903 if ( (!$pid && $this->admin
) ||
$this->doesRecordExist('pages',$pid,($insertTable=='pages'?
$this->pMap
['new']:$this->pMap
['editcontent'])) ) { // Check permissions
904 if ($this->isTableAllowedForThisPage($pid, $insertTable)) {
906 $this->recInsertAccessCache
[$insertTable][$pid]=$res; // Cache the result
908 $propArr = $this->getRecordProperties('pages',$pid);
909 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert record on page '%s' (%s) where this table, %s, is not allowed",11,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
912 $propArr = $this->getRecordProperties('pages',$pid);
913 $this->log($insertTable,$pid,$action,0,1,"Attempt to insert a record on page '%s' (%s) from table '%s' without permissions. Or non-existing page.",12,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
921 * Checks is a table is allowed on a certain page.
923 * $checkTable is the tablename
924 * $page_uid is the uid of the page to check
926 * @param [type] $page_uid: ...
927 * @param [type] $checkTable: ...
930 function isTableAllowedForThisPage($page_uid, $checkTable) {
931 global $TCA, $PAGES_TYPES;
932 $page_uid = intval($page_uid);
934 // Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
935 if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages') {
945 // Check non-root-level
946 $doktype = $this->pageInfo($page_uid,'doktype');
947 $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ?
$PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
948 $allowedArray = t3lib_div
::trimExplode(',',$allowedTableList,1);
949 if (strstr($allowedTableList,'*') ||
in_array($checkTable,$allowedArray)) { // If all tables or the table is listed as a allowed type, return true
956 * Checks if record exists
958 * Returns true if the record given by $table, $id and $perms
960 * @param string Record table name
961 * @param integer Record UID
962 * @param mixed Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array
965 function doesRecordExist($table,$id,$perms) {
971 // Processing the incoming $perms (from possible string to integer that can be AND'ed)
972 if (!t3lib_div
::testInt($perms)) {
973 if ($table!='pages') {
978 $perms = 'editcontent'; // This holds it all in case the record is not page!!
982 $perms = intval($this->pMap
[$perms]);
984 $perms = intval($perms);
987 if (!$perms) {debug('Internal ERROR: no permissions to check for non-admin user.');}
989 // For all tables: Check if record exists:
990 // Notice: If $perms are 0 (zero) no perms-clause is added!
991 if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) ||
$this->admin
)) {
992 if ($table != 'pages') {
994 // Find record without checking page:
995 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid', $table, 'uid='.intval($id).$this->deleteClause($table));
996 $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
997 t3lib_BEfunc
::fixVersioningPid($table,$output);
999 // If record found, check page as well:
1000 if (is_array($output)) {
1002 // Looking up the page for record:
1003 $mres = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
1004 $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
1006 // Return true if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
1007 if (is_array($pageRec) ||
(!$output['pid'] && $this->admin
)) {
1013 $mres = $this->doesRecordExist_pageLookUp($id, $perms);
1014 return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
1020 * Looks up a page based on permissions.
1022 * @param integer Page id
1023 * @param integer Permission integer
1024 * @return pointer MySQL result pointer (from exec_SELECTquery())
1026 * @see doesRecordExist()
1028 function doesRecordExist_pageLookUp($id, $perms) {
1031 return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1035 $this->deleteClause('pages').
1036 ($perms && !$this->admin ?
' AND '.$this->BE_USER
->getPagePermsClause($perms) : '').
1037 (!$this->admin
&& $TCA['pages']['ctrl']['editlock'] && ($perms & (2+
4+
16)) ?
' AND '.$TCA['pages']['ctrl']['editlock'].'=0':'') // admin users don't need check
1042 * Checks if a whole branch of pages exists
1044 * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
1045 * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
1046 * if $recurse is set, then the function will follow subpages. This MUST be set, if we need the idlist for deleting pages or else we get an incomplete list
1048 * @param [type] $inList: ...
1049 * @param [type] $pid: ...
1050 * @param [type] $perms: ...
1051 * @param [type] $recurse: ...
1052 * @return [type] ...
1054 function doesBranchExist($inList,$pid,$perms, $recurse) {
1056 $pid = intval($pid);
1057 $perms = intval($perms);
1059 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1060 'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
1062 'pid='.intval($pid).$this->deleteClause('pages'),
1066 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1067 if ($this->admin ||
$this->BE_USER
->doesUserHaveAccess($row,$perms)) { // IF admin, then it's OK
1068 $inList.=$row['uid'].',';
1069 if ($recurse) { // Follow the subpages recursively...
1070 $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
1071 if ($inList == -1) {return -1;} // No permissions somewhere in the branch
1074 return -1; // No permissions
1082 * Returns the value of the $field from page $id
1083 * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performanceloss since it doesn't look up the same record twice!
1085 * @param integer Page uid
1086 * @param string Field name for which to return value
1087 * @return string Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
1089 function pageInfo($id,$field) {
1090 if (!isset($this->pageCache
[$id])) {
1091 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
1092 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1093 $this->pageCache
[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1095 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1097 return $this->pageCache
[$id][$field];
1101 * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
1102 * NOTICE: No check for deleted or access!
1104 * @param string Table name
1105 * @param integer UID of the record from $table
1106 * @param string Field list for the SELECT query, eg. "*" or "uid,pid,..."
1107 * @return mixed Returns the selected record on success, otherwise false.
1109 function recordInfo($table,$id,$fieldList) {
1111 if (is_array($TCA[$table])) {
1112 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
1113 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1114 return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1120 * Returns an array with record properties, like header and pid
1122 * @param [type] $table: ...
1123 * @param [type] $id: ...
1124 * @return [type] ...
1126 function getRecordProperties($table,$id) {
1127 $row = ($table=='pages' && !$id) ?
array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
1128 t3lib_BEfunc
::fixVersioningPid($table,$row);
1129 return $this->getRecordPropertiesFromRow($table,$row);
1133 * Returns an array with record properties, like header and pid, based on the row
1135 * @param [type] $table: ...
1136 * @param [type] $row: ...
1137 * @return [type] ...
1139 function getRecordPropertiesFromRow($table,$row) {
1143 'header' => $row[$TCA[$table]['ctrl']['label']],
1144 'pid' => $row['pid'],
1145 'event_pid' => ($table=='pages'?
$row['uid']:$row['pid'])
1152 * [Describe function...]
1154 * @param [type] $fieldArray: ...
1155 * @param [type] $TSConfig_p: ...
1156 * @return [type] ...
1158 function setTSconfigPermissions($fieldArray,$TSConfig_p) {
1159 if (strcmp($TSConfig_p['userid'],'')) $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
1160 if (strcmp($TSConfig_p['groupid'],'')) $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
1161 if (strcmp($TSConfig_p['user'],'')) $fieldArray['perms_user']=t3lib_div
::testInt($TSConfig_p['user']) ?
$TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
1162 if (strcmp($TSConfig_p['group'],'')) $fieldArray['perms_group']=t3lib_div
::testInt($TSConfig_p['group']) ?
$TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
1163 if (strcmp($TSConfig_p['everybody'],'')) $fieldArray['perms_everybody']=t3lib_div
::testInt($TSConfig_p['everybody']) ?
$TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
1169 * Returns a fieldArray with default values.
1171 * @param [type] $table: ...
1172 * @return [type] ...
1174 function newFieldArray($table) {
1176 t3lib_div
::loadTCA($table);
1177 $fieldArray=Array();
1178 if (is_array($TCA[$table]['columns'])) {
1179 reset ($TCA[$table]['columns']);
1180 while (list($field,$content)=each($TCA[$table]['columns'])) {
1181 if (isset($this->defaultValues
[$table][$field])) {
1182 $fieldArray[$field] = $this->defaultValues
[$table][$field];
1183 } elseif (isset($content['config']['default'])) {
1184 $fieldArray[$field] = $content['config']['default'];
1188 if ($table=='pages') { // Set default permissions for a page.
1189 $fieldArray['perms_userid'] = $this->userid
;
1190 $fieldArray['perms_groupid'] = intval($this->BE_USER
->firstMainGroup
);
1191 $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions
['user']);
1192 $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions
['group']);
1193 $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions
['everybody']);
1199 * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
1201 * @param [type] $table: ...
1202 * @param [type] $data: ...
1203 * @return [type] ...
1205 function overrideFieldArray($table,$data) {
1206 if (is_array($this->overrideValues
[$table])) {
1207 $data = array_merge($data,$this->overrideValues
[$table]); // Candidate for t3lib_div::array_merge() if integer-keys will some day make trouble...
1213 * Calculates the bitvalue of the permissions given in a string, comma-sep
1215 * @param [type] $string: ...
1216 * @return [type] ...
1218 function assemblePermissions($string) {
1219 $keyArr = t3lib_div
::trimExplode(',',$string,1);
1221 while(list(,$key)=each($keyArr)) {
1222 if ($key && isset($this->pMap
[$key])) {
1223 $value |
= $this->pMap
[$key];
1248 /*********************************************
1250 * Evaluation of input values
1252 ********************************************/
1255 * Evaluates a value according to $table/$field settings.
1256 * This function is for real database fields - NOT FlexForm "pseudo" fields.
1257 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
1259 * @param string Table name
1260 * @param string Field name
1261 * @param string Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
1262 * @param string The record-uid, mainly - but not exclusively - used for logging
1263 * @param string 'update' or 'new' flag
1264 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1265 * @param integer $tscPID
1266 * @return array Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
1268 function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID) {
1269 global $TCA, $PAGES_TYPES;
1270 t3lib_div
::loadTCA($table);
1272 $res = Array(); // result array
1273 $recFID = $table.':'.$id.':'.$field;
1275 // Processing special case of field pages.doktype
1276 if ($table=='pages' && $field=='doktype') {
1277 // If the user may not use this specific doktype, we issue a warning
1278 if (! ($this->admin || t3lib_div
::inList($this->BE_USER
->groupData
['pagetypes_select'],$value))) {
1279 $propArr = $this->getRecordProperties($table,$id);
1280 $this->log($table,$id,5,0,1,"You cannot change the 'doktype' of page '%s' to the desired value.",1,array($propArr['header']),$propArr['event_pid']);
1283 if ($status=='update') {
1284 // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
1285 $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ?
$PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
1286 if ($onlyAllowedTables) {
1287 $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
1288 if ($theWrongTables) {
1289 $propArr = $this->getRecordProperties($table,$id);
1290 $this->log($table,$id,5,0,1,"'doktype' of page '%s' could not be changed because the page contains records from disallowed tables; %s",2,array($propArr['header'],$theWrongTables),$propArr['event_pid']);
1297 // Get current value:
1298 $curValueRec = $this->recordInfo($table,$id,$field);
1299 $curValue = $curValueRec[$field];
1301 // Getting config for the field
1302 $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
1304 // Preform processing:
1305 $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray
[$table][$id][$field],$tscPID);
1311 * Branches out evaluation of a field value based on its type as configured in TCA
1312 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
1314 * @param array The result array. The processed value (if any!) is set in the "value" key.
1315 * @param string The value to set.
1316 * @param array Field configuration from TCA
1317 * @param string Table name
1318 * @param integer Return UID
1319 * @param [type] $curValue: ...
1320 * @param [type] $status: ...
1321 * @param integer The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
1322 * @param [type] $recFID: ...
1323 * @param string Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
1324 * @param [type] $uploadedFiles: ...
1325 * @param [type] $tscPID: ...
1326 * @return array Returns the evaluated $value as key "value" in this array.
1328 function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID) {
1330 $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
1332 switch ($tcaFieldConf['type']) {
1336 $res['value'] = $value;
1339 $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
1342 $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
1345 $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
1349 $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1352 if ($field) { // FlexForms are only allowed for real fields.
1353 $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
1357 #debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
1365 * Evaluate "input" type values.
1367 * @param array The result array. The processed value (if any!) is set in the "value" key.
1368 * @param string The value to set.
1369 * @param array Field configuration from TCA
1370 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1371 * @param string Field name
1372 * @return array Modified $res array
1374 function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='') {
1375 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1377 // Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
1378 if (intval($tcaFieldConf['max'])>0) {$value = substr($value,0,intval($tcaFieldConf['max']));}
1380 // Checking range of value:
1381 if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox']) { // If value is not set to the allowed checkbox-value then it is checked against the ranges
1382 if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper']) {$value=$tcaFieldConf['range']['upper'];}
1383 if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower']) {$value=$tcaFieldConf['range']['lower'];}
1386 // Process evaluation settings:
1387 $evalCodesArray = t3lib_div
::trimExplode(',',$tcaFieldConf['eval'],1);
1388 $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
1390 // Process UNIQUE settings:
1391 if ($field && $realPid>=0) { // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
1392 if ($res['value'] && in_array('uniqueInPid',$evalCodesArray)) {
1393 $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
1395 if ($res['value'] && in_array('unique',$evalCodesArray)) {
1396 $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
1404 * Evaluates 'check' 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 * @return array Modified $res array
1412 function checkValue_check($res,$value,$tcaFieldConf,$PP) {
1413 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1415 $itemC = count($tcaFieldConf['items']);
1416 if (!$itemC) {$itemC=1;}
1417 $maxV = pow(2,$itemC);
1419 if ($value<0) {$value=0;}
1420 if ($value>$maxV) {$value=$maxV;}
1421 $res['value'] = $value;
1427 * Evaluates 'radio' type values.
1429 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1430 * @param string The value to set.
1431 * @param array Field configuration from TCA
1432 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1433 * @return array Modified $res array
1435 function checkValue_radio($res,$value,$tcaFieldConf,$PP) {
1436 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1438 if (is_array($tcaFieldConf['items'])) {
1439 foreach($tcaFieldConf['items'] as $set) {
1440 if (!strcmp($set[1],$value)) {
1441 $res['value'] = $value;
1451 * Evaluates 'group' or 'select' type values.
1453 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1454 * @param string The value to set.
1455 * @param array Field configuration from TCA
1456 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1457 * @param [type] $uploadedFiles: ...
1458 * @param string Field name
1459 * @return array Modified $res array
1461 function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1462 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1464 // Detecting if value send is an array and if so, implode it around a comma:
1465 if (is_array($value)) {
1466 $value = implode(',',$value);
1469 // 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.
1470 // Anyways, this should NOT disturb anything else:
1471 $value = $this->convNumEntityToByteValue($value);
1473 // When values are send as group or select they come as comma-separated values which are exploded by this function:
1474 $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
1476 // If not multiple is set, then remove duplicates:
1477 if (!$tcaFieldConf['multiple']) {
1478 $valueArray = array_unique($valueArray);
1481 // This could be a good spot for parsing the array through a validation-function which checks if the values are allright (except that database references are not in their final form - but that is the point, isn't it?)
1482 // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
1484 // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
1485 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode']) {
1486 $preCount = count($valueArray);
1487 foreach($valueArray as $kk => $vv) {
1488 if (!$this->BE_USER
->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode'])) {
1489 unset($valueArray[$kk]);
1493 // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
1494 if ($preCount && !count($valueArray)) {
1500 if ($tcaFieldConf['type']=='group') {
1501 switch($tcaFieldConf['internal_type']) {
1503 $valueArray = $this->checkValue_group_select_file(
1515 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group');
1519 // For select types which has a foreign table attached:
1520 if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table']) {
1521 $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select');
1524 // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
1526 // Checking the number of items, that it is correct.
1527 // If files, there MUST NOT be too many files in the list at this point, so check that prior to this code.
1528 $valueArrayC = count($valueArray);
1529 $minI = isset($tcaFieldConf['minitems']) ?
intval($tcaFieldConf['minitems']):0;
1531 // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
1532 $maxI = isset($tcaFieldConf['maxitems']) ?
intval($tcaFieldConf['maxitems']):1;
1533 if ($valueArrayC > $maxI) {$valueArrayC=$maxI;} // Checking for not too many elements
1535 // Dumping array to list
1537 foreach($valueArray as $nextVal) {
1538 if ($valueArrayC==0) {break;}
1542 $res['value'] = implode(',',$newVal);
1548 * Handling files for group/select function
1550 * @param [type] $valueArray: ...
1551 * @param [type] $tcaFieldConf: ...
1552 * @param [type] $curValue: ...
1553 * @param [type] $uploadedFileArray: ...
1554 * @param [type] $status: ...
1555 * @param [type] $table: ...
1556 * @param [type] $id: ...
1557 * @param [type] $recFID: ...
1558 * @return array Modified value array
1559 * @see checkValue_group_select()
1561 function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID) {
1563 // If any files are uploaded:
1564 if (is_array($uploadedFileArray) &&
1565 $uploadedFileArray['name'] &&
1566 strcmp($uploadedFileArray['tmp_name'],'none')) {
1567 $valueArray[]=$uploadedFileArray['tmp_name'];
1568 $this->alternativeFileName
[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
1571 // Creating fileFunc object.
1572 if (!$this->fileFunc
) {
1573 $this->fileFunc
= t3lib_div
::makeInstance('t3lib_basicFileFunctions');
1574 $this->include_filefunctions
=1;
1576 // Setting permitted extensions.
1577 $all_files = Array();
1578 $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
1579 $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ?
$tcaFieldConf['disallowed'] : '*';
1580 $all_files['ftpspace'] = $all_files['webspace'];
1581 $this->fileFunc
->init('', $all_files);
1583 // If there is an upload folder defined:
1584 if ($tcaFieldConf['uploadfolder']) {
1586 $propArr = $this->getRecordProperties($table,$id);
1588 // Get destrination path:
1589 $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
1591 // If we are updating:
1592 if ($status=='update') {
1594 // Finding the CURRENT files listed, either from MM or from the current record.
1595 $theFileValues=array();
1596 if ($tcaFieldConf['MM']) { // If MM relations for the files also!
1597 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1598 $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
1599 reset($dbAnalysis->itemArray
);
1600 while (list($somekey,$someval)=each($dbAnalysis->itemArray
)) {
1601 if ($someval['id']) {
1602 $theFileValues[]=$someval['id'];
1606 $theFileValues=t3lib_div
::trimExplode(',',$curValue,1);
1609 // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
1610 if (count($theFileValues)) {
1611 // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
1612 foreach($valueArray as $key => $theFile) {
1613 if ($theFile && !strstr(t3lib_div
::fixWindowsFilePath($theFile),'/')) {
1614 $theFileValues = t3lib_div
::removeArrayEntryByValue($theFileValues,$theFile);
1618 // This array contains the filenames in the uploadfolder that should be deleted:
1619 foreach($theFileValues as $key => $theFile) {
1620 $theFile = trim($theFile);
1621 if (@is_file
($dest.'/'.$theFile)) {
1622 $this->removeFilesStore
[]=$dest.'/'.$theFile;
1623 } elseif ($theFile) {
1624 $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
1630 // Traverse the submitted values:
1631 foreach($valueArray as $key => $theFile) {
1632 // NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
1633 if (strstr(t3lib_div
::fixWindowsFilePath($theFile),'/')) {
1635 $maxSize = intval($tcaFieldConf['max_size']);
1637 $theDestFile=''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!! (Change: 22/12/2000)
1639 // Check various things before copying file:
1640 if (@is_dir
($dest) && (@is_file
($theFile) || @is_uploaded_file
($theFile))) { // File and destination must exist
1642 // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
1643 if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name']) {
1644 $fileSize = $uploadedFileArray['size'];
1646 $fileSize = filesize($theFile);
1649 if (!$maxSize ||
$fileSize<=($maxSize*1024)) { // Check file size:
1650 // Prepare filename:
1651 $theEndFileName = isset($this->alternativeFileName
[$theFile]) ?
$this->alternativeFileName
[$theFile] : $theFile;
1652 $fI = t3lib_div
::split_fileref($theEndFileName);
1654 // Check for allowed extension:
1655 if ($this->fileFunc
->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
1656 $theDestFile = $this->fileFunc
->getUniqueName($this->fileFunc
->cleanFileName($fI['file']), $dest);
1658 // If we have a unique destination filename, then write the file:
1660 t3lib_div
::upload_copy_move($theFile,$theDestFile);
1661 $this->copiedFileMap
[$theFile] = $theDestFile;
1663 if (!@is_file
($theDestFile)) $this->log($table,$id,5,0,1,"Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)",16,array($theFile, dirname($theDestFile), $recFID),$propArr['event_pid']);
1664 } else $this->log($table,$id,5,0,1,"Copying file '%s' failed!: No destination file (%s) possible!. (%s)",11,array($theFile, $theDestFile, $recFID),$propArr['event_pid']);
1665 } else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
1666 } else $this->log($table,$id,5,0,1,"Filesize (%s) of file '%s' exceeds limit (%s). (%s)",13,array(t3lib_div
::formatSize($fileSize),$theFile,t3lib_div
::formatSize($maxSize*1024),$recFID),$propArr['event_pid']);
1667 } else $this->log($table,$id,5,0,1,'The destination (%s) or the source file (%s) does not exist. (%s)',14,array($dest, $theFile, $recFID),$propArr['event_pid']);
1669 // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
1670 if (@is_file
($theDestFile)) {
1671 $info = t3lib_div
::split_fileref($theDestFile);
1672 $valueArray[$key]=$info['file']; // The value is set to the new filename
1674 unset($valueArray[$key]); // The value is set to the new filename
1679 // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
1680 if ($tcaFieldConf['MM']) {
1681 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
1682 $dbAnalysis->tableArray
['files']=array(); // dummy
1685 while (list($key,$theFile)=each($valueArray)) {
1687 $dbAnalysis->itemArray
[]['id']=$theFile;
1689 if ($status=='update') {
1690 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
1692 $this->dbAnalysisStore
[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
1694 $cc=count($dbAnalysis->itemArray
);
1695 $valueArray = array($cc);
1703 * Evaluates 'flex' type values.
1705 * @param array The result array. The processed value (if any!) is set in the 'value' key.
1706 * @param string The value to set.
1707 * @param array Field configuration from TCA
1708 * @param array Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
1709 * @param array Uploaded files for the field
1710 * @param array Current record array.
1711 * @param string Field name
1712 * @return array Modified $res array
1714 function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field) {
1715 list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
1717 if (is_array($value)) {
1719 // Get current value array:
1720 $dataStructArray = t3lib_BEfunc
::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord
,$table);
1721 #debug($this->checkValue_currentRecord);
1722 $currentValueArray = t3lib_div
::xml2array($curValue);
1723 if (!is_array($currentValueArray)) $currentValueArray = array();
1724 if (is_array($currentValueArray['meta']['currentLangId'])) unset($currentValueArray['meta']['currentLangId']); // Remove all old meta for languages...
1726 // Evaluation of input values:
1727 $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
1729 // Create XML and convert charsets from input value:
1730 $xmlValue = $this->checkValue_flexArray2Xml($value);
1732 // If we wanted to set UTF fixed:
1733 // $storeInCharset='utf-8';
1734 // $currentCharset=$GLOBALS['LANG']->charSet;
1735 // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
1736 $storeInCharset=$GLOBALS['LANG']->charSet
;
1738 // Merge them together IF they are both arrays:
1739 // Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same (provided that the current value was already stored IN the charset that the new value is converted to).
1740 if (is_array($currentValueArray)) {
1741 $arrValue = t3lib_div
::xml2array($xmlValue);
1742 $arrValue = t3lib_div
::array_merge_recursive_overrule($currentValueArray,$arrValue);
1743 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1746 // Temporary fix to delete flex form elements:
1747 $deleteCMDs = t3lib_div
::_GP('_DELETE_FLEX_FORMdata');
1748 if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
1749 $arrValue = t3lib_div
::xml2array($xmlValue);
1750 $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
1751 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1754 // Temporary fix to move flex form elements up:
1755 $moveCMDs = t3lib_div
::_GP('_MOVEUP_FLEX_FORMdata');
1756 if (is_array($moveCMDs[$table][$id][$field]['data'])) {
1757 $arrValue = t3lib_div
::xml2array($xmlValue);
1758 $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'up');
1759 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1762 // Temporary fix to move flex form elements down:
1763 $moveCMDs = t3lib_div
::_GP('_MOVEDOWN_FLEX_FORMdata');
1764 if (is_array($moveCMDs[$table][$id][$field]['data'])) {
1765 $arrValue = t3lib_div
::xml2array($xmlValue);
1766 $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'down');
1767 $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
1770 // Create the value XML:
1772 $res['value'].='<?xml version="1.0" encoding="'.$storeInCharset.'" standalone="yes" ?>'.chr(10);
1773 $res['value'].=$xmlValue;
1774 } else { // Passthrough...:
1775 $res['value']=$value;
1782 * [Describe function...]
1784 * @param [type] $array: ...
1785 * @return [type] ...
1787 function checkValue_flexArray2Xml($array) {
1788 $output = t3lib_div
::array2xml($array,'',0,'T3FlexForms',4,array('parentTagMap' => array(
1789 /* 'data' => 'sheets',
1790 'sheets' => 'language',
1791 'language' => 'fieldname',
1792 'el' => 'fieldname' */
1798 * Deletes a flex form element
1800 * @param array &$valueArrayToRemoveFrom: by reference
1801 * @param [type] $deleteCMDS: ... *
1804 function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS) {
1805 if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
1806 foreach($deleteCMDS as $key => $value) {
1807 if (is_array($deleteCMDS[$key])) {
1808 $this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
1810 unset($valueArrayToRemoveFrom[$key]);
1817 * Deletes a flex form element
1819 * @param array &$valueArrayToMoveIn: by reference
1820 * @param [type] $moveCMDS: ... *
1821 * @param string $direction: 'up' or 'down'
1823 * TODO: Like _DELETE_FLEX_FORMdata, this is only a temporary solution!
1825 function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction) {
1826 if (is_array($valueArrayToMoveIn) && is_array($moveCMDS)) {
1828 // Only execute the first move command:
1829 list ($key, $value) = each ($moveCMDS);
1831 if (is_array($moveCMDS[$key])) {
1832 $this->_MOVE_FLEX_FORMdata($valueArrayToMoveIn[$key],$moveCMDS[$key], $direction);
1834 switch ($direction) {
1837 $tmpArr = $valueArrayToMoveIn[$key];
1838 $valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key-1];
1839 $valueArrayToMoveIn[$key-1] = $tmpArr;
1843 if ($key < count($valueArrayToMoveIn)) {
1844 $tmpArr = $valueArrayToMoveIn[$key];
1845 $valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key+
1];
1846 $valueArrayToMoveIn[$key+
1] = $tmpArr;
1871 /*********************************************
1873 * Helper functions for evaluation functions.
1875 ********************************************/
1879 * Gets a unique value for $table/$id/$field based on $value
1881 * @param string Table name
1882 * @param string Field name for which $value must be unique
1883 * @param string Value string.
1884 * @param integer UID to filter out in the lookup (the record itself...)
1885 * @param integer If set, the value will be unique for this PID
1886 * @return string Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
1888 function getUnique($table,$field,$value,$id,$newPid=0) {
1892 t3lib_div
::loadTCA($table);
1895 if (intval($newPid)) { $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AND pid>=0'; } // "AND pid>=0" for versioning
1896 $whereAdd.=$this->deleteClause($table);
1898 // If the field is configured in TCA, proceed:
1899 if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field])) {
1901 // Look for a record which might already have the value:
1902 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table).' AND uid!='.intval($id).$whereAdd);
1905 // For as long as records with the test-value existing, try again (with incremented numbers appended).
1906 while ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
1907 $newValue = $value.$counter;
1908 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table).' AND uid!='.intval($id).$whereAdd);
1910 if ($counter>100) { break; } // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
1912 // If the new value is there:
1913 $value = strlen($newValue) ?
$newValue : $value;
1919 * Evaluation of 'input'-type values based on 'eval' list
1921 * @param string Value
1922 * @param array Array of evaluations to traverse.
1923 * @param string Is-in string
1924 * @return string Modified $value
1926 function checkValue_input_Eval($value,$evalArray,$is_in) {
1931 foreach($evalArray as $func) {
1939 $value = intval($value);
1943 for ($a=strlen($value); $a>0; $a--) {
1944 if (substr($value,$a-1,1)=='.' ||
substr($value,$a-1,1)==',') {
1945 $theDec = substr($value,$a);
1946 $value = substr($value,0,$a-1);
1950 $theDec = ereg_replace('[^0-9]','',$theDec).'00';
1951 $value = intval(str_replace(' ','',$value)).'.'.substr($theDec,0,2);
1954 if (strlen($value)!=32){$set=false;}
1957 $value = trim($value);
1960 $value = strtoupper($value);
1961 # $value = strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÂÊÛÔÎÆØÅÄÖÜ'); // WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
1964 $value = strtolower($value);
1965 # $value = strtr($value, 'ÁÉÚÍÂÊÛÔÎÆØÅÄÖÜ', 'áéúíâêûôîæøåäöü'); // WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
1968 if (!$value) {$set=0;}
1974 for ($a=0;$a<$c;$a++
) {
1975 $char = substr($value,$a,1);
1976 if (strstr($is_in,$char)) {
1984 $value = str_replace(' ','',$value);
1987 $value = ereg_replace('[^a-zA-Z]','',$value);
1990 $value = ereg_replace('[^0-9]','',$value);
1993 $value = ereg_replace('[^a-zA-Z0-9]','',$value);
1996 $value = ereg_replace('[^a-zA-Z0-9_-]','',$value);
2000 if ($set) {$res['value'] = $value;}
2005 * Returns data for group/db and select fields
2007 * @param array Current value array
2008 * @param array TCA field config
2009 * @param integer Record id, used for look-up of MM relations (local_uid)
2010 * @param string Status string ('update' or 'new')
2011 * @param string The type, either 'select' or 'group'
2012 * @return array Modified value array
2014 function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type) {
2015 $tables = $type=='group'?
$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
2016 $prep = $type=='group'?
$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
2018 $dbAnalysis = t3lib_div
::makeInstance('t3lib_loadDBGroup');
2019 $dbAnalysis->registerNonTableValues
=$tcaFieldConf['allowNonIdValues'] ?
1 : 0;
2020 $dbAnalysis->start(implode(',',$valueArray),$tables);
2022 if ($tcaFieldConf['MM']) {
2023 if ($status=='update') {
2024 $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
2026 $this->dbAnalysisStore
[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep); // This will be traversed later to execute the actions
2028 $cc=count($dbAnalysis->itemArray
);
2029 $valueArray = array($cc);
2031 $valueArray = $dbAnalysis->getValueArray($prep);
2032 if ($type=='select' && $prep) {
2033 $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
2037 // Here we should se if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
2042 * Explodes the $value, which is a list of files/uids (group select)
2044 * @param string Input string, comma separated values. For each part it will also be detected if a '|' is found and the first part will then be used if that is the case. Further the value will be rawurldecoded.
2045 * @return array The value array.
2047 function checkValue_group_select_explodeSelectGroupValue($value) {
2048 $valueArray = t3lib_div
::trimExplode(',',$value,1);
2050 while(list($key,$newVal)=each($valueArray)) {
2051 $temp=explode('|',$newVal,2);
2052 $valueArray[$key] = str_replace(',','',str_replace('|','',rawurldecode($temp[0])));
2058 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
2059 * See checkValue_flex_procInData_travDS() for more details.
2061 * @param array The 'data' part of the INPUT flexform data
2062 * @param array The 'data' part of the CURRENT flexform data
2063 * @param array The uploaded files for the 'data' part of the INPUT flexform data
2064 * @param array Data structure for the form (might be sheets or not). Only values in the data array which has a configuration in the data structure will be processed.
2065 * @param array A set of parameters to pass through for the calling of the evaluation functions
2066 * @param string Optional call back function, see checkValue_flex_procInData_travDS()
2067 * @return array The modified 'data' part.
2068 * @see checkValue_flex_procInData_travDS()
2070 function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='') {
2071 #debug(array($dataPart,$dataPart_current,$dataStructArray));
2072 if (is_array($dataPart)) {
2073 foreach($dataPart as $sKey => $sheetDef) {
2074 list ($dataStruct,$actualSheet) = t3lib_div
::resolveSheetDefInDS($dataStructArray,$sKey);
2075 #debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
2076 if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef)) {
2077 foreach($sheetDef as $lKey => $lData) {
2078 $this->checkValue_flex_procInData_travDS(
2079 $dataPart[$sKey][$lKey],
2080 $dataPart_current[$sKey][$lKey],
2081 $uploadedFiles[$sKey][$lKey],
2082 $dataStruct['ROOT']['el'],
2096 * Processing of the sheet/language data array
2097 * When it finds a field with a value the processing is done by ->checkValue_SW() by default but if a call back function name is given that method in this class will be called for the processing instead.
2099 * @param array New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
2100 * @param array Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
2101 * @param array Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
2102 * @param array Data structure which fits the data array
2103 * @param array A set of parameters to pass through for the calling of the evaluation functions / call back function
2104 * @param string Call back function, default is checkValue_SW(). If $this->callBackObj is set to an object, the callback function in that object is called instead.
2105 * @param [type] $structurePath: ...
2107 * @see checkValue_flex_procInData()
2109 function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath) {
2110 if (is_array($DSelements)) {
2112 // For each DS element:
2113 foreach($DSelements as $key => $dsConf) {
2116 if ($DSelements[$key]['type']=='array') {
2117 if (is_array($dataValues[$key]['el'])) {
2118 if ($DSelements[$key]['section']) {
2119 foreach($dataValues[$key]['el'] as $ik => $el) {
2121 if (is_array($dataValues[$key]['el'][$ik][$theKey]['el'])) {
2122 $this->checkValue_flex_procInData_travDS(
2123 $dataValues[$key]['el'][$ik][$theKey]['el'],
2124 $dataValues_current[$key]['el'][$ik][$theKey]['el'],
2125 $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
2126 $DSelements[$key]['el'][$theKey]['el'],
2129 $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
2134 if (!isset($dataValues[$key]['el'])) $dataValues[$key]['el']=array();
2135 $this->checkValue_flex_procInData_travDS(
2136 $dataValues[$key]['el'],
2137 $dataValues_current[$key]['el'],
2138 $uploadedFiles[$key]['el'],
2139 $DSelements[$key]['el'],
2142 $structurePath.$key.'/el/'
2147 if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key])) {
2148 foreach($dataValues[$key] as $vKey => $data) {
2150 if ($callBackFunc) {
2151 if (is_object($this->callBackObj
)) {
2152 $res = $this->callBackObj
->$callBackFunc(
2154 $dsConf['TCEforms']['config'],
2155 $dataValues[$key][$vKey],
2156 $dataValues_current[$key][$vKey],
2157 $uploadedFiles[$key][$vKey],
2158 $structurePath.$key.'/'.$vKey.'/'
2161 $res = $this->$callBackFunc(
2163 $dsConf['TCEforms']['config'],
2164 $dataValues[$key][$vKey],
2165 $dataValues_current[$key][$vKey],
2166 $uploadedFiles[$key][$vKey]
2170 list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
2172 $res = $this->checkValue_SW(
2174 $dataValues[$key][$vKey],
2175 $dsConf['TCEforms']['config'],
2178 $dataValues_current[$key][$vKey],
2183 $uploadedFiles[$key][$vKey],
2188 // Look for RTE transformation of field:
2189 if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations
) {
2191 // Unsetting trigger field - we absolutely don't want that into the data storage!
2192 unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
2194 if (isset($res['value'])) {
2196 // Calculating/Retrieving some values here:
2197 list(,,$recFieldName) = explode(':', $CVrecFID);
2198 $theTypeString = t3lib_BEfunc
::getTCAtypeValue($CVtable,$this->checkValue_currentRecord
);
2199 $specConf = t3lib_BEfunc
::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
2201 // Find, thisConfig:
2202 $RTEsetup = $this->BE_USER
->getTSConfig('RTE',t3lib_BEfunc
::getPagesTSconfig($CVtscPID));
2203 $thisConfig = t3lib_BEfunc
::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
2205 // Get RTE object, draw form and set flag:
2206 $RTEobj = &t3lib_BEfunc
::RTEgetObj();
2207 if (is_object($RTEobj)) {
2208 $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord
,$specConf,$thisConfig,'',$CVrealPid);
2210 debug('NO RTE OBJECT FOUND!');
2216 // Adding the value:
2217 if (isset($res['value'])) {
2218 $dataValues[$key][$vKey] = $res['value'];
2246 /*********************************************
2248 * Storing data to Database Layer
2250 ********************************************/
2254 * Update database record
2255 * Does not check permissions but expects them to be verified on beforehand
2257 * @param string Record table name
2258 * @param integer Record uid
2259 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
2262 function updateDB($table,$id,$fieldArray) {
2265 if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id)) {
2266 unset($fieldArray['uid']); // Do NOT update the UID field, ever!
2268 if (count($fieldArray)) {
2270 // Execute the UPDATE query:
2271 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
2273 // If succees, do...:
2274 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2275 if ($this->checkStoredRecords
) {
2276 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
2280 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2281 $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
2283 // Set History data:
2284 $this->setHistory($table,$id,$theLogId);
2286 // Clear cache for relavant pages:
2287 $this->clear_cache($table,$id);
2289 // Unset the pageCache for the id if table was page.
2290 if ($table=='pages') unset($this->pageCache
[$id]);
2292 $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2299 * Compares the incoming field array with the current record and unsets all fields which are the same.
2300 * If the returned array is empty, then the record should not be updated!
2301 * $fieldArray must be an array.
2303 * @param string Record table name
2304 * @param integer Record uid
2305 * @param array Array of field=>value pairs intended to be inserted into the database. All keys with values matching exactly the current value will be unset!
2306 * @return array Returns $fieldArray
2308 function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray) {
2310 // Fetch the original record:
2311 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2312 $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
2314 // If the current record exists (which it should...), begin comparison:
2315 if (is_array($currentRecord)) {
2317 // Read all field types:
2319 $cRecTypes = array();
2320 foreach($currentRecord as $col => $val) {
2322 # $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($table,$col);
2323 $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
2329 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2331 // Unset the fields which are similar:
2332 foreach($fieldArray as $col => $val) {
2334 #!isset($currentRecord[$col]) || // Unset fields which were NOT found in the current record! [Uncommented because NULL fields will not return an entry in the array!]
2335 !strcmp($val,$currentRecord[$col]) ||
// Unset fields which matched exactly.
2336 ($cRecTypes[$col]=='int' && $currentRecord[$col]==0 && !strcmp($val,'')) // Now, a situation where TYPO3 tries to put an empty string into an integer field, we should not strcmp the integer-zero and '', but rather accept them to be similar.
2338 unset($fieldArray[$col]);
2340 $this->historyRecords
[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
2341 $this->historyRecords
[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
2344 } else { // If the current record does not exist this is an error anyways and we just return an empty array here.
2345 $fieldArray = array();
2352 * Insert into database
2353 * Does not check permissions but expects them to be verified on beforehand
2355 * @param string Record table name
2356 * @param string "NEW...." uid string
2357 * @param array Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done. "pid" must point to the destination of the record!
2358 * @param boolean Set to true if new version is created.
2359 * @param integer Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
2362 function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0) {
2365 if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid'])) {
2366 unset($fieldArray['uid']); // Do NOT insert the UID field, ever!
2368 if (count($fieldArray)) {
2370 // Check for "suggestedUid".
2371 // This feature is used by the import functionality to force a new record to have a certain UID value.
2372 // This is only recommended for use when the destination server is a passive mirrow of another server.
2373 // As a security measure this feature is available only for Admin Users (for now)
2374 $suggestedUid = intval($suggestedUid);
2375 if ($this->BE_USER
->isAdmin() && $suggestedUid && $this->suggestedInsertUids
[$table.':'.$suggestedUid]) {
2376 // When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
2377 if ($this->suggestedInsertUids
[$table.':'.$suggestedUid]==='DELETE') {
2379 $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($suggestedUid));
2381 $fieldArray['uid'] = $suggestedUid;
2384 // Execute the INSERT query:
2385 $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
2387 // If succees, do...:
2388 if (!$GLOBALS['TYPO3_DB']->sql_error()) {
2390 // Set mapping for NEW... -> real uid:
2391 $NEW_id = $id; // the NEW_id now holds the 'NEW....' -id
2392 $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
2393 $this->substNEWwithIDs
[$NEW_id] = $id;
2394 $this->substNEWwithIDs_table
[$NEW_id] = $table;
2396 // Checking the record is properly saved and writing to log
2397 if ($this->checkStoredRecords
) {
2398 $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
2402 $this->log($table,$id,1,0,0,"New version created of table '%s', uid '%s'",10,array($table,$fieldArray['t3ver_oid']),$newRow['pid'],$NEW_id);
2405 if ($table=='pages') {
2406 $thePositionID = $this->getInterfacePagePositionID($id);
2410 $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
2411 $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
2412 $this->log($table,$id,1,$thePositionID,0,"Record '%s' (%s) was inserted on page '%s' (%s)",10,array($propArr['header'],$table.':'.$id,$page_propArr['header'],$newRow['pid']),$newRow['pid'],$NEW_id);
2414 // Clear cache for relavant pages:
2415 $this->clear_cache($table,$id);
2418 $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
2425 * Checking stored record to see if the written values are properly updated.
2427 * @param string Record table name
2428 * @param integer Record uid
2429 * @param array Array of field=>value pairs to insert/update
2430 * @param string Action, for logging only.
2431 * @return array Selected row
2432 * @see insertDB(), updateDB()
2434 function checkStoredRecord($table,$id,$fieldArray,$action) {
2438 if (is_array($TCA[$table]) && $id) {
2439 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
2440 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
2441 // Traverse array of values that was inserted into the database and compare with the actually stored value:
2442 $errorString = array();
2443 foreach($fieldArray as $key => $value) {
2444 if ($this->checkStoredRecords_loose
&& !$value && !$row[$key]) {
2446 } elseif (strcmp($value,$row[$key])) {
2448 // debug(array("$value != ".$row[$key]));
2449 $errorString[] = $key;
2453 // Set log message if there were fields with unmatching values:
2454 if (count($errorString)) {
2455 $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
2458 // Return selected rows:
2461 $GLOBALS['TYPO3_DB']->sql_free_result($res);
2466 * Executing dbAnalysisStore
2468 * @return [type] ...
2470 function dbAnalysisStoreExec() {
2471 reset($this->dbAnalysisStore
);
2472 while(list($k,$v)=each($this->dbAnalysisStore
)) {
2473 $id = $this->substNEWwithIDs
[$v[2]];
2476 $v[0]->writeMM($v[1],$v[2],$v[3]);
2482 * Executing dbAnalysisStore
2484 * @return [type] ...
2486 function removeRegisteredFiles() {
2487 reset($this->removeFilesStore
);
2488 while(list($k,$v)=each($this->removeFilesStore
)) {
2495 * Clearing the cache based on a page being updated
2496 * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
2497 * Else just clear the cache for the parent page of the record.
2499 * @param string Table name of record that was just updated.
2500 * @param integer UID of updated / inserted record
2503 function clear_cache($table,$uid) {
2504 global $TCA, $TYPO3_CONF_VARS;
2506 $uid = intval($uid);
2507 if (is_array($TCA[$table]) && $uid > 0) {
2509 // Get Page TSconfig relavant:
2510 list($tscPID) = t3lib_BEfunc
::getTSCpid($table,$uid,'');
2511 $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
2513 if (!$TSConfig['clearCache_disable']) {
2515 // If table is "pages":
2516 if (t3lib_extMgm
::isLoaded('cms')) {
2517 $list_cache = array();
2518 if ($table=='pages') {
2520 // Builds list of pages on the SAME level as this page (siblings)
2521 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2522 'A.pid AS pid, B.uid AS uid',
2524 'A.uid='.intval($uid).' AND B.pid=A.pid AND B.deleted=0'
2528 while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2529 $list_cache[] = $row_tmp['uid'];
2530 $pid_tmp = $row_tmp['pid'];
2532 // Add children as well:
2533 if ($TSConfig['clearCache_pageSiblingChildren']) {
2534 $res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2537 'pid='.intval($row_tmp['uid']).' AND deleted=0'
2539 while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2)) {
2540 $list_cache[] = $row_tmp2['uid'];
2545 // Finally, add the parent page as well:
2546 $list_cache[] = $pid_tmp;
2548 // Add grand-parent as well:
2549 if ($TSConfig['clearCache_pageGrandParent']) {
2550 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
2553 'uid='.intval($pid_tmp)
2555 if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2556 $list_cache[] = $row_tmp['pid'];
2559 } else { // For other tables than "pages", delete cache for the records "parent page".
2560 $list_cache[] = intval($this->getPID($table,$uid));
2563 // Call pre-processing function for clearing of cache for page ids:
2564 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'])) {
2565 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName) {
2566 $_params = array('pageIdArray' => &$list_cache, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()');
2567 // Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
2568 t3lib_div
::callUserFunction($funcName,$_params,$this);
2572 // Delete cache for selected pages:
2573 if (is_array($list_cache)) {
2574 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2575 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
2580 // Clear cache for pages entered in TSconfig:
2581 if ($TSConfig['clearCacheCmd']) {
2582 $Commands = t3lib_div
::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
2583 $Commands = array_unique($Commands);
2584 foreach($Commands as $cmdPart) {
2585 $this->clear_cacheCmd($cmdPart);
2589 // Call post processing function for clear-cache:
2590 global $TYPO3_CONF_VARS;
2591 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'])) {
2592 $_params = array('table' => $table,'uid' => $uid,'uid_page' => $uid_page,'TSConfig' => $TSConfig);
2593 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef) {
2594 t3lib_div
::callUserFunction($_funcRef,$_params,$this);
2601 * Returns the pid of a record from $table with $uid
2603 * @param string Table name
2604 * @param integer Record uid
2605 * @return integer PID value (unless the record did not exist in which case FALSE)
2607 function getPID($table,$uid) {
2608 $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
2609 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
2638 /*********************************************
2640 * PROCESSING COMMANDS
2642 ********************************************/
2645 * Processing the cmd-array
2646 * See "TYPO3 Core API" for a description of the options.
2650 function process_cmdmap() {
2653 // Traverse command map:
2654 reset ($this->cmdmap
);
2655 while (list($table,) = each($this->cmdmap
)) {
2657 // Check if the table may be modified!
2658 $modifyAccessList = $this->checkModifyAccessList($table);
2659 if (!$modifyAccessList) {
2660 $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
2663 // Check basic permissions and circumstances:
2664 if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap
[$table]) && $modifyAccessList) {
2666 // Traverse the command map:
2667 foreach($this->cmdmap
[$table] as $id => $incomingCmdArray) {
2668 if (is_array($incomingCmdArray)) { // have found a command.
2670 // Get command and value (notice, only one command is observed at a time!):
2671 reset($incomingCmdArray);
2672 $command = key($incomingCmdArray);
2673 $value = current($incomingCmdArray);
2675 // Init copyMapping array:
2676 $this->copyMappingArray
= Array(); // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
2678 // Branch, based on command
2681 $this->moveRecord($table,$id,$value);
2684 if ($table == 'pages') {
2685 $this->copyPages($id,$value);
2687 $this->copyRecord($table,$id,$value,1);
2691 $this->copyRecord_localize($table,$id,$value);
2694 switch ((string)$value['action']) {
2696 $this->versionizeTree
= t3lib_div
::intInRange($value['treeLevels'],-1,4); // Max 4 levels of versioning...
2697 if ($table == 'pages' && $this->versionizeTree
>=0) {
2698 $this->versionizePages($id,$value['label']);
2700 $this->versionizeRecord($table,$id,$value['label']);
2704 $this->version_swap($table,$id,$value['swapWith'],$value['swapContent']);
2709 if ($table == 'pages') {
2710 $this->deletePages($id);
2712 $this->deleteRecord($table,$id, 0);
2716 // Merging the copy-array info together for remapping purposes.
2717 $this->copyMappingArray_merged
= t3lib_div
::array_merge_recursive_overrule($this->copyMappingArray_merged
,$this->copyMappingArray
);
2723 #debug($this->copyMappingArray_merged,'$this->copyMappingArray_merged');
2724 #debug($this->registerDBList,'$this->registerDBList');
2726 // Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
2727 $this->remapListedDBRecords();
2733 * @param string Table name to move
2734 * @param integer Record uid to move
2735 * @param integer Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
2738 function moveRecord($table,$uid,$destPid) {
2742 $sortRow = $TCA[$table]['ctrl']['sortby'];
2743 $destPid = intval($destPid);
2744 $origDestPid = $destPid;
2747 $propArr = $this->getRecordProperties($table,$uid); // Get this before we change the pid (for logging)
2748 $resolvedPid = $this->resolvePid($table,$destPid); // This is the actual pid of the moving.
2750 // Finding out, if the record may be moved from where it is. If the record is a non-page, then it depends on edit-permissions.
2751 // If the record is a page, then there are two options: If the page is moved within itself, (same pid) it's edit-perms of the pid. If moved to another place then its both delete-perms of the pid and new-page perms on the destination.
2752 if ($table!='pages' ||
$resolvedPid==$propArr['pid']) {
2753 $mayMoveAccess = $this->checkRecordUpdateAccess($table,$uid); // Edit rights for the record...
2755 $mayMoveAccess = $this->doesRecordExist($table,$uid,'delete');
2758 // Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new), unless the pages is moved on the same pid, then edit-rights are checked
2759 if ($table!='pages' ||
$resolvedPid!=$propArr['pid']) {
2760 $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4); // Edit rights for the record...
2762 $mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
2765 // Checking if the pid is negativ, but no sorting row is defined. In that case, find the correct pid. Basically this check make the error message 4-13 meaning less... But you can always remove this check if you prefer the error instead of a no-good action (which is to move the record to its own page...)
2766 if ($destPid<0 && !$sortRow) {
2767 $destPid = $resolvedPid;
2771 $updateFields = array();
2772 if ($TCA[$table]['ctrl']['tstamp']) {
2773 $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
2776 // If moving is allowed, begin the processing:
2777 if ($mayMoveAccess) {
2778 if ($destPid>=0) { // insert as first element on page (where uid = $destPid)
2779 if ($mayInsertAccess) {
2780 if ($table!='pages' ||
$this->destNotInsideSelf ($destPid,$uid)) {
2781 $this->clear_cache($table,$uid); // clear cache before moving
2783 $updateFields['pid'] = $destPid; // Setting PID
2785 // table is sorted by 'sortby'
2787 $sortNumber = $this->getSortNumber($table,$uid,$destPid);
2788 $updateFields[$sortRow] = $sortNumber;
2791 // Create query for update:
2792 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2795 $newPropArr = $this->getRecordProperties($table,$uid);
2796 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2797 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2799 if ($destPid!=$propArr['pid']) {
2800 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
2801 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2803 $this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2805 $this->clear_cache($table,$uid); // clear cache after moving
2806 $this->fixUniqueInPid($table,$uid);
2807 // fixCopyAfterDuplFields
2808 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);} // origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
2810 $destPropArr = $this->getRecordProperties('pages',$destPid);
2811 $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
2814 } else { // Put after another record
2815 if ($sortRow) { // table is being sorted
2816 $sortInfo = $this->getSortNumber($table,$uid,$destPid);
2817 $destPid = $sortInfo['pid']; // Setting the destPid to the new pid of the record.
2818 if (is_array($sortInfo)) { // If not an array, there was an error (which is already logged)
2819 if ($mayInsertAccess) {
2820 if ($table!='pages' ||
$this->destNotInsideSelf($destPid,$uid)) {
2821 $this->clear_cache($table,$uid); // clear cache before moving
2823 // We now update the pid and sortnumber
2824 $updateFields['pid'] = $destPid;
2825 $updateFields[$sortRow] = $sortInfo['sortNumber'];
2826 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
2829 if ($table=='pages') {
2830 $thePositionID = $this->getInterfacePagePositionID($uid);
2834 $this->log($table,$uid,4,$thePositionID,0,'');
2837 $newPropArr = $this->getRecordProperties($table,$uid);
2838 $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
2839 if ($destPid!=$propArr['pid']) {
2840 $newpagePropArr = $this->getRecordProperties('pages',$destPid);
2841 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']); // Logged to old page
2842 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2844 $this->log($table,$uid,4,$thePositionID,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid); // Logged to new page
2847 // clear cache after moving
2848 $this->clear_cache($table,$uid);
2851 $this->fixUniqueInPid($table,$uid);
2853 // fixCopyAfterDuplFields
2854 if ($origDestPid<0) {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
2856 $destPropArr = $this->getRecordProperties('pages',$destPid);
2857 $this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
2862 $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after another record, although the table has no sorting row.",13,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
2866 $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
2874 * @param string Element table
2875 * @param integer Element UID
2876 * @param integer $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
2877 * @param boolean $first is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
2878 * @param array Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!