- Clear All Cache also for the cached imagesizes (see clear_cacheCmd)
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tcemain.php
index 1965043..2da4bba 100755 (executable)
  *
  *
  *
- *  182: class t3lib_TCEmain   
- *  269:     function start($data,$cmd,$altUserObject='')      
- *  314:     function setMirror($mirror)       
- *  339:     function setDefaultsFromUserTS($userTS)   
- *  363:     function process_uploads($postFiles)      
- *  393:     function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)   
+ *  190: class t3lib_TCEmain   
+ *  275:     function start($data,$cmd,$altUserObject='')      
+ *  308:     function setMirror($mirror)       
+ *  333:     function setDefaultsFromUserTS($userTS)
+ *  357:     function process_uploads($postFiles)      
+ *  387:     function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)   
  *
  *              SECTION: PROCESSING DATA
- *  429:     function process_datamap() 
- *  600:     function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)    
- *  756:     function checkModifyAccessList($table)    
- *  768:     function isRecordInWebMount($table,$id)   
- *  782:     function isInWebMount($pid)       
- *  799:     function checkRecordUpdateAccess($table,$id)      
- *  824:     function checkRecordInsertAccess($insertTable,$pid,$action=1)     
- *  860:     function isTableAllowedForThisPage($page_uid, $checkTable)        
- *  895:     function doesRecordExist($table,$id,$perms)       
- *  958:     function doesBranchExist($inList,$pid,$perms, $recurse)   
- *  987:     function pageInfo($id,$field)     
- * 1007:     function recordInfo($table,$id,$fieldList)        
- * 1024:     function getRecordProperties($table,$id)  
- * 1036:     function getRecordPropertiesFromRow($table,$row)  
- * 1055:     function setTSconfigPermissions($fieldArray,$TSConfig_p)  
- * 1071:     function newFieldArray($table)    
- * 1102:     function overrideFieldArray($table,$data) 
- * 1115:     function assemblePermissions($string)     
+ *  423:     function process_datamap() 
+ *  586:     function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
+ *  757:     function checkModifyAccessList($table)    
+ *  769:     function isRecordInWebMount($table,$id)   
+ *  783:     function isInWebMount($pid)       
+ *  800:     function checkRecordUpdateAccess($table,$id)      
+ *  825:     function checkRecordInsertAccess($insertTable,$pid,$action=1)     
+ *  861:     function isTableAllowedForThisPage($page_uid, $checkTable)        
+ *  896:     function doesRecordExist($table,$id,$perms)       
+ *  991:     function doesBranchExist($inList,$pid,$perms, $recurse)   
+ * 1026:     function pageInfo($id,$field)     
+ * 1046:     function recordInfo($table,$id,$fieldList)        
+ * 1063:     function getRecordProperties($table,$id)  
+ * 1075:     function getRecordPropertiesFromRow($table,$row)  
+ * 1094:     function setTSconfigPermissions($fieldArray,$TSConfig_p)
+ * 1110:     function newFieldArray($table)    
+ * 1141:     function overrideFieldArray($table,$data) 
+ * 1154:     function assemblePermissions($string)     
  *
  *              SECTION: Evaluation of input values
- * 1164:     function checkValue($table,$field,$value,$id,$status,$realPid)    
- * 1220:     function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles)     
- * 1259:     function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')        
- * 1297:     function checkValue_check($res,$value,$tcaFieldConf,$PP)  
- * 1320:     function checkValue_radio($res,$value,$tcaFieldConf,$PP)  
- * 1345:     function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles)    
- * 1423:     function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)  
- * 1568:     function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$curRecordArr,$field)       
- * 1627:     function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)      
+ * 1204:     function checkValue($table,$field,$value,$id,$status,$realPid,$currentRecord)
+ * 1264:     function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$currentRecord=array())
+ * 1303:     function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
+ * 1341:     function checkValue_check($res,$value,$tcaFieldConf,$PP)
+ * 1364:     function checkValue_radio($res,$value,$tcaFieldConf,$PP)
+ * 1389:     function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles)
+ * 1471:     function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
+ * 1624:     function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$curRecordArr,$field)
+ * 1681:     function checkValue_flexArray2Xml($array)
+ * 1698:     function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)      
  *
  *              SECTION: Helper functions for evaluation functions.
- * 1675:     function getUnique($table,$field,$value,$id,$newPid=0)    
- * 1708:     function checkValue_input_Eval($value,$evalArray,$is_in)  
- * 1796:     function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)       
- * 1829:     function checkValue_group_select_explodeSelectGroupValue($value)  
- * 1850:     function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams) 
- * 1884:     function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams)  
+ * 1746:     function getUnique($table,$field,$value,$id,$newPid=0)    
+ * 1784:     function checkValue_input_Eval($value,$evalArray,$is_in)
+ * 1872:     function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)
+ * 1905:     function checkValue_group_select_explodeSelectGroupValue($value)
+ * 1928:     function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
+ * 1965:     function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc='')
  *
- *              SECTION: ...
- * 1984:     function updateDB($table,$id,$fieldArray) 
- * 2023:     function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)     
- * 2069:     function insertDB($table,$id,$fieldArray) 
- * 2120:     function checkStoredRecord($table,$id,$fieldArray,$action)        
- * 2146:     function dbAnalysisStoreExec()    
- * 2162:     function removeRegisteredFiles()  
- * 2180:     function clear_cache($table,$uid) 
- * 2261:     function getPID($table,$uid)      
+ *              SECTION: Storing data to Database Layer
+ * 2076:     function updateDB($table,$id,$fieldArray) 
+ * 2122:     function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
+ * 2170:     function insertDB($table,$id,$fieldArray) 
+ * 2224:     function checkStoredRecord($table,$id,$fieldArray,$action)        
+ * 2259:     function dbAnalysisStoreExec()    
+ * 2275:     function removeRegisteredFiles()  
+ * 2292:     function clear_cache($table,$uid) 
+ * 2358:     function getPID($table,$uid)      
  *
- *              SECTION: PROCESSING COMMANDS
- * 2303:     function process_cmdmap() 
- * 2360:     function moveRecord($table,$uid,$destPid) 
- * 2493:     function copyRecord($table,$uid,$destPid,$first=0)        
- * 2630:     function copyPages($uid,$destPid) 
- * 2680:     function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)        
- * 2708:     function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)        
- * 2730:     function compileAdminTables()     
- * 2747:     function fixUniqueInPid($table,$uid)      
- * 2783:     function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())   
- * 2808:     function extFileFields ($table)   
- * 2834:     function getCopyHeader ($table,$pid,$field,$value,$count,$prevTitle="")   
- * 2860:     function resolvePid ($table,$pid) 
- * 2878:     function prependLabel ($table)    
- * 2895:     function clearPrefixFromValue($table,$value)      
- * 2906:     function remapListedDBRecords()   
- * 2969:     function extFileFunctions($table,$field,$filelist,$func)  
- * 3001:     function deleteRecord($table,$uid, $noRecordCheck)        
- * 3057:     function deletePages($uid)        
- * 3099:     function deleteSpecificPage($uid) 
- * 3124:     function noRecordsFromUnallowedTables($inList)    
+ *              SECTION: Processing Commands
+ * 2400:     function process_cmdmap() 
+ * 2457:     function moveRecord($table,$uid,$destPid) 
+ * 2595:     function copyRecord($table,$uid,$destPid,$first=0)        
+ * 2727:     function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)     
+ * 2755:     function copyRecord_procFilesRefs($conf, $uid, $value)    
+ * 2806:     function copyPages($uid,$destPid) 
+ * 2859:     function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)        
+ * 2888:     function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)        
+ * 2909:     function compileAdminTables()     
+ * 2926:     function fixUniqueInPid($table,$uid)      
+ * 2962:     function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())   
+ * 2987:     function extFileFields ($table)   
+ * 3013:     function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')    
+ * 3042:     function prependLabel($table)     
+ * 3059:     function resolvePid($table,$pid)  
+ * 3077:     function clearPrefixFromValue($table,$value)      
+ * 3088:     function remapListedDBRecords()   
+ * 3171:     function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)   
+ * 3197:     function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)     
+ * 3242:     function extFileFunctions($table,$field,$filelist,$func)  
+ * 3274:     function deleteRecord($table,$uid, $noRecordCheck)        
+ * 3332:     function deletePages($uid)        
+ * 3374:     function deleteSpecificPage($uid) 
+ * 3398:     function noRecordsFromUnallowedTables($inList)    
  *
  *              SECTION: MISC FUNCTIONS
- * 3186:     function getSortNumber($table,$uid,$pid)  
- * 3247:     function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid) 
- * 3276:     function rmComma ($input) 
- * 3286:     function destPathFromUploadFolder ($folder)       
- * 3297:     function destNotInsideSelf ($dest,$id)    
- * 3326:     function getExcludeListArray()    
- * 3350:     function doesPageHaveUnallowedTables($page_uid,$doktype)  
- * 3380:     function deleteClause($table)     
- * 3396:     function tableReadOnly($table)    
- * 3408:     function tableAdminOnly($table)   
- * 3422:     function getInterfacePagePositionID($uid) 
- * 3451:     function getTCEMAIN_TSconfig($tscPID)     
- * 3465:     function getTableEntries($table,$TSconfig)        
- * 3479:     function setHistory($table,$id,$logId)            
- * 3516:     function clearHistory($table,$id,$keepEntries=10,$maxAgeSeconds=604800)           
- * 3565:     function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=0,$data=array(),$event_pid=-1,$NEWid="") 
- * 3579:     function printLogErrorMessages($redirect) 
- * 3625:     function clear_cacheCmd($cacheCmd)        
+ * 3460:     function getSortNumber($table,$uid,$pid)  
+ * 3525:     function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid) 
+ * 3554:     function rmComma ($input) 
+ * 3564:     function convNumEntityToByteValue($input) 
+ * 3586:     function destPathFromUploadFolder ($folder)       
+ * 3597:     function destNotInsideSelf ($dest,$id)    
+ * 3623:     function getExcludeListArray()    
+ * 3647:     function doesPageHaveUnallowedTables($page_uid,$doktype)  
+ * 3680:     function deleteClause($table)     
+ * 3696:     function tableReadOnly($table)    
+ * 3708:     function tableAdminOnly($table)   
+ * 3722:     function getInterfacePagePositionID($uid) 
+ * 3755:     function isReferenceField($conf)  
+ * 3765:     function getTCEMAIN_TSconfig($tscPID)
+ * 3779:     function getTableEntries($table,$TSconfig)
+ * 3793:     function setHistory($table,$id,$logId)            
+ * 3830:     function clearHistory($table,$id,$keepEntries=10,$maxAgeSeconds=604800)           
+ * 3878:     function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=0,$data=array(),$event_pid=-1,$NEWid='') 
+ * 3892:     function printLogErrorMessages($redirect) 
+ * 3936:     function clear_cacheCmd($cacheCmd)        
+ * 3985:     function removeCacheFiles()       
  *
- * TOTAL FUNCTIONS: 84
+ * TOTAL FUNCTIONS: 92
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
 // *******************************
 // Including necessary libraries
 // *******************************
-require_once (PATH_t3lib."class.t3lib_loaddbgroup.php");
-require_once (PATH_t3lib."class.t3lib_parsehtml_proc.php");
-require_once (PATH_t3lib."class.t3lib_stdgraphic.php");
-require_once (PATH_t3lib."class.t3lib_basicfilefunc.php");
+require_once (PATH_t3lib.'class.t3lib_loaddbgroup.php');
+require_once (PATH_t3lib.'class.t3lib_parsehtml_proc.php');
+require_once (PATH_t3lib.'class.t3lib_stdgraphic.php');
+require_once (PATH_t3lib.'class.t3lib_basicfilefunc.php');
 
 
 
@@ -166,34 +174,32 @@ require_once (PATH_t3lib."class.t3lib_basicfilefunc.php");
 /**
  * This is the TYPO3 Core Engine class for manipulation of the database
  * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
- * 
+ *
  * Dependencies:
- * - $GLOBALS["TCA"] must exist
- * - $GLOBALS["LANG"] (languageobject) may be preferred, but not fatal.
- * 
+ * - $GLOBALS['TCA'] must exist
+ * - $GLOBALS['LANG'] (languageobject) may be preferred, but not fatal.
+ *
  * 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...
- * 
- * tce_db.php for further comments and SYNTAX! Also see document "Inside TYPO3" for details.
- * 
+ *
+ * tce_db.php for further comments and SYNTAX! Also see document 'Inside TYPO3' for details.
+ *
  * @author     Kasper Skaarhoj <kasper@typo3.com>
  * @package TYPO3
  * @subpackage t3lib
  */
 class t3lib_TCEmain    {
-       var $debug = 0;
-       var $log_table = "sys_log";
+       var $log_table = 'sys_log';
        
-       var $clearCache_like = 0;               // If set, the clear_cache function will make a text-search for references to the page-id for which to clear cache and delete cached information for those pages in the result.
        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
        var $checkStoredRecords_loose=1;        // If set, values '' and 0 will equal each other when the stored records are checked.
-       var $sortIntervals = 256;               // The interval between sorting numbers used with tables with a "sorting" field defined. Min 1
+       var $sortIntervals = 256;               // The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
 
        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
        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
-       var $neverHideAtCopy = 0;               // Boolean. If set, then the "hideAtCopy" flag for tables will be ignored.
+       var $neverHideAtCopy = 0;               // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
        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.
-       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)
-       var $stripslashes_values=1;             // If set, incoming values in the data-array have their slashes stripped. This is default, because tce_main expects HTTP_POST_VARS and HTTP_GET_VARS to be slashed (which is probably done in init.php). If you supply your own data to the data-array, you can just unset this flag and slashes will not be stripped then. NOTICE: This flag may be set false by default in the future! ALWAYS supply a stripped (normalized values) array for data!!!!
+       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)
+       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!
        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.
        var $enableLogging=1;                   // If set, actions are logged.
 
@@ -201,31 +207,31 @@ class t3lib_TCEmain       {
        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.
        var $dontProcessTransformations=0;      // Boolean: If set, then transformations are NOT performed on the input.
        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.
-       
+
        var $pMap = Array(              // Permission mapping
-               "show" => 1,                    // 1st bit
-               "edit" => 2,                    // 2nd bit
-               "delete" => 4,                  // 3rd bit
-               "new" => 8,                             // 4th bit
-               "editcontent" => 16             // 5th bit
+               'show' => 1,                    // 1st bit
+               'edit' => 2,                    // 2nd bit
+               'delete' => 4,                  // 3rd bit
+               'new' => 8,                             // 4th bit
+               'editcontent' => 16             // 5th bit
        );
        var $defaultPermissions = array(                // Can be overridden from $TYPO3_CONF_VARS
-               "user" => "show,edit,delete,new,editcontent",
-               "group" => "show,edit,new,editcontent",
-               "everybody" => ""
+               'user' => 'show,edit,delete,new,editcontent',
+               'group' => 'show,edit,new,editcontent',
+               'everybody' => ''
        );
-       
 
-       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.
+
+       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.
        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.
        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.
        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!
-       
+
                // *********
                // internal
                // *********
        var $fileFunc;          // May contain an object
-       var $last_log_id;       
+       var $last_log_id;
        var $BE_USER;           // The user-object the the script uses. If not set from outside, this is set to the current global $BE_USER.
        var $userid;            // will be set to uid of be_user executing this script
        var $username;          // will be set to username of be_user executing this script
@@ -241,30 +247,30 @@ class t3lib_TCEmain       {
        var $cachedTSconfig = array();
        var $substNEWwithIDs = Array();
        var $substNEWwithIDs_table = Array();
-       var $recUpdateAccessCache = Array();    // Used by function checkRecordUpdateAccess() to store whether a record is updatable or not.
+       var $recUpdateAccessCache = Array();    // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
        var $recInsertAccessCache = Array();
        var $isRecordInWebMount_Cache=array();
        var $isInWebMount_Cache=array();
-       var $pageCache = Array();
+       var $pageCache = Array();                                       // Used for caching page records in pageInfo()
        var $copyMappingArray = Array();                // Use by the copy action to track the ids of new pages so subpages are correctly inserted!
        var $copyMappingArray_merged = Array();         // This array is the sum of all copying operations in this class
-       var $registerDBList=array();                            
+       var $registerDBList=array();
        var $dbAnalysisStore=array();
        var $removeFilesStore=array();
        var $copiedFileMap=array();
-       
 
+       var $checkValue_currentRecord=array();          // Set to "currentRecord" during checking of values.
 
 
        /**
         * Initializing.
-        * For details, see 'Inside TYPO3' document.
-        * This function does not start the processing of data, by merely initializes the object
-        * 
+        * For details, see 'TYPO3 Core API' document.
+        * This function does not start the processing of data, but merely initializes the object
+        *
         * @param       array           Data to be modified or inserted in the database
         * @param       array           Commands to copy, move, delete records.
         * @param       object          An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
-        * @return      void            
+        * @return      void
         */
        function start($data,$cmd,$altUserObject='')    {
                        // Initializing BE_USER
@@ -291,25 +297,13 @@ class t3lib_TCEmain       {
                        reset($cmd);
                        $this->cmdmap = $cmd;
                }
-               
-                       // Output debug information
-               if ($this->debug)       {
-                       echo '<BR>User Information:';
-                       debug(Array('username'=>$this->username, 'userid'=>$this->userid, 'admin'=>$this->admin));
-                       echo '<BR>DataMap:';
-                       debug($this->data);
-                       debug($this->datamap);
-                       echo '<BR>CommandMap:';
-                       debug($this->cmd);
-                       debug($this->cmdmap);
-               }
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       array           This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
-        * @return      void            
+        * @return      void
         */
        function setMirror($mirror)     {
                if (is_array($mirror))  {
@@ -332,16 +326,15 @@ class t3lib_TCEmain       {
 
        /**
         * Initializes default values coming from User TSconfig
-        * 
+        *
         * @param       array           User TSconfig array
-        * @return      void            
+        * @return      void
         */
        function setDefaultsFromUserTS($userTS) {
                global $TCA;
                if (is_array($userTS))  {
-                       reset($userTS);
-                       while(list($k,$v)=each($userTS))        {
-                               $k=substr($k,0,-1);
+                       foreach($userTS as $k => $v)    {
+                               $k = substr($k,0,-1);
                                if ($k && is_array($v) && isset($TCA[$k]))      {
                                        if (is_array($this->defaultValues[$k])) {
                                                $this->defaultValues[$k] = array_merge($this->defaultValues[$k],$v);
@@ -356,9 +349,9 @@ class t3lib_TCEmain {
        /**
         * Processing of uploaded files.
         * 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.
-        * 
+        *
         * @param       array           HTTP_POST_FILES array
-        * @return      void            
+        * @return      void
         */
        function process_uploads($postFiles)    {
                if (is_array($postFiles))       {
@@ -382,11 +375,11 @@ class t3lib_TCEmain       {
        
        /**
         * Traverse the upload array if needed to rearrange values.
-        * 
+        *
         * @param       array           $this->uploadedFileArray passed by reference
         * @param       array           Input array  (HTTP_POST_FILES parts)
         * @param       string          The current HTTP_POST_FILES array key to set on the outermost level.
-        * @return      void            
+        * @return      void
         * @access private
         * @see process_uploads()
         */
@@ -423,7 +416,7 @@ class t3lib_TCEmain {
        /**
         * Processing the data-array
         * Call this function to process the data-array set by start()
-        * 
+        *
         * @return      [type]          ...
         */
        function process_datamap() {
@@ -433,10 +426,10 @@ class t3lib_TCEmain       {
                        // 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.
                $orderOfTables = Array();
                if (isset($this->datamap['pages']))     {               // Set pages first.
-                       $orderOfTables[]="pages";
+                       $orderOfTables[]='pages';
                }
                while (list($table,) = each($this->datamap))    {
-                       if ($table!="pages")    {
+                       if ($table!='pages')    {
                                $orderOfTables[]=$table;
                        }
                }
@@ -464,25 +457,22 @@ class t3lib_TCEmain       {
                                        // $incomingFieldArray is the array of fields
                                while (list($id,$incomingFieldArray) = each($this->datamap[$table]))    {
                                        if (is_array($incomingFieldArray))      { 
-                                               if ($this->debug)       {
-                                                       debug("INCOMING RECORD: ".$table.":".$id);
-                                                       debug($incomingFieldArray);
-                                               }
+
                                                        // ******************************
                                                        // Checking access to the record
                                                        // ******************************
                                                $recordAccess=0;
-                                               $old_pid_value = "";
+                                               $old_pid_value = '';
                                                if (!t3lib_div::testInt($id)) {               // Is it a new record? (Then Id is a string)
                                                        $fieldArray = $this->newFieldArray($table);     // Get a fieldArray with default values
-                                                       if (isset($incomingFieldArray["pid"]))  {       // A pid must be set for new records.
+                                                       if (isset($incomingFieldArray['pid']))  {       // A pid must be set for new records.
                                                                        // $value = the pid
-                                                               $pid_value = $incomingFieldArray["pid"];
+                                                               $pid_value = $incomingFieldArray['pid'];
 
                                                                        // Checking and finding numerical pid, it may be a string-reference to another value
                                                                $OK = 1;
-                                                               if (strstr($pid_value,"NEW"))   {       // If a NEW... id
-                                                                       if (substr($pid_value,0,1)=="-") {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
+                                                               if (strstr($pid_value,'NEW'))   {       // If a NEW... id
+                                                                       if (substr($pid_value,0,1)=='-') {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
                                                                        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.
                                                                                $old_pid_value = $pid_value;
                                                                                $pid_value=intval($negFlag*$this->substNEWwithIDs[$pid_value]); 
@@ -492,30 +482,30 @@ class t3lib_TCEmain       {
 
                                                                        // The $pid_value is now the numerical pid at this point
                                                                if ($OK)        {
-                                                                       $sortRow = $TCA[$table]["ctrl"]["sortby"];
+                                                                       $sortRow = $TCA[$table]['ctrl']['sortby'];
                                                                        if ($pid_value>=0)      {       // Points to a page on which to insert the element, possibly in the top of the page
                                                                                if ($sortRow)   {       // If this table is sorted we better find the top sorting number
                                                                                        $fieldArray[$sortRow] = $this->getSortNumber($table,0,$pid_value);
                                                                                }
-                                                                               $fieldArray["pid"] = $pid_value;        // The numerical pid is inserted in the data array
+                                                                               $fieldArray['pid'] = $pid_value;        // The numerical pid is inserted in the data array
                                                                        } else {        // points to another record before ifself
                                                                                if ($sortRow)   {       // If this table is sorted we better find the top sorting number
                                                                                        $tempArray=$this->getSortNumber($table,0,$pid_value);   // Because $pid_value is < 0, getSortNumber returns an array
-                                                                                       $fieldArray["pid"] = $tempArray["pid"];
-                                                                                       $fieldArray[$sortRow] = $tempArray["sortNumber"];
+                                                                                       $fieldArray['pid'] = $tempArray['pid'];
+                                                                                       $fieldArray[$sortRow] = $tempArray['sortNumber'];
                                                                                } else {        // Here we fetch the PID of the record that we point to...
-                                                                                       $tempdata = $this->recordInfo($table,abs($pid_value),"pid");
-                                                                                       $fieldArray["pid"]=$tempdata["pid"];
+                                                                                       $tempdata = $this->recordInfo($table,abs($pid_value),'pid');
+                                                                                       $fieldArray['pid']=$tempdata['pid'];
                                                                                }
                                                                        }
                                                                }
                                                        }
-                                                       $theRealPid = $fieldArray["pid"];
+                                                       $theRealPid = $fieldArray['pid'];
                                                                // Now, check if we may insert records on this pid.
                                                        if ($theRealPid>=0)     {
                                                                $recordAccess = $this->checkRecordInsertAccess($table,$theRealPid);     // Checks if records can be inserted on this $pid.
                                                        } else {
-                                                               debug("Internal ERROR: pid should not be less than zero!");
+                                                               debug('Internal ERROR: pid should not be less than zero!');
                                                        }
                                                        $status='new';                                          // Yes new record, change $record_status to 'insert'
                                                } else {        // Nope... $id is a number
@@ -523,49 +513,48 @@ class t3lib_TCEmain       {
                                                        $recordAccess = $this->checkRecordUpdateAccess($table,$id);
                                                        if (!$recordAccess)             {
                                                                $propArr = $this->getRecordProperties($table,$id);
-                                                               $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"]);
+                                                               $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']);
                                                        } else {        // Here we fetch the PID of the record that we point to...
-                                                               $tempdata = $this->recordInfo($table,$id,"pid");
-                                                               $theRealPid=$tempdata["pid"];
+                                                               $tempdata = $this->recordInfo($table,$id,'pid');
+                                                               $theRealPid=$tempdata['pid'];
                                                        }
                                                        $status='update';       // the default is 'update' 
                                                }
                                                
-                                               if ($this->debug)       {debug("STATUS: ".$status."  RecordAccess:".$recordAccess);     }
                                                        // **************************************
                                                        // If access was granted above, proceed:
                                                        // **************************************
                                                if ($recordAccess)      {
-//debug("tce_main",-2);
-                                                       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.
+//debug('tce_main',-2);
+                                                       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.
                                                        $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
 //debug($TSConfig);
-                                                       if ($status=="new" && $table=="pages" && is_array($TSConfig["permissions."]))   {
-                                                               $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig["permissions."]);
+                                                       if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.']))   {
+                                                               $fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
                                                        }
 
-//debug(array($table,$tscPID)); 
-                                               
+//debug(array($table,$tscPID));
+
                                                        $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
                                                        $fieldArray = $this->overrideFieldArray($table,$fieldArray);
 
-                                                               // Setting system fields 
-                                                       if ($status=="new")     {
-                                                               if ($TCA[$table]["ctrl"]["crdate"])     {
-                                                                       $fieldArray[$TCA[$table]["ctrl"]["crdate"]]=time();
+                                                               // Setting system fields
+                                                       if ($status=='new')     {
+                                                               if ($TCA[$table]['ctrl']['crdate'])     {
+                                                                       $fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
                                                                }
-                                                               if ($TCA[$table]["ctrl"]["cruser_id"])  {
-                                                                       $fieldArray[$TCA[$table]["ctrl"]["cruser_id"]]=$this->userid;
+                                                               if ($TCA[$table]['ctrl']['cruser_id'])  {
+                                                                       $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
                                                                }
                                                        } elseif ($this->checkSimilar) {
                                                                $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
                                                        }
-                                                       if ($TCA[$table]["ctrl"]["tstamp"])     {
-                                                               $fieldArray[$TCA[$table]["ctrl"]["tstamp"]]=time();
+                                                       if ($TCA[$table]['ctrl']['tstamp'])     {
+                                                               $fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
                                                        }
 
                                                                // Performing insert/update
-                                                       if ($status=="new")     {
+                                                       if ($status=='new')     {
 //                                                             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!
                                                                $this->insertDB($table,$id,$fieldArray);
                                                        } else {
@@ -582,60 +571,74 @@ class t3lib_TCEmain       {
 
        /**
         * Filling in the field array
-        * 
-        * $incomingFieldArray is which fields/values you want to set
-        * Preset $fieldArray with "pid" maybe (pid and uid will be not be overridden anyway)
         * $this->exclude_array is used to filter fields if needed.
-        * $status = "new" or "update"
-        * 
-        * @param       [type]          $table: ...
+        *
+        * @param       string          Table name
         * @param       [type]          $id: ...
-        * @param       [type]          $fieldArray: ...
-        * @param       [type]          $incomingFieldArray: ...
+        * @param       array           Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
+        * @param       array           $incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
         * @param       [type]          $realPid: ...
-        * @param       [type]          $status: ...
+        * @param       string          $status = 'new' or 'update'
         * @param       [type]          $tscPID: ...
         * @return      [type]          ...
         */
        function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)  {
                global $TCA;
-               $fieldArray_orig = $fieldArray;
+
                t3lib_div::loadTCA($table);
+
+                       // Setting 'currentRecord' and 'checkValueRecord':
+               if (strstr($id,'NEW'))  {
+                       $currentRecord = $checkValueRecord = $fieldArray;       // must have the 'current' array - not the values after processing below...
+
+                               // IF $incomingFieldArray is an array, overlay it.
+                               // 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...
+                       if (is_array($incomingFieldArray) && is_array($checkValueRecord))       {
+                               $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
+                       }
+               } else {
+                       $currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*'); // We must use the current values as basis for this!
+               }
+               $this->checkValue_currentRecord = $checkValueRecord;
+
                        /*
                                In the following all incoming value-fields are tested:
                                - Are the user allowed to change the field?
                                - Is the field uid/pid (which are already set)
                                - perms-fields for pages-table, then do special things...
                                - If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue
-                               
+
                                If everything is OK, the field is entered into $fieldArray[]
                        */
-               reset ($incomingFieldArray);            // Reset the array of fields
-               while (list($field,$fieldValue) = each($incomingFieldArray))    {
-                       if (!in_array($table."-".$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field])      {       // The field must be editable.
+               foreach($incomingFieldArray as $field => $fieldValue)   {
+                       if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field])      {       // The field must be editable.
+
+
+                                       // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
                                if ($this->stripslashes_values) {
                                        if (is_array($fieldValue))      {
                                                t3lib_div::stripSlashesOnArray($fieldValue);
-                                       } else $fieldValue=stripslashes($fieldValue);
-                               }               // Strip slashes
+                                       } else $fieldValue = stripslashes($fieldValue);
+                               }
+
                                switch ($field) {
-                                       case "uid":
-                                       case "pid":
+                                       case 'uid':
+                                       case 'pid':
                                                // Nothing happens, already set
                                        break;
-                                       case "perms_userid":
-                                       case "perms_groupid":
-                                       case "perms_user":
-                                       case "perms_group":
-                                       case "perms_everybody":
+                                       case 'perms_userid':
+                                       case 'perms_groupid':
+                                       case 'perms_user':
+                                       case 'perms_group':
+                                       case 'perms_everybody':
                                                        // Permissions can be edited by the owner or the administrator
-                                               if ($table=="pages" && ($this->admin || $status=="new" || $this->pageInfo($id,"perms_userid")==$this->userid) ) {
+                                               if ($table=='pages' && ($this->admin || $status=='new' || $this->pageInfo($id,'perms_userid')==$this->userid) ) {
                                                        $value=intval($fieldValue);
                                                        switch($field)  {
-                                                               case "perms_userid":
+                                                               case 'perms_userid':
                                                                        $fieldArray[$field]=$value;
                                                                break;
-                                                               case "perms_groupid":
+                                                               case 'perms_groupid':
                                                                        $fieldArray[$field]=$value;
                                                                break;
                                                                default:
@@ -647,94 +650,113 @@ class t3lib_TCEmain      {
                                                }
                                        break;
                                        default:
-                                               if (isset($TCA[$table]["columns"][$field]))     {
+                                               if (isset($TCA[$table]['columns'][$field]))     {
                                                                // Evaluating the value.
-                                                       $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid);
-                                                       if (isset($res["value"]))       {
-                                                               $fieldArray[$field]=$res["value"];
+                                                       $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
+                                                       if (isset($res['value']))       {
+                                                               $fieldArray[$field]=$res['value'];
                                                        }
                                                }
                                        break;
                                }
                        }
                }
-               
+
                        // Checking for RTE-transformations of fields:
-               if (strstr($id,"NEW"))  {
-                       $currentRecord = $fieldArray_orig;      // changed to "_orig" 170502 - must have the "current" array - not the values set in the form.
-               } else {
-                       $currentRecord = $this->recordInfo($table,$id,"*");     // We must use the current values as basis for this!
-               }
-//debug($currentRecord);
-//                     debug($id);
-               $types_fieldConfig=t3lib_BEfunc::getTCAtypes($table,$currentRecord);
+               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
                $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
                if (is_array($types_fieldConfig))       {
                        reset($types_fieldConfig);
-                       while(list(,$vconf)=each($types_fieldConfig))   {
+                       while(list(,$vconf) = each($types_fieldConfig)) {
                                        // Write file configuration:
-                               $eFile=t3lib_parsehtml_proc::evalWriteFile($vconf["spec"]["static_write"],array_merge($currentRecord,$fieldArray));     // inserted array_merge($currentRecord,$fieldArray) 170502
+                               $eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray));   // inserted array_merge($currentRecord,$fieldArray) 170502
 //debug($eFile);
                                        // RTE transformations:
                                if (!$this->dontProcessTransformations) {
-                                       if ($vconf["spec"]["richtext"] && !$this->disableRTE)   {
+                                       if (isset($fieldArray[$vconf['field']]))        {
+                                                       // Look for transformation flag:
+                                               switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']])      {
+                                                       case 'RTE':
+                                                               $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
+                                                               $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
+
+                                                                       // Set alternative relative path for RTE images/links:
+                                                               $RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';
+
+                                                                       // Get RTE object, draw form and set flag:
+                                                               $RTEobj = &t3lib_BEfunc::RTEgetObj();
+                                                               if (is_object($RTEobj)) {
+                                                                       $fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
+                                                               } else {
+                                                                       debug('NO RTE OBJECT FOUND!');
+                                                               }
+                                                       break;
+                                               }
+                                       }
+
+                                       // These transformations has been removed and the one above inserted; content is now transformed if a flag is sent with the field, typ. "_TRANSFORM_".[fieldname] = "RTE"
+                                       // This is more safe, doesn't require us to calculate if a transformation has to be done and finally; it is now possible to use RTEs in FlexForms as well!
+/*
+                                       if ($vconf['spec']['richtext'] && !$this->disableRTE)   {
                                                        // Cross transformation?
                                                $this->crossRTEtransformation=0;        // Crosstransformation is, when a record is saved, the CType has changed and the other type might also use the RTE - then the transformation of THAT rte is used instead. This is usefull only if we know the TBE interface did it, because in that interface the CType value changes the interface and allows extended options in RTE without first saving the type-shift.
                                                if ($this->crossRTEtransformation)      {
                                                        $next_types_fieldConfig=t3lib_BEfunc::getTCAtypes($table,array_merge($currentRecord,$fieldArray),1);
-                                                       if ($next_types_fieldConfig[$vconf["field"]]["spec"]["richtext"])       {       // RTE must be enabled for the fields
-                                                               $vconf["spec"] = $next_types_fieldConfig[$vconf["field"]]["spec"];
+                                                       if ($next_types_fieldConfig[$vconf['field']]['spec']['richtext'])       {       // RTE must be enabled for the fields
+                                                               $vconf['spec'] = $next_types_fieldConfig[$vconf['field']]['spec'];
                                                                $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,array_merge($currentRecord,$fieldArray));
                                                        }
                                                }
 //debug($theTypeString);
                                                        // transform if...
-                                               if ($vconf["spec"]["rte_transform"])    {
-                                                       $p=t3lib_BEfunc::getSpecConfParametersFromArray($vconf["spec"]["rte_transform"]["parameters"]);
-                                                       if ($p["mode"]) {       // There must be a mode set for transformation
-                                                               if (isset($fieldArray[$vconf["field"]]))        {
+                                               if ($vconf['spec']['rte_transform'])    {
+                                                       $p=t3lib_BEfunc::getSpecConfParametersFromArray($vconf['spec']['rte_transform']['parameters']);
+                                                       if ($p['mode']) {       // There must be a mode set for transformation
+                                                               if (isset($fieldArray[$vconf['field']]))        {
                                                                        if ($tscPID>=0) {
-//debug("RTEsetup");
-                                                                               $RTEsetup = $this->BE_USER->getTSConfig("RTE",t3lib_BEfunc::getPagesTSconfig($tscPID));
-                                                                               $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup["properties"],$table,$vconf["field"],$theTypeString);
-                                                                               if (!$thisConfig["disabled"] && (!$p["flag"] || !$currentRecord[$p["flag"]]) && $this->BE_USER->isRTE())        {       // ... and any disable flag should not be set!
-                                                                                       $parseHTML = t3lib_div::makeInstance("t3lib_parsehtml_proc");
-                                                                                       $parseHTML->init($table.":".$vconf["field"],$currentRecord["pid"]);
-                                                                                       if (is_array($eFile))   {$parseHTML->setRelPath(dirname($eFile["relEditFile"]));}
-                                                                                       $fieldArray[$vconf["field"]]=$parseHTML->RTE_transform($fieldArray[$vconf["field"]],$vconf["spec"],"db",$thisConfig);
+//debug('RTEsetup');
+                                                                               $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
+                                                                               $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
+                                                                               if (!$thisConfig['disabled'] && (!$p['flag'] || !$currentRecord[$p['flag']]) && $this->BE_USER->isRTE())        {       // ... and any disable flag should not be set!
+                                                                                       $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
+                                                                                       $parseHTML->init($table.':'.$vconf['field'],$currentRecord['pid']);
+                                                                                       if (is_array($eFile))   {$parseHTML->setRelPath(dirname($eFile['relEditFile']));}
+                                                                                       $fieldArray[$vconf['field']]=$parseHTML->RTE_transform($fieldArray[$vconf['field']],$vconf['spec'],'db',$thisConfig);
                                                                                }
                                                                        }
                                                                }
                                                        }
                                                }
                                        }
+                                       */
                                }
 
                                        // Write file configuration:
                                if (is_array($eFile))   {
                                        $mixedRec = array_merge($currentRecord,$fieldArray);
-                                       $SW_fileContent = t3lib_div::getUrl($eFile["editFile"]);
-                                       $parseHTML = t3lib_div::makeInstance("t3lib_parsehtml_proc");
-                                       $parseHTML->init("","");
+                                       $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
+                                       $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
+                                       $parseHTML->init('','');
 
-                                       $eFileMarker = $eFile["markerField"]&&trim($mixedRec[$eFile["markerField"]]) ? trim($mixedRec[$eFile["markerField"]]) : "###TYPO3_STATICFILE_EDIT###";
-                                       $insertContent = str_replace($eFileMarker,"",$mixedRec[$eFile["contentField"]]);        // must replace the marker if present in content!
+                                       $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
+                                       $insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]);        // must replace the marker if present in content!
 
                                        $SW_fileNewContent = $parseHTML->substituteSubpart(
                                                $SW_fileContent,
                                                $eFileMarker,
                                                chr(10).$insertContent.chr(10),
                                                1,1);
-                                       t3lib_div::writeFile($eFile["editFile"],$SW_fileNewContent);
+                                       t3lib_div::writeFile($eFile['editFile'],$SW_fileNewContent);
                                        
                                                // Write status:
-                                       if (!strstr($id,"NEW") && $eFile["statusField"])        {
-                                               $SWq = t3lib_BEfunc::DBcompileUpdate($table,"uid=".intval($id),
+                                       if (!strstr($id,'NEW') && $eFile['statusField'])        {
+                                               $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
+                                                       $table,
+                                                       'uid='.intval($id),
                                                        array(
-                                                               $eFile["statusField"]=>$eFile["relEditFile"]." updated ".date("d-m-Y H:i:s").", bytes ".strlen($mixedRec[$eFile["contentField"]])
+                                                               $eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
                                                        )
                                                );
-                                               mysql(TYPO3_db,$SWq);
                                        }
                                } elseif ($eFile && is_string($eFile))  {
                                        $this->log($insertTable,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
@@ -744,38 +766,38 @@ class t3lib_TCEmain       {
                        // Return fieldArray
                return $fieldArray;
        }
-       
+
        /**
         * Checking group modify_table access list
-        * 
+        *
         * Returns true if the user has general access to modify the $table
-        * 
+        *
         * @param       [type]          $table: ...
         * @return      [type]          ...
         */
        function checkModifyAccessList($table)  {
-               $res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData["tables_modify"],$table)));
+               $res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData['tables_modify'],$table)));
                return $res;
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $id: ...
         * @return      [type]          ...
         */
        function isRecordInWebMount($table,$id) {
-               if (!isset($this->isRecordInWebMount_Cache[$table.":".$id]))    {
+               if (!isset($this->isRecordInWebMount_Cache[$table.':'.$id]))    {
                        $recP=$this->getRecordProperties($table,$id);
-                       $this->isRecordInWebMount_Cache[$table.":".$id]=$this->isInWebMount($recP["event_pid"]);
+                       $this->isRecordInWebMount_Cache[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
                }
-               return $this->isRecordInWebMount_Cache[$table.":".$id];
+               return $this->isRecordInWebMount_Cache[$table.':'.$id];
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $pid: ...
         * @return      [type]          ...
         */
@@ -789,9 +811,9 @@ class t3lib_TCEmain {
        
        /**
         * Checks if user may update a certain record.
-        * 
+        *
         * Returns true if the user may update the record given by $table and $id
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $id: ...
         * @return      [type]          ...
@@ -802,8 +824,8 @@ class t3lib_TCEmain {
                if ($TCA[$table] && intval($id)>0)      {
                        if (isset($this->recUpdateAccessCache[$table][$id]))    {       // If information is cached, return it
                                return $this->recUpdateAccessCache[$table][$id];
-                               // Check if record exists and 1) if "pages" the page may be edited, 2) if page-content the page allows for editing
-                       } elseif ($this->doesRecordExist($table,$id,"edit"))    {
+                               // Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
+                       } elseif ($this->doesRecordExist($table,$id,'edit'))    {
                                $res = 1;
                        }
                        $this->recUpdateAccessCache[$table][$id]=$res;  // Cache the result
@@ -813,9 +835,9 @@ class t3lib_TCEmain {
 
        /**
         * Checks if user may insert a certain record.
-        * 
+        *
         * Returns true if the user may insert a record from table $insertTable on page $pid
-        * 
+        *
         * @param       [type]          $insertTable: ...
         * @param       [type]          $pid: ...
         * @param       [type]          $action: ...
@@ -829,18 +851,18 @@ class t3lib_TCEmain       {
                        if (isset($this->recInsertAccessCache[$insertTable][$pid]))     {       // If information is cached, return it
                                return $this->recInsertAccessCache[$insertTable][$pid];
                        } else {
-                                       // 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
-                               if ( (!$pid && $this->admin) || $this->doesRecordExist("pages",$pid,($insertTable=="pages"?$this->pMap["new"]:$this->pMap["editcontent"])) )    {               // Check permissions
+                                       // 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
+                               if ( (!$pid && $this->admin) || $this->doesRecordExist('pages',$pid,($insertTable=='pages'?$this->pMap['new']:$this->pMap['editcontent'])) )    {               // Check permissions
                                        if ($this->isTableAllowedForThisPage($pid, $insertTable))       {
                                                $res = 1;
                                                $this->recInsertAccessCache[$insertTable][$pid]=$res;   // Cache the result
                                        } else {
-                                               $propArr = $this->getRecordProperties("pages",$pid);
-                                               $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"]);
+                                               $propArr = $this->getRecordProperties('pages',$pid);
+                                               $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']);
                                        }
                                } else {
-                                       $propArr = $this->getRecordProperties("pages",$pid);
-                                       $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"]);
+                                       $propArr = $this->getRecordProperties('pages',$pid);
+                                       $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']);
                                }
                        }
                }
@@ -849,10 +871,10 @@ class t3lib_TCEmain       {
 
        /**
         * Checks is a table is allowed on a certain page.
-        * 
+        *
         * $checkTable is the tablename
         * $page_uid is the uid of the page to check
-        * 
+        *
         * @param       [type]          $page_uid: ...
         * @param       [type]          $checkTable: ...
         * @return      [type]          ...
@@ -862,7 +884,7 @@ class t3lib_TCEmain {
                $page_uid = intval($page_uid);
                
                        // 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.
-               if (($TCA[$checkTable]["ctrl"]["rootLevel"] xor !$page_uid) && $TCA[$checkTable]["ctrl"]["rootLevel"]!=-1 && $checkTable!="pages")      {       
+               if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages')      {       
                        return false;
                }
                
@@ -873,10 +895,10 @@ class t3lib_TCEmain       {
                        }
                } else {
                                // Check non-root-level
-                       $doktype = $this->pageInfo($page_uid,"doktype");
-                       $allowedTableList = isset($PAGES_TYPES[$doktype]["allowedTables"]) ? $PAGES_TYPES[$doktype]["allowedTables"] : $PAGES_TYPES["default"]["allowedTables"];
-                       $allowedArray = t3lib_div::trimExplode(",",$allowedTableList,1);
-                       if (strstr($allowedTableList,"*") || in_array($checkTable,$allowedArray))       {               // If all tables or the table is listed as a allowed type, return true
+                       $doktype = $this->pageInfo($page_uid,'doktype');
+                       $allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
+                       $allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
+                       if (strstr($allowedTableList,'*') || in_array($checkTable,$allowedArray))       {               // If all tables or the table is listed as a allowed type, return true
                                return true;
                        }
                }
@@ -884,12 +906,12 @@ class t3lib_TCEmain       {
 
        /**
         * Checks if record exists
-        * 
-        * Returns true if the record given by $table,$id and $perms (which is either a number that is bitwise AND'ed or a string, which points to a key in the ->pMap array)
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $perms: ...
+        *
+        * Returns true if the record given by $table, $id and $perms
+        *
+        * @param       string          Record table name
+        * @param       integer         Record UID
+        * @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
         * @return      [type]          ...
         */
        function doesRecordExist($table,$id,$perms)     {
@@ -898,57 +920,89 @@ class t3lib_TCEmain       {
                $res = 0;
                $id = intval($id);
 
-                       // Processing the incoming $perms
+                       // Processing the incoming $perms (from possible string to integer that can be AND'ed)
                if (!t3lib_div::testInt($perms))        {
-                       if ($table!="pages")    {
+                       if ($table!='pages')    {
                                switch($perms)  {
-                                       case "edit":
-                                       case "delete":
-                                       case "new":
-                                               $perms = "editcontent";         // This holds it all in case the record is not page!!
+                                       case 'edit':
+                                       case 'delete':
+                                       case 'new':
+                                               $perms = 'editcontent';         // This holds it all in case the record is not page!!
                                        break;
                                }
                        }
-                       $perms=intval($this->pMap[$perms]);
+                       $perms = intval($this->pMap[$perms]);
                } else {
                        $perms = intval($perms);
                }
 
-               if (!$perms)    {debug("Internal ERROR: no permissions to check for non-admin user.");}
+               if (!$perms)    {debug('Internal ERROR: no permissions to check for non-admin user.');}
        
                        // For all tables: Check if record exists:
                        // Notice: If $perms are 0 (zero) no perms-clause is added!
-               if ($TCA[$table] && $id>0 && ($this->isRecordInWebMount($table,$id)||$this->admin))     {               // 130502: added isRecordInWebMount() to check for pages being inside the page mounts...!
-                       if ($table != "pages")  {
-                               $query = "select $table.uid from $table,pages where $table.pid=pages.uid && $table.uid=".$id.$this->deleteClause("pages");
-                               if ($perms && !$this->admin)    {       $query.=" AND ".$this->BE_USER->getPagePermsClause($perms);             }       // admin users don't need check
-                               $mres = mysql(TYPO3_db,$query);
-                               echo mysql_error();
-                               if (mysql_num_rows($mres))      {
-                                       return true;
+               if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) || $this->admin)) {
+                       if ($table != 'pages')  {
+                       
+                                       // Find record without checking page:
+                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($id).$this->deleteClause($table));
+                               $output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
+
+                                       // If record found, check page as well:
+                               if (is_array($output))  {
+
+                                               // Looking up the page for record:
+                                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                               'uid', 
+                                                               'pages', 
+                                                               'uid='.intval($output['pid']).
+                                                                       $this->deleteClause('pages').
+                                                                       ($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '')     // admin users don't need check
+                                                       );
+                                       $pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
+
+                                               // 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):
+                                       if (is_array($pageRec) || (!$output['pid'] && $this->admin))    {
+                                               return TRUE;
+                                       }
+                               }
+                               return FALSE;
+                                       /*
+                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                               $table.'.uid', 
+                                                               $table.',pages', 
+                                                               $table.'.pid=pages.uid && '.$table.'.uid='.intval($id).
+                                                                               $this->deleteClause('pages').
+                                                                               ($perms && !$this->admin ? " AND ".$this->BE_USER->getPagePermsClause($perms) : '')     // admin users don't need check
+                                                       );
+                               if ($GLOBALS['TYPO3_DB']->sql_num_rows($mres))  {
+                                       return TRUE;
                                } else {
                                        if ($this->admin)       {       // admin may do stuff on records in the root
-                                               $query = "select uid from $table where uid=".$id.$this->deleteClause($table);
-                                               $mres = mysql(TYPO3_db,$query);
-                                               return mysql_num_rows($mres);
+                                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'uid='.intval($id).$this->deleteClause($table));
+                                               return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
                                        }
                                }
+                                       */
                        } else {
-                               $query = "select uid from pages where uid=".$id.$this->deleteClause("pages");
-                               if ($perms && !$this->admin)    {       $query.=" AND ".$this->BE_USER->getPagePermsClause($perms);             }       // admin users don't need check
-                               $mres = mysql(TYPO3_db,$query);
-                               return mysql_num_rows($mres);
+                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                               'uid', 
+                                                               'pages',
+                                                               'uid='.intval($id).
+                                                                       $this->deleteClause('pages').
+                                                                       ($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '')     // admin users don't need check
+                                                       );
+                               return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
                        }
                }
        }
 
        /**
         * Checks if a whole branch of pages exists
-        * 
+        *
         * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
         * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
         * 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
-        * 
+        *
         * @param       [type]          $inList: ...
         * @param       [type]          $pid: ...
         * @param       [type]          $perms: ...
@@ -960,11 +1014,16 @@ class t3lib_TCEmain      {
                $pid = intval($pid);
                $perms = intval($perms);
                if ($pid>=0)    {
-                       $query = "select uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody from pages where pid=".$pid.$this->deleteClause("pages")." order by sorting";
-                       $mres = mysql(TYPO3_db,$query);
-                       while ($row = mysql_fetch_assoc($mres)) {
+                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                               'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody', 
+                                               'pages', 
+                                               'pid='.intval($pid).$this->deleteClause('pages'),
+                                               '',
+                                               'sorting'
+                                       );
+                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))     {
                                if ($this->admin || $this->BE_USER->doesUserHaveAccess($row,$perms))    {       // IF admin, then it's OK
-                                       $inList.=$row['uid'].",";
+                                       $inList.=$row['uid'].',';
                                        if ($recurse)   {       // Follow the subpages recursively...
                                                $inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
                                                if ($inList == -1)      {return -1;}            // No permissions somewhere in the branch
@@ -979,56 +1038,57 @@ class t3lib_TCEmain      {
 
        /**
         * Returns the value of the $field from page $id
-        * 
-        * @param       [type]          $id: ...
-        * @param       [type]          $field: ...
-        * @return      [type]          ...
+        * 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!
+        *
+        * @param       integer         Page uid
+        * @param       string          Field name for which to return value
+        * @return      string          Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
         */
        function pageInfo($id,$field)   {
                if (!isset($this->pageCache[$id]))      {
-                       $res = mysql(TYPO3_db,"select * from pages where uid='$id'");
-                       if (mysql_num_rows($res))       {
-                               $this->pageCache[$id]=mysql_fetch_assoc($res);
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
+                       if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {
+                               $this->pageCache[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
                return $this->pageCache[$id][$field];
        }
 
        /**
-        * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be "*")
-        * 
-        * No check for deleted or access!
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $fieldList: ...
-        * @return      [type]          ...
+        * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
+        * NOTICE: No check for deleted or access!
+        *
+        * @param       string          Table name
+        * @param       integer         UID of the record from $table
+        * @param       string          Field list for the SELECT query, eg. "*" or "uid,pid,..."
+        * @return      mixed           Returns the selected record on success, otherwise false.
         */
        function recordInfo($table,$id,$fieldList)      {
                global $TCA;
-               if ($TCA[$table])       {
-                       $res = mysql(TYPO3_db,'SELECT '.$fieldList.' FROM '.$table.' WHERE uid='.intval($id));
-                       if (mysql_num_rows($res))       {
-                               return mysql_fetch_assoc($res);
+               if (is_array($TCA[$table]))     {
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
+                       if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {
+                               return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        }
                }
        }
 
        /**
         * Returns an array with record properties, like header and pid
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $id: ...
         * @return      [type]          ...
         */
        function getRecordProperties($table,$id)        {
-               $row = ($table=="pages" && !$id) ? array("title"=>"[root-level]", "uid" => 0, "pid" => 0) :$this->recordInfo($table,$id,"*");
+               $row = ($table=='pages' && !$id) ? array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
                return $this->getRecordPropertiesFromRow($table,$row);
        }
 
        /**
         * Returns an array with record properties, like header and pid, based on the row
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $row: ...
         * @return      [type]          ...
@@ -1037,9 +1097,9 @@ class t3lib_TCEmain       {
                global $TCA;
                if ($TCA[$table])       {
                        $out = array(
-                               "header" => $row[$TCA[$table]["ctrl"]["label"]],
-                               "pid" => $row["pid"],
-                               "event_pid" => ($table=="pages"?$row["uid"]:$row["pid"])
+                               'header' => $row[$TCA[$table]['ctrl']['label']],
+                               'pid' => $row['pid'],
+                               'event_pid' => ($table=='pages'?$row['uid']:$row['pid'])
                        );
                        return $out;
                }
@@ -1047,24 +1107,24 @@ class t3lib_TCEmain     {
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $fieldArray: ...
         * @param       [type]          $TSConfig_p: ...
         * @return      [type]          ...
         */
        function setTSconfigPermissions($fieldArray,$TSConfig_p)        {
-               if (strcmp($TSConfig_p["userid"],""))   $fieldArray["perms_userid"]=intval($TSConfig_p["userid"]);
-               if (strcmp($TSConfig_p["groupid"],""))  $fieldArray["perms_groupid"]=intval($TSConfig_p["groupid"]);
-               if (strcmp($TSConfig_p["user"],""))                     $fieldArray["perms_user"]=t3lib_div::testInt($TSConfig_p["user"]) ? $TSConfig_p["user"] : $this->assemblePermissions($TSConfig_p["user"]);
-               if (strcmp($TSConfig_p["group"],""))            $fieldArray["perms_group"]=t3lib_div::testInt($TSConfig_p["group"]) ? $TSConfig_p["group"] : $this->assemblePermissions($TSConfig_p["group"]);
-               if (strcmp($TSConfig_p["everybody"],""))        $fieldArray["perms_everybody"]=t3lib_div::testInt($TSConfig_p["everybody"]) ? $TSConfig_p["everybody"] : $this->assemblePermissions($TSConfig_p["everybody"]);
+               if (strcmp($TSConfig_p['userid'],''))   $fieldArray['perms_userid']=intval($TSConfig_p['userid']);
+               if (strcmp($TSConfig_p['groupid'],''))  $fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
+               if (strcmp($TSConfig_p['user'],''))                     $fieldArray['perms_user']=t3lib_div::testInt($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
+               if (strcmp($TSConfig_p['group'],''))            $fieldArray['perms_group']=t3lib_div::testInt($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
+               if (strcmp($TSConfig_p['everybody'],''))        $fieldArray['perms_everybody']=t3lib_div::testInt($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);
 
                return $fieldArray;
        }       
        
        /**
         * Returns a fieldArray with default values.
-        * 
+        *
         * @param       [type]          $table: ...
         * @return      [type]          ...
         */
@@ -1072,29 +1132,29 @@ class t3lib_TCEmain     {
                global $TCA;
                t3lib_div::loadTCA($table);
                $fieldArray=Array();
-               if (is_array($TCA[$table]["columns"]))  {
-                       reset ($TCA[$table]["columns"]);
-                       while (list($field,$content)=each($TCA[$table]["columns"]))     {
+               if (is_array($TCA[$table]['columns']))  {
+                       reset ($TCA[$table]['columns']);
+                       while (list($field,$content)=each($TCA[$table]['columns']))     {
                                if (isset($this->defaultValues[$table][$field]))        {
                                        $fieldArray[$field] = $this->defaultValues[$table][$field];
-                               } elseif (isset($content["config"]["default"])) {
-                                       $fieldArray[$field] = $content["config"]["default"];
+                               } elseif (isset($content['config']['default'])) {
+                                       $fieldArray[$field] = $content['config']['default'];
                                }
                        }
                }
-               if ($table=="pages")    {               // Set default permissions for a page.
-                       $fieldArray["perms_userid"] = $this->userid;
-                       $fieldArray["perms_groupid"] = intval($this->BE_USER->firstMainGroup);
-                       $fieldArray["perms_user"] = $this->assemblePermissions($this->defaultPermissions["user"]);
-                       $fieldArray["perms_group"] = $this->assemblePermissions($this->defaultPermissions["group"]);
-                       $fieldArray["perms_everybody"] = $this->assemblePermissions($this->defaultPermissions["everybody"]);
+               if ($table=='pages')    {               // Set default permissions for a page.
+                       $fieldArray['perms_userid'] = $this->userid;
+                       $fieldArray['perms_groupid'] = intval($this->BE_USER->firstMainGroup);
+                       $fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions['user']);
+                       $fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions['group']);
+                       $fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions['everybody']);
                }
                return $fieldArray;
        }
        
        /**
         * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $data: ...
         * @return      [type]          ...
@@ -1108,12 +1168,12 @@ class t3lib_TCEmain     {
 
        /**
         * Calculates the bitvalue of the permissions given in a string, comma-sep
-        * 
+        *
         * @param       [type]          $string: ...
         * @return      [type]          ...
         */
        function assemblePermissions($string)   {
-               $keyArr = t3lib_div::trimExplode(",",$string,1);
+               $keyArr = t3lib_div::trimExplode(',',$string,1);
                $value=0;
                while(list(,$key)=each($keyArr))        {
                        if ($key && isset($this->pMap[$key]))   {
@@ -1150,24 +1210,25 @@ class t3lib_TCEmain     {
 
        /**
         * Evaluates a value according to $table/$field settings.
-        * This function is for real database field - not FlexForm fields.
+        * This function is for real database fields - NOT FlexForm "pseudo" fields.
         * 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() )
-        * 
+        *
         * @param       string          Table name
         * @param       string          Field name
-        * @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.
+        * @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.
         * @param       string          The record-uid, mainly - but not exclusively - used for logging
-        * @param       string          "update" or "new" flag
+        * @param       string          'update' or 'new' flag
         * @param       [type]          $realPid: ...
-        * @return      string          Returns the evaluated $value
+        * @param       integer         $tscPID
+        * @return      array           Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
         */
-       function checkValue($table,$field,$value,$id,$status,$realPid)  {
+       function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)  {
                global $TCA, $PAGES_TYPES;
                t3lib_div::loadTCA($table);
 
                $res = Array(); // result array
                $recFID = $table.':'.$id.':'.$field;
-               
+
                        // Processing special case of field pages.doktype
                if ($table=='pages' && $field=='doktype')       {
                                // If the user may not use this specific doktype, we issue a warning
@@ -1193,52 +1254,58 @@ class t3lib_TCEmain     {
                        // Get current value:
                $curValueRec = $this->recordInfo($table,$id,$field);
                $curValue = $curValueRec[$field];
-                                                       
+
                        // Getting config for the field
                $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
-               
+
                        // Preform processing:
-               $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field]);
+               $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);
 
                return $res;
        }
-       
+
        /**
-        * @param       [type]          $res: ...
-        * @param       [type]          $value: ...
-        * @param       [type]          $tcaFieldConf: ...
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
+        * Branches out evaluation of a field value based on its type as configured in TCA
+        * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
+        *
+        * @param       array           The result array. The processed value (if any!) is set in the "value" key.
+        * @param       string          The value to set.
+        * @param       array           Field configuration from TCA
+        * @param       string          Table name
+        * @param       integer         Return UID
         * @param       [type]          $curValue: ...
         * @param       [type]          $status: ...
         * @param       [type]          $realPid: ...
         * @param       [type]          $recFID: ...
         * @param       string          Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
         * @param       [type]          $uploadedFiles: ...
-        * @return      [type]          ...
+        * @return      array           Returns the evaluated $value as key "value" in this array.
         */
-       function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles)   {
+       function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)   {
+
+               $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
+
                switch ($tcaFieldConf['type']) {
                        case 'text':
                        case 'passthrough':
-                               $res['value']=$value;
+                               $res['value'] = $value;
                        break;
                        case 'input':
-                               $res = $this->checkValue_input($res,$value,$tcaFieldConf,array($table,$id,$curValue,$status,$realPid,$recFID),$field);
+                               $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
                        break;
                        case 'check':
-                               $res = $this->checkValue_check($res,$value,$tcaFieldConf,array($table,$id,$curValue,$status,$realPid,$recFID));
+                               $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
                        break;
                        case 'radio':
-                               $res = $this->checkValue_radio($res,$value,$tcaFieldConf,array($table,$id,$curValue,$status,$realPid,$recFID));
+                               $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
                        break;
                        case 'group':
                        case 'select':
-                               $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,array($table,$id,$curValue,$status,$realPid,$recFID),$uploadedFiles);
+                               $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles);
                        break;
                        case 'flex':
                                if ($field)     {       // FlexForms are only allowed for real fields.
-                                       $res = $this->checkValue_flex($res,$value,$tcaFieldConf,array($table,$id,$curValue,$status,$realPid,$recFID),$uploadedFiles,$this->recordInfo($table,$id,'*'),$field);
+                                       $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
                                }
                        break;
                }
@@ -1248,12 +1315,12 @@ class t3lib_TCEmain     {
 
        /**
         * Evaluate "input" type values.
-        * 
+        *
         * @param       array           The result array. The processed value (if any!) is set in the "value" key.
         * @param       string          The value to set.
         * @param       array           Field configuration from TCA
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
-        * @param       [type]          $field: ...
+        * @param       string          Field name
         * @return      array           Modified $res array
         */
        function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')      {
@@ -1261,17 +1328,17 @@ class t3lib_TCEmain     {
 
                        // Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
                if (intval($tcaFieldConf['max'])>0)     {$value = substr($value,0,intval($tcaFieldConf['max']));}
-               
+
                        // Checking range of value:
                if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox'])        {       // If value is not set to the allowed checkbox-value then it is checked against the ranges
                        if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper'])     {$value=$tcaFieldConf['range']['upper'];}
                        if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower'])     {$value=$tcaFieldConf['range']['lower'];}
                }
-               
+
                        // Process evaluation settings:
                $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
                $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
-               
+
                        // Process UNIQUE settings:
                if ($field)     {       // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields!
                        if ($res['value'] && in_array('uniqueInPid',$evalCodesArray))   {
@@ -1281,14 +1348,14 @@ class t3lib_TCEmain     {
                                $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
                        }
                }
-               
+
                return $res;
        }
 
        /**
-        * Evaluates "check" type values.
-        * 
-        * @param       array           The result array. The processed value (if any!) is set in the "value" key.
+        * Evaluates 'check' type values.
+        *
+        * @param       array           The result array. The processed value (if any!) is set in the 'value' key.
         * @param       string          The value to set.
         * @param       array           Field configuration from TCA
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
@@ -1309,9 +1376,9 @@ class t3lib_TCEmain       {
        }
 
        /**
-        * Evaluates "radio" type values.
-        * 
-        * @param       array           The result array. The processed value (if any!) is set in the "value" key.
+        * Evaluates 'radio' type values.
+        *
+        * @param       array           The result array. The processed value (if any!) is set in the 'value' key.
         * @param       string          The value to set.
         * @param       array           Field configuration from TCA
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
@@ -1333,9 +1400,9 @@ class t3lib_TCEmain       {
        }
 
        /**
-        * Evaluates "group" or "select" type values.
-        * 
-        * @param       array           The result array. The processed value (if any!) is set in the "value" key.
+        * Evaluates 'group' or 'select' type values.
+        *
+        * @param       array           The result array. The processed value (if any!) is set in the 'value' key.
         * @param       string          The value to set.
         * @param       array           Field configuration from TCA
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
@@ -1345,10 +1412,10 @@ class t3lib_TCEmain     {
        function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles)  {
                list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
 
-                       // This converts all occurencies of "&#123;" to the byte 123 in the string - this is needed in very rare cases where filenames with special characters (like æøå, umlaud etc) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not MOzilla and Opera.
+                       // This converts all occurencies of '&#123;' to the byte 123 in the string - this is needed in very rare cases where filenames with special characters (like æøå, umlaud etc) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
                        // Anyways, this should NOT disturb anything else:
                $value = $this->convNumEntityToByteValue($value);
-               
+
                        // When values are send as group or select they come as comma-separated values which are exploded by this function:
                $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
 
@@ -1412,7 +1479,7 @@ class t3lib_TCEmain       {
 
        /**
         * Handling files for group/select function
-        * 
+        *
         * @param       [type]          $valueArray: ...
         * @param       [type]          $tcaFieldConf: ...
         * @param       [type]          $curValue: ...
@@ -1428,7 +1495,7 @@ class t3lib_TCEmain       {
 
                        // If any files are uploaded:
                if (is_array($uploadedFileArray) && 
-                       $uploadedFileArray['name'] && 
+                       $uploadedFileArray['name'] &&
                        strcmp($uploadedFileArray['tmp_name'],'none'))  {
                                $valueArray[]=$uploadedFileArray['tmp_name'];
                                $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
@@ -1530,7 +1597,7 @@ class t3lib_TCEmain       {
                                                                } 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']);
                                                        } else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
                                                } 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']);
-                                       } 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']);
+                                       } 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']);
 
                                                // If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
                                        if (@is_file($theDestFile))     {
@@ -1566,77 +1633,93 @@ class t3lib_TCEmain     {
        }
        
        /**
-        * Evaluates "flex" type values.
-        * 
-        * @param       array           The result array. The processed value (if any!) is set in the "value" key.
+        * Evaluates 'flex' type values.
+        *
+        * @param       array           The result array. The processed value (if any!) is set in the 'value' key.
         * @param       string          The value to set.
         * @param       array           Field configuration from TCA
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
         * @param       array           Uploaded files for the field
         * @param       array           Current record array.
-        * @param       [type]          $field: ...
+        * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$curRecordArr,$field)     {
+       function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)   {
                list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
 
                if (is_array($value))   {
 
                                // Get current value array:
-                       $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$curRecordArr,$table);
+                       $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table);
+#debug($this->checkValue_currentRecord);
                        $currentValueArray = t3lib_div::xml2array($curValue);
+                       if (!is_array($currentValueArray))      $currentValueArray = array();
                        if (is_array($currentValueArray['meta']['currentLangId']))              unset($currentValueArray['meta']['currentLangId']);     // Remove all old meta for languages...
 
                                // Evaluation of input values:
-                       $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,array($table,$id,$curValue,$status,$realPid,$recFID));
+                       $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
 
                                // Create XML and convert charsets from input value:
-                       $xmlValue = t3lib_div::array2xml($value,'',0,'T3FlexForms');
+                       $xmlValue = $this->checkValue_flexArray2Xml($value);
 
                                // If we wanted to set UTF fixed:
                        // $storeInCharset='utf-8';
                        // $currentCharset=$GLOBALS['LANG']->charSet;
                        // $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
                        $storeInCharset=$GLOBALS['LANG']->charSet;
-                       
+
                                // Merge them together IF they are both arrays:
                                // 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).
                        if (is_array($currentValueArray))       {
                                $arrValue = t3lib_div::xml2array($xmlValue);
                                $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
-                               $xmlValue = t3lib_div::array2xml($arrValue,'',0,'T3FlexForms');
+                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
                        }
-                       
+
                                // Temporary fix to delete elements:
-                       $deleteCMDs=t3lib_div::_GP('_DELETE_FLEX_FORMdata');
-                       
+                       $deleteCMDs = t3lib_div::_GP('_DELETE_FLEX_FORMdata');
+
                        if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
                                $arrValue = t3lib_div::xml2array($xmlValue);
                                $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
-#debug($deleteCMDs[$table][$id][$field]['data']);
-#debug($arrValue);
-                               $xmlValue = t3lib_div::array2xml($arrValue,'',0,'T3FlexForms');
+                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue);
                        }
 
                                // Create the value XML:
                        $res['value']='';
                        $res['value'].='<?xml version="1.0" encoding="'.$storeInCharset.'" standalone="yes" ?>'.chr(10);
                        $res['value'].=$xmlValue;
-               } else {
+               } else {        // Passthrough...:
                        $res['value']=$value;
-               }               
-               
+               }
+
                return $res;
        }
 
        /**
         * [Describe function...]
-        * 
+        *
+        * @param       [type]          $array: ...
+        * @return      [type]          ...
+        */
+       function checkValue_flexArray2Xml($array)       {
+               $output = t3lib_div::array2xml($array,'',0,'T3FlexForms',4,array('parentTagMap' => array(
+/*                                                             'data' => 'sheets',
+                                                               'sheets' => 'language',
+                                                               'language' => 'fieldname',
+                                                               'el' => 'fieldname'             */
+                                                       )));
+               return $output;
+       }
+
+       /**
+        * [Describe function...]
+        *
         * @param       [type]          $$valueArrayToRemoveFrom: ...
         * @param       [type]          $deleteCMDS: ...
         * @return      [type]          ...
         */
-       function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)    {       
+       function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)    {
                if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
                        foreach($deleteCMDS as $key => $value)  {
                                if (is_array($deleteCMDS[$key]))        {
@@ -1676,42 +1759,47 @@ class t3lib_TCEmain     {
 
        /**
         * Gets a unique value for $table/$id/$field based on $value
-        * 
+        *
         * @param       string          Table name
         * @param       string          Field name for which $value must be unique
         * @param       string          Value string.
-        * @param       [type]          $id: ...
+        * @param       integer         UID to filter out in the lookup (the record itself...)
         * @param       integer         If set, the value will be unique for this PID
         * @return      string          Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
         */
        function getUnique($table,$field,$value,$id,$newPid=0)  {
                global $TCA;
-               
+
+                       // Initialize:
                t3lib_div::loadTCA($table);
                $whereAdd='';
                $newValue='';
-               if (intval($newPid))    {$whereAdd.=' AND pid='.intval($newPid);}
+               if (intval($newPid))    { $whereAdd.=' AND pid='.intval($newPid); }
                $whereAdd.=$this->deleteClause($table);
-               
-               if (isset($TCA[$table]['columns'][$field]))     {
+
+                       // If the field is configured in TCA, proceed:
+               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field]))        {
+
                                // Look for a record which might already have the value:
-                       $res = mysql(TYPO3_db,'SELECT uid FROM '.$table.' WHERE '.$field.'="'.addslashes($value).'" AND uid!='.intval($id).$whereAdd);
-                       $counter=0;
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'="'.$GLOBALS['TYPO3_DB']->quoteStr($value, $table).'" AND uid!='.intval($id).$whereAdd);
+                       $counter = 0;
+                       
                                // For as long as records with the test-value existing, try again (with incremented numbers appended).
-                       while (mysql_num_rows($res))    {
+                       while ($GLOBALS['TYPO3_DB']->sql_num_rows($res))        {
                                $newValue = $value.$counter;
-                               $res = mysql(TYPO3_db,'SELECT uid FROM '.$table.' WHERE '.$field.'="'.addslashes($newValue).'" AND uid!='.intval($id).$whereAdd);
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'="'.$GLOBALS['TYPO3_DB']->quoteStr($newValue, $table).'" AND uid!='.intval($id).$whereAdd);
                                $counter++;
-                               if ($counter>100)       {break;}
+                               if ($counter>100)       { break; }      // At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
                        }
-                       $value = $newValue ? $newValue : $value;
-               }       
+                               // If the new value is there:
+                       $value = strlen($newValue) ? $newValue : $value;
+               }
                return $value;
        }
 
        /**
         * Evaluation of 'input'-type values based on 'eval' list
-        * 
+        *
         * @param       string          Value
         * @param       array           Array of evaluations to traverse.
         * @param       string          Is-in string
@@ -1797,12 +1885,12 @@ class t3lib_TCEmain     {
 
        /**
         * Returns data for group/db and select fields
-        * 
+        *
         * @param       array           Current value array
         * @param       array           TCA field config
         * @param       integer         Record id, used for look-up of MM relations (local_uid)
-        * @param       string          Status string ("update" or "new")
-        * @param       string          The type, either "select" or "group"
+        * @param       string          Status string ('update' or 'new')
+        * @param       string          The type, either 'select' or 'group'
         * @return      array           Modified value array
         */
        function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)     {
@@ -1834,8 +1922,8 @@ class t3lib_TCEmain       {
 
        /**
         * Explodes the $value, which is a list of files/uids (group select)
-        * 
-        * @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.
+        *
+        * @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.
         * @return      array           The value array.
         */
        function checkValue_group_select_explodeSelectGroupValue($value)        {
@@ -1847,24 +1935,26 @@ class t3lib_TCEmain     {
                }
                return $valueArray;
        }
-               
+
        /**
-        * Processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
-        * 
-        * @param       array           The "data" part of the INPUT flexform data
-        * @param       array           The "data" part of the CURRENT flexform data
-        * @param       array           The uploaded files for the "data" part of the INPUT flexform data
+        * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
+        * See checkValue_flex_procInData_travDS() for more details.
+        *
+        * @param       array           The 'data' part of the INPUT flexform data
+        * @param       array           The 'data' part of the CURRENT flexform data
+        * @param       array           The uploaded files for the 'data' part of the INPUT flexform data
         * @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.
         * @param       array           A set of parameters to pass through for the calling of the evaluation functions
-        * @return      array           The modified "data" part.
+        * @param       string          Optional call back function, see checkValue_flex_procInData_travDS()
+        * @return      array           The modified 'data' part.
         * @see checkValue_flex_procInData_travDS()
         */
-       function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams      {
-#debug(array($dataPart,$dataPart_current));
+       function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')      {
+#debug(array($dataPart,$dataPart_current,$dataStructArray));
                if (is_array($dataPart))        {
                        foreach($dataPart as $sKey => $sheetDef)        {
                                list ($dataStruct,$actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sKey);
-
+#debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
                                if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef))        {
                                        foreach($sheetDef as $lKey => $lData)   {
                                                $this->checkValue_flex_procInData_travDS(
@@ -1872,33 +1962,36 @@ class t3lib_TCEmain     {
                                                        $dataPart_current[$sKey][$lKey],
                                                        $uploadedFiles[$sKey][$lKey],
                                                        $dataStruct['ROOT']['el'],
-                                                       $pParams
+                                                       $pParams,
+                                                       $callBackFunc
                                                );
                                        }
                                }
                        }
                }
-       
-               return $dataPart;       
+
+               return $dataPart;
        }
 
        /**
         * Processing of the sheet/language data array
-        * 
-        * @param       array           Multidimensional Data array for sheet/language, passed by reference!
+        * 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.
+        *
+        * @param       array           New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
+        * @param       array           Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
+        * @param       array           Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
         * @param       array           Data structure which fits the data array
-        * @param       array           A set of parameters to pass through for the calling of the evaluation functions
-        * @param       [type]          $DSelements: ...
-        * @param       [type]          $pParams: ...
-        * @return      void            
+        * @param       array           A set of parameters to pass through for the calling of the evaluation functions / call back function
+        * @param       string          Call back function, default is checkValue_SW().
+        * @return      void
         * @see checkValue_flex_procInData()
         */
-       function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams       {
+       function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc='')       {
                if (is_array($DSelements))      {
-                       
+
                                // For each DS element:
                        foreach($DSelements as $key => $dsConf) {
-                                       
+
                                                // Array/Section:
                                if ($DSelements[$key]['type']=='array') {
                                        if (is_array($dataValues[$key]['el']))  {
@@ -1911,7 +2004,8 @@ class t3lib_TCEmain       {
                                                                                        $dataValues_current[$key]['el'][$ik][$theKey]['el'],
                                                                                        $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
                                                                                        $DSelements[$key]['el'][$theKey]['el'],
-                                                                                       $pParams
+                                                                                       $pParams,
+                                                                                       $callBackFunc
                                                                                );
                                                                }
                                                        }
@@ -1922,40 +2016,80 @@ class t3lib_TCEmain     {
                                                                        $dataValues_current[$key]['el'],
                                                                        $uploadedFiles[$key]['el'],
                                                                        $DSelements[$key]['el'],
-                                                                       $pParams
+                                                                       $pParams,
+                                                                       $callBackFunc
                                                                );
                                                }
                                        }
                                } else {
                                        if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key]))     {
                                                foreach($dataValues[$key] as $vKey => $data)    {
-                                                       list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID) = $pParams;
-
-                                                       $res = $this->checkValue_SW(
-                                                                               array(),
-                                                                               $dataValues[$key][$vKey],
-                                                                               $dsConf['TCEforms']['config'],
-                                                                               $CVtable,
-                                                                               $CVid,
-                                                                               $dataValues_current[$key][$vKey],
-                                                                               $CVstatus,
-                                                                               $CVrealPid,
-                                                                               $CVrecFID,
-                                                                               '',
-                                                                               $uploadedFiles[$key][$vKey]
-                                                                       );
-                                                       
-                                                               // Evaluating the value.
-                                                       if (isset($res["value"]))       {
-                                                               $dataValues[$key][$vKey]=$res["value"];
-                                                       }               
 
-                                               }                       
+                                                       if ($callBackFunc)      {
+                                                               $res = $this->$callBackFunc(
+                                                                                       $pParams,
+                                                                                       $dsConf['TCEforms']['config'],
+                                                                                       $dataValues[$key][$vKey],
+                                                                                       $dataValues_current[$key][$vKey],
+                                                                                       $uploadedFiles[$key][$vKey]
+                                                                               );
+                                                       } else {        // Default
+                                                               list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;
+
+                                                               $res = $this->checkValue_SW(
+                                                                                       array(),
+                                                                                       $dataValues[$key][$vKey],
+                                                                                       $dsConf['TCEforms']['config'],
+                                                                                       $CVtable,
+                                                                                       $CVid,
+                                                                                       $dataValues_current[$key][$vKey],
+                                                                                       $CVstatus,
+                                                                                       $CVrealPid,
+                                                                                       $CVrecFID,
+                                                                                       '',
+                                                                                       $uploadedFiles[$key][$vKey],
+                                                                                       array(),
+                                                                                       $CVtscPID
+                                                                               );
+
+                                                                       // Look for RTE transformation of field:
+                                                               if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations)      {
+
+                                                                               // Unsetting trigger field - we absolutely don't want that into the data storage!
+                                                                       unset($dataValues[$key]['_TRANSFORM_'.$vKey]);
+
+                                                                       if (isset($res['value']))       {
+
+                                                                                       // Calculating/Retrieving some values here:
+                                                                               list(,,$recFieldName) = explode(':', $CVrecFID);
+                                                                               $theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable,$this->checkValue_currentRecord);
+                                                                               $specConf = t3lib_BEfunc::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);
+
+                                                                                       // Find, thisConfig:
+                                                                               $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($CVtscPID));
+                                                                               $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);
+
+                                                                                       // Get RTE object, draw form and set flag:
+                                                                               $RTEobj = &t3lib_BEfunc::RTEgetObj();
+                                                                               if (is_object($RTEobj)) {
+                                                                                       $res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord,$specConf,$thisConfig,'',$CVrealPid);
+                                                                               } else {
+                                                                                       debug('NO RTE OBJECT FOUND!');
+                                                                               }
+                                                                       }
+                                                               }
+                                                       }
+
+                                                               // Adding the value:
+                                                       if (isset($res['value']))       {
+                                                               $dataValues[$key][$vKey] = $res['value'];
+                                                       }
+                                               }
                                        }
                                }
                        }
                }
-       }       
+       }
 
 
 
@@ -1978,46 +2112,52 @@ class t3lib_TCEmain     {
 
        /*********************************************
         *
-        * ...
+        * Storing data to Database Layer
         *
         ********************************************/
 
 
        /**
-        * Update database
-        * 
+        * Update database record
         * Does not check permissions but expects them to be verified on beforehand
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $fieldArray: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Record table name
+        * @param       integer         Record uid
+        * @param       array           Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
+        * @return      void
         */
        function updateDB($table,$id,$fieldArray)       {
                global $TCA;
-               if ($this->debug)       {debug($fieldArray);}
-               if (is_array($fieldArray) && $TCA[$table] && intval($id) )      {
-                       reset($fieldArray);
-                       $fA=array();
-                       while (list($col,$val)=each($fieldArray))       {
-                               if ($col != "uid")      {       // Do not update the uid field
-                                       $fA[]=$col."='".addslashes($val)."'";
-                               }
-                       }
-                       if (count($fA)) {
-                               $query= "UPDATE ".$table." set ".implode($fA,",")." WHERE uid = ".intval($id);
-                               @mysql(TYPO3_db,$query);
-                               if ($this->debug)       {echo $query."<BR>".mysql_error();}
-                               if (!mysql_error())     {
-                                       if ($this->checkStoredRecords)  {$newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);}
-                                       $propArr=$this->getRecordPropertiesFromRow($table,$newRow);
-                                       $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr["header"],$table.":".$id),$propArr["event_pid"]);
-                                       $this->setHistory($table,$id,$theLogId);
-                                       $this->clear_cache($table,$id);
-                                       if ($table=="pages")    unset($this->pageCache[$id]);   // Unset the pageCache for the id if table was page.
-                               } else {
-                                       $this->log($table,$id,2,0,2,"MySQL error: '%s' (%s)",12,array(mysql_error(),$table.":".$id));
-                               }
+
+               if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id))     {
+                       unset($fieldArray['uid']);      // Do NOT update the UID field, ever!
+
+                       if (count($fieldArray)) {
+
+                                       // Execute the UPDATE query:
+                               $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);
+
+                                       // If succees, do...:
+                               if (!$GLOBALS['TYPO3_DB']->sql_error()) {
+                                       if ($this->checkStoredRecords)  {
+                                               $newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
+                                       }
+
+                                               // Set log entry:
+                                       $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
+                                       $theLogId = $this->log($table,$id,2,$recpid,0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
+
+                                               // Set History data:
+                                       $this->setHistory($table,$id,$theLogId);
+
+                                               // Clear cache for relavant pages:
+                                       $this->clear_cache($table,$id);
+
+                                               // Unset the pageCache for the id if table was page.
+                                       if ($table=='pages')    unset($this->pageCache[$id]);
+                               } else {
+                                       $this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
+                               }
                        }
                }
        }
@@ -2026,93 +2166,100 @@ class t3lib_TCEmain    {
         * Compares the incoming field array with the current record and unsets all fields which are the same.
         * If the returned array is empty, then the record should not be updated!
         * $fieldArray must be an array.
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $fieldArray: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Record table name
+        * @param       integer         Record uid
+        * @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!
+        * @return      array           Returns $fieldArray
         */
        function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)   {
-               unset($currentRecord);
-               $res = mysql(TYPO3_db,"SELECT * FROM $table WHERE uid=".intval($id));
-               
-                       // Fetch the types of the fields.
-               if (mysql_num_rows($res))       {
-                       $currentRecord = mysql_fetch_assoc($res);
-                       $c=0;
-                       reset($currentRecord);
-                       $cRecTypes=array();
-                       while (list($col,$val)=each($currentRecord))    {
-                               $cRecTypes[$col]=mysql_field_type($res,$c);
+
+                       // Fetch the original record:
+               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
+               $currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+
+                       // If the current record exists (which it should...), begin comparison:
+               if (is_array($currentRecord))   {
+
+                               // Read all field types:
+                       $c = 0;
+                       $cRecTypes = array();
+                       foreach($currentRecord as $col => $val) {
+                               $cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
                                $c++;
                        }
-               }
 
-                       // Unset the fields which are similar.
-               if (is_array($currentRecord))   {       // If current record exists...
-                       reset($fieldArray);
-                       while (list($col,$val)=each($fieldArray))       {
-                               if (!isset($currentRecord[$col]) || 
-                                               !strcmp($val,$currentRecord[$col]) ||
-                                               ($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.
-                                       )       {       // The field must exist in the current record and it MUST be different to the letter.
+                               // Free result:
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+
+                               // Unset the fields which are similar:
+                       foreach($fieldArray as $col => $val)    {
+                               if (
+                                               #!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!]
+                                               !strcmp($val,$currentRecord[$col]) ||   // Unset fields which matched exactly.
+                                               ($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.
+                                       )       {
                                        unset($fieldArray[$col]);
                                } else {
-                                       $this->historyRecords[$table.":".$id]["oldRecord"][$col] = $currentRecord[$col];
-                                       $this->historyRecords[$table.":".$id]["newRecord"][$col] = $fieldArray[$col];
+                                       $this->historyRecords[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
+                                       $this->historyRecords[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
                                }
                        }
                } else {        // If the current record does not exist this is an error anyways and we just return an empty array here.
-                       $fieldArray=array();
+                       $fieldArray = array();
                }
+
                return $fieldArray;
        }
-       
+
        /**
         * Insert into database
-        * 
         * Does not check permissions but expects them to be verified on beforehand
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $fieldArray: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Record table name
+        * @param       string          "NEW...." uid string
+        * @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!
+        * @return      void
         */
        function insertDB($table,$id,$fieldArray)       {
                global $TCA;
-               if ($this->debug)       {debug($fieldArray);}
-               if (is_array($fieldArray) && $TCA[$table] && isset($fieldArray["pid"])) {
-                       reset($fieldArray);
-                       $fA=array();
-                       while (list($col,$val)=each($fieldArray))       {
-                               if ($col != "uid")      {       // Cannot insert uid
-                                       $fA["f"][]=$col;
-                                       $fA["v"][]="'".addslashes($val)."'";
-                               }
-                       }
-                       if (count($fA)) {
-                               $query = "INSERT INTO ".$table." (".implode($fA["f"],",").") VALUES (".implode($fA["v"],",").")";
-                               @mysql(TYPO3_db,$query);
-                               if ($this->debug)       {echo $query."<BR>".mysql_error();}
-                               if (!mysql_error())     {
-                                       $NEW_id = $id;  // the NEW_id now holds the "NEWaæsdfjæs9345" -id
-                                       $id = mysql_insert_id();
+
+               if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid']))       {
+                       unset($fieldArray['uid']);      // Do NOT insert the UID field, ever!
+
+                       if (count($fieldArray)) {
+
+                                       // Execute the INSERT query:
+                               $GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);
+
+                                       // If succees, do...:
+                               if (!$GLOBALS['TYPO3_DB']->sql_error()) {
+
+                                               // Set mapping for NEW... -> real uid:
+                                       $NEW_id = $id;          // the NEW_id now holds the 'NEW....' -id
+                                       $id = $GLOBALS['TYPO3_DB']->sql_insert_id();
                                        $this->substNEWwithIDs[$NEW_id] = $id;
                                        $this->substNEWwithIDs_table[$NEW_id] = $table;
-                                       if($this->debug)        {debug($this->substNEWwithIDs);}
-                                       if ($table=="pages")    {
+
+                                               // Checking the record is properly saved and writing to log
+                                       if ($this->checkStoredRecords)  {
+                                               $newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
+                                       }
+
+                                               // Set log entry:
+                                       if ($table=='pages')    {
                                                $thePositionID = $this->getInterfacePagePositionID($id);
                                        } else {
-                                               $thePositionID=0;
+                                               $thePositionID = 0;
                                        }
-                                               // Checking the record is properly saved and writing to log
-                                       if ($this->checkStoredRecords)  {$newRow=$this->checkStoredRecord($table,$id,$fieldArray,1);}
-                                       $propArr=$this->getRecordPropertiesFromRow($table,$newRow);
-                                       $page_propArr= $this->getRecordProperties("pages",$propArr["pid"]);
-                                       $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);
+                                       $propArr = $this->getRecordPropertiesFromRow($table,$newRow);
+                                       $page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
+                                       $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);
+
+                                               // Clear cache for relavant pages:
                                        $this->clear_cache($table,$id);
                                } else {
-                                       $this->log($table,$id,1,0,2,"MySQL error: '%s' (%s)",12,array(mysql_error(),$table.":".$id));
+                                       $this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
                                }
                        }
                }
@@ -2120,39 +2267,47 @@ class t3lib_TCEmain     {
 
        /**
         * Checking stored record to see if the written values are properly updated.
-        * 
-        * $action is only for logging
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $id: ...
-        * @param       [type]          $fieldArray: ...
-        * @param       [type]          $action: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Record table name
+        * @param       integer         Record uid
+        * @param       array           Array of field=>value pairs to insert/update
+        * @param       string          Action, for logging only.
+        * @return      array           Selected row
+        * @see insertDB(), updateDB()
         */
        function checkStoredRecord($table,$id,$fieldArray,$action)      {
                global $TCA;
+
                $id = intval($id);
-               if ($TCA[$table] && $id)        {
-                       $res = mysql(TYPO3_db,"select * from $table where uid = $id");
-                       if ($row=mysql_fetch_assoc($res))       {
-                               reset($fieldArray);
-                               $errorString=array();
-                               while(list($key,$value)=each($fieldArray)){
+               if (is_array($TCA[$table]) && $id)      {
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
+                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+
+                                       // Traverse arrow of values that was inserted into the database and compare with the actually stored value:
+                               $errorString = array();
+                               foreach($fieldArray as $key => $value)  {
                                        if ($this->checkStoredRecords_loose && !$value && !$row[$key])  {
                                                // Nothing...
-                                       } elseif (strcmp($value,$row[$key]))    {$errorString[]=$key;}
+                                       } elseif (strcmp($value,$row[$key]))    {
+                                               $errorString[] = $key;
+                                       }
                                }
+
+                                       // Set log message if there were fields with unmatching values:
                                if (count($errorString))        {
-                                       $this->log($table,$id,$action,0,102,"These fields are not properly updated in database: (".implode(",",$errorString).") Probably value mismatch with fieldtype.");                      
+                                       $this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
                                }
+
+                                       // Return selected rows:
                                return $row;
                        }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
        }
-       
+
        /**
         * Executing dbAnalysisStore
-        * 
+        *
         * @return      [type]          ...
         */
        function dbAnalysisStoreExec()  {
@@ -2168,7 +2323,7 @@ class t3lib_TCEmain       {
 
        /**
         * Executing dbAnalysisStore
-        * 
+        *
         * @return      [type]          ...
         */
        function removeRegisteredFiles()        {
@@ -2181,70 +2336,58 @@ class t3lib_TCEmain     {
 
        /**
         * Clearing the cache based on a page being updated
-        * 
-        * If the $table is "pages" then cache is cleared for all pages on the same level (and subsequent?)
+        * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
         * Else just clear the cache for the parent page of the record.
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $uid: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Table name of record that was just updated.
+        * @param       integer         UID of updated / inserted record
+        * @return      void
         */
        function clear_cache($table,$uid) {
                global $TCA;
+
                $uid = intval($uid);
-               if ($TCA[$table] && $uid > 0)   {
-                       if ($table=='pages')    {
-                                       // Builds list of pages on the SAME level as this page
-                               $res_tmp = mysql(TYPO3_db,"select A.pid as pid ,B.uid as uid ,B.title as title from $table A, $table B where A.uid=$uid and B.pid=A.pid");
-                               $list_cache='(';
-                               while ($row_tmp = mysql_fetch_assoc($res_tmp)) {
-                                       $list_cache.=$row_tmp["uid"].',';
-                                       $pid_tmp=$row_tmp["pid"];
-                               }
-                               $list_cache.=$pid_tmp.')';
-                               $query = "DELETE FROM cache_pages WHERE page_id IN $list_cache";
-                               if ($this->debug)       {echo $query."<BR>";}
-                               $res_tmp = mysql(TYPO3_db,$query);
-                               if ($this->debug)       {echo mysql_affected_rows()."<BR>";}
-
-                                       // $query2 is used to clear the caching of the template-setup. This should only be needed when pages are moved or the template is rebuild. I should consider doing this only in these cases or make it a manual operation...
-                               $query2 = "DELETE FROM cache_pagesection WHERE page_id IN $list_cache";
-                               $res_tmp = mysql(TYPO3_db,$query2);
-
-                                       // Deletes all cached pages with a reference to the page. This is being tested
-                               if ($this->clearCache_like)     {
-                                       $query = "DELETE FROM cache_pages WHERE (".
-                                                               "HTML like '%?id=".$uid."%'".
-                                                               " OR HTML like '%?id=".$uid."&%'".
-                                                               " OR HTML like '%?".$uid."%'".
-                                                               " OR HTML like '%?".$uid."&%'".
-                                                               ")";
-                                       if ($this->debug)       {echo $query."<BR>";}
-                                       $res_tmp = mysql(TYPO3_db,$query);
-                                       if ($this->debug)       {echo mysql_affected_rows()."<BR>";}
-                               }
-                       } else {
-                               $uid_page = $this->getPID($table,$uid);
-                               if ($uid_page>0)        {
-                                       $query="delete from cache_pages where page_id=$uid_page";
-                                       if ($this->debug)       {echo $query."<BR>";}
-                                       $res_tmp = mysql(TYPO3_db,$query);
-                                       if ($this->debug)       {echo mysql_affected_rows()."<BR>";}
+               if (is_array($TCA[$table]) && $uid > 0) {
 
+                               // If table is "pages":
+                       if (t3lib_extMgm::isLoaded('cms'))      {
+                               if ($table=='pages')    {
 
-                                       $query2="delete from cache_pagesection where page_id=$uid_page";
-                                       $res_tmp = mysql(TYPO3_db,$query2);
+                                               // Builds list of pages on the SAME level as this page:
+                                       $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                                       'A.pid AS pid, B.uid AS uid, B.title AS title',
+                                                                       $table.' AS A, '.$table.' AS  B',
+                                                                       'A.uid='.intval($uid).' AND B.pid=A.pid'
+                                                               );
+
+                                       $list_cache = array();
+                                       $pid_tmp = 0;
+                                       while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
+                                               $list_cache[] = $row_tmp['uid'];
+                                               $pid_tmp = $row_tmp['pid'];
+                                       }
+                                       $list_cache[] = $pid_tmp;
+
+                                               // Delete cache for selected pages:
+                                       $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
+                                       $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
+                               } else {        // For other tables than "pages", delete cache for the records "parent page".
+                                       $uid_page = $this->getPID($table,$uid);
+                                       if ($uid_page>0)        {
+                                               $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id='.intval($uid_page));
+                                               $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id='.intval($uid_page));
+                                       }
                                }
                        }
-                       
+
                                // Clear cache for pages entered in TSconfig:
-                       list($tscPID)=t3lib_BEfunc::getTSCpid($table,$uid,'');
+                       list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
                        $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
                        if ($TSConfig['clearCacheCmd']) {
                                $Commands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
                                $Commands = array_unique($Commands);
                                foreach($Commands as $cmdPart)  {
-                                       $this->clear_cacheCmd($cmdPart);        
+                                       $this->clear_cacheCmd($cmdPart);
                                }
                        }
 
@@ -2261,16 +2404,16 @@ class t3lib_TCEmain     {
 
        /**
         * Returns the pid of a record from $table with $uid
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $uid: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Table name
+        * @param       integer         Record uid
+        * @return      integer         PID value (unless the record did not exist in which case FALSE)
         */
        function getPID($table,$uid)    {
-               $res_tmp = mysql(TYPO3_db,"select pid from $table where uid=".intval($uid));
-               if (mysql_num_rows($res_tmp))   {
-                       return mysql_result($res_tmp,0,"pid");
-               } else {return "";}
+               $res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
+               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp))     {
+                       return $row['pid'];
+               }
        }
 
 
@@ -2291,22 +2434,22 @@ class t3lib_TCEmain     {
 
 
 
-       
-       
-       
-       
-       
-       
+
+
+
+
+
+
        /*********************************************
         *
-        * PROCESSING COMMANDS
-        * 
+        * Processing Commands
+        *
         ********************************************/
 
        /**
         * Processing the cmd-array
-        * 
-        * @return      [type]          ...
+        *
+        * @return      void
         */
        function process_cmdmap() {
                global $TCA;
@@ -2326,12 +2469,12 @@ class t3lib_TCEmain     {
                                                $command = key($incomingCmdArray);
                                                $value = current($incomingCmdArray);
                                                switch ($command)       {
-                                                       case "move":
+                                                       case 'move':
                                                                $this->moveRecord($table,$id,$value);
                                                        break;
-                                                       case "copy":
-                                                               $this->copyMappingArray = Array();              // Must clear this array before call from here to those functions.
-                                                               if ($table == "pages")  {
+                                                       case 'copy':
+                                                               $this->copyMappingArray = Array();              // Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.
+                                                               if ($table == 'pages')  {
                                                                        $this->copyPages($id,$value);
                                                                } else {
                                                                        $this->copyRecord($table,$id,$value,1);
@@ -2340,8 +2483,8 @@ class t3lib_TCEmain       {
                                                                        // Merging the copy-array info together for remapping purposes.
                                                                $this->copyMappingArray_merged= t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged,$this->copyMappingArray);
                                                        break;
-                                                       case "delete":
-                                                               if ($table == "pages")  {
+                                                       case 'delete':
+                                                               if ($table == 'pages')  {
                                                                        $this->deletePages($id);
                                                                } else {
                                                                        $this->deleteRecord($table,$id, 0);
@@ -2357,9 +2500,9 @@ class t3lib_TCEmain       {
 
        /**
         * Moving records
-        * 
+        *
         * $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
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @param       [type]          $destPid: ...
@@ -2367,7 +2510,8 @@ class t3lib_TCEmain       {
         */
        function moveRecord($table,$uid,$destPid)       {
                global $TCA;
-               $sortRow = $TCA[$table]["ctrl"]["sortby"];
+               
+               $sortRow = $TCA[$table]['ctrl']['sortby'];
                $destPid = intval($destPid);
                $origDestPid = $destPid;
                if ($TCA[$table])       {
@@ -2376,94 +2520,98 @@ class t3lib_TCEmain     {
 
                                // 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. 
                                // 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.
-                       if ($table!="pages" || $resolvedPid==$propArr["pid"])   {
+                       if ($table!='pages' || $resolvedPid==$propArr['pid'])   {
                                $mayMoveAccess=$this->checkRecordUpdateAccess($table,$uid);     // Edit rights for the record...
                        } else {
-                               $mayMoveAccess=$this->doesRecordExist($table,$uid,"delete");
+                               $mayMoveAccess=$this->doesRecordExist($table,$uid,'delete');
                        }
                        
                                // 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
-                       if ($table!="pages" || $resolvedPid!=$propArr["pid"])   {
+                       if ($table!='pages' || $resolvedPid!=$propArr['pid'])   {
                                $mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4);       // Edit rights for the record...
                        } else {
                                $mayInsertAccess=$this->checkRecordUpdateAccess($table,$uid);
                        }
 
                                // 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...)
-                       if ($destPid<0 && !$sortRow)    {       
+                       if ($destPid<0 && !$sortRow)    {
                                $destPid = $resolvedPid;
                        }
                        
-                               // 
-                       if ($TCA[$table]["ctrl"]["tstamp"])     {
-                               $tstampC = ", ".$TCA[$table]["ctrl"]["tstamp"]."=".time();
-                       } else $tstampC="";
-
+                               // Timestamp field:
+                       $updateFields = array();
+                       if ($TCA[$table]['ctrl']['tstamp'])     {
+                               $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
+                       }
                        
                        if ($mayMoveAccess)     {
                                if ($destPid>=0)        {       // insert as first element on page (where uid = $destPid)
                                        if ($mayInsertAccess)   {
-                                               if ($table!="pages" || $this->destNotInsideSelf ($destPid,$uid))        {
+                                               if ($table!='pages' || $this->destNotInsideSelf ($destPid,$uid))        {
                                                        $this->clear_cache($table,$uid);        // clear cache before moving 
-                                                       if ($sortRow)   {       // table is sorted by 'sortby'
+
+                                                       $updateFields['pid'] = $destPid;        // Setting PID
+
+                                                               // table is sorted by 'sortby'
+                                                       if ($sortRow)   {
                                                                $sortNumber = $this->getSortNumber($table,$uid,$destPid);
-                                                               $query = "UPDATE $table SET pid='$destPid', $sortRow='$sortNumber'".$tstampC." WHERE uid = '$uid'";             // We now update the pid and sortnumber
-                                                               $res = mysql(TYPO3_db,$query);
-                                                               if ($this->debug)       {echo $table.$uid.": Update pid(".$destPid.") and sorting number(".$sortNumber.")<BR>";}
-                                                       } else {        // table is NOT sorted
-                                                               $query = "UPDATE $table SET pid='$destPid'".$tstampC." WHERE uid = '$uid'";     // We need only update the pid as this table is not sorted
-                                                               $res = mysql(TYPO3_db,$query);
-                                                               if ($this->debug)       {echo $table.$uid.": Update pid only (no sorting)<BR>";}
+                                                               $updateFields[$sortRow] = $sortNumber;
                                                        }
                                                        
-                                                                       // Logging...
+                                                               // Create query for update:
+                                                       $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
+                                                       
+                                                               // Logging...
                                                        $newPropArr = $this->getRecordProperties($table,$uid);
-                                                       $oldpagePropArr = $this->getRecordProperties("pages",$propArr["pid"]);
-                                                       $newpagePropArr = $this->getRecordProperties("pages",$destPid);
+                                                       $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
+                                                       $newpagePropArr = $this->getRecordProperties('pages',$destPid);
 
-                                                       if ($destPid!=$propArr["pid"])  {
-                                                               $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
-                                                               $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
+                                                       if ($destPid!=$propArr['pid'])  {
+                                                               $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
+                                                               $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
                                                        } else {
-                                                               $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
+                                                               $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
                                                        }
                                                        $this->clear_cache($table,$uid);        // clear cache after moving 
                                                        $this->fixUniqueInPid($table,$uid);
                                                                // fixCopyAfterDuplFields
                                                        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.
                                                } else {
-                                                       $destPropArr = $this->getRecordProperties("pages",$destPid);
-                                                       $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"]);
+                                                       $destPropArr = $this->getRecordProperties('pages',$destPid);
+                                                       $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']);
                                                }
                                        }
                                } else {        // Put after another record
                                        if ($sortRow)   {       // table is being sorted
                                                $sortInfo = $this->getSortNumber($table,$uid,$destPid);
-                                               $destPid = $sortInfo["pid"];    // Setting the destPid to the new pid of the record.
+                                               $destPid = $sortInfo['pid'];    // Setting the destPid to the new pid of the record.
                                                if (is_array($sortInfo))        {       // If not an array, there was an error (which is already logged)
                                                        if ($mayInsertAccess)   {
-                                                               if ($table!="pages" || $this->destNotInsideSelf ($destPid,$uid))        {
+                                                               if ($table!='pages' || $this->destNotInsideSelf ($destPid,$uid))        {
                                                                        $this->clear_cache($table,$uid);        // clear cache before moving 
-                                                                       $query = "UPDATE $table SET pid='".$destPid."', $sortRow='".$sortInfo["sortNumber"]."'".$tstampC." WHERE uid = '$uid'";         // We now update the pid and sortnumber
-                                                                       $res = mysql(TYPO3_db,$query);
-                                                                       if ($this->debug)       {echo $table.$uid.": Update pid(".$destPid.") and sorting number(".$sortInfo["sortNumber"].")<BR>";}
+                                                                       
+                                                                       $updateFields['pid'] = $destPid;
+                                                                       $updateFields[$sortRow] = $sortInfo['sortNumber'];
+
+                                                                       $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);             // We now update the pid and sortnumber
+
                                                                                // Logging...
-                                                                       if ($table=="pages")    {
+                                                                       if ($table=='pages')    {
                                                                                $thePositionID = $this->getInterfacePagePositionID($uid);
                                                                        } else {
-                                                                               $thePositionID=0;
+                                                                               $thePositionID = 0;
                                                                        }
                                                                        
-                                                                       $this->log($table,$uid,4,$thePositionID,0,"");
+                                                                       $this->log($table,$uid,4,$thePositionID,0,'');
                                                                        // Logging...
                                                                        $newPropArr = $this->getRecordProperties($table,$uid);
-                                                                       $oldpagePropArr = $this->getRecordProperties("pages",$propArr["pid"]);
-                                                                       if ($destPid!=$propArr["pid"])  {
-                                                                               $newpagePropArr = $this->getRecordProperties("pages",$destPid);
-                                                                               $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
-                                                                               $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
+                                                                       $oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
+                                                                       if ($destPid!=$propArr['pid'])  {
+                                                                               $newpagePropArr = $this->getRecordProperties('pages',$destPid);
+                                                                               $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
+                                                                               $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
                                                                        } else {
-                                                                               $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
+                                                                               $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
                                                                        }
                                                                        $this->clear_cache($table,$uid);        // clear cache after moving 
                                                                                // fixUniqueInPid
@@ -2471,27 +2619,27 @@ class t3lib_TCEmain     {
                                                                                // fixCopyAfterDuplFields
                                                                        if ($origDestPid<0)     {$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
                                                                } else {
-                                                                       $destPropArr = $this->getRecordProperties("pages",$destPid);
-                                                                       $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"]);
+                                                                       $destPropArr = $this->getRecordProperties('pages',$destPid);
+                                                                       $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']);
                                                                }
                                                        }
                                                }
                                        } else {
-                                               $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"]);
+                                               $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']);
                                        }
                                }
                        } else {
-                               $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"]);
+                               $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']);
                        }
                }
        }
 
        /**
         * Copying records
-        * 
+        *
         * $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
-        * $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
-        * 
+        * $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
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @param       [type]          $destPid: ...
@@ -2503,17 +2651,17 @@ class t3lib_TCEmain     {
                $uid = intval($uid);
                if ($TCA[$table] && $uid)       {
                        t3lib_div::loadTCA($table);
-                       if ($this->doesRecordExist($table,$uid,"show")) {
+                       if ($this->doesRecordExist($table,$uid,'show')) {
                                $data = Array();
-                               $nonFields = explode(",","uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody");
-                               $row = $this->recordInfo($table,$uid,"*");
+                               $nonFields = explode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody');
+                               $row = $this->recordInfo($table,$uid,'*');
                                if (is_array($row))     {
-                                       $theNewID = uniqid("NEW");
+                                       $theNewID = uniqid('NEW');
 //                                     $fileFieldArr = $this->extFileFields($table);           // Fetches all fields that holds references to files
-                                       $enableField = isset($TCA[$table]["ctrl"]["enablecolumns"]) ? $TCA[$table]["ctrl"]["enablecolumns"]["disabled"] : "";
-                                       $headerField = $TCA[$table]["ctrl"]["label"];
+                                       $enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ? $TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
+                                       $headerField = $TCA[$table]['ctrl']['label'];
                                        $defaultData = $this->newFieldArray($table);
-                                       
+
                                        $tscPID=t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$destPid);       // NOT using t3lib_BEfunc::getTSCpid() because we need the real pid - not the id of a page, if the input is a page...
                                        $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
                                        $tE = $this->getTableEntries($table,$TSConfig);
@@ -2522,70 +2670,63 @@ class t3lib_TCEmain     {
                                        reset($row);
                                        while (list($field,$value)=each($row))  {
                                                if (!in_array($field,$nonFields))       {
-                                                       $conf = $TCA[$table]["columns"][$field]["config"];
-                                                       
-                                                       if ($field=="pid")      {
+                                                       $conf = $TCA[$table]['columns'][$field]['config'];
+
+                                                       if ($field=='pid')      {
                                                                $value = $destPid;
                                                        }
 
-                                                       if ($TCA[$table]["ctrl"]["setToDefaultOnCopy"] && t3lib_div::inList($TCA[$table]["ctrl"]["setToDefaultOnCopy"],$field)) {
+                                                       if ($TCA[$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div::inList($TCA[$table]['ctrl']['setToDefaultOnCopy'],$field)) {
                                                                $value = $defaultData[$field];
                                                        } else {
-                                                               if ($first && $field==$enableField && $TCA[$table]["ctrl"]["hideAtCopy"] && !$this->neverHideAtCopy && !$tE["disableHideAtCopy"])       {
+                                                               if ($first && $field==$enableField && $TCA[$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy'])       {
                                                                        $value=1;
                                                                }
-                                                               if ($first && $field==$headerField && $TCA[$table]["ctrl"]["prependAtCopy"] && !$tE["disablePrependAtCopy"])    {
-                                                                       $value = $this->getCopyHeader ($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
+                                                               if ($first && $field==$headerField && $TCA[$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy'])    {
+                                                                       $value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
                                                                }
-       
-                                                                       // Take care of files...
-                                                               if ($conf["type"]=="group" && $conf["internal_type"]=="file")   {
-                                                                       if ($conf["MM"])        {
-                                                                               $theFileValues=array();
-                                                                               $dbAnalysis = t3lib_div::makeInstance("t3lib_loadDBGroup");
-                                                                               $dbAnalysis->start("","files",$conf["MM"],$uid);
-                                                                               reset($dbAnalysis->itemArray);
-                                                                               while (list($somekey,$someval)=each($dbAnalysis->itemArray))    {
-       //                                                                              debug($someval["id"]);
-                                                                                       if ($someval["id"])     {
-                                                                                               $theFileValues[]=$someval["id"];
-                                                                                       }
-                                                                               }
-                                                                       } else {
-                                                                               $theFileValues = explode(",",$value);
+
+                                                                       // Process references and files, currently that means only the files, prepending absolute paths (so the TCEmain engine will detect the file as new and one that should be made into a copy)
+                                                               $value = $this->copyRecord_procFilesRefs($conf, $uid, $value);
+
+                                                                       // Register if there are references to take care of (no change to value):
+                                                               if ($this->isReferenceField($conf))     {
+                                                                       $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
+                                                                       $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
+                                                                       if ($conf['MM'])        {
+                                                                               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                                                               $dbAnalysis->start('',$allowedTables,$conf['MM'],$uid);
+                                                                               $value = implode(',',$dbAnalysis->getValueArray($prependName));
                                                                        }
-       //                                                              debug($theFileValues);
-                                                                       reset($theFileValues);
-                                                                       $uploadFolder = $conf["uploadfolder"];
-                                                                       $dest = $this->destPathFromUploadFolder($uploadFolder);
-                                                                       $newValue = array();
-                                                                       while (list(,$file)=each($theFileValues))       {
-                                                                               if (trim($file))        {
-                                                                                       $realFile = $dest."/".trim($file);
-                                                                                       if (@is_file($realFile))        {
-                                                                                               $newValue[]=$realFile;
-                                                                                       }
-                                                                               }
+                                                                       if ($value)     {       // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
+                                                                               $this->registerDBList[$table][$uid][$field] = $value;
                                                                        }
-                                                                       $value = implode(",",$newValue);
                                                                }
-                                                                       // db record lists:
-                                                               if (($conf["type"]=="group" && $conf["internal_type"]=="db") || ($conf["type"]=="select" && $conf["foreign_table"]))    {
-                                                                       $allowedTables = $conf["type"]=="group" ? $conf["allowed"] : $conf["foreign_table"].",".$conf["neg_foreign_table"];
-                                                                       $prependName = $conf["type"]=="group" ? $conf["prepend_tname"] : $conf["neg_foreign_table"];
-                                                                       if ($conf["MM"])        {
-                                                                               $dbAnalysis = t3lib_div::makeInstance("t3lib_loadDBGroup");
-                                                                               $dbAnalysis->start("",$allowedTables,$conf["MM"],$uid);
-                                                                               $value = implode(",",$dbAnalysis->getValueArray($prependName));
-                                                                       }
-                                                                       if ($value)     {
-                                                                               $this->registerDBList[$table][$uid][$field]=$value;
+
+                                                                       // For "flex" fieldtypes we need to traverse the structure for two reasons: If there are file references they have to be prepended with absolute paths and if there are database reference they MIGHT need to be remapped (still done in remapListedDBRecords())
+                                                               if ($conf['type']=='flex')      {
+
+                                                                               // Get current value array:
+                                                                       $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table);
+                                                                       $currentValueArray = t3lib_div::xml2array($value);
+
+                                                                               // Traversing the XML structure, processing files:
+                                                                       if (is_array($currentValueArray))       {
+                                                                               $currentValueArray['data'] = $this->checkValue_flex_procInData(
+                                                                                                       $currentValueArray['data'],
+                                                                                                       array(),        // Not used.
+                                                                                                       array(),        // Not used.
+                                                                                                       $dataStructArray,
+                                                                                                       array($table,$uid,$field),      // Parameters.
+                                                                                                       'copyRecord_flexFormCallBack'
+                                                                                               );
+                                                                               $value = $currentValueArray;    // Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
                                                                        }
                                                                }
                                                        }
 
                                                                // Add value to array.
-                                                       $value=addSlashes($value);      // Added 15-03-00
+#                                                      $value=addSlashes($value);      // Added 15-03-00, Remove 11-02-04 (see below)
                                                        $data[$table][$theNewID][$field]=$value;
                                                }
                                        }
@@ -2597,17 +2738,18 @@ class t3lib_TCEmain     {
 //debug($data[$table][$theNewID]);
                                        }       // 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.
 
-                                       
+
                                                // Do the copy:
 //debug($data[$table][$theNewID]);
-                                       $copyTCE = t3lib_div::makeInstance("t3lib_TCEmain");
+#debug($data,'COPY RECORD:');
+                                       $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
+                                       $copyTCE->stripslashes_values=0;        // Added 11-02-04
                                        $copyTCE->copyTree = $this->copyTree;
                                        $copyTCE->cachedTSconfig = $this->cachedTSconfig;       // Copy forth the cached TSconfig
-                                       $copyTCE->debug = $this->debug;
                                        $copyTCE->dontProcessTransformations=1;         // Transformations should NOT be carried out during copy
-       //                              $copyTCE->enableLogging = $table=="pages"?1:0;  // If enabled the list-view does not update...
-       
-                                       $copyTCE->start($data,"",$this->BE_USER);
+       //                              $copyTCE->enableLogging = $table=='pages'?1:0;  // If enabled the list-view does not update...
+
+                                       $copyTCE->start($data,'',$this->BE_USER);
                                        $copyTCE->process_datamap();
 
                                        $theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
@@ -2617,86 +2759,170 @@ class t3lib_TCEmain    {
                                        $this->cachedTSconfig = $copyTCE->cachedTSconfig;       // Copy back the cached TSconfig
                                        unset($copyTCE);
                                } else {
-                                       $this->log($table,$uid,3,0,1,"Attempt to copy record that did not exist!");
+                                       $this->log($table,$uid,3,0,1,'Attempt to copy record that did not exist!');
                                }
                        } else {
-                               $this->log($table,$uid,3,0,1,"Attempt to copy record without permission");
+                               $this->log($table,$uid,3,0,1,'Attempt to copy record without permission');
                        }
-               }               
-       }       
+               }
+       }
+
+       /**
+        * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
+        *
+        * @param       array           Array of parameters in num-indexes: table, uid, field
+        * @param       array           TCA field configuration (from Data Structure XML)
+        * @param       string          The value of the flexForm field
+        * @param       string          Not used.
+        * @param       string          Not used.
+        * @return      array           Result array with key "value" containing the value of the processing.
+        * @see copyRecord(), checkValue_flex_procInData_travDS()
+        */
+       function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)   {
+
+                       // Extract parameters:
+               list($table, $uid, $field) = $pParams;
+
+                       // Process references and files, currently that means only the files, prepending absolute paths:
+               $dataValue = $this->copyRecord_procFilesRefs($dsConf, $uid, $dataValue);
+
+                       // If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
+               if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
+                       $this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
+               }
+
+                       // Return
+               return array('value' => $dataValue);
+       }
+
+       /**
+        * Modifying a field value for any situation regarding files/references:
+        * For attached files: take current filenames and prepend absolute paths so they get copied.
+        * For DB references: Nothing done.
+        *
+        * @param       array           TCE field config
+        * @param       integer         Record UID
+        * @param       string          Field value (eg. list of files)
+        * @return      string          The (possibly modified) value
+        * @see copyRecord(), copyRecord_flexFormCallBack()
+        */
+       function copyRecord_procFilesRefs($conf, $uid, $value)  {
+
+                       // Prepend absolute paths to files:
+               if ($conf['type']=='group' && $conf['internal_type']=='file')   {
+
+                               // Get an array with files as values:
+                       if ($conf['MM'])        {
+                               $theFileValues = array();
+
+                               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                               $dbAnalysis->start('', 'files', $conf['MM'], $uid);
+
+                               foreach($dbAnalysis->itemArray as $somekey => $someval) {
+                                       if ($someval['id'])     {
+                                               $theFileValues[] = $someval['id'];
+                                       }
+                               }
+                       } else {
+                               $theFileValues = t3lib_div::trimExplode(',',$value,1);
+                       }
+
+                               // Traverse this array of files:
+                       $uploadFolder = $conf['uploadfolder'];
+                       $dest = $this->destPathFromUploadFolder($uploadFolder);
+                       $newValue = array();
+
+                       foreach($theFileValues as $file)        {
+                               if (trim($file))        {
+                                       $realFile = $dest.'/'.trim($file);
+                                       if (@is_file($realFile))        {
+                                               $newValue[] = $realFile;
+                                       }
+                               }
+                       }
+
+                               // Implode the new filelist into the new value (all files have absolute paths now which means they will get copied when entering TCEmain as new values...)
+                       $value = implode(',',$newValue);
+               }
+
+                       // Return the new value:
+               return $value;
+       }
 
        /**
         * Copying pages
-        * 
         * Main function for copying pages.
-        * $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
-        * 
-        * @param       [type]          $uid: ...
-        * @param       [type]          $destPid: ...
-        * @return      [type]          ...
+        *
+        * @param       integer         Page UID to copy
+        * @param       integer         Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
+        * @return      void
         */
        function copyPages($uid,$destPid)       {
                $uid = intval($uid);
                $destPid = intval($destPid);
-//             $this->copyMappingArray = Array();              // This must be done, but it's comment out because it's done in process_cmdmap()
 
                        // Finding list of tables to copy.
-               $copyTablesArray = ($this->admin) ? $this->compileAdminTables() : explode(",",$this->BE_USER->groupData["tables_modify"]);      // These are the tables, the user may modify
-               if (!strstr($this->copyWhichTables,"*"))        {               // If not all tables are allowed then make a list of allowed tables: That is the tables that figure in both allowed tables and the copyTable-list
-                       reset($copyTablesArray);
-                       while(list($k,$table)=each($copyTablesArray))   {
-                               if (!$table || !t3lib_div::inList($this->copyWhichTables.",pages",$table))      {       // pages are always going...
+               $copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',',$this->BE_USER->groupData['tables_modify']);        // These are the tables, the user may modify
+               if (!strstr($this->copyWhichTables,'*'))        {               // If not all tables are allowed then make a list of allowed tables: That is the tables that figure in both allowed tables AND the copyTable-list
+                       foreach($copyTablesArray as $k => $table)       {
+                               if (!$table || !t3lib_div::inList($this->copyWhichTables.',pages',$table))      {       // pages are always going...
                                        unset($copyTablesArray[$k]);
                                }
                        }
                }
                $copyTablesArray = array_unique($copyTablesArray);
-               if ($this->admin || in_array("pages",$copyTablesArray)) {       // If we're allowed to copy pages
-                       $this->copySpecificPage($uid,$destPid,$copyTablesArray,1);      // Copy this page we're on. And set first-flag!
-                       $theNewRootID = $this->copyMappingArray["pages"][$uid];         // This is the new ID of the rootpage of the copyaction. This ID is excluded when the list is gathered lateron
-                       if ($theNewRootID && $this->copyTree)   {       // If we're going to copy recursively...
+
+                       // Begin to copy pages if we're allowed to:
+               if ($this->admin || in_array('pages',$copyTablesArray)) {
+
+                               // Copy this page we're on. And set first-flag!
+                       $this->copySpecificPage($uid,$destPid,$copyTablesArray,1);
+                       $theNewRootID = $this->copyMappingArray['pages'][$uid];         // This is the new ID of the rootpage of the copyaction. This ID is excluded when the list is gathered lateron
+
+                               // If we're going to copy recursively...:
+                       if ($theNewRootID && $this->copyTree)   {
+
+                                       // Get ALL subpages to copy:
                                $CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($this->copyTree), $theNewRootID);
-                               if ($this->debug) {debug($CPtable);}
-                               // Now copying the pages
-                               reset($CPtable);
-                               while (list($thePageUid,$thePagePid)=each($CPtable))    {
-                                       $newPid = $this->copyMappingArray["pages"][$thePagePid];
+
+                                       // Now copying the subpages:
+                               foreach($CPtable as $thePageUid => $thePagePid) {
+                                       $newPid = $this->copyMappingArray['pages'][$thePagePid];
                                        if (isset($newPid))     {
                                                $this->copySpecificPage($thePageUid,$newPid,$copyTablesArray);
                                        } else {
-                                               $this->log("pages",$uid,5,0,1,"Something went wrong during copying branch");
+                                               $this->log('pages',$uid,5,0,1,'Something went wrong during copying branch');
                                                break;
                                        }
                                }
                        }       // else the page was not copied. Too bad...
                } else {
-                       $this->log("pages",$uid,5,0,1,"Attempt to copy page without permission to this table");
+                       $this->log('pages',$uid,5,0,1,'Attempt to copy page without permission to this table');
                }
        }
 
        /**
         * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
-        * 
-        * $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
-        * 
-        * @param       [type]          $uid: ...
-        * @param       [type]          $destPid: ...
-        * @param       [type]          $copyTablesArray: ...
-        * @param       [type]          $first: ...
-        * @return      [type]          ...
+        *
+        * @param       integer         Page uid
+        * @param       integer         Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
+        * @param       array           Table on pages to copy along with the page.
+        * @param       boolean         Set if this the the root page being copied.
+        * @return      void
         */
        function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)      {
                global $TCA;
-               $this->copyRecord("pages",$uid,$destPid,$first);        // Copy the page itselft.
-               $theNewRootID = $this->copyMappingArray["pages"][$uid]; // The new uid
-               if ($theNewRootID)      {               // copy of the page went fine
-                       reset($copyTablesArray);
-                       while(list(,$table)=each($copyTablesArray))     {
-                               if ($table && $TCA[$table] && $table!="pages")  {       // all records under the page is copied.
-                                       $orderby = ($TCA[$table]["ctrl"]["sortby"]) ? " ORDER BY ".$TCA[$table]["ctrl"]["sortby"]." DESC" : "";
-                                       $query = "SELECT uid FROM $table WHERE pid = $uid ".$this->deleteClause($table).$orderby;
-                                       $mres = mysql(TYPO3_db,$query);
-                                       while ($row = mysql_fetch_assoc($mres)) {
+
+                       // Copy the page itself:
+               $this->copyRecord('pages',$uid,$destPid,$first);
+               $theNewRootID = $this->copyMappingArray['pages'][$uid]; // The new uid
+
+                       // If a new page was created upon the copy operation we will proceed with all the tables ON that page:
+               if ($theNewRootID)      {
+                       foreach($copyTablesArray as $table)     {
+                               if ($table && is_array($TCA[$table]) && $table!='pages')        {       // all records under the page is copied.
+                                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table), '', ($TCA[$table]['ctrl']['sortby'] ? $TCA[$table]['ctrl']['sortby'].' DESC' : ''));
+                                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))     {
                                                $this->copyRecord($table,$row['uid'], $theNewRootID);   // Copying each of the underlying records...
                                        }
                                }
@@ -2706,7 +2932,7 @@ class t3lib_TCEmain       {
 
        /**
         * Returns array, $CPtable, of pages under the $pid going down to $counter levels
-        * 
+        *
         * @param       [type]          $CPtable: ...
         * @param       [type]          $pid: ...
         * @param       [type]          $counter: ...
@@ -2715,12 +2941,11 @@ class t3lib_TCEmain     {
         */
        function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)      {
                if ($counter)   {
-                       $addW =  !$this->admin ? " AND ".$this->BE_USER->getPagePermsClause($this->pMap["show"]) : "";
-                       $query = "SELECT uid FROM pages WHERE pid = $pid ".$this->deleteClause("pages").$addW." ORDER BY sorting DESC";
-                       $mres = mysql(TYPO3_db,$query);
-                       while($row=mysql_fetch_assoc($mres))    {
-                               if ($row["uid"]!=$rootID)       {
-                                       $CPtable[$row["uid"]]=$pid;
+                       $addW =  !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($this->pMap['show']) : '';
+                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'pid='.intval($pid).$this->deleteClause('pages').$addW, '', 'sorting DESC');
+                       while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))      {
+                               if ($row['uid']!=$rootID)       {
+                                       $CPtable[$row['uid']] = $pid;
                                        if ($counter-1) {       // If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
                                                $CPtable = $this->int_pageTreeInfo($CPtable,$row['uid'],$counter-1, $rootID);
                                        }
@@ -2732,7 +2957,7 @@ class t3lib_TCEmain       {
 
        /**
         * List of all tables (those administrators has access to)
-        * 
+        *
         * @return      [type]          ...
         */
        function compileAdminTables()   {
@@ -2747,7 +2972,7 @@ class t3lib_TCEmain       {
        
        /**
         * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @return      [type]          ...
@@ -2756,14 +2981,14 @@ class t3lib_TCEmain     {
                global $TCA;
                if ($TCA[$table])       {
                        t3lib_div::loadTCA($table);
-                       reset ($TCA[$table]["columns"]);
-                       $curData=$this->recordInfo($table,$uid,"*");
+                       reset ($TCA[$table]['columns']);
+                       $curData=$this->recordInfo($table,$uid,'*');
                        $newData=array();
-                       while (list($field,$conf)=each($TCA[$table]["columns"]))        {
-                               if ($conf["config"]["type"]=="input")   {
-                                       $evalCodesArray = t3lib_div::trimExplode(",",$conf["config"]["eval"],1);
-                                       if (in_array("uniqueInPid",$evalCodesArray))    {
-                                               $newV = $this->getUnique($table,$field,$curData[$field],$uid,$curData["pid"]);
+                       while (list($field,$conf)=each($TCA[$table]['columns']))        {
+                               if ($conf['config']['type']=='input')   {
+                                       $evalCodesArray = t3lib_div::trimExplode(',',$conf['config']['eval'],1);
+                                       if (in_array('uniqueInPid',$evalCodesArray))    {
+                                               $newV = $this->getUnique($table,$field,$curData[$field],$uid,$curData['pid']);
                                                if (strcmp($newV,$curData[$field]))     {
                                                        $newData[$field]=$newV;
                                                }
@@ -2780,7 +3005,7 @@ class t3lib_TCEmain       {
        /**
         * When er record is copied you can specify fields from the previous record which should be copied into the new one
         * This function is also called with new elements. But then $update must be set to zero and $newData containing the data array. In that case data in the incoming array is NOT overridden. (250202)
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @param       [type]          $prevUid: ...
@@ -2790,13 +3015,13 @@ class t3lib_TCEmain     {
         */
        function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array()) {
                global $TCA;
-               if ($TCA[$table] && $TCA[$table]["ctrl"]["copyAfterDuplFields"])        {
+               if ($TCA[$table] && $TCA[$table]['ctrl']['copyAfterDuplFields'])        {
                        t3lib_div::loadTCA($table);
-                       $prevData=$this->recordInfo($table,$prevUid,"*");
-                       $theFields = t3lib_div::trimExplode(",",$TCA[$table]["ctrl"]["copyAfterDuplFields"],1);
+                       $prevData=$this->recordInfo($table,$prevUid,'*');
+                       $theFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['copyAfterDuplFields'],1);
                        reset($theFields);
                        while(list(,$field)=each($theFields))   {
-                               if ($TCA[$table]["columns"][$field] && ($update || !isset($newData[$field])))   {
+                               if ($TCA[$table]['columns'][$field] && ($update || !isset($newData[$field])))   {
                                        $newData[$field]=$prevData[$field];
                                }
                        }
@@ -2809,7 +3034,7 @@ class t3lib_TCEmain       {
 
        /**
         * Returns all fieldnames from a table which are a list of files
-        * 
+        *
         * @param       [type]          $table: ...
         * @return      [type]          ...
         */
@@ -2817,10 +3042,10 @@ class t3lib_TCEmain     {
                global $TCA;
                $listArr=array();
                t3lib_div::loadTCA($table);
-               if ($TCA[$table]["columns"])    {
-                       reset($TCA[$table]["columns"]);
-                       while (list($field,$configArr)=each($TCA[$table]["columns"]))   {
-                               if ($configArr["config"]["type"]=="group" && $configArr["config"]["internal_type"]=="file")     {
+               if ($TCA[$table]['columns'])    {
+                       reset($TCA[$table]['columns']);
+                       while (list($field,$configArr)=each($TCA[$table]['columns']))   {
+                               if ($configArr['config']['type']=='group' && $configArr['config']['internal_type']=='file')     {
                                        $listArr[]=$field;
                                }
                        }
@@ -2830,134 +3055,155 @@ class t3lib_TCEmain   {
 
        /**
         * Get copy header
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $pid: ...
-        * @param       [type]          $field: ...
-        * @param       [type]          $value: ...
-        * @param       [type]          $count: ...
-        * @param       [type]          $prevTitle: ...
-        * @return      [type]          ...
+        *
+        * @param       string          Table name
+        * @param       integer         PID value in which other records to test might be
+        * @param       string          Field name to get header value for.
+        * @param       string          Current field value
+        * @param       integer         Counter (number of recursions)
+        * @param       string          Previous title we checked for (in previous recursion)
+        * @return      string          The field value, possibly appended with a "copy label"
         */
-       function getCopyHeader ($table,$pid,$field,$value,$count,$prevTitle="") {
+       function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')  {
                global $TCA;
+
+                       // Set title value to check for:
                if ($count)     {
                        $checkTitle = $value.sprintf($this->prependLabel($table),$count);
                }       else {
                        $checkTitle = $value;
                }
+
+                       // Do check:
                if ($prevTitle != $checkTitle || $count<100)    {
-                       $query = "SELECT uid FROM ".$table." WHERE pid=".$pid." AND ".$field."='".addslashes($checkTitle)."'".$this->deleteClause($table)." LIMIT 1";
-                       $res = mysql(TYPO3_db,$query);
-                       echo mysql_error();
-                       if (mysql_num_rows($res))       {
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($pid).' AND '.$field.'="'.$GLOBALS['TYPO3_DB']->quoteStr($checkTitle, $table).'"'.$this->deleteClause($table), '', '', '1');
+                       if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {
                                return $this->getCopyHeader($table,$pid,$field,$value,$count+1,$checkTitle);
-                       } else {
-                               return $checkTitle;
                        }
-               } else {return $checkTitle;}
+               }
+
+                       // Default is to just return the current input title if no other was returned before:
+               return $checkTitle;
        }
 
        /**
-        * Get the final pid based on $table and $pid ($destPid type... pos/neg)
-        * 
-        * @param       [type]          $table: ...
-        * @param       [type]          $pid: ...
-        * @return      [type]          ...
+        * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
+        *
+        * @param       string          Table name
+        * @return      string          Label to append, containing "%s" for the number
+        * @see getCopyHeader()
         */
-       function resolvePid ($table,$pid)       {
+       function prependLabel($table)   {
                global $TCA;
-               $pid=intval($pid);
-               if ($pid < 0)   {
-                       $query = "SELECT pid FROM ".$table." WHERE uid=".abs($pid);
-                       $res = mysql(TYPO3_db,$query);
-                       $row = mysql_fetch_assoc($res);
-                       $pid = $row["pid"];
+               if (is_object($GLOBALS['LANG']))        {
+                       $label = $GLOBALS['LANG']->sL($TCA[$table]['ctrl']['prependAtCopy']);
+               } else {
+                       list($label) = explode('|',$TCA[$table]['ctrl']['prependAtCopy']);
                }
-               return $pid;
+               return $label;
        }
 
        /**
-        * return prepend label
-        * 
-        * @param       [type]          $table: ...
-        * @return      [type]          ...
+        * Get the final pid based on $table and $pid ($destPid type... pos/neg)
+        *
+        * @param       string          Table name
+        * @param       integer         "Destination pid" : If the value is >= 0 it's just returned directly (through intval() though) but if the value is <0 then the method looks up the record with the uid equal to abs($pid) (positive number) and returns the PID of that record! The idea is that negative numbers point to the record AFTER WHICH the position is supposed to be!
+        * @return      integer
         */
-       function prependLabel ($table)  {
+       function resolvePid($table,$pid)        {
                global $TCA;
-               if (is_object($GLOBALS["LANG"]))        {
-                       $label = $GLOBALS["LANG"]->sL($TCA[$table]["ctrl"]["prependAtCopy"]);
-               } else {
-                       list($label) = explode("|",$TCA[$table]["ctrl"]["prependAtCopy"]);
+               $pid=intval($pid);
+               if ($pid < 0)   {
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.abs($pid));
+                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+                       $pid = intval($row['pid']);
                }
-               return $label;
+               return $pid;
        }
-       
+
        /**
         * Removes the prependAtCopy prefix on values
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $value: ...
         * @return      [type]          ...
         */
        function clearPrefixFromValue($table,$value)    {
                global $TCA;
-               $regex = sprintf(quotemeta($this->prependLabel($table)),"[0-9]*")."$";
-               return @ereg_replace($regex,"",$value);
+               $regex = sprintf(quotemeta($this->prependLabel($table)),'[0-9]*').'$';
+               return @ereg_replace($regex,'',$value);
        }
        
        /**
-        * Processes the list of DBrecords registered by the copy-function.
-        * 
-        * @return      [type]          ...
+        * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
+        *
+        * @return      void
         */
        function remapListedDBRecords() {
                global $TCA;
-//             debug($this->registerDBList);
-//             debug($this->copyMappingArray_merged);
+#debug($this->registerDBList);
+#debug($this->copyMappingArray_merged);
                if (count($this->registerDBList))       {
                        reset($this->registerDBList);
                        while(list($table,$records)=each($this->registerDBList))        {
                                t3lib_div::loadTCA($table);
                                reset($records);
                                while(list($uid,$fields)=each($records))        {
-                                       $newData=array();
+                                       $newData = array();
                                        $theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
-                                       reset($fields);
-                                       while(list($fieldName,$value)=each($fields))    {
-                                               $conf=$TCA[$table]["columns"][$fieldName]["config"];
-                                               $set=0;
-                                               $allowedTables = $conf["type"]=="group" ? $conf["allowed"] : $conf["foreign_table"].",".$conf["neg_foreign_table"];
-                                               $prependName = $conf["type"]=="group" ? $conf["prepend_tname"] : "";
-                                               $dontRemapTables = t3lib_div::trimExplode(",",$conf["dontRemapTablesOnCopy"],1);
-
-                                               $dbAnalysis = t3lib_div::makeInstance("t3lib_loadDBGroup");
-                                               $dbAnalysis->registerNonTableValues = ($conf['type']=='select' && $conf['allowNonIdValues']) ? 1 : 0;
-                                               $dbAnalysis->start($value,$allowedTables, $conf["MM"], $theUidToUpdate);
-
-                                               reset($dbAnalysis->itemArray);
-                                               while(list($k,$v) = each($dbAnalysis->itemArray))       {
-                                                       $mapID = $this->copyMappingArray_merged[$v["table"]][$v["id"]];
-                                                       if ($mapID && !in_array($v["table"],$dontRemapTables))  {
-                                                               $dbAnalysis->itemArray[$k]["id"]=$mapID;
-                                                               $set=1;
-                                                       }
-                                               }
-                                               if ($set)       {
-                                                       if ($conf["MM"])        {
-                                                               $dbAnalysis->writeMM($conf["MM"],$theUidToUpdate,$prependName);
-                                                               $valueArray = array();
-                                                       } else {
-                                                               $vArray = $dbAnalysis->getValueArray($prependName);
-                                                               if ($conf['type']=='select')    {
-                                                                       $vArray = $dbAnalysis->convertPosNeg($vArray,$conf['foreign_table'],$conf['neg_foreign_table']);
+
+                                       foreach($fields as $fieldName => $value)        {
+                                               $conf = $TCA[$table]['columns'][$fieldName]['config'];
+
+                                               switch($conf['type'])   {
+                                                       case 'group':
+                                                       case 'select':
+                                                               $vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate);
+                                                               if (is_array($vArray))  {
+                                                                       $newData[$fieldName] = implode(',',$vArray);
                                                                }
-                                                               $newData[$fieldName] = implode(",",$vArray);
-                                                       }
+                                                       break;
+                                                       case 'flex':
+                                                               if ($value=='FlexForm_reference')       {
+                                                                       $origRecordRow = $this->recordInfo($table,$theUidToUpdate,'*'); // This will fetch the new row for the element
+
+                                                                       if (is_array($origRecordRow))   {
+
+                                                                                       // Get current data structure and value array:
+                                                                               $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $origRecordRow, $table);
+                                                                               $currentValueArray = t3lib_div::xml2array($origRecordRow[$fieldName]);
+#debug($dataStructArray);
+#debug($currentValueArray);
+#debug($origRecordRow);
+#debug($currentValueArray['data']);
+                                                                                       // Do recursive processing of the XML data:
+                                                                               $currentValueArray['data'] = $this->checkValue_flex_procInData(
+                                                                                                       $currentValueArray['data'],
+                                                                                                       array(),        // Not used.
+                                                                                                       array(),        // Not used.
+                                                                                                       $dataStructArray,
+                                                                                                       array($table,$theUidToUpdate,$fieldName),       // Parameters.
+                                                                                                       'remapListedDBRecords_flexFormCallBack'
+                                                                                               );
+#debug($currentValueArray['data']);
+                                                                                       // The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
+                                                                               if (is_array($currentValueArray['data']))       {
+                                                                                       $newData[$fieldName] =
+                                                                                               '<?xml version="1.0" encoding="'.$GLOBALS['LANG']->charSet.'" standalone="yes" ?>'.chr(10).
+                                                                                               $this->checkValue_flexArray2Xml($currentValueArray);
+                                                                               }
+                                                                       }
+                                                               }
+                                                       break;
+                                                       default:
+                                                               debug('Field type should not appear here: '. $conf['type']);
+                                                       break;
                                                }
                                        }
+
                                        if (count($newData))    {       // If any fields were changed, those fields are updated!
                                                $this->updateDB($table,$theUidToUpdate,$newData);
+#debug($this->recordInfo($table,$theUidToUpdate,'*'),'Stored result:');
        //                                      debug($newData);
                                        }
                                }
@@ -2966,8 +3212,81 @@ class t3lib_TCEmain      {
        }
 
        /**
+        * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
+        *
+        * @param       array           Set of parameters in numeric array: table, uid, field
+        * @param       array           TCA config for field (from Data Structure of course)
+        * @param       string          Field value (from FlexForm XML)
+        * @param       string          Not used
+        * @param       string          Not used
+        * @return      array           Array where the "value" key carries the value.
+        * @see checkValue_flex_procInData_travDS(), remapListedDBRecords()
+        */
+       function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2) {
+
+                       // Extract parameters:
+               list($table,$uid,$field)        = $pParams;
+
+                       // If references are set for this field, set flag so they can be corrected later:
+               if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
+                       $vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid);
+                       if (is_array($vArray))  {
+                               $dataValue = implode(',',$vArray);
+                       }
+               }
+
+                       // Return
+               return array('value' => $dataValue);
+       }
+
+       /**
+        * Performs remapping of old UID values to NEW uid values for a DB reference field.
+        *
+        * @param       array           TCA field config
+        * @param       string          Field value
+        * @param       integer         UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
+        * @return      array           Returns array of items ready to implode for field content.
+        * @see remapListedDBRecords()
+        */
+       function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)   {
+
+                       // Initialize variables
+               $set = FALSE;   // Will be set true if an upgrade should be done...
+               $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];             // Allowed tables for references.
+               $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : '';    // Table name to prepend the UID
+               $dontRemapTables = t3lib_div::trimExplode(',',$conf['dontRemapTablesOnCopy'],1);        // Which tables that should possibly not be remapped
+
+                       // Convert value to list of references:
+               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+               $dbAnalysis->registerNonTableValues = ($conf['type']=='select' && $conf['allowNonIdValues']) ? 1 : 0;
+               $dbAnalysis->start($value, $allowedTables, $conf['MM'], $MM_localUid);
+
+                       // Traverse those references and map IDs:
+               foreach($dbAnalysis->itemArray as $k => $v)     {
+                       $mapID = $this->copyMappingArray_merged[$v['table']][$v['id']];
+                       if ($mapID && !in_array($v['table'],$dontRemapTables))  {
+                               $dbAnalysis->itemArray[$k]['id'] = $mapID;
+                               $set = TRUE;
+                       }
+               }
+
+                       // If a change has been done, set the new value(s)
+               if ($set)       {
+                       if ($conf['MM'])        {
+                               $dbAnalysis->writeMM($conf['MM'], $theUidToUpdate, $prependName);
+                       } else {
+                               $vArray = $dbAnalysis->getValueArray($prependName);
+                               if ($conf['type']=='select')    {
+                                       $vArray = $dbAnalysis->convertPosNeg($vArray, $conf['foreign_table'], $conf['neg_foreign_table']);
+                               }
+                               return $vArray;
+                       }
+               }
+       }
+
+       /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $field: ...
         * @param       [type]          $filelist: ...
@@ -2977,17 +3296,17 @@ class t3lib_TCEmain     {
        function extFileFunctions($table,$field,$filelist,$func)        {
                global $TCA;
                t3lib_div::loadTCA($table);
-               $uploadFolder = $TCA[$table]["columns"][$field]["config"]["uploadfolder"];
+               $uploadFolder = $TCA[$table]['columns'][$field]['config']['uploadfolder'];
                if ($uploadFolder && trim($filelist))   {
                        $uploadPath = $this->destPathFromUploadFolder($uploadFolder);
-                       $fileArray = explode(",",$filelist);
+                       $fileArray = explode(',',$filelist);
                        while (list(,$theFile)=each($fileArray))        {
                                $theFile=trim($theFile);
                                if ($theFile)   {
                                        switch($func)   {
-                                               case "deleteAll":
-                                                       if (@is_file($uploadPath."/".$theFile)) {
-                                                               unlink ($uploadPath."/".$theFile);
+                                               case 'deleteAll':
+                                                       if (@is_file($uploadPath.'/'.$theFile)) {
+                                                               unlink ($uploadPath.'/'.$theFile);
                                                        } else {
                                                                $this->log($table,0,3,0,100,"Delete: Referenced file that was supposed to be deleted together with it's record didn't exist");
                                                        }
@@ -3000,7 +3319,7 @@ class t3lib_TCEmain       {
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @param       [type]          $noRecordCheck: ...
@@ -3012,63 +3331,65 @@ class t3lib_TCEmain     {
                global $TCA;
                $uid = intval($uid);
                if ($TCA[$table] && $uid)       {
-                       $deleteRow = $TCA[$table]["ctrl"]["delete"];
-                       if ($noRecordCheck || $this->doesRecordExist($table,$uid,"delete"))     {
+                       $deleteRow = $TCA[$table]['ctrl']['delete'];
+                       if ($noRecordCheck || $this->doesRecordExist($table,$uid,'delete'))     {
                                if ($deleteRow) {
-                                       $sortOpt = $TCA[$table]["ctrl"]["sortby"];
-                                       if ($sortOpt)   {               // If the table is sorted, then the sorting number is set very high
-                                               $sortOpt = ", ".$sortOpt." = 1000000000";
-                                       } else {
-                                               $sortOpt = "";
+                                       $updateFields = array(
+                                               $deleteRow => 1
+                                       );
+
+                                               // If the table is sorted, then the sorting number is set very high
+                                       if ($TCA[$table]['ctrl']['sortby'])     {
+                                               $updateFields[$TCA[$table]['ctrl']['sortby']] = 1000000000;
                                        }
-                                       $query="update $table set $deleteRow = 1".$sortOpt." where uid = $uid";
+                                       
+                                       $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
                                } else {
-                                       $query="delete from $table where uid = $uid";
-                                       $fileFieldArr = $this->extFileFields($table);           // Fetches all fields that holds references to files
+
+                                               // Fetches all fields that holds references to files
+                                       $fileFieldArr = $this->extFileFields($table);
                                        if (count($fileFieldArr))       {
-                                               $preQuery = "SELECT ".implode(",",$fileFieldArr)." FROM $table WHERE uid = $uid";
-                                               $mres = mysql(TYPO3_db,$preQuery);
-                                               if ($row=mysql_fetch_assoc($mres))      {
+                                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',$fileFieldArr), $table, 'uid='.intval($uid));
+                                               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))        {
                                                        $fArray = $fileFieldArr;
-                                                       reset($fArray);
-                                                       while (list(,$theField)=each($fArray))  {       // MISSING: Support for MM file relations
-                                                               $this->extFileFunctions($table,$theField,$row[$theField],"deleteAll");          // This deletes files that belonged to this record.
+                                                       
+                                                       foreach($fArray as $theField)   {       // MISSING: Support for MM file relations!
+                                                               $this->extFileFunctions($table,$theField,$row[$theField],'deleteAll');          // This deletes files that belonged to this record.
                                                        }
                                                } else {
-                                                       $this->log($table,$uid,3,0,100,"Delete: Zero rows in result when trying to read filenames from record which should be deleted");
+                                                       $this->log($table,$uid,3,0,100,'Delete: Zero rows in result when trying to read filenames from record which should be deleted');
                                                }
                                        }
+
+                                       $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($uid));
                                }
-                               if ($uid)       {               // ekstra check
-                                       $this->clear_cache($table,$uid);
-                                       @mysql(TYPO3_db,$query);
-                                       if ($this->debug)       {echo $query."<BR>".mysql_error();}
-                                       if (!mysql_error())     {
-                                               $this->log($table,$uid,3,0,0,"");
-                                       } else {
-                                               $this->log($table,$uid,3,0,100,mysql_error());
-                                       }
+
+                               if (!$GLOBALS['TYPO3_DB']->sql_error()) {
+                                       $this->log($table,$uid,3,0,0,'');
+                               } else {
+                                       $this->log($table,$uid,3,0,100,$GLOBALS['TYPO3_DB']->sql_error());
                                }
+
                                $this->clear_cache($table,$uid);        // clear cache
                        } else {
-                               $this->log($table,$uid,3,0,1,"Attempt to delete record without delete-permissions");
+                               $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions');
                        }
                }               
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $uid: ...
         * @return      [type]          ...
         */
        function deletePages($uid)      {
-               if ($this->doesRecordExist("pages",$uid,"delete"))      {       // If we may at all delete this page
+               if ($this->doesRecordExist('pages',$uid,'delete'))      {       // If we may at all delete this page
                        if ($this->deleteTree)  {
-                               $brExist = $this->doesBranchExist("",$uid,$this->pMap["delete"],1);     // returns the branch
+                               $brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1);     // returns the branch
                                if ($brExist != -1)     {       // Checks if we had permissions
                                        if ($this->noRecordsFromUnallowedTables($brExist.$uid)) {
-                                               $uidArray = explode(",",$brExist);
+                                               $uidArray = explode(',',$brExist);
                                                while (list(,$listUid)=each($uidArray)) {
                                                        if (trim($listUid))     {
                                                                $this->deleteSpecificPage($listUid);
@@ -3076,31 +3397,31 @@ class t3lib_TCEmain     {
                                                }
                                                $this->deleteSpecificPage($uid);
                                        } else {
-                                               $this->log("pages",$uid,3,0,1,"Attempt to delete records from disallowed tables");
+                                               $this->log('pages',$uid,3,0,1,'Attempt to delete records from disallowed tables');
                                        }
                                } else {
-                                       $this->log("pages",$uid,3,0,1,"Attempt to delete pages in branch without permissions");
+                                       $this->log('pages',$uid,3,0,1,'Attempt to delete pages in branch without permissions');
                                }                                               
                        } else {
-                               $brExist = $this->doesBranchExist("",$uid,$this->pMap["delete"],1);     // returns the branch
-                               if ($brExist == "")     {       // Checks if branch exists
+                               $brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1);     // returns the branch
+                               if ($brExist == '')     {       // Checks if branch exists
                                        if ($this->noRecordsFromUnallowedTables($uid))  {
                                                $this->deleteSpecificPage($uid);
                                        } else {
-                                               $this->log("pages",$uid,3,0,1,"Attempt to delete records from disallowed tables");
+                                               $this->log('pages',$uid,3,0,1,'Attempt to delete records from disallowed tables');
                                        }
                                } else {
-                                       $this->log("pages",$uid,3,0,1,"Attempt to delete page which has subpages");
+                                       $this->log('pages',$uid,3,0,1,'Attempt to delete page which has subpages');
                                }
                        }
                } else {
-                       $this->log("pages",$uid,3,0,1,"Attempt to delete page without permissions");
+                       $this->log('pages',$uid,3,0,1,'Attempt to delete page without permissions');
                }
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $uid: ...
         * @return      [type]          ...
         */
@@ -3111,21 +3432,20 @@ class t3lib_TCEmain     {
                $uid = intval($uid);
                if ($uid)       {
                        while (list($table)=each($TCA)) {
-                               if ($table!="pages")    {
-                                       $query = "select uid from $table where pid = $uid ".$this->deleteClause($table);
-                                       $mres = mysql(TYPO3_db,$query);
-                                       while ($row = mysql_fetch_assoc($mres)) {
+                               if ($table!='pages')    {
+                                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table));
+                                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))     {
                                                $this->deleteRecord($table,$row['uid'], 1);
                                        }
                                }
                        }
-                       $this->deleteRecord("pages",$uid, 1);
+                       $this->deleteRecord('pages',$uid, 1);
                }
        }
 
        /**
         * [Describe function...]
-        * 
+        *
         * @param       [type]          $inList: ...
         * @return      [type]          ...
         */
@@ -3135,9 +3455,9 @@ class t3lib_TCEmain       {
                reset ($TCA);
                $inList = trim($this->rmComma(trim($inList)));
                if ($inList && !$this->admin)   {
-                       while (list($table)=each($TCA)) {
-                               $mres = mysql(TYPO3_db,"select count(*) from $table where pid in ($inList)");
-                               $count = mysql_fetch_row($mres);
+                       while (list($table) = each($TCA))       {
+                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, 'pid IN ('.$inList.')');
+                               $count = $GLOBALS['TYPO3_DB']->sql_fetch_row($mres);
                                if ($count[0] && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table)))       {
                                        return false;
                                }
@@ -3179,13 +3499,13 @@ class t3lib_TCEmain     {
 
        /**
         * Returning sorting number
-        * 
-        * $table is the tablename, 
-        * $uid is set, if the record exists already, 
+        *
+        * $table is the tablename,
+        * $uid is set, if the record exists already,
         * $pid is the pointer to the position, neg=before other record, pos=on-top of page. $pid must be an integer
-        * 
+        *
         * Returns false if the sortby field does not exist.
-        * 
+        *
         * @param       [type]          $table: ...
         * @param       [type]          $uid: ...
         * @param       [type]          $pid: ...
@@ -3193,13 +3513,12 @@ class t3lib_TCEmain     {
         */
        function getSortNumber($table,$uid,$pid)        {
                global $TCA;
-               if ($TCA[$table] && $TCA[$table]["ctrl"]["sortby"])     {
-                       $sortRow = $TCA[$table]["ctrl"]["sortby"];
+               if ($TCA[$table] && $TCA[$table]['ctrl']['sortby'])     {
+                       $sortRow = $TCA[$table]['ctrl']['sortby'];
                        if ($pid>=0)    {       // Sorting number is in the top
-                               $res=mysql(TYPO3_db,"SELECT $sortRow,pid,uid FROM $table WHERE pid ='$pid' ".$this->deleteClause($table)." ORDER BY $sortRow ASC LIMIT 1");             // Fetches the first record under this pid
-                               if ($row=mysql_fetch_assoc($res))       {       // There was a page
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'pid='.intval($pid).$this->deleteClause($table), '', $sortRow.' ASC', '1');          // Fetches the first record under this pid
+                               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {       // There was a page
                                        if ($row['uid']==$uid)  {       // The top record was the record it self, so we return its current sortnumber
-                                               if ($this->debug)       {echo $table.": The top page was it self, pid=".$pid."..<BR>";}
                                                return $row[$sortRow];
                                        }
                                        if ($row[$sortRow] < 1) {       // If the pages sortingnumber < 1 we must resort the records under this pid
@@ -3209,20 +3528,25 @@ class t3lib_TCEmain     {
                                                return floor($row[$sortRow]/2);
                                        }
                                } else {        // No pages, so we choose the default value as sorting-number
-                                       if ($this->debug)       {echo $table.": No previous rec on this parent page, pid=".$pid."..<BR>";}
                                        return $this->sortIntervals;
                                }
                        } else {        // Sorting number is inside the list
-                               $res=mysql(TYPO3_db,"select $sortRow,pid,uid from $table where uid ='".abs($pid)."' ".$this->deleteClause($table));             // Fetches the record which is supposed to be the prev record
-                               if ($row=mysql_fetch_assoc($res))       {       // There was a record
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'uid='.abs($pid).$this->deleteClause($table));               // Fetches the record which is supposed to be the prev record
+                               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {       // There was a record
                                        if ($row['uid']==$uid)  {       // If the record happends to be it self
-                                               if ($this->debug)       {echo $table.": The previous page was it self, uid=".$uid."..<BR>";}
                                                $sortNumber = $row[$sortRow];
                                        } else {
-                                               $subres=mysql(TYPO3_db,"SELECT $sortRow,pid,uid FROM $table WHERE pid='".$row['pid']."' AND $sortRow>='".$row[$sortRow]."' ".$this->deleteClause($table)." ORDER BY $sortRow ASC LIMIT 2");             // Fetches the next record in order to calculate the in bewteen sortNumber
-                                               if (mysql_num_rows($subres)==2) {       // There was a record afterwards
-                                                       mysql_data_seek($subres, 1);    // forwards to the second result
-                                                       $subrow=mysql_fetch_assoc($subres);     // There was a record afterwards
+                                               $subres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                                               $sortRow.',pid,uid', 
+                                                                               $table, 
+                                                                               'pid='.intval($row['pid']).' AND '.$sortRow.'>='.intval($row[$sortRow]).$this->deleteClause($table),
+                                                                               '', 
+                                                                               $sortRow.' ASC', 
+                                                                               '2'
+                                                                       );              // Fetches the next record in order to calculate the in between sortNumber
+                                               if ($GLOBALS['TYPO3_DB']->sql_num_rows($subres)==2)     {       // There was a record afterwards
+                                                       $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);                         // Forward to the second result...
+                                                       $subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);       // There was a record afterwards
                                                        $sortNumber = $row[$sortRow]+ floor(($subrow[$sortRow]-$row[$sortRow])/2);      // The sortNumber is found in between these values
                                                        if ($sortNumber<=$row[$sortRow] || $sortNumber>=$subrow[$sortRow])      {       // The sortNumber happend NOT to be between the two surrounding numbers, so we'll have to resort the list
                                                                $sortNumber = $this->resorting($table,$row['pid'],$sortRow,  $row['uid']);      // By this special param, resorting reserves and returns the sortnumber after the uid
@@ -3231,10 +3555,10 @@ class t3lib_TCEmain     {
                                                        $sortNumber = $row[$sortRow]+$this->sortIntervals;
                                                }
                                        }
-                                       return Array("pid"=>$row['pid'], "sortNumber"=>$s