[TASK] Remove t3lib_superadmin
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tcemain.php
index 73f340e..2367eef 100644 (file)
 <?php
 /***************************************************************
 <?php
 /***************************************************************
-*  Copyright notice
-*
-*  (c) 1999-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
-*  All rights reserved
-*
-*  This script is part of the TYPO3 project. The TYPO3 project is
-*  free software; you can redistribute it and/or modify
-*  it under the terms of the GNU General Public License as published by
-*  the Free Software Foundation; either version 2 of the License, or
-*  (at your option) any later version.
-*
-*  The GNU General Public License can be found at
-*  http://www.gnu.org/copyleft/gpl.html.
-*  A copy is found in the textfile GPL.txt and important notices to the license
-*  from the author is found in LICENSE.txt distributed with these scripts.
-*
-*
-*  This script is distributed in the hope that it will be useful,
-*  but WITHOUT ANY WARRANTY; without even the implied warranty of
-*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-*  GNU General Public License for more details.
-*
-*  This copyright notice MUST APPEAR in all copies of the script!
-***************************************************************/
-/**
- * Contains the TYPO3 Core Engine
- *
- * $Id$
- * Revised for TYPO3 3.9 October 2005 by Kasper Skaarhoj
- *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
- */
-/**
- * [CLASS/FUNCTION INDEX of SCRIPT]
- *
- *
- *
- *  242: class t3lib_TCEmain
- *  367:     function start($data,$cmd,$altUserObject='')
- *  406:     function setMirror($mirror)
- *  431:     function setDefaultsFromUserTS($userTS)
- *  454:     function process_uploads($postFiles)
- *  492:     function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
- *
- *              SECTION: PROCESSING DATA
- *  528:     function process_datamap()
- *  886:     function placeholderShadowing($table,$id)
- *  929:     function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
- *
- *              SECTION: Evaluation of input values
- * 1152:     function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
- * 1212:     function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
- * 1261:     function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
- * 1299:     function checkValue_check($res,$value,$tcaFieldConf,$PP)
- * 1322:     function checkValue_radio($res,$value,$tcaFieldConf,$PP)
- * 1348:     function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
- * 1458:     function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
- * 1632:     function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
- * 1709:     function checkValue_flexArray2Xml($array, $addPrologue=FALSE)
- * 1721:     function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
- * 1743:     function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)
- * 1783:     function checkValue_inline($res,$value,$tcaFieldConf,$PP,$field)
- * 1825:     function checkValue_checkMax($tcaFieldConf, $valueArray)
- *
- *              SECTION: Helper functions for evaluation functions.
- * 1877:     function getUnique($table,$field,$value,$id,$newPid=0)
- * 1915:     function checkValue_input_Eval($value,$evalArray,$is_in)
- * 2012:     function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type,$currentTable)
- * 2058:     function checkValue_group_select_explodeSelectGroupValue($value)
- * 2082:     function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
- * 2121:     function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)
- *
- *              SECTION: PROCESSING COMMANDS
- * 2267:     function process_cmdmap()
- *
- *              SECTION: Cmd: Copying
- * 2407:     function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
- * 2529:     function copyPages($uid,$destPid)
- * 2583:     function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
- * 2617:     function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
- * 2681:     function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
- * 2705:     function insertNewCopyVersion($table,$fieldArray,$realPid)
- * 2757:     function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$realDestPid)
- * 2836:     function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
- * 2864:     function copyRecord_procFilesRefs($conf, $uid, $value)
- *
- *              SECTION: Cmd: Moving, Localizing
- * 2933:     function moveRecord($table,$uid,$destPid)
- * 3128:     function moveRecord_procFields($table,$uid,$destPid)
- * 3148:     function moveRecord_procBasedOnFieldType($table,$uid,$destPid,$field,$value,$conf)
- * 3182:     function localize($table,$uid,$language)
- *
- *              SECTION: Cmd: Deleting
- * 3296:     function deleteAction($table, $id)
- * 3343:     function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE)
- * 3360:     function deleteVersionsForRecord($table, $uid, $forceHardDelete)
- * 3382:     function undeleteRecord($table,$uid)
- * 3399:     function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)
- * 3512:     function deleteRecord_flexFormCallBack($dsArr, $dataValue, $PA, $structurePath, &$pObj)
- * 3539:     function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE)
- * 3567:     function deleteSpecificPage($uid,$forceHardDelete=FALSE)
- * 3592:     function canDeletePage($uid)
- * 3619:     function cannotDeleteRecord($table,$id)
- * 3638:     function deleteRecord_procFields($table, $uid, $undeleteRecord = false)
- * 3661:     function deleteRecord_procBasedOnFieldType($table, $uid, $field, $value, $conf, $undeleteRecord = false)
+ *  Copyright notice
  *
  *
- *              SECTION: Cmd: Versioning
- * 3722:     function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1)
- * 3798:     function versionizePages($uid,$label,$versionizeTree)
- * 3861:     function version_swap($table,$id,$swapWith,$swapIntoWS=0)
- * 4032:     function version_clearWSID($table,$id)
- * 4066:     function version_setStage($table,$id,$stageId,$comment='')
+ *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
+ *  All rights reserved
  *
  *
- *              SECTION: Cmd: Helper functions
- * 4111:     function remapListedDBRecords()
- * 4192:     function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
- * 4219:     function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid, $table)
- * 4265:     function remapListedDBRecords_procInline($conf, $value, $uid, $table)
+ *  This script is part of the TYPO3 project. The TYPO3 project is
+ *  free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
  *
  *
- *              SECTION: Access control / Checking functions
- * 4308:     function checkModifyAccessList($table)
- * 4320:     function isRecordInWebMount($table,$id)
- * 4334:     function isInWebMount($pid)
- * 4348:     function checkRecordUpdateAccess($table,$id)
- * 4372:     function checkRecordInsertAccess($insertTable,$pid,$action=1)
- * 4406:     function isTableAllowedForThisPage($page_uid, $checkTable)
- * 4439:     function doesRecordExist($table,$id,$perms)
- * 4504:     function doesRecordExist_pageLookUp($id, $perms)
- * 4530:     function doesBranchExist($inList,$pid,$perms,$recurse)
- * 4564:     function tableReadOnly($table)
- * 4576:     function tableAdminOnly($table)
- * 4590:     function destNotInsideSelf($dest,$id)
- * 4622:     function getExcludeListArray()
- * 4645:     function doesPageHaveUnallowedTables($page_uid,$doktype)
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *  A copy is found in the textfile GPL.txt and important notices to the license
+ *  from the author is found in LICENSE.txt distributed with these scripts.
  *
  *
- *              SECTION: Information lookup
- * 4694:     function pageInfo($id,$field)
- * 4714:     function recordInfo($table,$id,$fieldList)
- * 4735:     function getRecordProperties($table,$id,$noWSOL=FALSE)
- * 4751:     function getRecordPropertiesFromRow($table,$row)
  *
  *
- *              SECTION: Storing data to Database Layer
- * 4794:     function updateDB($table,$id,$fieldArray)
- * 4846:     function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE)
- * 4919:     function checkStoredRecord($table,$id,$fieldArray,$action)
- * 4956:     function setHistory($table,$id,$logId)
- * 4989:     function clearHistory($maxAgeSeconds=604800,$table)
- * 5003:     function updateRefIndex($table,$id)
+ *  This script is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
  *
  *
- *              SECTION: Misc functions
- * 5035:     function getSortNumber($table,$uid,$pid)
- * 5108:     function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
- * 5139:     function setTSconfigPermissions($fieldArray,$TSConfig_p)
- * 5156:     function newFieldArray($table)
- * 5188:     function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray)
- * 5212:     function overrideFieldArray($table,$data)
- * 5228:     function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
- * 5274:     function assemblePermissions($string)
- * 5291:     function rmComma($input)
- * 5301:     function convNumEntityToByteValue($input)
- * 5323:     function destPathFromUploadFolder($folder)
- * 5333:     function deleteClause($table)
- * 5349:     function getTCEMAIN_TSconfig($tscPID)
- * 5364:     function getTableEntries($table,$TSconfig)
- * 5377:     function getPID($table,$uid)
- * 5390:     function dbAnalysisStoreExec()
- * 5406:     function removeRegisteredFiles()
- * 5418:     function removeCacheFiles()
- * 5432:     function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
- * 5453:     function compileAdminTables()
- * 5470:     function fixUniqueInPid($table,$uid)
- * 5506:     function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
- * 5531:     function extFileFields($table)
- * 5552:     function getUniqueFields($table)
- * 5577:     function isReferenceField($conf)
- * 5588:     function getInlineFieldType($conf)
- * 5611:     function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
- * 5640:     function prependLabel($table)
- * 5657:     function resolvePid($table,$pid)
- * 5687:     function clearPrefixFromValue($table,$value)
- * 5702:     function extFileFunctions($table,$field,$filelist,$func)
- * 5732:     function noRecordsFromUnallowedTables($inList)
- * 5758:     function notifyStageChange($stat,$stageId,$table,$id,$comment)
- * 5853:     function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE)
- *
- *              SECTION: Clearing cache
- * 5899:     function clear_cache($table,$uid)
- * 6009:     function clear_cacheCmd($cacheCmd)
- *
- *              SECTION: Logging
- * 6113:     function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='')
- * 6130:     function newlog($message, $error=0)
- * 6140:     function printLogErrorMessages($redirect)
- *
- *              SECTION: Internal (do not use outside Core!)
- * 6202:     function internal_clearPageCache()
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
+/**
+ * Contains the TYPO3 Core Engine
  *
  *
- * TOTAL FUNCTIONS: 126
- * (This index is automatically created/updated by the extension "extdeveval")
+ * Revised for TYPO3 3.9 October 2005 by Kasper Skårhøj
  *
  *
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  */
 
 
  */
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
 /**
  * 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.
 /**
  * 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.
  *
  * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
  *
  *
  * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage t3lib
  */
  * @package TYPO3
  * @subpackage t3lib
  */
-class t3lib_TCEmain    {
-
-
-               // *********************
-               // Public variables you can configure before using the class:
-               // *********************
+class t3lib_TCEmain {
 
 
-       var $storeLogMessages = TRUE;                   // Boolean: If true, 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 = TRUE;                              // Boolean: If true, actions are logged to sys_log.
-       var $reverseOrder = FALSE;                              // Boolean: If true, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
-       var $checkSimilar = TRUE;                               // Boolean: If true, 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 $stripslashes_values = TRUE;                // Boolean: If true, 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 $checkStoredRecords = TRUE;                 // Boolean: 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 = TRUE;   // Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
-       var $deleteTree = FALSE;                                // 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 deleted ONLY if it has no branch
-       var $neverHideAtCopy = FALSE;                   // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
-       var $dontProcessTransformations = FALSE;        // Boolean: If set, then transformations are NOT performed on the input.
-       var $clear_flexFormData_vDEFbase = FALSE;       // Boolean: If set, .vDEFbase values are unset in flexforms.
-       var $updateModeL10NdiffData = TRUE;             // Boolean/Mixed: TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value. FALSE: Will not update anything. "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
-       var $updateModeL10NdiffDataClear = FALSE;       // Boolean: If true, the translation diff. fields will in fact be reset so that they indicate that all needs to change again! It's meant as the opposite of declaring the record translated.
-       var $bypassWorkspaceRestrictions = FALSE;       // Boolean: If true, workspace restrictions are bypassed on edit an create actions (process_datamap()). YOU MUST KNOW what you do if you use this feature!
-       var $bypassFileHandling = FALSE;                        // Boolean: If true, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away. YOU MUST KNOW what you are doing with this feature!
-       var $bypassAccessCheckForRecords = FALSE;       // Boolean: If true, access check, check for deleted etc. for records is bypassed. YOU MUST KNOW what you are doing if you use this feature!
 
 
-       var $copyWhichTables = '*';                             // String. Comma-list. 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 $generalComment = '';                               // General comment, eg. for staging in workspaces.
+       // *********************
+       // Public variables you can configure before using the class:
+       // *********************
 
 
-       var $copyTree = 0;                                              // Integer. 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 $storeLogMessages = TRUE; // Boolean: If TRUE, 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 = TRUE; // Boolean: If TRUE, actions are logged to sys_log.
+       var $reverseOrder = FALSE; // Boolean: If TRUE, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
+       var $checkSimilar = TRUE; // Boolean: If TRUE, 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 $stripslashes_values = TRUE; // Boolean: If TRUE, 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 $checkStoredRecords = TRUE; // Boolean: 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 = TRUE; // Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
+       var $deleteTree = FALSE; // 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 deleted ONLY if it has no branch
+       var $neverHideAtCopy = FALSE; // Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
+       var $dontProcessTransformations = FALSE; // Boolean: If set, then transformations are NOT performed on the input.
+       var $clear_flexFormData_vDEFbase = FALSE; // Boolean: If set, .vDEFbase values are unset in flexforms.
+       var $updateModeL10NdiffData = TRUE; // Boolean/Mixed: TRUE: (traditional) Updates when record is saved. For flexforms, updates if change is made to the localized value. FALSE: Will not update anything. "FORCE_FFUPD" (string): Like TRUE, but will force update to the FlexForm Field
+       var $updateModeL10NdiffDataClear = FALSE; // Boolean: If TRUE, the translation diff. fields will in fact be reset so that they indicate that all needs to change again! It's meant as the opposite of declaring the record translated.
+       var $bypassWorkspaceRestrictions = FALSE; // Boolean: If TRUE, workspace restrictions are bypassed on edit an create actions (process_datamap()). YOU MUST KNOW what you do if you use this feature!
+       var $bypassFileHandling = FALSE; // Boolean: If TRUE, file handling of attached files (addition, deletion etc) is bypassed - the value is saved straight away. YOU MUST KNOW what you are doing with this feature!
+       var $bypassAccessCheckForRecords = FALSE; // Boolean: If TRUE, access check, check for deleted etc. for records is bypassed. YOU MUST KNOW what you are doing if you use this feature!
 
 
-       var $defaultValues = array();                   // Array [table][fields]=value: New records are created with default values and you can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
-       var $overrideValues = array();                  // Array [table][fields]=value: 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!
-       var $alternativeFileName = array();             // Array [filename]=alternative_filename: 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 $alternativeFilePath = array();             // Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
-       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 $suggestedInsertUids=array();               // Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be true, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)
+       var $copyWhichTables = '*'; // String. Comma-list. 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 $callBackObj;                                               // Object. Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
+       var $copyTree = 0; // Integer. 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 $defaultValues = array(); // Array [table][fields]=value: New records are created with default values and you can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
+       var $overrideValues = array(); // Array [table][fields]=value: 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!
+       var $alternativeFileName = array(); // Array [filename]=alternative_filename: 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 $alternativeFilePath = array(); // Array [filename]=alternative_filepath: Same as alternativeFileName but with relative path to the file
+       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 $suggestedInsertUids = array(); // Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be TRUE, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)
 
 
+       var $callBackObj; // Object. Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.
 
 
 
 
-               // *********************
-               // Internal variables (mapping arrays) which can be used (read-only) from outside
-               // *********************
-       var $autoVersionIdMap = Array();                        // Contains mapping of auto-versionized records.
-       var $substNEWwithIDs = Array();                         // When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
-       var $substNEWwithIDs_table = Array();           // Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
-       var $newRelatedIDs = Array();                           // Holds the tables and there the ids of newly created child records from IRRE
-       var $copyMappingArray_merged = Array();         // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
-       var $copiedFileMap = Array();                           // A map between input file name and final destination for files being attached to records.
-       var $RTEmagic_copyIndex = Array();                      // Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
-       var $errorLog = Array();                                        // Errors are collected in this variable.
-       var $accumulateForNotifEmail = Array();         // For accumulating information about workspace stages raised on elements so a single mail is sent as notification.
+       // *********************
+       // Internal variables (mapping arrays) which can be used (read-only) from outside
+       // *********************
 
 
+       var $autoVersionIdMap = array(); // Contains mapping of auto-versionized records.
+       var $substNEWwithIDs = array(); // When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
+       var $substNEWwithIDs_table = array(); // Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
+       var $newRelatedIDs = array(); // Holds the tables and there the ids of newly created child records from IRRE
+       var $copyMappingArray_merged = array(); // This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
+       var $copiedFileMap = array(); // A map between input file name and final destination for files being attached to records.
+       var $RTEmagic_copyIndex = array(); // Contains [table][id][field] of fiels where RTEmagic images was copied. Holds old filename as key and new filename as value.
+       var $errorLog = array(); // Errors are collected in this variable.
 
 
 
 
-               // *********************
-               // Internal Variables, do not touch.
-               // *********************
+       // *********************
+       // Internal Variables, do not touch.
+       // *********************
 
 
-               // Variables set in init() function:
+       // Variables set in init() function:
        /**
         * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
         *
         * @var t3lib_beUserAuth
         */
        var $BE_USER;
        /**
         * The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
         *
         * @var t3lib_beUserAuth
         */
        var $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
-       var $admin;                     // will be set if user is admin
+       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
+       var $admin; // will be set if user is admin
 
 
-       var $defaultPermissions = array(                // Can be overridden from $TYPO3_CONF_VARS
+       var $defaultPermissions = array( // Can be overridden from $GLOBALS['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 $exclude_array;                     // The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
-       var $datamap = Array();         // Set with incoming data array
-       var $cmdmap = Array();          // Set with incoming cmd array
+       var $exclude_array; // The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
+       var $datamap = array(); // Set with incoming data array
+       var $cmdmap = array(); // Set with incoming cmd array
 
                // Internal static:
 
                // Internal static:
-       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
+       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
        );
        );
-       var $sortIntervals = 256;                                       // Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
+       var $sortIntervals = 256; // Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1
 
                // Internal caching arrays
 
                // Internal caching arrays
-       var $recUpdateAccessCache = Array();            // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
-       var $recInsertAccessCache = Array();            // User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
-       var $isRecordInWebMount_Cache=array();          // Caching array for check of whether records are in a webmount
-       var $isInWebMount_Cache=array();                        // Caching array for page ids in webmounts
-       var $cachedTSconfig = array();                          // Caching for collecting TSconfig for page ids
-       var $pageCache = Array();                                       // Used for caching page records in pageInfo()
-       var $checkWorkspaceCache = Array();                     // Array caching workspace access for BE_USER
+       var $recUpdateAccessCache = array(); // Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
+       var $recInsertAccessCache = array(); // User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
+       var $isRecordInWebMount_Cache = array(); // Caching array for check of whether records are in a webmount
+       var $isInWebMount_Cache = array(); // Caching array for page ids in webmounts
+       var $cachedTSconfig = array(); // Caching for collecting TSconfig for page ids
+       var $pageCache = array(); // Used for caching page records in pageInfo()
+       var $checkWorkspaceCache = array(); // Array caching workspace access for BE_USER
 
                // Other arrays:
 
                // Other arrays:
-       var $dbAnalysisStore=array();                           // For accumulation of MM relations that must be written after new records are created.
-       var $removeFilesStore=array();                          // For accumulation of files which must be deleted after processing of all input content
-       var $uploadedFileArray = array();                       // Uploaded files, set by process_uploads()
-       var $registerDBList=array();                            // Used for tracking references that might need correction after operations
-       var $registerDBPids=array();                            // Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
-       var $copyMappingArray = Array();                        // Used by the copy action to track the ids of new pages so subpages are correctly inserted! THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE! Read from copyMappingArray_merged instead which is accumulating this information.
-       var $remapStack = array();                                      // array used for remapping uids and values at the end of process_datamap
-       var $remapStackRecords = array();                       // array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
-       var $updateRefIndexStack = array();                     // array used for additional calls to $this->updateRefIndex
-       var $callFromImpExp = false;                            // tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
-       var $newIndexMap = array();                                     // Array for new flexform index mapping
-
-               // Various
+       var $dbAnalysisStore = array(); // For accumulation of MM relations that must be written after new records are created.
+       var $removeFilesStore = array(); // For accumulation of files which must be deleted after processing of all input content
+       var $uploadedFileArray = array(); // Uploaded files, set by process_uploads()
+       var $registerDBList = array(); // Used for tracking references that might need correction after operations
+       var $registerDBPids = array(); // Used for tracking references that might need correction in pid field after operations (e.g. IRRE)
+       var $copyMappingArray = array(); // Used by the copy action to track the ids of new pages so subpages are correctly inserted! THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE! Read from copyMappingArray_merged instead which is accumulating this information.
+       var $remapStack = array(); // array used for remapping uids and values at the end of process_datamap
+       var $remapStackRecords = array(); // array used for remapping uids and values at the end of process_datamap (e.g. $remapStackRecords[<table>][<uid>] = <index in $remapStack>)
+       protected $remapStackChildIds = array(); // array used for checking whether new children need to be remapped
+       protected $remapStackActions = array(); // array used for executing addition actions after remapping happened (sett processRemapStack())
+       protected $remapStackRefIndex = array(); // array used for executing post-processing on the reference index
+       var $updateRefIndexStack = array(); // array used for additional calls to $this->updateRefIndex
+       var $callFromImpExp = FALSE; // tells, that this TCEmain was called from tx_impext - this variable is set by tx_impexp
+       var $newIndexMap = array(); // Array for new flexform index mapping
+
+       // Various
        /**
         * basicFileFunctions object
         *
         * @var t3lib_basicFileFunctions
         */
        /**
         * basicFileFunctions object
         *
         * @var t3lib_basicFileFunctions
         */
-       var $fileFunc;                                                          // For "singleTon" file-manipulation object
-       var $checkValue_currentRecord=array();          // Set to "currentRecord" during checking of values.
-       var $autoVersioningUpdate = FALSE;                      // A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
+       var $fileFunc; // For "singleTon" file-manipulation object
+       var $checkValue_currentRecord = array(); // Set to "currentRecord" during checking of values.
+       var $autoVersioningUpdate = FALSE; // A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.
 
 
-       protected $disableDeleteClause = false;         // Disable delete clause
+       protected $disableDeleteClause = FALSE; // Disable delete clause
        protected $checkModifyAccessListHookObjects;
        protected $checkModifyAccessListHookObjects;
+       protected $version_remapMMForVersionSwap_reg;
 
 
-
-
-
-
-
-
-
-
-
+       /**
+        * The outer most instance of t3lib_TCEmain
+        * (t3lib_TCEmain instantiates itself on versioning and localization)
+        * @var t3lib_TCEmain
+        */
+       protected $outerMostInstance = NULL;
 
        /**
         * Initializing.
 
        /**
         * Initializing.
@@ -376,7 +190,7 @@ class t3lib_TCEmain {
         * @param       object          An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
         * @return      void
         */
         * @param       object          An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
         * @return      void
         */
-       function start($data,$cmd,$altUserObject='')    {
+       public function start($data, $cmd, $altUserObject = '') {
 
                        // Initializing BE_USER
                $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
 
                        // Initializing BE_USER
                $this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
@@ -384,19 +198,25 @@ class t3lib_TCEmain       {
                $this->username = $this->BE_USER->user['username'];
                $this->admin = $this->BE_USER->user['admin'];
 
                $this->username = $this->BE_USER->user['username'];
                $this->admin = $this->BE_USER->user['admin'];
 
-               if ($GLOBALS['BE_USER']->uc['recursiveDelete'])    {
+               if ($this->BE_USER->uc['recursiveDelete']) {
                        $this->deleteTree = 1;
                }
 
                        $this->deleteTree = 1;
                }
 
-               if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData===TRUE)     {
+               if ($GLOBALS['TYPO3_CONF_VARS']['BE']['explicitConfirmationOfTranslation'] && $this->updateModeL10NdiffData === TRUE) {
                        $this->updateModeL10NdiffData = FALSE;
                }
 
                        // Initializing default permissions for pages
                $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
                        $this->updateModeL10NdiffData = FALSE;
                }
 
                        // Initializing default permissions for pages
                $defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
-               if (isset($defaultPermissions['user']))         {$this->defaultPermissions['user'] = $defaultPermissions['user'];}
-               if (isset($defaultPermissions['group']))                {$this->defaultPermissions['group'] = $defaultPermissions['group'];}
-               if (isset($defaultPermissions['everybody']))            {$this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];}
+               if (isset($defaultPermissions['user'])) {
+                       $this->defaultPermissions['user'] = $defaultPermissions['user'];
+               }
+               if (isset($defaultPermissions['group'])) {
+                       $this->defaultPermissions['group'] = $defaultPermissions['group'];
+               }
+               if (isset($defaultPermissions['everybody'])) {
+                       $this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];
+               }
 
                        // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
                $this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();
 
                        // generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
                $this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();
@@ -406,7 +226,7 @@ class t3lib_TCEmain {
                        reset($data);
                        $this->datamap = $data;
                }
                        reset($data);
                        $this->datamap = $data;
                }
-               if (is_array($cmd))     {
+               if (is_array($cmd)) {
                        reset($cmd);
                        $this->cmdmap = $cmd;
                }
                        reset($cmd);
                        $this->cmdmap = $cmd;
                }
@@ -419,14 +239,13 @@ class t3lib_TCEmain       {
         * @param       array           This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
         * @return      void
         */
         * @param       array           This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
         * @return      void
         */
-       function setMirror($mirror)     {
-               if (is_array($mirror))  {
+       function setMirror($mirror) {
+               if (is_array($mirror)) {
                        foreach ($mirror as $table => $uid_array) {
                        foreach ($mirror as $table => $uid_array) {
-                               if (isset($this->datamap[$table]))      {
-                                       reset($uid_array);
+                               if (isset($this->datamap[$table])) {
                                        foreach ($uid_array as $id => $uidList) {
                                        foreach ($uid_array as $id => $uidList) {
-                                               if (isset($this->datamap[$table][$id])) {
-                                                       $theIdsInArray = t3lib_div::trimExplode(',',$uidList,1);
+                                               if (isset($this->datamap[$table][$id])) {
+                                                       $theIdsInArray = t3lib_div::trimExplode(',', $uidList, 1);
                                                        foreach ($theIdsInArray as $copyToUid) {
                                                                $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
                                                        }
                                                        foreach ($theIdsInArray as $copyToUid) {
                                                                $this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
                                                        }
@@ -443,14 +262,13 @@ class t3lib_TCEmain       {
         * @param       array           User TSconfig array
         * @return      void
         */
         * @param       array           User TSconfig array
         * @return      void
         */
-       function setDefaultsFromUserTS($userTS) {
-               global $TCA;
-               if (is_array($userTS))  {
-                       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);
+       function setDefaultsFromUserTS($userTS) {
+               if (is_array($userTS)) {
+                       foreach ($userTS as $k => $v) {
+                               $k = substr($k, 0, -1);
+                               if ($k && is_array($v) && isset($GLOBALS['TCA'][$k])) {
+                                       if (is_array($this->defaultValues[$k])) {
+                                               $this->defaultValues[$k] = array_merge($this->defaultValues[$k], $v);
                                        } else {
                                                $this->defaultValues[$k] = $v;
                                        }
                                        } else {
                                                $this->defaultValues[$k] = $v;
                                        }
@@ -466,29 +284,28 @@ class t3lib_TCEmain       {
         * @param       array           $_FILES array
         * @return      void
         */
         * @param       array           $_FILES array
         * @return      void
         */
-       function process_uploads($postFiles)    {
+       function process_uploads($postFiles) {
 
 
-               if (is_array($postFiles))       {
+               if (is_array($postFiles)) {
 
                                // Editing frozen:
 
                                // Editing frozen:
-                       if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze'])    {
-                               $this->newlog('All editing in this workspace has been frozen!',1);
+                       if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
+                               $this->newlog('All editing in this workspace has been frozen!', 1);
                                return FALSE;
                        }
 
                                return FALSE;
                        }
 
-                       reset($postFiles);
-                       $subA = current($postFiles);
-                       if (is_array($subA))    {
-                               if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size']))       {
+                       $subA = reset($postFiles);
+                       if (is_array($subA)) {
+                               if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size'])) {
                                                // Initialize the uploadedFilesArray:
                                                // Initialize the uploadedFilesArray:
-                                       $this->uploadedFileArray=array();
+                                       $this->uploadedFileArray = array();
 
                                                // For each entry:
 
                                                // For each entry:
-                                       foreach($subA as $key => $values)       {
-                                               $this->process_uploads_traverseArray($this->uploadedFileArray,$values,$key);
+                                       foreach ($subA as $key => $values) {
+                                               $this->process_uploads_traverseArray($this->uploadedFileArray, $values, $key);
                                        }
                                } else {
                                        }
                                } else {
-                                       $this->uploadedFileArray=$subA;
+                                       $this->uploadedFileArray = $subA;
                                }
                        }
                }
                                }
                        }
                }
@@ -504,30 +321,17 @@ class t3lib_TCEmain       {
         * @access private
         * @see process_uploads()
         */
         * @access private
         * @see process_uploads()
         */
-       function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet) {
-               if (is_array($inputArr))        {
-                       foreach($inputArr as $key => $value)    {
-                               $this->process_uploads_traverseArray($outputArr[$key],$inputArr[$key],$keyToSet);
+       function process_uploads_traverseArray(&$outputArr, $inputArr, $keyToSet) {
+               if (is_array($inputArr)) {
+                       foreach ($inputArr as $key => $value) {
+                               $this->process_uploads_traverseArray($outputArr[$key], $inputArr[$key], $keyToSet);
                        }
                } else {
                        }
                } else {
-                       $outputArr[$keyToSet]=$inputArr;
+                       $outputArr[$keyToSet] = $inputArr;
                }
        }
 
 
                }
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*********************************************
         *
         * HOOKS
        /*********************************************
         *
         * HOOKS
@@ -551,12 +355,12 @@ class t3lib_TCEmain       {
        function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
                        // Process hook directly:
                if (!isset($this->remapStackRecords[$table][$id])) {
        function hook_processDatamap_afterDatabaseOperations(&$hookObjectsArr, &$status, &$table, &$id, &$fieldArray) {
                        // Process hook directly:
                if (!isset($this->remapStackRecords[$table][$id])) {
-                       foreach($hookObjectsArr as $hookObj)    {
+                       foreach ($hookObjectsArr as $hookObj) {
                                if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
                                        $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
                                }
                        }
                                if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
                                        $hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
                                }
                        }
-                       // If this record is in remapStack (e.g. when using IRRE), values will be updated/remapped later on. So the hook will also be called later:
+                               // If this record is in remapStack (e.g. when using IRRE), values will be updated/remapped later on. So the hook will also be called later:
                } else {
                        $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
                                'status' => $status,
                } else {
                        $this->remapStackRecords[$table][$id]['processDatamap_afterDatabaseOperations'] = array(
                                'status' => $status,
@@ -576,11 +380,11 @@ class t3lib_TCEmain       {
                if (!isset($this->checkModifyAccessListHookObjects)) {
                        $this->checkModifyAccessListHookObjects = array();
 
                if (!isset($this->checkModifyAccessListHookObjects)) {
                        $this->checkModifyAccessListHookObjects = array();
 
-                       if(is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
-                               foreach($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
+                       if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'])) {
+                               foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'] as $classData) {
                                        $hookObject = t3lib_div::getUserObj($classData);
 
                                        $hookObject = t3lib_div::getUserObj($classData);
 
-                                       if(!($hookObject instanceof t3lib_TCEmain_checkModifyAccessListHook)) {
+                                       if (!($hookObject instanceof t3lib_TCEmain_checkModifyAccessListHook)) {
                                                throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
                                        }
 
                                                throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_checkModifyAccessListHook', 1251892472);
                                        }
 
@@ -593,17 +397,6 @@ class t3lib_TCEmain        {
        }
 
 
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
        /*********************************************
         *
         * PROCESSING DATA
        /*********************************************
         *
         * PROCESSING DATA
@@ -616,58 +409,60 @@ class t3lib_TCEmain       {
         *
         * @return      void
         */
         *
         * @return      void
         */
-       function process_datamap() {
-               global $TCA, $TYPO3_CONF_VARS;
+       public function process_datamap() {
                        // Keep versionized(!) relations here locally:
                $registerDBList = array();
 
                        // Keep versionized(!) relations here locally:
                $registerDBList = array();
 
+               $this->registerElementsToBeDeleted();
+               $this->datamap = $this->unsetElementsToBeDeleted($this->datamap);
+
                        // Editing frozen:
                        // Editing frozen:
-               if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze'])    {
-                       $this->newlog('All editing in this workspace has been frozen!',1);
+               if ($this->BE_USER->workspace !== 0 && $this->BE_USER->workspaceRec['freeze']) {
+                       $this->newlog('All editing in this workspace has been frozen!', 1);
                        return FALSE;
                }
 
                        // First prepare user defined objects (if any) for hooks which extend this function:
                $hookObjectsArr = array();
                        return FALSE;
                }
 
                        // First prepare user defined objects (if any) for hooks which extend this function:
                $hookObjectsArr = array();
-               if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
-                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
+               if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
+                       foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
                                $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
                        }
                }
 
                        // Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
                                $hookObjectsArr[] = t3lib_div::getUserObj($classRef);
                        }
                }
 
                        // Organize tables so that the pages-table is 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 = array();
+               if (isset($this->datamap['pages'])) { // Set pages first.
+                       $orderOfTables[] = 'pages';
                }
                $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
 
                        // Process the tables...
                }
                $orderOfTables = array_unique(array_merge($orderOfTables, array_keys($this->datamap)));
 
                        // Process the tables...
-               foreach($orderOfTables as $table)       {
-                               /* Check if
-                                       - table is set in $TCA,
-                                       - table is NOT readOnly
-                                       - the table is set with content in the data-array (if not, there's nothing to process...)
-                                       - permissions for tableaccess OK
-                               */
+               foreach ($orderOfTables as $table) {
+                       /* Check if
+                                  - table is set in $GLOBALS['TCA'],
+                                  - table is NOT readOnly
+                                  - the table is set with content in the data-array (if not, there's nothing to process...)
+                                  - permissions for tableaccess OK
+                          */
                        $modifyAccessList = $this->checkModifyAccessList($table);
                        $modifyAccessList = $this->checkModifyAccessList($table);
-                       if (!$modifyAccessList) {
+                       if (!$modifyAccessList) {
                                $id = 0;
                                $id = 0;
-                               $this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
+                               $this->log($table, $id, 2, 0, 1, "Attempt to modify table '%s' without permission", 1, array($table));
                        }
                        }
-                       if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList)      {
-                               if ($this->reverseOrder)        {
+                       if (isset($GLOBALS['TCA'][$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList) {
+                               if ($this->reverseOrder) {
                                        $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
                                }
 
                                        // For each record from the table, do:
                                        // $id is the record uid, may be a string if new records...
                                        // $incomingFieldArray is the array of fields
                                        $this->datamap[$table] = array_reverse($this->datamap[$table], 1);
                                }
 
                                        // For each record from the table, do:
                                        // $id is the record uid, may be a string if new records...
                                        // $incomingFieldArray is the array of fields
-                               foreach($this->datamap[$table] as $id => $incomingFieldArray)   {
-                                       if (is_array($incomingFieldArray))      {
+                               foreach ($this->datamap[$table] as $id => $incomingFieldArray) {
+                                       if (is_array($incomingFieldArray)) {
 
                                                        // Hook: processDatamap_preProcessFieldArray
 
                                                        // Hook: processDatamap_preProcessFieldArray
-                                               foreach($hookObjectsArr as $hookObj)    {
+                                               foreach ($hookObjectsArr as $hookObj) {
                                                        if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
                                                                $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
                                                        }
                                                        if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
                                                                $hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
                                                        }
@@ -681,23 +476,37 @@ class t3lib_TCEmain       {
                                                $old_pid_value = '';
                                                $this->autoVersioningUpdate = FALSE;
 
                                                $old_pid_value = '';
                                                $this->autoVersioningUpdate = FALSE;
 
-                                               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 (!t3lib_utility_Math::canBeInterpretedAsInteger($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.
                                                                        // $value = the pid
                                                                $pid_value = $incomingFieldArray['pid'];
 
                                                                        // Checking and finding numerical pid, it may be a string-reference to another value
                                                                $OK = 1;
                                                                        // $value = the 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 (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]);
-                                                                       } else {$OK = 0;}       // If not found in the substArray we must stop the process...
-                                                               } elseif ($pid_value>=0 && $this->BE_USER->workspace!==0 && $TCA[$table]['ctrl']['versioning_followPages'])     {       // PID points to page, the workspace is an offline space and the table follows page during versioning: This means we must check if the PID page has a version in the workspace with swapmode set to 0 (zero = page+content) and if so, change the pid to the uid of that version.
-                                                                       if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid_value, 'uid,t3ver_swapmode'))      {       // Looks for workspace version of page.
-                                                                               if ($WSdestPage['t3ver_swapmode']==0)   {       // if swapmode is zero, then change pid value.
+                                                               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.
+                                                                               if ($negFlag === 1) {
+                                                                                       $old_pid_value = $this->substNEWwithIDs[$pid_value];
+                                                                               }
+                                                                               $pid_value = intval($negFlag * $this->substNEWwithIDs[$pid_value]);
+                                                                       } else {
+                                                                               $OK = 0;
+                                                                       } // If not found in the substArray we must stop the process...
+                                                               } elseif ($pid_value >= 0 && $this->BE_USER->workspace !== 0
+                                                                       && $GLOBALS['TCA'][$table]['ctrl']['versioning_followPages']) {
+                                                                               // PID points to page, the workspace is an offline space and the table follows
+                                                                               // page during versioning: This means we must check if the PID page has a version
+                                                                               // in the workspace with swapmode set to 0 (zero = page+content) and if so, change
+                                                                               // the pid to the uid of that version.
+                                                                       if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid_value, 'uid,t3ver_swapmode')) { // Looks for workspace version of page.
+                                                                               if ($WSdestPage['t3ver_swapmode'] == 0) { // if swapmode is zero, then change pid value.
                                                                                        $pid_value = $WSdestPage['uid'];
                                                                                }
                                                                        }
                                                                                        $pid_value = $WSdestPage['uid'];
                                                                                }
                                                                        }
@@ -705,21 +514,21 @@ class t3lib_TCEmain       {
                                                                $pid_value = intval($pid_value);
 
                                                                        // The $pid_value is now the numerical pid at this point
                                                                $pid_value = intval($pid_value);
 
                                                                        // The $pid_value is now the numerical pid at this point
-                                                               if ($OK)        {
-                                                                       $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);
+                                                               if ($OK) {
+                                                                       $sortRow = $GLOBALS['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
-                                                                       } 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'] = $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'];
+                                                                               } 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'];
                                                                                }
                                                                        }
                                                                }
                                                                                }
                                                                        }
                                                                }
@@ -727,26 +536,26 @@ class t3lib_TCEmain       {
                                                        $theRealPid = $fieldArray['pid'];
 
                                                                // Now, check if we may insert records on this 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.
-                                                               if ($recordAccess)      {
-                                                                       $this->addDefaultPermittedLanguageIfNotSet($table,$incomingFieldArray);
-                                                                       $recordAccess = $this->BE_USER->recordEditAccessInternals($table,$incomingFieldArray,TRUE);
-                                                                       if (!$recordAccess)             {
-                                                                               $this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
-                                                                       } elseif(!$this->bypassWorkspaceRestrictions)   {
+                                                       if ($theRealPid >= 0) {
+                                                               $recordAccess = $this->checkRecordInsertAccess($table, $theRealPid); // Checks if records can be inserted on this $pid.
+                                                               if ($recordAccess) {
+                                                                       $this->addDefaultPermittedLanguageIfNotSet($table, $incomingFieldArray);
+                                                                       $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $incomingFieldArray, TRUE);
+                                                                       if (!$recordAccess) {
+                                                                               $this->newlog("recordEditAccessInternals() check failed. [" . $this->BE_USER->errorMsg . "]", 1);
+                                                                       } elseif (!$this->bypassWorkspaceRestrictions) {
                                                                                        // Workspace related processing:
                                                                                        // Workspace related processing:
-                                                                               if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid,$table))  {       // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
-                                                                                       if ($res<0)     {
+                                                                               if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid, $table)) { // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
+                                                                                       if ($res < 0) {
                                                                                                $recordAccess = FALSE;
                                                                                                $recordAccess = FALSE;
-                                                                                               $this->newlog('Stage for versioning root point and users access level did not allow for editing',1);
+                                                                                               $this->newlog('Stage for versioning root point and users access level did not allow for editing', 1);
                                                                                        }
                                                                                        }
-                                                                               } else {        // So, if no live records were allowed, we have to create a new version of this record:
-                                                                                       if ($TCA[$table]['ctrl']['versioningWS'])       {
+                                                                               } else { // So, if no live records were allowed, we have to create a new version of this record:
+                                                                                       if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
                                                                                                $createNewVersion = TRUE;
                                                                                        } else {
                                                                                                $recordAccess = FALSE;
                                                                                                $createNewVersion = TRUE;
                                                                                        } else {
                                                                                                $recordAccess = FALSE;
-                                                                                               $this->newlog('Record could not be created in this workspace in this branch',1);
+                                                                                               $this->newlog('Record could not be created in this workspace in this branch', 1);
                                                                                        }
                                                                                }
                                                                        }
                                                                                        }
                                                                                }
                                                                        }
@@ -754,23 +563,25 @@ class t3lib_TCEmain       {
                                                        } else {
                                                                debug('Internal ERROR: pid should not be less than zero!');
                                                        }
                                                        } else {
                                                                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
+                                                       $status = 'new'; // Yes new record, change $record_status to 'insert'
+                                               } else { // Nope... $id is a number
                                                        $fieldArray = array();
                                                        $fieldArray = array();
-                                                       $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']);
-                                                       } else {        // Next check of the record permissions (internals)
-                                                               $recordAccess = $this->BE_USER->recordEditAccessInternals($table,$id);
-                                                               if (!$recordAccess)             {
-                                                                       $propArr = $this->getRecordProperties($table,$id);
-                                                                       $this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
-                                                               } else {        // Here we fetch the PID of the record that we point to...
-                                                                       $tempdata = $this->recordInfo($table,$id,'pid'.($TCA[$table]['ctrl']['versioningWS']?',t3ver_wsid,t3ver_stage':''));
+                                                       $recordAccess = $this->checkRecordUpdateAccess($table, $id, $incomingFieldArray, $hookObjectsArr);
+                                                       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']);
+                                                       } else { // Next check of the record permissions (internals)
+                                                               $recordAccess = $this->BE_USER->recordEditAccessInternals($table, $id);
+                                                               if (!$recordAccess) {
+                                                                       $propArr = $this->getRecordProperties($table, $id);
+                                                                       $this->newlog("recordEditAccessInternals() check failed. [" . $this->BE_USER->errorMsg . "]", 1);
+                                                               } else { // Here we fetch the PID of the record that we point to...
+                                                                       $tempdata = $this->recordInfo($table, $id, 'pid' .
+                                                                               ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : '')
+                                                                       );
                                                                        $theRealPid = $tempdata['pid'];
 
                                                                        $theRealPid = $tempdata['pid'];
 
-                                                                       // Use the new id of the versionized record we're trying to write to:
+                                                                               // Use the new id of the versionized record we're trying to write to:
                                                                                // (This record is a child record of a parent and has already been versionized.)
                                                                        if ($this->autoVersionIdMap[$table][$id]) {
                                                                                        // For the reason that creating a new version of this record, automatically
                                                                                // (This record is a child record of a parent and has already been versionized.)
                                                                        if ($this->autoVersionIdMap[$table][$id]) {
                                                                                        // For the reason that creating a new version of this record, automatically
@@ -782,12 +593,13 @@ class t3lib_TCEmain       {
                                                                                $recordAccess = TRUE;
                                                                                $this->autoVersioningUpdate = TRUE;
 
                                                                                $recordAccess = TRUE;
                                                                                $this->autoVersioningUpdate = TRUE;
 
-                                                                               // Checking access in case of offline workspace:
-                                                                       } elseif (!$this->bypassWorkspaceRestrictions && $errorCode = $this->BE_USER->workspaceCannotEditRecord($table,$tempdata)) {
-                                                                               $recordAccess = FALSE;          // Versioning is required and it must be offline version!
+                                                                                       // Checking access in case of offline workspace:
+                                                                       } elseif (!$this->bypassWorkspaceRestrictions && $errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $tempdata)) {
+                                                                               $recordAccess = FALSE; // Versioning is required and it must be offline version!
 
                                                                                        // Auto-creation of version: In offline workspace, test if versioning is enabled and look for workspace version of input record. If there is no versionized record found we will create one and save to that.
 
                                                                                        // Auto-creation of version: In offline workspace, test if versioning is enabled and look for workspace version of input record. If there is no versionized record found we will create one and save to that.
-                                                                               if ($this->BE_USER->workspaceAllowAutoCreation($table,$id,$theRealPid)) {
+                                                                               if ($this->BE_USER->workspaceAllowAutoCreation($table, $id, $theRealPid)) {
+                                                                                       /** @var $tce t3lib_TCEmain */
                                                                                        $tce = t3lib_div::makeInstance('t3lib_TCEmain');
                                                                                        /* @var $tce t3lib_TCEmain  */
                                                                                        $tce->stripslashes_values = 0;
                                                                                        $tce = t3lib_div::makeInstance('t3lib_TCEmain');
                                                                                        /* @var $tce t3lib_TCEmain  */
                                                                                        $tce->stripslashes_values = 0;
@@ -796,22 +608,22 @@ class t3lib_TCEmain       {
                                                                                        $cmd = array();
                                                                                        $cmd[$table][$id]['version'] = array(
                                                                                                'action' => 'new',
                                                                                        $cmd = array();
                                                                                        $cmd[$table][$id]['version'] = array(
                                                                                                'action' => 'new',
-                                                                                               'treeLevels' => -1,     // Default is to create a version of the individual records... element versioning that is.
-                                                                                               'label' => 'Auto-created for WS #'.$this->BE_USER->workspace
+                                                                                               'treeLevels' => -1, // Default is to create a version of the individual records... element versioning that is.
+                                                                                               'label' => 'Auto-created for WS #' . $this->BE_USER->workspace
                                                                                        );
                                                                                        );
-                                                                                       $tce->start(array(),$cmd);
+                                                                                       $tce->start(array(), $cmd);
                                                                                        $tce->process_cmdmap();
                                                                                        $tce->process_cmdmap();
-                                                                                       $this->errorLog = array_merge($this->errorLog,$tce->errorLog);
+                                                                                       $this->errorLog = array_merge($this->errorLog, $tce->errorLog);
 
                                                                                                // If copying was successful, share the new uids (also of related children):
 
                                                                                                // If copying was successful, share the new uids (also of related children):
-                                                                                       if ($tce->copyMappingArray[$table][$id])        {
+                                                                                       if ($tce->copyMappingArray[$table][$id]) {
                                                                                                foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
                                                                                                        foreach ($origIdArray as $origId => $newId) {
                                                                                                                $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
                                                                                                                $this->autoVersionIdMap[$origTable][$origId] = $newId;
                                                                                                        }
                                                                                                }
                                                                                                foreach ($tce->copyMappingArray as $origTable => $origIdArray) {
                                                                                                        foreach ($origIdArray as $origId => $newId) {
                                                                                                                $this->uploadedFileArray[$origTable][$newId] = $this->uploadedFileArray[$origTable][$origId];
                                                                                                                $this->autoVersionIdMap[$origTable][$origId] = $newId;
                                                                                                        }
                                                                                                }
-                                                                                               $this->RTEmagic_copyIndex = t3lib_div::array_merge_recursive_overrule($this->RTEmagic_copyIndex, $tce->RTEmagic_copyIndex);             // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
+                                                                                               $this->RTEmagic_copyIndex = t3lib_div::array_merge_recursive_overrule($this->RTEmagic_copyIndex, $tce->RTEmagic_copyIndex); // See where RTEmagic_copyIndex is used inside fillInFieldArray() for more information...
 
                                                                                                        // Update registerDBList, that holds the copied relations to child records:
                                                                                                $registerDBList = array_merge($registerDBList, $tce->registerDBList);
 
                                                                                                        // Update registerDBList, that holds the copied relations to child records:
                                                                                                $registerDBList = array_merge($registerDBList, $tce->registerDBList);
@@ -823,64 +635,71 @@ class t3lib_TCEmain       {
                                                                                                $id = $this->autoVersionIdMap[$table][$id];
                                                                                                $recordAccess = TRUE;
                                                                                                $this->autoVersioningUpdate = TRUE;
                                                                                                $id = $this->autoVersionIdMap[$table][$id];
                                                                                                $recordAccess = TRUE;
                                                                                                $this->autoVersioningUpdate = TRUE;
-                                                                                       } else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version failed!",1);
-                                                                               } else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version not allowed in workspace!",1);
+                                                                                       } else {
+                                                                                               $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '" . $errorCode . "'). Auto-creation of version failed!", 1);
+                                                                                       }
+                                                                               } else {
+                                                                                       $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '" . $errorCode . "'). Auto-creation of version not allowed in workspace!", 1);
+                                                                               }
                                                                        }
                                                                }
                                                        }
                                                                        }
                                                                }
                                                        }
-                                                       $status = 'update';     // the default is 'update'
+                                                       $status = 'update'; // the default is 'update'
                                                }
 
                                                        // If access was granted above, proceed to create or update record:
                                                }
 
                                                        // If access was granted above, proceed to create or update record:
-                                               if ($recordAccess)      {
+                                               if ($recordAccess) {
 
 
-                                                       list($tscPID) = t3lib_BEfunc::getTSCpid($table,$id,$old_pid_value ? $old_pid_value : $fieldArray['pid']);       // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
+                                                       list($tscPID) = t3lib_BEfunc::getTSCpid($table, $id, $old_pid_value ? $old_pid_value : $fieldArray['pid']); // Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
                                                        $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
                                                        $TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
-                                                       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.']);
                                                        }
                                                        }
-                                                       if ($createNewVersion)  {
+                                                       if ($createNewVersion) {
                                                                $newVersion_placeholderFieldArray = $fieldArray;
                                                        }
 
                                                                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
                                                                $newVersion_placeholderFieldArray = $fieldArray;
                                                        }
 
                                                                // Processing of all fields in incomingFieldArray and setting them in $fieldArray
-                                                       $fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);
+                                                       $fieldArray = $this->fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $theRealPid, $status, $tscPID);
 
                                                                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
 
                                                                // Forcing some values unto field array:
 
                                                                // NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!
 
                                                                // Forcing some values unto field array:
-                                                       $fieldArray = $this->overrideFieldArray($table,$fieldArray);    // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
-                                                       if ($createNewVersion)  {
-                                                               $newVersion_placeholderFieldArray = $this->overrideFieldArray($table,$newVersion_placeholderFieldArray);
+                                                       $fieldArray = $this->overrideFieldArray($table, $fieldArray); // NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
+                                                       if ($createNewVersion) {
+                                                               $newVersion_placeholderFieldArray = $this->overrideFieldArray($table, $newVersion_placeholderFieldArray);
                                                        }
 
                                                                // Setting system fields
                                                        }
 
                                                                // Setting system fields
-                                                       if ($status=='new')     {
-                                                               if ($TCA[$table]['ctrl']['crdate'])     {
-                                                                       $fieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
+                                                       if ($status == 'new') {
+                                                               if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
+                                                                       $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
                                                                        if ($createNewVersion) {
                                                                        if ($createNewVersion) {
-                                                                               $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
+                                                                               $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
                                                                        }
                                                                }
                                                                        }
                                                                }
-                                                               if ($TCA[$table]['ctrl']['cruser_id'])  {
-                                                                       $fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
-                                                                       if ($createNewVersion)  $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
+                                                               if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
+                                                                       $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
+                                                                       if ($createNewVersion) {
+                                                                               $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $this->userid;
+                                                                       }
                                                                }
                                                                }
-                                                       } elseif ($this->checkSimilar) {        // Removing fields which are equal to the current value:
-                                                               $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
+                                                       } elseif ($this->checkSimilar) { // Removing fields which are equal to the current value:
+                                                               $fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table, $id, $fieldArray);
                                                        }
                                                        }
-                                                       if ($TCA[$table]['ctrl']['tstamp'] && count($fieldArray))       {
-                                                               $fieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
+                                                       if ($GLOBALS['TCA'][$table]['ctrl']['tstamp'] && count($fieldArray)) {
+                                                               $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
                                                                if ($createNewVersion) {
                                                                if ($createNewVersion) {
-                                                                       $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
+                                                                       $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
                                                                }
                                                        }
                                                                }
                                                        }
-                                                       if ($TCA[$table]['ctrl']['versioningWS']) {
+                                                               // Set stage to "Editing" to make sure we restart the workflow
+                                                       if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
                                                                $fieldArray['t3ver_stage'] = 0;
                                                        }
 
                                                                // Hook: processDatamap_postProcessFieldArray
                                                                $fieldArray['t3ver_stage'] = 0;
                                                        }
 
                                                                // Hook: processDatamap_postProcessFieldArray
-                                                       foreach($hookObjectsArr as $hookObj)    {
+                                                       foreach ($hookObjectsArr as $hookObj) {
                                                                if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
                                                                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
                                                                }
                                                                if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
                                                                        $hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
                                                                }
@@ -889,51 +708,62 @@ class t3lib_TCEmain       {
                                                                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
                                                                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
                                                        if (is_array($fieldArray)) {
                                                                // Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
                                                                // Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
                                                        if (is_array($fieldArray)) {
-                                                               if ($status=='new')     {
-                                                                       if ($createNewVersion)  {       // This creates a new version of the record with online placeholder and offline version
-                                                                               $versioningType = $table==='pages' ? $this->BE_USER->workspaceVersioningTypeGetClosest(t3lib_div::intInRange($TYPO3_CONF_VARS['BE']['newPagesVersioningType'],-1,1)) : -1;
-                                                                               if ($this->BE_USER->workspaceVersioningTypeAccess($versioningType))     {
+                                                               if ($status == 'new') {
+                                                                       if ($createNewVersion) { // This creates a new version of the record with online placeholder and offline version
+                                                                               $versioningType = ($table === 'pages'
+                                                                                       ? $this->BE_USER->workspaceVersioningTypeGetClosest(
+                                                                                               t3lib_utility_Math::forceIntegerInRange($GLOBALS['TYPO3_CONF_VARS']['BE']['newPagesVersioningType'], -1, 1))
+                                                                                       : -1);
+                                                                               if ($this->BE_USER->workspaceVersioningTypeAccess($versioningType)) {
                                                                                        $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
                                                                                        $newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
-                                                                                       $newVersion_placeholderFieldArray['t3ver_state'] = 1;   // Setting placeholder state value for temporary record
-                                                                                       $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace;    // Setting workspace - only so display of place holders can filter out those from other workspaces.
-                                                                                       $newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['label']] = '[PLACEHOLDER, WS#'.$this->BE_USER->workspace.']';
-                                                                                       $this->insertDB($table,$id,$newVersion_placeholderFieldArray,FALSE);    // Saving placeholder as 'original'
+                                                                                       $newVersion_placeholderFieldArray['t3ver_state'] = 1; // Setting placeholder state value for temporary record
+                                                                                       $newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace; // Setting workspace - only so display of place holders can filter out those from other workspaces.
+                                                                                       $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = '[PLACEHOLDER, WS#' . $this->BE_USER->workspace . ']';
+                                                                                       $this->insertDB($table, $id, $newVersion_placeholderFieldArray, FALSE); // Saving placeholder as 'original'
 
                                                                                                // For the actual new offline version, set versioning values to point to placeholder:
                                                                                        $fieldArray['pid'] = -1;
                                                                                        $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
                                                                                        $fieldArray['t3ver_id'] = 1;
 
                                                                                                // For the actual new offline version, set versioning values to point to placeholder:
                                                                                        $fieldArray['pid'] = -1;
                                                                                        $fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
                                                                                        $fieldArray['t3ver_id'] = 1;
-                                                                                       $fieldArray['t3ver_state'] = -1;        // Setting placeholder state value for version (so it can know it is currently a new version...)
+                                                                                       $fieldArray['t3ver_state'] = -1; // Setting placeholder state value for version (so it can know it is currently a new version...)
                                                                                        $fieldArray['t3ver_label'] = 'First draft version';
                                                                                        $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
                                                                                        $fieldArray['t3ver_label'] = 'First draft version';
                                                                                        $fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
-                                                                                       if ($table==='pages') {         // Swap mode set to "branch" so we can build branches for pages.
+                                                                                       if ($table === 'pages') { // Swap mode set to "branch" so we can build branches for pages.
                                                                                                $fieldArray['t3ver_swapmode'] = $versioningType;
                                                                                        }
                                                                                                $fieldArray['t3ver_swapmode'] = $versioningType;
                                                                                        }
-                                                                                       $phShadowId = $this->insertDB($table,$id,$fieldArray,TRUE,0,TRUE);      // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
-                                                                                       if ($phShadowId)        {
-                                                                                               $this->placeholderShadowing($table,$phShadowId);
+                                                                                       $phShadowId = $this->insertDB($table, $id, $fieldArray, TRUE, 0, TRUE); // When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
+                                                                                       if ($phShadowId) {
+                                                                                                       // Processes fields of the placeholder record:
+                                                                                               $this->triggerRemapAction(
+                                                                                                       $table,
+                                                                                                       $id,
+                                                                                                       array($this, 'placeholderShadowing'),
+                                                                                                       array($table, $phShadowId)
+                                                                                               );
                                                                                                        // Hold auto-versionized ids of placeholders:
                                                                                                $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
                                                                                        }
                                                                                                        // Hold auto-versionized ids of placeholders:
                                                                                                $this->autoVersionIdMap[$table][$this->substNEWwithIDs[$id]] = $phShadowId;
                                                                                        }
-                                                                               } else $this->newlog('Versioning type "'.$versioningType.'" was not allowed, so could not create new record.',1);
+                                                                               } else {
+                                                                                       $this->newlog('Versioning type "' . $versioningType . '" was not allowed, so could not create new record.', 1);
+                                                                               }
                                                                        } else {
                                                                        } else {
-                                                                               $this->insertDB($table,$id,$fieldArray,FALSE,$incomingFieldArray['uid']);
+                                                                               $this->insertDB($table, $id, $fieldArray, FALSE, $incomingFieldArray['uid']);
                                                                        }
                                                                } else {
                                                                        }
                                                                } else {
-                                                                       $this->updateDB($table,$id,$fieldArray);
-                                                                       $this->placeholderShadowing($table,$id);
+                                                                       $this->updateDB($table, $id, $fieldArray);
+                                                                       $this->placeholderShadowing($table, $id);
                                                                }
                                                        }
 
                                                                }
                                                        }
 
-                                                               /*
-                                                                * Hook: processDatamap_afterDatabaseOperations
-                                                                *
-                                                                * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
-                                                                *               but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
-                                                                */
+                                                       /*
+                                                                                                                        * Hook: processDatamap_afterDatabaseOperations
+                                                                                                                        *
+                                                                                                                        * Note: When using the hook after INSERT operations, you will only get the temporary NEW... id passed to your hook as $id,
+                                                                                                                        *               but you can easily translate it to the real uid of the inserted record using the $this->substNEWwithIDs array.
+                                                                                                                        */
                                                        $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
                                                        $this->hook_processDatamap_afterDatabaseOperations($hookObjectsArr, $status, $table, $id, $fieldArray);
-                                               }       // if ($recordAccess)   {
-                                       }       // if (is_array($incomingFieldArray))   {
+                                               } // if ($recordAccess) {
+                                       } // if (is_array($incomingFieldArray)) {
                                }
                        }
                }
                                }
                        }
                }
@@ -948,11 +778,15 @@ class t3lib_TCEmain       {
                 *
                 * Note: When this hook gets called, all operations on the submitted data have been finished.
                 */
                 *
                 * Note: When this hook gets called, all operations on the submitted data have been finished.
                 */
-               foreach($hookObjectsArr as $hookObj) {
+               foreach ($hookObjectsArr as $hookObj) {
                        if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
                                $hookObj->processDatamap_afterAllOperations($this);
                        }
                }
                        if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
                                $hookObj->processDatamap_afterAllOperations($this);
                        }
                }
+
+               if ($this->isOuterMostInstance()) {
+                       $this->resetElementsToBeDeleted();
+               }
        }
 
        /**
        }
 
        /**
@@ -962,31 +796,31 @@ class t3lib_TCEmain       {
         * @param       integer         Record uid
         * @return      void
         */
         * @param       integer         Record uid
         * @return      void
         */
-       function placeholderShadowing($table,$id)       {
-               global $TCA;
-
+       function placeholderShadowing($table, $id) {
                t3lib_div::loadTCA($table);
                t3lib_div::loadTCA($table);
-               if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'*'))    {
-                       if ((int)$liveRec['t3ver_state']>0)     {
-                               $justStoredRecord = t3lib_BEfunc::getRecord($table,$id);
+               if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table, $id, '*')) {
+                       if ((int) $liveRec['t3ver_state'] > 0) {
+                               $justStoredRecord = t3lib_BEfunc::getRecord($table, $id);
                                $newRecord = array();
 
                                $newRecord = array();
 
-                               $shadowCols = $TCA[$table]['ctrl']['shadowColumnsForNewPlaceholders'];
-                               $shadowCols.= ','.$TCA[$table]['ctrl']['languageField'];
-                               $shadowCols.= ','.$TCA[$table]['ctrl']['transOrigPointerField'];
-                               $shadowCols.= ','.$TCA[$table]['ctrl']['type'];
-                               $shadowCols.= ','.$TCA[$table]['ctrl']['label'];
-
-                               $shadowColumns = array_unique(t3lib_div::trimExplode(',', $shadowCols,1));
-                               foreach($shadowColumns as $fieldName)   {
-                                       if (strcmp($justStoredRecord[$fieldName],$liveRec[$fieldName]) && isset($TCA[$table]['columns'][$fieldName]) && $fieldName!=='uid' && $fieldName!=='pid')       {
+                               $shadowCols = $GLOBALS['TCA'][$table]['ctrl']['shadowColumnsForNewPlaceholders'];
+                               $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['languageField'];
+                               $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
+                               $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['type'];
+                               $shadowCols .= ',' . $GLOBALS['TCA'][$table]['ctrl']['label'];
+
+                               $shadowColumns = array_unique(t3lib_div::trimExplode(',', $shadowCols, 1));
+                               foreach ($shadowColumns as $fieldName) {
+                                       if (strcmp($justStoredRecord[$fieldName], $liveRec[$fieldName])
+                                               && isset($GLOBALS['TCA'][$table]['columns'][$fieldName])
+                                               && $fieldName !== 'uid' && $fieldName !== 'pid') {
                                                $newRecord[$fieldName] = $justStoredRecord[$fieldName];
                                        }
                                }
 
                                                $newRecord[$fieldName] = $justStoredRecord[$fieldName];
                                        }
                                }
 
-                               if (count($newRecord))  {
-                                       $this->newlog2('Shadowing done on fields <i>'.implode(',',array_keys($newRecord)).'</i> in placeholder record '.$table.':'.$liveRec['uid'].' (offline version UID='.$id.')', $table, $liveRec['uid'], $liveRec['pid']);
-                                       $this->updateDB($table,$liveRec['uid'],$newRecord);
+                               if (count($newRecord)) {
+                                       $this->newlog2('Shadowing done on fields <i>' . implode(',', array_keys($newRecord)) . '</i> in placeholder record ' . $table . ':' . $liveRec['uid'] . ' (offline version UID=' . $id . ')', $table, $liveRec['uid'], $liveRec['pid']);
+                                       $this->updateDB($table, $liveRec['uid'], $newRecord);
                                }
                        }
                }
                                }
                        }
                }
@@ -1005,8 +839,7 @@ class t3lib_TCEmain        {
         * @param       integer         $tscPID: TSconfig PID
         * @return      array           Field Array
         */
         * @param       integer         $tscPID: TSconfig PID
         * @return      array           Field Array
         */
-       function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)  {
-               global $TCA;
+       function fillInFieldArray($table, $id, $fieldArray, $incomingFieldArray, $realPid, $status, $tscPID) {
 
                        // Initialize:
                t3lib_div::loadTCA($table);
 
                        // Initialize:
                t3lib_div::loadTCA($table);
@@ -1015,59 +848,63 @@ class t3lib_TCEmain      {
                $diffStorageFlag = FALSE;
 
                        // Setting 'currentRecord' and 'checkValueRecord':
                $diffStorageFlag = FALSE;
 
                        // Setting 'currentRecord' and 'checkValueRecord':
-               if (strstr($id,'NEW'))  {
-                       $currentRecord = $checkValueRecord = $fieldArray;       // must have the 'current' array - not the values after processing below...
+               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 $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))       {
+                       if (is_array($incomingFieldArray) && is_array($checkValueRecord)) {
                                $checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
                        }
                } else {
                                $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!
+                       $currentRecord = $checkValueRecord = $this->recordInfo($table, $id, '*'); // We must use the current values as basis for this!
 
 
-                       t3lib_BEfunc::fixVersioningPid($table,$currentRecord);  // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
+                       t3lib_BEfunc::fixVersioningPid($table, $currentRecord); // This is done to make the pid positive for offline versions; Necessary to have diff-view for pages_language_overlay in workspaces.
 
                                // Get original language record if available:
                        if (is_array($currentRecord)
 
                                // Get original language record if available:
                        if (is_array($currentRecord)
-                                       && $TCA[$table]['ctrl']['transOrigDiffSourceField']
-                                       && $TCA[$table]['ctrl']['languageField']
-                                       && $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
-                                       && $TCA[$table]['ctrl']['transOrigPointerField']
-                                       && intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0)   {
+                               && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']
+                               && $GLOBALS['TCA'][$table]['ctrl']['languageField']
+                               && $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']] > 0
+                               && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']
+                               && intval($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]) > 0) {
 
 
-                               $lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
-                               $originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
-                               t3lib_BEfunc::workspaceOL($lookUpTable,$originalLanguageRecord);
-                               $originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
+                               $lookUpTable = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] ? $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable'] : $table;
+                               $originalLanguageRecord = $this->recordInfo($lookUpTable, $currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']], '*');
+                               t3lib_BEfunc::workspaceOL($lookUpTable, $originalLanguageRecord);
+                               $originalLanguage_diffStorage = unserialize($currentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']]);
                        }
                }
                $this->checkValue_currentRecord = $checkValueRecord;
 
                        }
                }
                $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
+               /*
+                          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[]
-                       */
-               foreach($incomingFieldArray as $field => $fieldValue)   {
-                       if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field])      {       // The field must be editable.
+                          If everything is OK, the field is entered into $fieldArray[]
+                  */
+               foreach ($incomingFieldArray as $field => $fieldValue) {
+                       if (!in_array($table . '-' . $field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field]) { // The field must be editable.
 
                                        // Checking if a value for language can be changed:
 
                                        // Checking if a value for language can be changed:
-                               $languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);
+                               $languageDeny = $GLOBALS['TCA'][$table]['ctrl']['languageField']
+                                       && !strcmp($GLOBALS['TCA'][$table]['ctrl']['languageField'], $field)
+                                       && !$this->BE_USER->checkLanguageAccess($fieldValue);
 
 
-                               if (!$languageDeny)     {
+                               if (!$languageDeny) {
                                                // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
                                                // Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
-                                       if ($this->stripslashes_values) {
-                                               if (is_array($fieldValue))      {
+                                       if ($this->stripslashes_values) {
+                                               if (is_array($fieldValue)) {
                                                        t3lib_div::stripSlashesOnArray($fieldValue);
                                                        t3lib_div::stripSlashesOnArray($fieldValue);
-                                               } else $fieldValue = stripslashes($fieldValue);
+                                               } else {
+                                                       $fieldValue = stripslashes($fieldValue);
+                                               }
                                        }
 
                                        }
 
-                                       switch ($field) {
+                                       switch ($field) {
                                                case 'uid':
                                                case 'pid':
                                                        // Nothing happens, already set
                                                case 'uid':
                                                case 'pid':
                                                        // Nothing happens, already set
@@ -1078,18 +915,18 @@ class t3lib_TCEmain      {
                                                case 'perms_group':
                                                case 'perms_everybody':
                                                                // Permissions can be edited by the owner or the administrator
                                                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) ) {
-                                                               $value=intval($fieldValue);
-                                                               switch($field)  {
+                                                       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;
+                                                                               $fieldArray[$field] = $value;
                                                                        break;
                                                                        case 'perms_groupid':
                                                                        break;
                                                                        case 'perms_groupid':
-                                                                               $fieldArray[$field]=$value;
+                                                                               $fieldArray[$field] = $value;
                                                                        break;
                                                                        default:
                                                                        break;
                                                                        default:
-                                                                               if ($value>=0 && $value<pow(2,5))       {
-                                                                                       $fieldArray[$field]=$value;
+                                                                               if ($value >= 0 && $value < pow(2, 5)) {
+                                                                                       $fieldArray[$field] = $value;
                                                                                }
                                                                        break;
                                                                }
                                                                                }
                                                                        break;
                                                                }
@@ -1106,68 +943,70 @@ class t3lib_TCEmain      {
                                                        // t3ver_label is not here because it CAN be edited as a regular field!
                                                break;
                                                default:
                                                        // t3ver_label is not here because it CAN be edited as a regular field!
                                                break;
                                                default:
-                                                       if (isset($TCA[$table]['columns'][$field]))     {
+                                                       if (isset($GLOBALS['TCA'][$table]['columns'][$field])) {
                                                                        // Evaluating the value
                                                                        // Evaluating the value
-                                                               $res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
-                                                               if (isset($res['value']))       {
+                                                               $res = $this->checkValue($table, $field, $fieldValue, $id, $status, $realPid, $tscPID);
+                                                               if (isset($res['value'])) {
                                                                        $fieldArray[$field] = $res['value'];
                                                                }
 
                                                                        // Add the value of the original record to the diff-storage content:
                                                                        $fieldArray[$field] = $res['value'];
                                                                }
 
                                                                        // Add the value of the original record to the diff-storage content:
-                                                               if ($this->updateModeL10NdiffData && $TCA[$table]['ctrl']['transOrigDiffSourceField'])  {
+                                                               if ($this->updateModeL10NdiffData && $GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']) {
                                                                        $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
                                                                        $diffStorageFlag = TRUE;
                                                                }
 
                                                                        // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
                                                                        $originalLanguage_diffStorage[$field] = $this->updateModeL10NdiffDataClear ? '' : $originalLanguageRecord[$field];
                                                                        $diffStorageFlag = TRUE;
                                                                }
 
                                                                        // If autoversioning is happening we need to perform a nasty hack. The case is parallel to a similar hack inside checkValue_group_select_file().
-                                                                       // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied. That should be true for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
+                                                                       // When a copy or version is made of a record, a search is made for any RTEmagic* images in fields having the "images" soft reference parser applied. That should be TRUE for RTE fields. If any are found they are duplicated to new names and the file reference in the bodytext is updated accordingly.
                                                                        // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
                                                                        // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
                                                                        // However, with auto-versioning the submitted content of the field will just overwrite the corrected values. This leaves a) lost RTEmagic files and b) creates a double reference to the old files.
                                                                        // The only solution I can come up with is detecting when auto versioning happens, then see if any RTEmagic images was copied and if so make a stupid string-replace of the content !
-                                                               if ($this->autoVersioningUpdate===TRUE) {
-                                                                       if (is_array($this->RTEmagic_copyIndex[$table][$id][$field]))   {
-                                                                               foreach($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
-                                                                                       $fieldArray[$field] = str_replace(' src="'.$oldRTEmagicName.'"',' src="'.$newRTEmagicName.'"',$fieldArray[$field]);
+                                                               if ($this->autoVersioningUpdate === TRUE) {
+                                                                       if (is_array($this->RTEmagic_copyIndex[$table][$id][$field])) {
+                                                                               foreach ($this->RTEmagic_copyIndex[$table][$id][$field] as $oldRTEmagicName => $newRTEmagicName) {
+                                                                                       $fieldArray[$field] = str_replace(' src="' . $oldRTEmagicName . '"', ' src="' . $newRTEmagicName . '"', $fieldArray[$field]);
                                                                                }
                                                                        }
                                                                }
 
                                                                                }
                                                                        }
                                                                }
 
-                                                       } elseif ($TCA[$table]['ctrl']['origUid']===$field) {   // Allow value for original UID to pass by...
+                                                       } elseif ($GLOBALS['TCA'][$table]['ctrl']['origUid'] === $field) {
+                                                                       // Allow value for original UID to pass by...
                                                                $fieldArray[$field] = $fieldValue;
                                                        }
                                                break;
                                        }
                                                                $fieldArray[$field] = $fieldValue;
                                                        }
                                                break;
                                        }
-                               }       // Checking language.
-                       }       // Check exclude fields / disabled fields...
+                               } // Checking language.
+                       } // Check exclude fields / disabled fields...
                }
                        // Add diff-storage information:
                }
                        // Add diff-storage information:
-               if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']]))  {       // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
-                        $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
+               if ($diffStorageFlag && !isset($fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']])) {
+                               // If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
+                       $fieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
                }
 
                        // Checking for RTE-transformations of fields:
                }
 
                        // Checking for RTE-transformations of fields:
-               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
-               $theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
-               if (is_array($types_fieldConfig))       {
+               $types_fieldConfig = t3lib_BEfunc::getTCAtypes($table, $currentRecord);
+               $theTypeString = t3lib_BEfunc::getTCAtypeValue($table, $currentRecord);
+               if (is_array($types_fieldConfig)) {
                        foreach ($types_fieldConfig as $vconf) {
                                        // Write file configuration:
                        foreach ($types_fieldConfig as $vconf) {
                                        // 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
 
                                        // RTE transformations:
 
                                        // RTE transformations:
-                               if (!$this->dontProcessTransformations) {
-                                       if (isset($fieldArray[$vconf['field']]))        {
+                               if (!$this->dontProcessTransformations) {
+                                       if (isset($fieldArray[$vconf['field']])) {
                                                        // Look for transformation flag:
                                                        // Look for transformation flag:
-                                               switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']])      {
+                                               switch ((string) $incomingFieldArray['_TRANSFORM_' . $vconf['field']]) {
                                                        case 'RTE':
                                                        case 'RTE':
-                                                               $RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
-                                                               $thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);
+                                                               $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();
 
                                                                        // 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']);
+                                                               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!');
                                                                }
                                                                } else {
                                                                        debug('NO RTE OBJECT FOUND!');
                                                                }
@@ -1177,31 +1016,31 @@ class t3lib_TCEmain     {
                                }
 
                                        // Write file configuration:
                                }
 
                                        // Write file configuration:
-                               if (is_array($eFile))   {
-                                       $mixedRec = array_merge($currentRecord,$fieldArray);
+                               if (is_array($eFile)) {
+                                       $mixedRec = array_merge($currentRecord, $fieldArray);
                                        $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
                                        $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
                                        /* @var $parseHTML t3lib_parsehtml_proc */
                                        $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
                                        $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
                                        /* @var $parseHTML t3lib_parsehtml_proc */
-                                       $parseHTML->init('','');
+                                       $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);
+                                       $SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, LF . $insertContent . LF, 1, 1);
+                                       t3lib_div::writeFile($eFile['editFile'], $SW_fileNewContent);
 
                                                // Write status:
 
                                                // Write status:
-                                       if (!strstr($id,'NEW') && $eFile['statusField'])        {
+                                       if (!strstr($id, 'NEW') && $eFile['statusField']) {
                                                $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
                                                        $table,
                                                $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
                                                        $table,
-                                                       'uid='.intval($id),
+                                                       'uid=' . intval($id),
                                                        array(
                                                        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']])
                                                        )
                                                );
                                        }
                                                        )
                                                );
                                        }
-                               } elseif ($eFile && is_string($eFile))  {
-                                       $this->log($table,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
+                               } elseif ($eFile && is_string($eFile)) {
+                                       $this->log($table, $id, 2, 0, 1, "Write-file error: '%s'", 13, array($eFile), $realPid);
                                }
                        }
                }
                                }
                        }
                }
@@ -1210,16 +1049,6 @@ class t3lib_TCEmain      {
        }
 
 
        }
 
 
-
-
-
-
-
-
-
-
-
-
        /*********************************************
         *
         * Evaluation of input values
        /*********************************************
         *
         * Evaluation of input values
@@ -1240,29 +1069,31 @@ class t3lib_TCEmain     {
         * @param       integer         $tscPID
         * @return      array           Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['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,$tscPID)  {
-               global $TCA, $PAGES_TYPES;
+       function checkValue($table, $field, $value, $id, $status, $realPid, $tscPID) {
                t3lib_div::loadTCA($table);
 
                t3lib_div::loadTCA($table);
 
-               $res = Array(); // result array
-               $recFID = $table.':'.$id.':'.$field;
+               $res = array(); // result array
+               $recFID = $table . ':' . $id . ':' . $field;
 
                        // Processing special case of field pages.doktype
 
                        // Processing special case of field pages.doktype
-               if ($table=='pages' && $field=='doktype')       {
+               if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
                                // If the user may not use this specific doktype, we issue a warning
                                // If the user may not use this specific doktype, we issue a warning
-                       if (! ($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'],$value)))        {
-                               $propArr = $this->getRecordProperties($table,$id);
-                               $this->log($table,$id,5,0,1,"You cannot change the 'doktype' of page '%s' to the desired value.",1,array($propArr['header']),$propArr['event_pid']);
+                       if (!($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'], $value))) {
+                               $propArr = $this->getRecordProperties($table, $id);
+                               $this->log($table, $id, 5, 0, 1, "You cannot change the 'doktype' of page '%s' to the desired value.", 1, array($propArr['header']), $propArr['event_pid']);
                                return $res;
                                return $res;
-                       };
-                       if ($status=='update')  {
+                       }
+                       ;
+                       if ($status == 'update') {
                                        // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
                                        // This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
-                               $onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ? $PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
-                               if ($onlyAllowedTables) {
-                                       $theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
-                                       if ($theWrongTables)    {
-                                               $propArr = $this->getRecordProperties($table,$id);
-                                               $this->log($table,$id,5,0,1,"'doktype' of page '%s' could not be changed because the page contains records from disallowed tables; %s",2,array($propArr['header'],$theWrongTables),$propArr['event_pid']);
+                               $onlyAllowedTables = (isset($GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables'])
+                                       ? $GLOBALS['PAGES_TYPES'][$value]['onlyAllowedTables']
+                                       : $GLOBALS['PAGES_TYPES']['default']['onlyAllowedTables']);
+                               if ($onlyAllowedTables) {
+                                       $theWrongTables = $this->doesPageHaveUnallowedTables($id, $value);
+                                       if ($theWrongTables) {
+                                               $propArr = $this->getRecordProperties($table, $id);
+                                               $this->log($table, $id, 5, 0, 1, "'doktype' of page '%s' could not be changed because the page contains records from disallowed tables; %s", 2, array($propArr['header'], $theWrongTables), $propArr['event_pid']);
                                                return $res;
                                        }
                                }
                                                return $res;
                                        }
                                }
@@ -1270,25 +1101,25 @@ class t3lib_TCEmain     {
                }
 
                        // Get current value:
                }
 
                        // Get current value:
-               $curValueRec = $this->recordInfo($table,$id,$field);
+               $curValueRec = $this->recordInfo($table, $id, $field);
                $curValue = $curValueRec[$field];
 
                        // Getting config for the field
                $curValue = $curValueRec[$field];
 
                        // Getting config for the field
-               $tcaFieldConf = $TCA[$table]['columns'][$field]['config'];
+               $tcaFieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
 
                        // Preform processing:
 
                        // Preform processing:
-               $res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);
+               $res = $this->checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $this->uploadedFileArray[$table][$id][$field], $tscPID);
 
                return $res;
        }
 
        /**
 
                return $res;
        }
 
        /**
-        * Branches out evaluation of a field value based on its type as configured in TCA
+        * Branches out evaluation of a field value based on its type as configured in $GLOBALS['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.
         * 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       array           Field configuration from $GLOBALS['TCA']
         * @param       string          Table name
         * @param       integer         Return UID
         * @param       [type]          $curValue: ...
         * @param       string          Table name
         * @param       integer         Return UID
         * @param       [type]          $curValue: ...
@@ -1300,37 +1131,37 @@ class t3lib_TCEmain     {
         * @param       [type]          $tscPID: ...
         * @return      array           Returns the evaluated $value as key "value" in this array.
         */
         * @param       [type]          $tscPID: ...
         * @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,$tscPID)   {
+       function checkValue_SW($res, $value, $tcaFieldConf, $table, $id, $curValue, $status, $realPid, $recFID, $field, $uploadedFiles, $tscPID) {
 
 
-               $PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);
+               $PP = array($table, $id, $curValue, $status, $realPid, $recFID, $tscPID);
 
                switch ($tcaFieldConf['type']) {
                        case 'text':
 
                switch ($tcaFieldConf['type']) {
                        case 'text':
-                               $res = $this->checkValue_text($res,$value,$tcaFieldConf,$PP,$field);
+                               $res = $this->checkValue_text($res, $value, $tcaFieldConf, $PP, $field);
                        break;
                        case 'passthrough':
                        case 'user':
                                $res['value'] = $value;
                        break;
                        case 'input':
                        break;
                        case 'passthrough':
                        case 'user':
                                $res['value'] = $value;
                        break;
                        case 'input':
-                               $res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
+                               $res = $this->checkValue_input($res, $value, $tcaFieldConf, $PP, $field);
                        break;
                        case 'check':
                        break;
                        case 'check':
-                               $res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
+                               $res = $this->checkValue_check($res, $value, $tcaFieldConf, $PP);
                        break;
                        case 'radio':
                        break;
                        case 'radio':
-                               $res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
+                               $res = $this->checkValue_radio($res, $value, $tcaFieldConf, $PP);
                        break;
                        case 'group':
                        case 'select':
                        break;
                        case 'group':
                        case 'select':
-                               $res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
+                               $res = $this->checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
                        break;
                        case 'inline':
                        break;
                        case 'inline':
-                               $res = $this->checkValue_inline($res,$value,$tcaFieldConf,$PP,$field);
-                               break;
+                               $res = $this->checkValue_inline($res, $value, $tcaFieldConf, $PP, $field);
+                       break;
                        case 'flex':
                        case 'flex':
-                               if ($field)     {       // FlexForms are only allowed for real fields.
-                                       $res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
+                               if ($field) { // FlexForms are only allowed for real fields.
+                                       $res = $this->checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field);
                                }
                        break;
                        default:
                                }
                        break;
                        default:
@@ -1352,9 +1183,9 @@ class t3lib_TCEmain       {
         * @param       string          Field name
         * @return      array           Modified $res array
         */
         * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_text($res,$value,$tcaFieldConf,$PP,$field='')       {
-               $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
-               $res = $this->checkValue_text_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
+       function checkValue_text($res, $value, $tcaFieldConf, $PP, $field = '') {
+               $evalCodesArray = t3lib_div::trimExplode(',', $tcaFieldConf['eval'], 1);
+               $res = $this->checkValue_text_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
                return $res;
        }
 
                return $res;
        }
 
@@ -1368,8 +1199,8 @@ class t3lib_TCEmain       {
         * @param       string          Field name
         * @return      array           Modified $res array
         */
         * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')      {
-               list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
+       function checkValue_input($res, $value, $tcaFieldConf, $PP, $field = '') {
+               list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
                        // Secures the string-length to be less than max.
                if (intval($tcaFieldConf['max']) > 0) {
 
                        // Secures the string-length to be less than max.
                if (intval($tcaFieldConf['max']) > 0) {
@@ -1377,22 +1208,26 @@ class t3lib_TCEmain     {
                }
 
                        // Checking range of value:
                }
 
                        // 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'];}
+               if ($tcaFieldConf['range'] && $value != $tcaFieldConf['checkbox'] && $value != $tcaFieldConf['default']) {
+                       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:
                }
 
                        // Process evaluation settings:
-               $evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
-               $res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);
+               $evalCodesArray = t3lib_div::trimExplode(',', $tcaFieldConf['eval'], 1);
+               $res = $this->checkValue_input_Eval($value, $evalCodesArray, $tcaFieldConf['is_in']);
 
                        // Process UNIQUE settings:
 
                        // Process UNIQUE settings:
-               if ($field && $realPid>=0)      {       // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
-                       if ($res['value'] && in_array('uniqueInPid',$evalCodesArray))   {
-                               $res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
+               if ($field && $realPid >= 0) { // Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
+                       if ($res['value'] && in_array('uniqueInPid', $evalCodesArray)) {
+                               $res['value'] = $this->getUnique($table, $field, $res['value'], $id, $realPid);
                        }
                        }
-                       if ($res['value'] && in_array('unique',$evalCodesArray))        {
-                               $res['value'] = $this->getUnique($table,$field,$res['value'],$id);
+                       if ($res['value'] && in_array('unique', $evalCodesArray)) {
+                               $res['value'] = $this->getUnique($table, $field, $res['value'], $id);
                        }
                }
 
                        }
                }
 
@@ -1408,15 +1243,21 @@ class t3lib_TCEmain     {
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
         * @return      array           Modified $res array
         */
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
         * @return      array           Modified $res array
         */
-       function checkValue_check($res,$value,$tcaFieldConf,$PP)        {
-               list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
+       function checkValue_check($res, $value, $tcaFieldConf, $PP) {
+               list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
                $itemC = count($tcaFieldConf['items']);
 
                $itemC = count($tcaFieldConf['items']);
-               if (!$itemC)    {$itemC=1;}
-               $maxV = pow(2,$itemC);
+               if (!$itemC) {
+                       $itemC = 1;
+               }
+               $maxV = pow(2, $itemC);
 
 
-               if ($value<0)   {$value=0;}
-               if ($value>$maxV)       {$value=$maxV;}
+               if ($value < 0) {
+                       $value = 0;
+               }
+               if ($value > $maxV) {
+                       $value = $maxV;
+               }
                $res['value'] = $value;
 
                return $res;
                $res['value'] = $value;
 
                return $res;
@@ -1431,12 +1272,12 @@ class t3lib_TCEmain     {
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
         * @return      array           Modified $res array
         */
         * @param       array           Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
         * @return      array           Modified $res array
         */
-       function checkValue_radio($res,$value,$tcaFieldConf,$PP)        {
-               list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
+       function checkValue_radio($res, $value, $tcaFieldConf, $PP) {
+               list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
 
-               if (is_array($tcaFieldConf['items']))   {
-                       foreach($tcaFieldConf['items'] as $set) {
-                               if (!strcmp($set[1],$value))    {
+               if (is_array($tcaFieldConf['items'])) {
+                       foreach ($tcaFieldConf['items'] as $set) {
+                               if (!strcmp($set[1], $value)) {
                                        $res['value'] = $value;
                                        break;
                                }
                                        $res['value'] = $value;
                                        break;
                                }
@@ -1457,13 +1298,13 @@ class t3lib_TCEmain     {
         * @param       string          Field name
         * @return      array           Modified $res array
         */
         * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)   {
+       function checkValue_group_select($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
 
 
-               list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
+               list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
                        // Detecting if value sent is an array and if so, implode it around a comma:
 
                        // Detecting if value sent is an array and if so, implode it around a comma:
-               if (is_array($value))   {
-                       $value = implode(',',$value);
+               if (is_array($value)) {
+                       $value = implode(',', $value);
                }
 
                        // 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.
@@ -1474,42 +1315,42 @@ class t3lib_TCEmain     {
                $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
 
                        // If not multiple is set, then remove duplicates:
                $valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);
 
                        // If not multiple is set, then remove duplicates:
-               if (!$tcaFieldConf['multiple']) {
+               if (!$tcaFieldConf['multiple']) {
                        $valueArray = array_unique($valueArray);
                }
 
                        // If an exclusive key is found, discard all others:
                        $valueArray = array_unique($valueArray);
                }
 
                        // If an exclusive key is found, discard all others:
-               if ($tcaFieldConf['type']=='select' && $tcaFieldConf['exclusiveKeys'])  {
+               if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['exclusiveKeys']) {
                        $exclusiveKeys = t3lib_div::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
                        $exclusiveKeys = t3lib_div::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
-                       foreach($valueArray as $kk => $vv)      {
-                               if (in_array($vv, $exclusiveKeys))      {       // $vv is the item key!
-                                       $valueArray = Array($kk => $vv);
+                       foreach ($valueArray as $kk => $vv) {
+                               if (in_array($vv, $exclusiveKeys)) { // $vv is the item key!
+                                       $valueArray = array($kk => $vv);
                                        break;
                                }
                        }
                }
 
                                        break;
                                }
                        }
                }
 
-               // This could be a good spot for parsing the array through a validation-function which checks if the values are alright (except that database references are not in their final form - but that is the point, isn't it?)
-               // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
+                       // This could be a good spot for parsing the array through a validation-function which checks if the values are alright (except that database references are not in their final form - but that is the point, isn't it?)
+                       // NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!
 
                        // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
 
                        // Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
-               if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode'])       {
+               if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['authMode']) {
                        $preCount = count($valueArray);
                        $preCount = count($valueArray);
-                       foreach($valueArray as $kk => $vv)      {
-                               if (!$this->BE_USER->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode']))        {
+                       foreach ($valueArray as $kk => $vv) {
+                               if (!$this->BE_USER->checkAuthMode($table, $field, $vv, $tcaFieldConf['authMode'])) {
                                        unset($valueArray[$kk]);
                                }
                        }
 
                                // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
                                        unset($valueArray[$kk]);
                                }
                        }
 
                                // During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
-                       if ($preCount && !count($valueArray))   {
+                       if ($preCount && !count($valueArray)) {
                                return array();
                        }
                }
 
                        // For group types:
                                return array();
                        }
                }
 
                        // For group types:
-               if ($tcaFieldConf['type']=='group')     {
-                       switch($tcaFieldConf['internal_type'])  {
+               if ($tcaFieldConf['type'] == 'group') {
+                       switch ($tcaFieldConf['internal_type']) {
                                case 'file_reference':
                                case 'file':
                                        $valueArray = $this->checkValue_group_select_file(
                                case 'file_reference':
                                case 'file':
                                        $valueArray = $this->checkValue_group_select_file(
@@ -1524,30 +1365,31 @@ class t3lib_TCEmain     {
                                        );
                                break;
                                case 'db':
                                        );
                                break;
                                case 'db':
-                                       $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group', $table);
+                                       $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'group', $table, $field);
                                break;
                        }
                }
                        // For select types which has a foreign table attached:
                                break;
                        }
                }
                        // For select types which has a foreign table attached:
-               if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table'])  {
+               if ($tcaFieldConf['type'] == 'select' && $tcaFieldConf['foreign_table']) {
                                // check, if there is a NEW... id in the value, that should be substituded later
                                // check, if there is a NEW... id in the value, that should be substituded later
-                       if (strpos($value, 'NEW') !== false) {
+                       if (strpos($value, 'NEW') !== FALSE) {
                                $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
                                $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
+                               $this->addNewValuesToRemapStackChildIds($valueArray);
                                $this->remapStack[] = array(
                                        'func' => 'checkValue_group_select_processDBdata',
                                $this->remapStack[] = array(
                                        'func' => 'checkValue_group_select_processDBdata',
-                                       'args' => array($valueArray,$tcaFieldConf,$id,$status,'select',$table),
+                                       'args' => array($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field),
                                        'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
                                        'field' => $field
                                );
                                        'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
                                        'field' => $field
                                );
-                               $unsetResult = true;
+                               $unsetResult = TRUE;
                        } else {
                        } else {
-                               $valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select', $table);
+                               $valueArray = $this->checkValue_group_select_processDBdata($valueArray, $tcaFieldConf, $id, $status, 'select', $table, $field);
                        }
                }
 
                if (!$unsetResult) {
                        }
                }
 
                if (!$unsetResult) {
-                       $newVal=$this->checkValue_checkMax($tcaFieldConf, $valueArray);
-                       $res['value'] = implode(',',$newVal);
+                       $newVal = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
+                       $res['value'] = implode(',', $newVal);
                } else {
                        unset($res['value']);
                }
                } else {
                        unset($res['value']);
                }
@@ -1569,25 +1411,25 @@ class t3lib_TCEmain     {
         * @return      array           Modified value array
         * @see checkValue_group_select()
         */
         * @return      array           Modified value array
         * @see checkValue_group_select()
         */
-       function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)        {
+       function checkValue_group_select_file($valueArray, $tcaFieldConf, $curValue, $uploadedFileArray, $status, $table, $id, $recFID) {
 
 
-               if (!$this->bypassFileHandling) {       // If filehandling should NOT be bypassed, do processing:
+               if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
 
                                // If any files are uploaded, add them to value array
                        if (is_array($uploadedFileArray) &&
                                $uploadedFileArray['name'] &&
 
                                // If any files are uploaded, add them to value array
                        if (is_array($uploadedFileArray) &&
                                $uploadedFileArray['name'] &&
-                               strcmp($uploadedFileArray['tmp_name'],'none'))  {
-                                       $valueArray[]=$uploadedFileArray['tmp_name'];
-                                       $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
+                               strcmp($uploadedFileArray['tmp_name'], 'none')) {
+                               $valueArray[] = $uploadedFileArray['tmp_name'];
+                               $this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
                        }
 
                                // Creating fileFunc object.
                        }
 
                                // Creating fileFunc object.
-                       if (!$this->fileFunc)   {
+                       if (!$this->fileFunc) {
                                $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
                                $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
-                               $this->include_filefunctions=1;
+                               $this->include_filefunctions = 1;
                        }
                                // Setting permitted extensions.
                        }
                                // Setting permitted extensions.
-                       $all_files = Array();
+                       $all_files = array();
                        $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
                        $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
                        $all_files['ftpspace'] = $all_files['webspace'];
                        $all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
                        $all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
                        $all_files['ftpspace'] = $all_files['webspace'];
@@ -1596,15 +1438,15 @@ class t3lib_TCEmain     {
 
                        // If there is an upload folder defined:
                if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
 
                        // If there is an upload folder defined:
                if ($tcaFieldConf['uploadfolder'] && $tcaFieldConf['internal_type'] == 'file') {
-                       if (!$this->bypassFileHandling) {       // If filehandling should NOT be bypassed, do processing:
+                       if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
                                        // For logging..
                                        // For logging..
-                               $propArr = $this->getRecordProperties($table,$id);
+                               $propArr = $this->getRecordProperties($table, $id);
 
                                        // Get destrination path:
                                $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
 
                                        // If we are updating:
 
                                        // Get destrination path:
                                $dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);
 
                                        // If we are updating:
-                               if ($status=='update')  {
+                               if ($status == 'update') {
 
                                                // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
                                                // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
 
                                                // Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
                                                // Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
@@ -1615,70 +1457,71 @@ class t3lib_TCEmain     {
                                                // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
                                                // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
                                                // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
                                                // The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sent was based on uid 123 and hence contains the filename "logo.gif" from the original.
                                                // The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
                                                // If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
-                                       if ($this->autoVersioningUpdate===TRUE) {
-                                               foreach($valueArray as $key => $theFile)        {
-                                                       if ($theFile===basename($theFile))      {       // If it is an already attached file...
-                                                               $valueArray[$key] = PATH_site.$tcaFieldConf['uploadfolder'].'/'.$theFile;
+                                       if ($this->autoVersioningUpdate === TRUE) {
+                                               foreach ($valueArray as $key => $theFile) {
+                                                       if ($theFile === basename($theFile)) { // If it is an already attached file...
+                                                               $valueArray[$key] = PATH_site . $tcaFieldConf['uploadfolder'] . '/' . $theFile;
                                                        }
                                                }
                                        }
 
                                                // Finding the CURRENT files listed, either from MM or from the current record.
                                                        }
                                                }
                                        }
 
                                                // Finding the CURRENT files listed, either from MM or from the current record.
-                                       $theFileValues=array();
-                                       if ($tcaFieldConf['MM'])        {       // If MM relations for the files also!
+                                       $theFileValues = array();
+                                       if ($tcaFieldConf['MM']) { // If MM relations for the files also!
                                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
                                                /* @var $dbAnalysis t3lib_loadDBGroup */
                                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
                                                /* @var $dbAnalysis t3lib_loadDBGroup */
-                                               $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
+                                               $dbAnalysis->start('', 'files', $tcaFieldConf['MM'], $id);
                                                foreach ($dbAnalysis->itemArray as $item) {
                                                        if ($item['id']) {
                                                                $theFileValues[] = $item['id'];
                                                        }
                                                }
                                        } else {
                                                foreach ($dbAnalysis->itemArray as $item) {
                                                        if ($item['id']) {
                                                                $theFileValues[] = $item['id'];
                                                        }
                                                }
                                        } else {
-                                               $theFileValues=t3lib_div::trimExplode(',',$curValue,1);
+                                               $theFileValues = t3lib_div::trimExplode(',', $curValue, 1);
                                        }
                                        }
+                                       $currentFilesForHistory = implode(',', $theFileValues);
 
                                                // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
 
                                                // DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
-                                       if (count($theFileValues))      {
+                                       if (count($theFileValues)) {
                                                        // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
                                                        // Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
-                                               foreach($valueArray as $key => $theFile)        {
-                                                       if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile),'/'))   {
-                                                               $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues,$theFile);
+                                               foreach ($valueArray as $key => $theFile) {
+                                                       if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile), '/')) {
+                                                               $theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues, $theFile);
                                                        }
                                                }
 
                                                        // This array contains the filenames in the uploadfolder that should be deleted:
                                                        }
                                                }
 
                                                        // This array contains the filenames in the uploadfolder that should be deleted:
-                                               foreach($theFileValues as $key => $theFile)     {
+                                               foreach ($theFileValues as $key => $theFile) {
                                                        $theFile = trim($theFile);
                                                        $theFile = trim($theFile);
-                                                       if (@is_file($dest.'/'.$theFile))       {
-                                                               $this->removeFilesStore[]=$dest.'/'.$theFile;
+                                                       if (@is_file($dest . '/' . $theFile)) {
+                                                               $this->removeFilesStore[] = $dest . '/' . $theFile;
                                                        } elseif ($theFile) {
                                                        } elseif ($theFile) {
-                                                               $this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
+                                                               $this->log($table, $id, 5, 0, 1, "Could not delete file '%s' (does not exist). (%s)", 10, array($dest . '/' . $theFile, $recFID), $propArr['event_pid']);
                                                        }
                                                }
                                        }
                                }
 
                                        // Traverse the submitted values:
                                                        }
                                                }
                                        }
                                }
 
                                        // Traverse the submitted values:
-                               foreach($valueArray as $key => $theFile)        {
+                               foreach ($valueArray as $key => $theFile) {
                                                // NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
                                                // NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
-                                       if (strstr(t3lib_div::fixWindowsFilePath($theFile),'/'))        {
+                                       if (strstr(t3lib_div::fixWindowsFilePath($theFile), '/')) {
                                                        // Init:
                                                $maxSize = intval($tcaFieldConf['max_size']);
                                                        // Init:
                                                $maxSize = intval($tcaFieldConf['max_size']);
-                                               $cmd='';
-                                               $theDestFile='';                // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
+                                               $cmd = '';
+                                               $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
 
                                                        // Check various things before copying file:
 
                                                        // Check various things before copying file:
-                                               if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile)))      {               // File and destination must exist
+                                               if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile))) { // File and destination must exist
 
 
-                                                               // Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
-                                                       if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name'])     {
+                                                               // Finding size.
+                                                       if (is_uploaded_file($theFile) && $theFile == $uploadedFileArray['tmp_name']) {
                                                                $fileSize = $uploadedFileArray['size'];
                                                        } else {
                                                                $fileSize = filesize($theFile);
                                                        }
 
                                                                $fileSize = $uploadedFileArray['size'];
                                                        } else {
                                                                $fileSize = filesize($theFile);
                                                        }
 
-                                                       if (!$maxSize || $fileSize<=($maxSize*1024))    {       // Check file size:
+                                                       if (!$maxSize || $fileSize <= ($maxSize * 1024)) { // Check file size:
                                                                        // Prepare filename:
                                                                $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                                                $fI = t3lib_div::split_fileref($theEndFileName);
                                                                        // Prepare filename:
                                                                $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                                                $fI = t3lib_div::split_fileref($theEndFileName);
@@ -1688,60 +1531,93 @@ class t3lib_TCEmain     {
                                                                        $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
 
                                                                                // If we have a unique destination filename, then write the file:
                                                                        $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);
 
                                                                                // If we have a unique destination filename, then write the file:
-                                                                       if ($theDestFile)       {
-                                                                               t3lib_div::upload_copy_move($theFile,$theDestFile);
+                                                                       if ($theDestFile) {
+                                                                               t3lib_div::upload_copy_move($theFile, $theDestFile);
+
+                                                                                       // Hook for post-processing the upload action
+                                                                               if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'])) {
+                                                                                       foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processUpload'] as $classRef) {
+                                                                                               $hookObject = t3lib_div::getUserObj($classRef);
+
+                                                                                               if (!($hookObject instanceof t3lib_TCEmain_processUploadHook)) {
+                                                                                                       throw new UnexpectedValueException('$hookObject must implement interface t3lib_TCEmain_processUploadHook', 1279962349);
+                                                                                               }
+
+                                                                                               $hookObject->processUpload_postProcessAction($theDestFile, $this);
+                                                                                       }
+                                                                               }
+
                                                                                $this->copiedFileMap[$theFile] = $theDestFile;
                                                                                clearstatcache();
                                                                                $this->copiedFileMap[$theFile] = $theDestFile;
                                                                                clearstatcache();
-                                                                               if (!@is_file($theDestFile))    $this->log($table,$id,5,0,1,"Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)",16,array($theFile, dirname($theDestFile), $recFID),$propArr['event_pid']);
-                                                                       } 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']);
+                                                                               if (!@is_file($theDestFile)) {
+                                                                                       $this->log($table, $id, 5, 0, 1, "Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)", 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
+                                                                               }
+                                                                       } 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, "File extension '%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']);
+                                               }
 
                                                        // 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 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))     {
+                                               if (@is_file($theDestFile)) {
                                                        $info = t3lib_div::split_fileref($theDestFile);
                                                        $info = t3lib_div::split_fileref($theDestFile);
-                                                       $valueArray[$key]=$info['file']; // The value is set to the new filename
+                                                       $valueArray[$key] = $info['file']; // The value is set to the new filename
                                                } else {
                                                } else {
-                                                       unset($valueArray[$key]);       // The value is set to the new filename
+                                                       unset($valueArray[$key]); // The value is set to the new filename
                                                }
                                        }
                                }
                        }
 
                                // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
                                                }
                                        }
                                }
                        }
 
                                // If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
-                       if ($tcaFieldConf['MM'])        {
+                       if ($tcaFieldConf['MM']) {
                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
                                /* @var $dbAnalysis t3lib_loadDBGroup */
                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
                                /* @var $dbAnalysis t3lib_loadDBGroup */
-                               $dbAnalysis->tableArray['files']=array();       // dummy
+                               $dbAnalysis->tableArray['files'] = array(); // dummy
 
                                foreach ($valueArray as $key => $theFile) {
                                                // explode files
 
                                foreach ($valueArray as $key => $theFile) {
                                                // explode files
-                                               $dbAnalysis->itemArray[]['id']=$theFile;
+                                       $dbAnalysis->itemArray[]['id'] = $theFile;
                                }
                                }
-                               if ($status=='update')  {
-                                       $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
+                               if ($status == 'update') {
+                                       $dbAnalysis->writeMM($tcaFieldConf['MM'], $id, 0);
+                                       $newFiles = implode(',', $dbAnalysis->getValueArray());
+                                       list(, , $recFieldName) = explode(':', $recFID);
+                                       if ($currentFilesForHistory != $newFiles) {
+                                               $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = $currentFilesForHistory;
+                                               $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = $newFiles;
+                                       } else {
+                                               $this->mmHistoryRecords[$table . ':' . $id]['oldRecord'][$recFieldName] = '';
+                                               $this->mmHistoryRecords[$table . ':' . $id]['newRecord'][$recFieldName] = '';
+                                       }
                                } else {
                                } else {
-                                       $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);     // This will be traversed later to execute the actions
+                                       $this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0); // This will be traversed later to execute the actions
                                }
                                $valueArray = $dbAnalysis->countItems();
                        }
                        //store path relative to site root (if uploadfolder is not set or internal_type is file_reference)
                } else {
                                }
                                $valueArray = $dbAnalysis->countItems();
                        }
                        //store path relative to site root (if uploadfolder is not set or internal_type is file_reference)
                } else {
-                       if (count($valueArray)){
-                               if (!$this->bypassFileHandling) {       // If filehandling should NOT be bypassed, do processing:
+                       if (count($valueArray)) {
+                               if (!$this->bypassFileHandling) { // If filehandling should NOT be bypassed, do processing:
                                        $propArr = $this->getRecordProperties($table, $id); // For logging..
                                        $propArr = $this->getRecordProperties($table, $id); // For logging..
-                                       foreach($valueArray as &$theFile){
+                                       foreach ($valueArray as &$theFile) {
 
                                                        // if alernative File Path is set for the file, then it was an import
 
                                                        // if alernative File Path is set for the file, then it was an import
-                                               if ($this->alternativeFilePath[$theFile]){
+                                               if ($this->alternativeFilePath[$theFile]) {
 
                                                                // don't import the file if it already exists
                                                        if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
                                                                $theFile = PATH_site . $this->alternativeFilePath[$theFile];
 
                                                                // import the file
 
                                                                // don't import the file if it already exists
                                                        if (@is_file(PATH_site . $this->alternativeFilePath[$theFile])) {
                                                                $theFile = PATH_site . $this->alternativeFilePath[$theFile];
 
                                                                // import the file
-                                                       } elseif (@is_file($theFile)){
+                                                       } elseif (@is_file($theFile)) {
                                                                $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
                                                                if (!@is_dir($dest)) {
                                                                        t3lib_div::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
                                                                $dest = dirname(PATH_site . $this->alternativeFilePath[$theFile]);
                                                                if (!@is_dir($dest)) {
                                                                        t3lib_div::mkdir_deep(PATH_site, dirname($this->alternativeFilePath[$theFile]) . '/');
@@ -1750,10 +1626,10 @@ class t3lib_TCEmain     {
                                                                        // Init:
                                                                $maxSize = intval($tcaFieldConf['max_size']);
                                                                $cmd = '';
                                                                        // Init:
                                                                $maxSize = intval($tcaFieldConf['max_size']);
                                                                $cmd = '';
-                                                               $theDestFile = '';              // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
+                                                               $theDestFile = ''; // Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!
                                                                $fileSize = filesize($theFile);
 
                                                                $fileSize = filesize($theFile);
 
-                                                               if (!$maxSize || $fileSize <= ($maxSize * 1024))        {       // Check file size:
+                                                               if (!$maxSize || $fileSize <= ($maxSize * 1024)) { // Check file size:
                                                                                // Prepare filename:
                                                                        $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                                                        $fI = t3lib_div::split_fileref($theEndFileName);
                                                                                // Prepare filename:
                                                                        $theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
                                                                        $fI = t3lib_div::split_fileref($theEndFileName);
@@ -1763,17 +1639,25 @@ class t3lib_TCEmain     {
                                                                                $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
 
                                                                                        // Write the file:
                                                                                $theDestFile = PATH_site . $this->alternativeFilePath[$theFile];
 
                                                                                        // Write the file:
-                                                                               if ($theDestFile)       {
+                                                                               if ($theDestFile) {
                                                                                        t3lib_div::upload_copy_move($theFile, $theDestFile);
                                                                                        $this->copiedFileMap[$theFile] = $theDestFile;
                                                                                        clearstatcache();
                                                                                        t3lib_div::upload_copy_move($theFile, $theDestFile);
                                                                                        $this->copiedFileMap[$theFile] = $theDestFile;
                                                                                        clearstatcache();
-                                                                                       if (!@is_file($theDestFile)) $this->log($table, $id, 5, 0, 1, "Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)", 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
-                                                                               } 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']);
+                                                                                       if (!@is_file($theDestFile)) {
+                                                                                               $this->log($table, $id, 5, 0, 1, "Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)", 16, array($theFile, dirname($theDestFile), $recFID), $propArr['event_pid']);
+                                                                                       }
+                                                                               } 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, "File extension '%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']);
+                                                               }
 
                                                                        // 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 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))     {
+                                                               if (@is_file($theDestFile)) {
                                                                        $theFile = $theDestFile; // The value is set to the new filename
                                                                } else {
                                                                        unset($theFile); // The value is set to the new filename
                                                                        $theFile = $theDestFile; // The value is set to the new filename
                                                                } else {
                                                                        unset($theFile); // The value is set to the new filename
@@ -1785,6 +1669,7 @@ class t3lib_TCEmain       {
                                                        $theFile = substr($theFile, strlen(PATH_site));
                                                }
                                        }
                                                        $theFile = substr($theFile, strlen(PATH_site));
                                                }
                                        }
+                                       unset($theFile);
                                }
                        }
                }
                                }
                        }
                }
@@ -1804,55 +1689,59 @@ class t3lib_TCEmain     {
         * @param       string          Field name
         * @return      array           Modified $res array
         */
         * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)   {
-               list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;
+       function checkValue_flex($res, $value, $tcaFieldConf, $PP, $uploadedFiles, $field) {
+               list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
 
-               if (is_array($value))   {
+               if (is_array($value)) {
 
                                // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
                                // The problem is, that when copying a page, flexfrom XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that sake, the t3lib_BEfunc::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
 
                                // This value is necessary for flex form processing to happen on flexform fields in page records when they are copied.
                                // The problem is, that when copying a page, flexfrom XML comes along in the array for the new record - but since $this->checkValue_currentRecord does not have a uid or pid for that sake, the t3lib_BEfunc::getFlexFormDS() function returns no good DS. For new records we do know the expected PID so therefore we send that with this special parameter. Only active when larger than zero.
-                       $newRecordPidValue = $status=='new' ? $realPid : 0;
+                       $newRecordPidValue = $status == 'new' ? $realPid : 0;
 
                                // Get current value array:
 
                                // Get current value array:
-                       $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table,'',TRUE,$newRecordPidValue);
+                       $dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf, $this->checkValue_currentRecord, $table, '', TRUE, $newRecordPidValue);
 
                        $currentValueArray = t3lib_div::xml2array($curValue);
 
                        $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...
+                       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:
 
                                // Evaluation of input values:
-                       $value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);
+                       $value['data'] = $this->checkValue_flex_procInData($value['data'], $currentValueArray['data'], $uploadedFiles['data'], $dataStructArray, $PP);
 
                                // Create XML and convert charsets from input value:
 
                                // Create XML and convert charsets from input value:
-                       $xmlValue = $this->checkValue_flexArray2Xml($value,TRUE);
+                       $xmlValue = $this->checkValue_flexArray2Xml($value, TRUE);
 
                                // If we wanted to set UTF fixed:
 
                                // 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;
+                               // $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).
 
                                // 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))       {
+                       if (is_array($currentValueArray)) {
                                $arrValue = t3lib_div::xml2array($xmlValue);
                                $arrValue = t3lib_div::xml2array($xmlValue);
-                               $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
-                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
+                               $arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray, $arrValue);
+                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
                        }
 
                                // Action commands (sorting order and removals of elements)
                        $actionCMDs = t3lib_div::_GP('_ACTION_FLEX_FORMdata');
                        }
 
                                // Action commands (sorting order and removals of elements)
                        $actionCMDs = t3lib_div::_GP('_ACTION_FLEX_FORMdata');
-                       if (is_array($actionCMDs[$table][$id][$field]['data'])) {
+                       if (is_array($actionCMDs[$table][$id][$field]['data'])) {
                                $arrValue = t3lib_div::xml2array($xmlValue);
                                $arrValue = t3lib_div::xml2array($xmlValue);
-                               $this->_ACTION_FLEX_FORMdata($arrValue['data'],$actionCMDs[$table][$id][$field]['data']);
-                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
+                               $this->_ACTION_FLEX_FORMdata($arrValue['data'], $actionCMDs[$table][$id][$field]['data']);
+                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue, TRUE);
                        }
 
                                // Create the value XML:
                        }
 
                                // Create the value XML:
-                       $res['value']='';
-                       $res['value'].=$xmlValue;
-               } else {        // Passthrough...:
-                       $res['value']=$value;
+                       $res['value'] = '';
+                       $res['value'] .= $xmlValue;
+               } else { // Passthrough...:
+                       $res['value'] = $value;
                }
 
                return $res;
                }
 
                return $res;
@@ -1865,7 +1754,7 @@ class t3lib_TCEmain       {
         * @param       boolean         If set, the XML prologue is returned as well.
         * @return      string          Input array converted to XML
         */
         * @param       boolean         If set, the XML prologue is returned as well.
         * @return      string          Input array converted to XML
         */
-       function checkValue_flexArray2Xml($array, $addPrologue=FALSE)   {
+       function checkValue_flexArray2Xml($array, $addPrologue = FALSE) {
                $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
                /* @var $flexObj t3lib_flexformtools */
                return $flexObj->flexArray2Xml($array, $addPrologue);
                $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
                /* @var $flexObj t3lib_flexformtools */
                return $flexObj->flexArray2Xml($array, $addPrologue);
@@ -1878,27 +1767,27 @@ class t3lib_TCEmain     {
         * @param       array           $deleteCMDS: ...         *
         * @return      void
         */
         * @param       array           $deleteCMDS: ...         *
         * @return      void
         */
-       function _ACTION_FLEX_FORMdata(&$valueArray,$actionCMDs)        {
-               if (is_array($valueArray) && is_array($actionCMDs))     {
-                       foreach($actionCMDs as $key => $value)  {
-                               if ($key=='_ACTION')    {
+       function _ACTION_FLEX_FORMdata(&$valueArray, $actionCMDs) {
+               if (is_array($valueArray) && is_array($actionCMDs)) {
+                       foreach ($actionCMDs as $key => $value) {
+                               if ($key == '_ACTION') {
                                                // First, check if there are "commands":
                                                // First, check if there are "commands":
-                                       if (current($actionCMDs[$key])!=="")    {
+                                       if (current($actionCMDs[$key]) !== "") {
                                                asort($actionCMDs[$key]);
                                                $newValueArray = array();
                                                asort($actionCMDs[$key]);
                                                $newValueArray = array();
-                                               foreach($actionCMDs[$key] as $idx => $order)    {
-                                                       if (substr($idx,0,3)=="ID-")    {
+                                               foreach ($actionCMDs[$key] as $idx => $order) {
+                                                       if (substr($idx, 0, 3) == "ID-") {
                                                                $idx = $this->newIndexMap[$idx];
                                                        }
                                                                $idx = $this->newIndexMap[$idx];
                                                        }
-                                                       if ($order!="DELETE")   {       // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost files unless we act on this delete operation by traversing and deleting files that were referred to.
+                                                       if ($order != "DELETE") { // Just one reflection here: It is clear that when removing elements from a flexform, then we will get lost files unless we act on this delete operation by traversing and deleting files that were referred to.
                                                                $newValueArray[$idx] = $valueArray[$idx];
                                                        }
                                                        unset($valueArray[$idx]);
                                                }
                                                                $newValueArray[$idx] = $valueArray[$idx];
                                                        }
                                                        unset($valueArray[$idx]);
                                                }
-                                               $valueArray = t3lib_div::array_merge($newValueArray,$valueArray);
+                                               $valueArray = t3lib_div::array_merge($newValueArray, $valueArray);
                                        }
                                        }
-                               } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key]))      {
-                                       $this->_ACTION_FLEX_FORMdata($valueArray[$key],$actionCMDs[$key]);
+                               } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key])) {
+                                       $this->_ACTION_FLEX_FORMdata($valueArray[$key], $actionCMDs[$key]);
                                }
                        }
                }
                                }
                        }
                }
@@ -1915,11 +1804,11 @@ class t3lib_TCEmain     {
         * @param       string          Field name
         * @return      array           Modified $res array
         */
         * @param       string          Field name
         * @return      array           Modified $res array
         */
-       function checkValue_inline($res,$value,$tcaFieldConf,$PP,$field)        {
+       function checkValue_inline($res, $value, $tcaFieldConf, $PP, $field) {
                list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
                list($table, $id, $curValue, $status, $realPid, $recFID) = $PP;
 
-               if (!$tcaFieldConf['foreign_table'])    {
-                       return false;   // Fatal error, inline fields should always have a foreign_table defined
+               if (!$tcaFieldConf['foreign_table']) {
+                       return FALSE; // Fatal error, inline fields should always have a foreign_table defined
                }
 
                        // When values are sent they come as comma-separated values which are exploded by this function:
                }
 
                        // When values are sent they come as comma-separated values which are exploded by this function:
@@ -1931,8 +1820,9 @@ class t3lib_TCEmain       {
                        // Example for received data:
                        // $value = 45,NEW4555fdf59d154,12,123
                        // We need to decide whether we use the stack or can save the relation directly.
                        // Example for received data:
                        // $value = 45,NEW4555fdf59d154,12,123
                        // We need to decide whether we use the stack or can save the relation directly.
-               if(strpos($value, 'NEW') !== false || !t3lib_div::testInt($id)) {
+               if (strpos($value, 'NEW') !== FALSE || !t3lib_utility_Math::canBeInterpretedAsInteger($id)) {
                        $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
                        $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
+                       $this->addNewValuesToRemapStackChildIds($valueArray);
                        $this->remapStack[] = array(
                                'func' => 'checkValue_inline_processDBdata',
                                'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
                        $this->remapStack[] = array(
                                'func' => 'checkValue_inline_processDBdata',
                                'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
@@ -1940,7 +1830,7 @@ class t3lib_TCEmain       {
                                'field' => $field
                        );
                        unset($res['value']);
                                'field' => $field
                        );
                        unset($res['value']);
-               } elseif($value || t3lib_div::testInt($id)) {
+               } elseif ($value || t3lib_utility_Math::canBeInterpretedAsInteger($id)) {
                        $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
                }
 
                        $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
                }
 
@@ -1956,41 +1846,30 @@ class t3lib_TCEmain     {
         * @return      array           The truncated value array of items
         */
        function checkValue_checkMax($tcaFieldConf, $valueArray) {
         * @return      array           The truncated value array of items
         */
        function checkValue_checkMax($tcaFieldConf, $valueArray) {
-               // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
+                       // BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...
 
                $valueArrayC = count($valueArray);
 
                        // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
 
                $valueArrayC = count($valueArray);
 
                        // NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
-               $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']):1;
-               if ($valueArrayC > $maxI)       {$valueArrayC=$maxI;}   // Checking for not too many elements
+               $maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']) : 1;
+               if ($valueArrayC > $maxI) {
+                       $valueArrayC = $maxI;
+               } // Checking for not too many elements
 
                        // Dumping array to list
 
                        // Dumping array to list
-               $newVal=array();
-               foreach($valueArray as $nextVal)        {
-                       if ($valueArrayC==0)    {break;}
+               $newVal = array();
+               foreach ($valueArray as $nextVal) {
+                       if ($valueArrayC == 0) {
+                               break;
+                       }
                        $valueArrayC--;
                        $valueArrayC--;
-                       $newVal[]=$nextVal;
+                       $newVal[] = $nextVal;
                }
 
                return $newVal;
        }
 
 
                }
 
                return $newVal;
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /*********************************************
         *
         * Helper functions for evaluation functions.
        /*********************************************
         *
         * Helper functions for evaluation functions.
@@ -2007,29 +1886,34 @@ class t3lib_TCEmain     {
         * @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).
         */
         * @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;
+       function getUnique($table, $field, $value, $id, $newPid = 0) {
 
                        // Initialize:
                t3lib_div::loadTCA($table);
 
                        // Initialize:
                t3lib_div::loadTCA($table);
-               $whereAdd='';
-               $newValue='';
-               if (intval($newPid))    { $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AN