Removed the tree filter toggle
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tcemain.php
index 93a74ea..e94c908 100755 (executable)
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
-*  (c) 1999-2007 Kasper Skaarhoj (kasperYYYY@typo3.com)
+*  (c) 1999-2008 Kasper Skaarhoj (kasperYYYY@typo3.com)
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
@@ -256,6 +256,8 @@ class t3lib_TCEmain {
        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 $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!
@@ -287,6 +289,7 @@ class t3lib_TCEmain {
        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.
 
 
 
@@ -345,8 +348,14 @@ class t3lib_TCEmain        {
        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
+       /**
+        * 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.
@@ -383,6 +392,10 @@ class t3lib_TCEmain        {
                if ($GLOBALS['BE_USER']->uc['recursiveDelete'])    {
                        $this->deleteTree = 1;
                }
+               
+               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'];
@@ -768,6 +781,7 @@ class t3lib_TCEmain {
                                                                                        // 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)) {
                                                                                        $tce = t3lib_div::makeInstance('t3lib_TCEmain');
+                                                                                       /* @var $tce t3lib_TCEmain  */
                                                                                        $tce->stripslashes_values = 0;
 
                                                                                                // Setting up command for creating a new version of the record:
@@ -914,9 +928,19 @@ class t3lib_TCEmain        {
 
                        // Process the stack of relations to remap/correct
                $this->processRemapStack();
-
                $this->dbAnalysisStoreExec();
                $this->removeRegisteredFiles();
+
+               /*
+                * Hook: processDatamap_afterAllOperations
+                * 
+                * Note: When this hook gets called, all operations on the submitted data have been finished.
+                */
+               foreach($hookObjectsArr as $hookObj) {
+                       if (method_exists($hookObj, 'processDatamap_afterAllOperations')) {
+                               $hookObj->processDatamap_afterAllOperations($this);
+                       }
+               }
        }
 
        /**
@@ -1077,7 +1101,7 @@ class t3lib_TCEmain       {
                                                                        $fieldArray[$field]=$res['value'];
 
                                                                                // Add the value of the original record to the diff-storage content:
-                                                                       if ($TCA[$table]['ctrl']['transOrigDiffSourceField'])   {
+                                                                       if ($this->updateModeL10NdiffData && $TCA[$table]['ctrl']['transOrigDiffSourceField'])  {
                                                                                $originalLanguage_diffStorage[$field] = $originalLanguageRecord[$field];
                                                                                $diffStorageFlag = TRUE;
                                                                        }
@@ -1147,6 +1171,7 @@ class t3lib_TCEmain       {
                                        $mixedRec = array_merge($currentRecord,$fieldArray);
                                        $SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
                                        $parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
+                                       /* @var $parseHTML t3lib_parsehtml_proc */
                                        $parseHTML->init('','');
 
                                        $eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
@@ -1570,6 +1595,7 @@ class t3lib_TCEmain       {
                                        $theFileValues=array();
                                        if ($tcaFieldConf['MM'])        {       // If MM relations for the files also!
                                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                               /* @var $dbAnalysis t3lib_loadDBGroup */
                                                $dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
                                                reset($dbAnalysis->itemArray);
                                                while (list($somekey,$someval)=each($dbAnalysis->itemArray))    {
@@ -1655,6 +1681,7 @@ class t3lib_TCEmain       {
                                // 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'])        {
                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                               /* @var $dbAnalysis t3lib_loadDBGroup */
                                $dbAnalysis->tableArray['files']=array();       // dummy
 
                                reset($valueArray);
@@ -1722,27 +1749,11 @@ class t3lib_TCEmain     {
                                $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
                        }
 
-                               // Temporary fix to delete flex form elements:
-                       $deleteCMDs = t3lib_div::_GP('_DELETE_FLEX_FORMdata');
-                       if (is_array($deleteCMDs[$table][$id][$field]['data'])) {
-                               $arrValue = t3lib_div::xml2array($xmlValue);
-                               $this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
-                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
-                       }
-
-                               // Temporary fix to move flex form elements up:
-                       $moveCMDs = t3lib_div::_GP('_MOVEUP_FLEX_FORMdata');
-                       if (is_array($moveCMDs[$table][$id][$field]['data']))   {
-                               $arrValue = t3lib_div::xml2array($xmlValue);
-                               $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'up');
-                               $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
-                       }
-
-                               // Temporary fix to move flex form elements down:
-                       $moveCMDs = t3lib_div::_GP('_MOVEDOWN_FLEX_FORMdata');
-                       if (is_array($moveCMDs[$table][$id][$field]['data']))   {
+                               // Action commands (sorting order and removals of elements)
+                       $actionCMDs = t3lib_div::_GP('_ACTION_FLEX_FORMdata');
+                       if (is_array($actionCMDs[$table][$id][$field]['data'])) {
                                $arrValue = t3lib_div::xml2array($xmlValue);
-                               $this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'down');
+                               $this->_ACTION_FLEX_FORMdata($arrValue['data'],$actionCMDs[$table][$id][$field]['data']);
                                $xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
                        }
 
@@ -1765,77 +1776,38 @@ class t3lib_TCEmain     {
         */
        function checkValue_flexArray2Xml($array, $addPrologue=FALSE)   {
                $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
+               /* @var $flexObj t3lib_flexformtools */
                return $flexObj->flexArray2Xml($array, $addPrologue);
        }
 
        /**
-        * Deletes a flex form element
+        * Actions for flex form element (move, delete)
         *
         * @param       array           &$valueArrayToRemoveFrom: by reference
         * @param       array           $deleteCMDS: ...         *
         * @return      void
         */
-       function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)    {
-               if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS)) {
-                       foreach($deleteCMDS as $key => $value)  {
-                               if (is_array($deleteCMDS[$key]))        {
-                                       $this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
-                               } else {
-                                       unset($valueArrayToRemoveFrom[$key]);
-                               }
-                       }
-               }
-       }
-
-       /**
-        * Deletes a flex form element
-        *
-        * TODO: Like _DELETE_FLEX_FORMdata, this is only a temporary solution!
-        *
-        * @param       array           &$valueArrayToMoveIn: by reference
-        * @param       array           $moveCMDS: ...   *
-        * @param       string          $direction: 'up' or 'down'
-        * @return      void
-        */
-       function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)       {
-               if (is_array($valueArrayToMoveIn) && is_array($moveCMDS))       {
-
-                               // Only execute the first move command:
-                       list ($key, $value) = each ($moveCMDS);
-
-                       if (is_array($moveCMDS[$key]))  {
-                               $this->_MOVE_FLEX_FORMdata($valueArrayToMoveIn[$key],$moveCMDS[$key], $direction);
-                       } else {
-
-                                       // Keys may not be arranged in numerical order and there could be gaps. Therefore we create a nice index first:
-                               $keyOrder = array();
-                               $keyIndex = 0;
-                               $c=0;
-                               foreach($valueArrayToMoveIn as $kk => $vv)      {
-                                       if (is_array($vv))      {       // Sections are expected to be arrays and if not, it's gotta be an error in the XML data.
-                                               $c++;
-                                               $keyOrder[$c] = $kk;
-                                               if ($kk===$key) $keyIndex=$c;
-                                       }
-                               }
-
-                               if ($keyIndex>0)        {
-                                       switch ($direction) {
-                                               case 'up':
-                                                       if (isset($keyOrder[$keyIndex-1])) {
-                                                               $tmpArr = $valueArrayToMoveIn[$keyOrder[$keyIndex]];
-                                                               $valueArrayToMoveIn[$keyOrder[$keyIndex]] = $valueArrayToMoveIn[$keyOrder[$keyIndex-1]];
-                                                               $valueArrayToMoveIn[$keyOrder[$keyIndex-1]] = $tmpArr;
+       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":
+                                       if (current($actionCMDs[$key])!=="")    {
+                                               asort($actionCMDs[$key]);
+                                               $newValueArray = array();
+                                               foreach($actionCMDs[$key] as $idx => $order)    {
+                                                       if (substr($idx,0,3)=="ID-")    {
+                                                               $idx = $this->newIndexMap[$idx];
                                                        }
-                                               break;
-                                               case 'down':
-                                                       if (isset($keyOrder[$keyIndex+1])) {
-                                                               $tmpArr = $valueArrayToMoveIn[$keyOrder[$keyIndex]];
-                                                               $valueArrayToMoveIn[$keyOrder[$keyIndex]] = $valueArrayToMoveIn[$keyOrder[$keyIndex+1]];
-                                                               $valueArrayToMoveIn[$keyOrder[$keyIndex+1]] = $tmpArr;
+                                                       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];
                                                        }
-                                               break;
+                                                       unset($valueArray[$idx]);
+                                               }
+                                               $valueArray = t3lib_div::array_merge($newValueArray,$valueArray);
                                        }
+                               } elseif (is_array($actionCMDs[$key]) && isset($valueArray[$key]))      {
+                                       $this->_ACTION_FLEX_FORMdata($valueArray[$key],$actionCMDs[$key]);
                                }
                        }
                }
@@ -1853,7 +1825,7 @@ class t3lib_TCEmain       {
         * @return      array           Modified $res array
         */
        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
@@ -1871,17 +1843,14 @@ class t3lib_TCEmain     {
                if(strpos($value, 'NEW') !== false || !t3lib_div::testInt($id)) {
                        $this->remapStackRecords[$table][$id] = array('remapStackIndex' => count($this->remapStack));
                        $this->remapStack[] = array(
-                               'func' => 'checkValue_group_select_processDBdata',
-                               'args' => array($valueArray,$tcaFieldConf,$id,$status,'inline',$table),
-                               'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 5),
+                               'func' => 'checkValue_inline_processDBdata',
+                               'args' => array($valueArray, $tcaFieldConf, $id, $status, $table, $field),
+                               'pos' => array('valueArray' => 0, 'tcaFieldConf' => 1, 'id' => 2, 'table' => 4),
                                'field' => $field
                        );
                        unset($res['value']);
                } elseif($value || t3lib_div::testInt($id)) {
-                       $newValueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'inline', $table);
-                               // Checking that the number of items is correct
-                       $newVal = $this->checkValue_checkMax($tcaFieldConf, $newValueArray);
-                       $res['value'] = implode(',',$newVal);
+                       $res['value'] = $this->checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field);
                }
 
                return $res;
@@ -1994,12 +1963,17 @@ class t3lib_TCEmain     {
                        switch($func)   {
                                case 'int':
                                case 'year':
-                               case 'date':
-                               case 'datetime':
                                case 'time':
                                case 'timesec':
                                        $value = intval($value);
                                break;
+                               case 'date':
+                               case 'datetime':
+                                       $value = intval($value);
+                                       if ($value>0)   {
+                                               $value -= date('Z');
+                                       }
+                               break;
                                case 'double2':
                                        $theDec = 0;
                                        for ($a=strlen($value); $a>0; $a--)     {
@@ -2085,6 +2059,7 @@ class t3lib_TCEmain       {
                $prep = $type=='group'?$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];
 
                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+               /* @var $dbAnalysis t3lib_loadDBGroup */
                $dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
                $dbAnalysis->start(implode(',',$valueArray),$tables, '', 0, $currentTable, $tcaFieldConf);
 
@@ -2092,23 +2067,9 @@ class t3lib_TCEmain      {
                        if ($status=='update')  {
                                $dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
                        } else {
-                               $this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep);    // This will be traversed later to execute the actions
+                               $this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep,$currentTable);      // This will be traversed later to execute the actions
                        }
                        $valueArray = $dbAnalysis->countItems();
-               } elseif ($type == 'inline') {
-                       if ($tcaFieldConf['foreign_field']) {
-                                       // if the record was imported, sorting was also imported, so skip this
-                               $skipSorting = $this->callFromImpExp ? true : false;
-                                       // update record in intermediate table (sorting & pointer uid to parent record)
-                               $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
-                               $valueArray = $dbAnalysis->countItems();
-                       } else {
-                               $valueArray = $dbAnalysis->getValueArray($prep);
-                               if ($prep) {
-                                               // @TODO: Do we want to support relations to multiple tables in Comma Separated Lists?
-                                       $valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
-                               }
-                       }
                } else {
                        $valueArray = $dbAnalysis->getValueArray($prep);
                        if ($type=='select' && $prep)   {
@@ -2197,18 +2158,34 @@ class t3lib_TCEmain     {
                                if ($DSelements[$key]['type']=='array') {
                                        if (is_array($dataValues[$key]['el']))  {
                                                if ($DSelements[$key]['section'])       {
+                                                       $newIndexCounter=0;
                                                        foreach($dataValues[$key]['el'] as $ik => $el)  {
-                                                               $theKey = key($el);
-                                                               if (is_array($dataValues[$key]['el'][$ik][$theKey]['el']))      {
-                                                                       $this->checkValue_flex_procInData_travDS(
-                                                                                       $dataValues[$key]['el'][$ik][$theKey]['el'],
-                                                                                       $dataValues_current[$key]['el'][$ik][$theKey]['el'],
-                                                                                       $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
-                                                                                       $DSelements[$key]['el'][$theKey]['el'],
-                                                                                       $pParams,
-                                                                                       $callBackFunc,
-                                                                                       $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
-                                                                               );
+                                                               if (is_array($el))      {
+                                                                       if (!is_array($dataValues_current[$key]['el'])) $dataValues_current[$key]['el']=array();
+                                                                       
+                                                                       $theKey = key($el);
+
+                                                                       if (is_array($dataValues[$key]['el'][$ik][$theKey]['el']))      {
+                                                                               $this->checkValue_flex_procInData_travDS(
+                                                                                               $dataValues[$key]['el'][$ik][$theKey]['el'],
+                                                                                               is_array($dataValues_current[$key]['el'][$ik]) ? $dataValues_current[$key]['el'][$ik][$theKey]['el'] : array(),
+                                                                                               $uploadedFiles[$key]['el'][$ik][$theKey]['el'],
+                                                                                               $DSelements[$key]['el'][$theKey]['el'],
+                                                                                               $pParams,
+                                                                                               $callBackFunc,
+                                                                                               $structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
+                                                                                       );
+                                                                               
+                                                                                       // If element is added dynamically in the flexform of TCEforms, we map the ID-string to the next numerical index we can have in that particular section of elements:
+                                                                                       // The fact that the order changes is not important since order is controlled by a separately submitted index.
+
+                                                                               if (substr($ik,0,3)=="ID-")     {
+                                                                                       $newIndexCounter++;
+                                                                                       $this->newIndexMap[$ik] = (is_array($dataValues_current[$key]['el'])&&count($dataValues_current[$key]['el'])?max(array_keys($dataValues_current[$key]['el'])):0)+$newIndexCounter;      // Set mapping index
+                                                                                       $dataValues[$key]['el'][$this->newIndexMap[$ik]] = $dataValues[$key]['el'][$ik];        // Transfer values
+                                                                                       unset($dataValues[$key]['el'][$ik]);    // Unset original
+                                                                               }
+                                                                       }
                                                                }
                                                        }
                                                } else {
@@ -2244,7 +2221,8 @@ class t3lib_TCEmain       {
                                                                                                $dsConf['TCEforms']['config'],
                                                                                                $dataValues[$key][$vKey],
                                                                                                $dataValues_current[$key][$vKey],
-                                                                                               $uploadedFiles[$key][$vKey]
+                                                                                               $uploadedFiles[$key][$vKey],
+                                                                                               $structurePath.$key.'/'.$vKey.'/'
                                                                                        );
                                                                }
                                                        } else {        // Default
@@ -2298,6 +2276,23 @@ class t3lib_TCEmain      {
                                                        if (isset($res['value']))       {
                                                                $dataValues[$key][$vKey] = $res['value'];
                                                        }
+
+                                                               // Finally, check if new and old values are different (or no .vDEFbase value is found) and if so, we record the vDEF value for diff'ing.
+                                                               // We do this after $dataValues has been updated since I expect that $dataValues_current holds evaluated values from database (so this must be the right value to compare with).
+                                                       if (substr($vKey,-9)!='.vDEFbase')      {
+                                                               if ($this->clear_flexFormData_vDEFbase) {
+                                                                       $dataValues[$key][$vKey.'.vDEFbase'] = '';
+                                                               } elseif ($this->updateModeL10NdiffData && $GLOBALS['TYPO3_CONF_VARS']['BE']['flexFormXMLincludeDiffBase'] && $vKey!=='vDEF' && (strcmp($dataValues[$key][$vKey],$dataValues_current[$key][$vKey]) || !isset($dataValues_current[$key][$vKey.'.vDEFbase']) || $this->updateModeL10NdiffData==='FORCE_FFUPD'))   {
+                                                                               // Now, check if a vDEF value is submitted in the input data, if so we expect this has been processed prior to this operation (normally the case since those fields are higher in the form) and we can use that:
+                                                                       if (isset($dataValues[$key]['vDEF']))   {
+                                                                               $diffValue = $dataValues[$key]['vDEF'];
+                                                                       } else {        // If not found (for translators with no access to the default language) we use the one from the current-value data set:
+                                                                               $diffValue = $dataValues_current[$key]['vDEF'];
+                                                                       }
+                                                                               // Setting the reference value for vDEF for this translation. This will be used for translation tools to make a diff between the vDEF and vDEFbase to see if an update would be fitting.
+                                                                       $dataValues[$key][$vKey.'.vDEFbase'] = $diffValue;
+                                                               }
+                                                       }
                                                }
                                        }
                                }
@@ -2305,7 +2300,66 @@ class t3lib_TCEmain      {
                }
        }
 
+       /**
+        * Returns data for inline fields.
+        *
+        * @param       array           Current value array
+        * @param       array           TCA field config
+        * @param       integer         Record id
+        * @param       string          Status string ('update' or 'new')
+        * @param       string          Table name, needs to be passed to t3lib_loadDBGroup
+        * @param       string          The current field the values are modified for
+        * @return      string          Modified values
+        */
+       protected function checkValue_inline_processDBdata($valueArray, $tcaFieldConf, $id, $status, $table, $field)    {
+               $newValue = '';
+               $foreignTable = $tcaFieldConf['foreign_table'];
 
+               /*
+                * Fetch the related child records by using t3lib_loadDBGroup:
+                * @var $dbAnalysis t3lib_loadDBGroup
+                */
+               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+               $dbAnalysis->start(implode(',', $valueArray), $foreignTable, '', 0, $table, $tcaFieldConf);
+                       // If the localizazionMode is set to 'keep', the children for the localized parent are kept as in the original untranslated record:
+               $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $tcaFieldConf);
+               if ($localizationMode=='keep' && $status=='update') {
+                               // Fetch the current record and determine the original record:
+                       $row = t3lib_BEfunc::getRecordWSOL($table, $id);
+                       if (is_array($row)) {
+                               $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
+                               $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
+                                       // If language is set (e.g. 1) and also transOrigPointer (e.g. 123), use transOrigPointer as uid:
+                               if ($language>0 && $transOrigPointer) {
+                                       $id = $transOrigPointer;
+                                               // If we're in active localizationMode 'keep', prevent from writing data to the field of the parent record:
+                                               // (on removing the localized parent, the original (untranslated) children would then also be removed)
+                                       $keepTranslation = true;
+                               }
+                       }
+               }
+                       // IRRE with a pointer field (database normalization): 
+               if ($tcaFieldConf['foreign_field']) {
+                               // if the record was imported, sorting was also imported, so skip this
+                       $skipSorting = ($this->callFromImpExp ? true : false);
+                               // update record in intermediate table (sorting & pointer uid to parent record)
+                       $dbAnalysis->writeForeignField($tcaFieldConf, $id, 0, $skipSorting);
+                       $newValue = ($keepTranslation ? 0 : $dbAnalysis->countItems(false));
+                       // IRRE with comma separated values:
+               } else {
+                       $valueArray = $dbAnalysis->getValueArray();
+                               // Checking that the number of items is correct:
+                       $valueArray = $this->checkValue_checkMax($tcaFieldConf, $valueArray);
+                               // If a valid translation of the 'keep' mode is active, update relations in the original(!) record:
+                       if ($keepTranslation) {
+                               $this->updateDB($table, $transOrigPointer, array($field => implode(',', $valueArray)));
+                       } else {
+                               $newValue = implode(',', $valueArray);
+                       }
+               }
+
+               return $newValue;
+       }
 
 
 
@@ -2350,6 +2404,9 @@ class t3lib_TCEmain       {
                        }
                }
 #debug($this->cmdmap);
+               
+               $this->accumulateForNotifEmail = array();       // Reset notification array
+
                        // Traverse command map:
                reset($this->cmdmap);
                while(list($table,) = each($this->cmdmap))      {
@@ -2397,6 +2454,9 @@ class t3lib_TCEmain       {
                                                        case 'localize':
                                                                $this->localize($table,$id,$value);
                                                        break;
+                                                       case 'inlineLocalizeSynchronize':
+                                                               $this->inlineLocalizeSynchronize($table, $id, $value);
+                                                       break;
                                                        case 'version':
                                                                switch ((string)$value['action'])       {
                                                                        case 'new':
@@ -2432,6 +2492,7 @@ class t3lib_TCEmain       {
                                                                                $this->version_clearWSID($table,$id,TRUE);
                                                                        break;
                                                                        case 'setStage':
+                                                                               $elementList = array();
                                                                                $idList = $elementList[$table] = t3lib_div::trimExplode(',',$id,1);
                                                                                $setStageMode = $GLOBALS['BE_USER']->getTSConfigVal('options.workspaces.changeStageMode');
                                                                                if ($setStageMode == 'any' || $setStageMode == 'page') {
@@ -2456,9 +2517,10 @@ class t3lib_TCEmain      {
                                                                                                $this->findPageElementsForVersionStageChange($idList, $workspaceId, $elementList);
                                                                                        }
                                                                                }
+                                                                               
                                                                                foreach ($elementList as $tbl => $elementIdList) {
                                                                                        foreach($elementIdList as $id)  {
-                                                                                               $this->version_setStage($tbl,$id,$value['stageId'],$value['comment']?$value['comment']:$this->generalComment);
+                                                                                               $this->version_setStage($tbl,$id,$value['stageId'],$value['comment']?$value['comment']:$this->generalComment, TRUE);
                                                                                        }
                                                                                }
                                                                        break;
@@ -2487,6 +2549,16 @@ class t3lib_TCEmain      {
 
                        // Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
                $this->remapListedDBRecords();
+
+
+                       // Empty accumulation array:
+               foreach($this->accumulateForNotifEmail as $notifItem)   {
+                       $this->notifyStageChange($notifItem['shared'][0],$notifItem['shared'][1],implode(', ',$notifItem['elements']),0,$notifItem['shared'][2]);
+               }
+
+               $this->accumulateForNotifEmail = array();       // Reset notification array
+               
+#              die("REMOVE ME");
        }
 
 
@@ -2514,9 +2586,10 @@ class t3lib_TCEmain      {
         * @param       boolean         $first is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
         * @param       array           Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!
         * @param       string          Commalist of fields to exclude from the copy process (might get default values)
+        * @param       integer         Language ID (from sys_language table)
         * @return      integer         ID of new record, if any
         */
-       function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')    {
+       function copyRecord($table, $uid, $destPid, $first=0, $overrideValues=array(), $excludeFields='', $language=0) {
                global $TCA;
 
                $uid = $origUid = intval($uid);
@@ -2585,7 +2658,7 @@ class t3lib_TCEmain       {
                                                                        $value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
                                                                }
                                                                        // Processing based on the TCA config field type (files, references, flexforms...)
-                                                               $value = $this->copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$tscPID);
+                                                               $value = $this->copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $tscPID, $language);
                                                        }
 
                                                                // Add value to array.
@@ -2605,6 +2678,7 @@ class t3lib_TCEmain       {
 
                                                // Do the copy by simply submitting the array through TCEmain:
                                        $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
+                                       /* @var $copyTCE t3lib_TCEmain  */
                                        $copyTCE->stripslashes_values = 0;
                                        $copyTCE->copyTree = $this->copyTree;
                                        $copyTCE->cachedTSconfig = $this->cachedTSconfig;       // Copy forth the cached TSconfig
@@ -2872,11 +2946,12 @@ class t3lib_TCEmain     {
         * @param       array           Record array
         * @param       array           TCA field configuration
         * @param       integer         Real page id (pid) the record is copied to
+        * @param       integer         Language ID (from sys_language table)
         * @return      mixed           Processed value. Normally a string/integer, but can be an array for flexforms!
         * @access private
         * @see copyRecord()
         */
-       function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf,$realDestPid) {
+       function copyRecord_procBasedOnFieldType($table, $uid, $field, $value, $row, $conf, $realDestPid, $language=0) {
                global $TCA;
 
                        // Process references and files, currently that means only the files, prepending absolute paths (so the TCEmain engine will detect the file as new and one that should be made into a copy)
@@ -2887,9 +2962,23 @@ class t3lib_TCEmain      {
                if ($this->isReferenceField($conf) || $inlineSubType == 'mm')   {
                        $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
                        $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
-                       if ($conf['MM'])        {
+                       $localizeReferences = (isset($conf['foreign_table']) && t3lib_BEfunc::isTableLocalizable($conf['foreign_table']) && isset($conf['localizeReferencesAtParentLocalization']) && $conf['localizeReferencesAtParentLocalization']);
+                       if ($conf['MM'] || $language>0 && $localizeReferences) {
                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
-                               $dbAnalysis->start('', $allowedTables, $conf['MM'], $uid, $table, $conf);
+                               /* @var $dbAnalysis t3lib_loadDBGroup */
+                               $dbAnalysis->start($value, $allowedTables, $conf['MM'], $uid, $table, $conf);
+                               if (!$conf['MM']) {
+                                               // Localize referenced records of select fields:
+                                       foreach ($dbAnalysis->itemArray as $index => $item) {
+                                                       // Since select fields can reference many records, check whether there's already a localization:
+                                               $recordLocalization = t3lib_BEfunc::getRecordLocalization($item['table'], $item['id'], $language);
+                                               if (!$recordLocalization) {
+                                                       $dbAnalysis->itemArray[$index]['id'] = $this->localize($item['table'], $item['id'], $language);
+                                               } else {
+                                                       $dbAnalysis->itemArray[$index]['id'] = $recordLocalization[0]['uid'];
+                                               }
+                                       }
+                               }
                                $value = implode(',',$dbAnalysis->getValueArray($prependName));
                        }
                        if ($value)     {       // Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
@@ -2898,33 +2987,54 @@ class t3lib_TCEmain     {
 
                        // If another inline subtype is used (comma-separated-values or the foreign_field property):
                } elseif ($inlineSubType !== false) {
-                       $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
-                       $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
-
-                               // walk through the items, copy them and remember the new id
-                       foreach ($dbAnalysis->itemArray as $k => $v) {
-                               if (!t3lib_div::testInt($realDestPid)) {
-                                       $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
-                               } elseif ($realDestPid == -1) {
-                                       $newId = $this->versionizeRecord($v['table'], $v['id'], 'Auto-created for WS #'.$this->BE_USER->workspace);
-                               } else {
-                                       $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid);
-                               }
+                               // Get the localization mode for the current (parent) record (keep|select|all):
+                       $localizazionMode = t3lib_BEfunc::getInlineLocalizationMode($table, $field);
+                               // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
+                       if ($language>0 && $localizazionMode=='keep') {
+                               $value = ($inlineSubType=='field' ? 0 : '');
+                               // Execute copy or localization actions:
+                       } else {
+                               /*
+                                * Fetch the related child records by using t3lib_loadDBGroup:
+                                * @var $dbAnalysis t3lib_loadDBGroup
+                                */
+                               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                               $dbAnalysis->start($value, $conf['foreign_table'], '', $uid, $table, $conf);
+
+                                       // Walk through the items, copy them and remember the new id:
+                               foreach ($dbAnalysis->itemArray as $k => $v) {
+                                               // If language is set, this isn't a copy action but a localization of our parent/ancestor:
+                                       if ($language>0) {
+                                                       // If children should be localized when the parent gets localized the first time, just do it:
+                                               if ($localizazionMode!=false && isset($conf['behaviour']['localizeChildrenAtParentLocalization']) && $conf['behaviour']['localizeChildrenAtParentLocalization']) {
+                                                       $newId = $this->localize($v['table'], $v['id'], $language);
+                                               }
+                                               // If no language it set, this is a regular copy action:
+                                       } else {
+                                               if (!t3lib_div::testInt($realDestPid)) {
+                                                       $newId = $this->copyRecord($v['table'], $v['id'], -$v['id']);
+                                               } elseif ($realDestPid == -1) {
+                                                       $newId = $this->versionizeRecord($v['table'], $v['id'], 'Auto-created for WS #'.$this->BE_USER->workspace);
+                                               } else {
+                                                       $newId = $this->copyRecord_raw($v['table'], $v['id'], $realDestPid);
+                                               }
+                                       }
 
-                                       // If the current field is set on a page record, update the pid of related child records:
-                               if ($table == 'pages') {
-                                       $this->registerDBPids[$v['table']][$v['id']] = $uid;
-                                       // If the current field has ancestors that have a field on a page record, update the pid of related child records:
-                               } elseif (isset($this->registerDBPids[$table][$uid])) {
-                                       $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
+                                               // If the current field is set on a page record, update the pid of related child records:
+                                       if ($table == 'pages') {
+                                               $this->registerDBPids[$v['table']][$v['id']] = $uid;
+                                               // If the current field has ancestors that have a field on a page record, update the pid of related child records:
+                                       } elseif (isset($this->registerDBPids[$table][$uid])) {
+                                               $this->registerDBPids[$v['table']][$v['id']] = $this->registerDBPids[$table][$uid];
+                                       }
+
+                                       $dbAnalysis->itemArray[$k]['id'] = $newId;
                                }
 
-                               $dbAnalysis->itemArray[$k]['id'] = $newId;
+                                       // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
+                               $value = implode(',',$dbAnalysis->getValueArray());
+                               $this->registerDBList[$table][$uid][$field] = $value;
                        }
-
-                               // store the new values, we will set up the uids for the subtype later on
-                       $value = implode(',',$dbAnalysis->getValueArray());
-                       $this->registerDBList[$table][$uid][$field] = $value;
                }
 
                        // For "flex" fieldtypes we need to traverse the structure for two reasons: If there are file references they have to be prepended with absolute paths and if there are database reference they MIGHT need to be remapped (still done in remapListedDBRecords())
@@ -3000,6 +3110,7 @@ class t3lib_TCEmain       {
                                $theFileValues = array();
 
                                $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                               /* @var $dbAnalysis t3lib_loadDBGroup */
                                $dbAnalysis->start('', 'files', $conf['MM'], $uid);
 
                                foreach($dbAnalysis->itemArray as $somekey => $someval) {
@@ -3052,6 +3163,7 @@ class t3lib_TCEmain       {
                }
 
                        // Select all RTEmagic files in the reference table from the table/ID
+               /* @var $TYPO3_DB t3lib_DB */
                $recs = $TYPO3_DB->exec_SELECTgetRows(
                        '*',
                        'sys_refindex',
@@ -3178,75 +3290,82 @@ class t3lib_TCEmain     {
                                $mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
                        }
 
-                               // If moving is allowed, begin the processing:
-                       if ($mayMoveAccess)     {
-                               if ($mayInsertAccess)   {
-
-                                       if ($this->BE_USER->workspace!==0)      {       // Draft workspace...:
-                                                       // Get workspace version of the source record, if any:
-                                               $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
+                               // Checking if there is anything else disallowing moving the record by checking if editing is allowed
+                       $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table,$uid);
 
-                                                       // If no version exists and versioningWS is in version 2, a new placeholder is made automatically:
-                                               if (!$WSversion['uid'] && (int)$TCA[$table]['ctrl']['versioningWS']>=2 && (int)$moveRec['t3ver_state']!=3)      {
-                                                       $this->versionizeRecord($table,$uid,'Placeholder version for moving record');
-                                                       $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');       // Will not create new versions in live workspace though...
-                                               }
+                               // If moving is allowed, begin the processing:
+                       if ($mayEditAccess)     {
+                               if ($mayMoveAccess)     {
+                                       if ($mayInsertAccess)   {
+
+                                               if ($this->BE_USER->workspace!==0)      {       // Draft workspace...:
+                                                               // Get workspace version of the source record, if any:
+                                                       $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
+
+                                                               // If no version exists and versioningWS is in version 2, a new placeholder is made automatically:
+                                                       if (!$WSversion['uid'] && (int)$TCA[$table]['ctrl']['versioningWS']>=2 && (int)$moveRec['t3ver_state']!=3)      {
+                                                               $this->versionizeRecord($table,$uid,'Placeholder version for moving record');
+                                                               $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');       // Will not create new versions in live workspace though...
+                                                       }
 
-                                                       // Check workspace permissions:
-                                               $workspaceAccessBlocked = array();
-                                               $recIsNewVersion = (int)$moveRec['t3ver_state']>0;      // Element was in "New/Deleted/Moved" so it can be moved...
-                                               $destRes = $this->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid,$table);
-                                               $canMoveRecord = $recIsNewVersion || (int)$TCA[$table]['ctrl']['versioningWS']>=2;
+                                                               // Check workspace permissions:
+                                                       $workspaceAccessBlocked = array();
+                                                       $recIsNewVersion = (int)$moveRec['t3ver_state']>0;      // Element was in "New/Deleted/Moved" so it can be moved...
+                                                       $destRes = $this->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid,$table);
+                                                       $canMoveRecord = $recIsNewVersion || (int)$TCA[$table]['ctrl']['versioningWS']>=2;
 
-                                                       // Workspace source check:
-                                               if (!$recIsNewVersion)  {
-                                                       if ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid))       {
-                                                               $workspaceAccessBlocked['src1']='Record could not be edited in workspace: '.$errorCode.' ';
-                                                       } else {
-                                                               if (!$canMoveRecord && $this->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'],$table)<=0)       {
-                                                                       $workspaceAccessBlocked['src2']='Could not remove record from table "'.$table.'" from its page "'.$moveRec['pid'].'" ';
+                                                               // Workspace source check:
+                                                       if (!$recIsNewVersion)  {
+                                                               if ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid))       {
+                                                                       $workspaceAccessBlocked['src1']='Record could not be edited in workspace: '.$errorCode.' ';
+                                                               } else {
+                                                                       if (!$canMoveRecord && $this->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'],$table)<=0)       {
+                                                                               $workspaceAccessBlocked['src2']='Could not remove record from table "'.$table.'" from its page "'.$moveRec['pid'].'" ';
+                                                                       }
                                                                }
                                                        }
-                                               }
-                                       
-                                                       // Workspace destination check:
-                                               if (!($destRes>0 || ($canMoveRecord && !$destRes)))     {       // All records can be inserted if $destRes is greater than zero. Only new versions can be inserted if $destRes is false. NO RECORDS can be inserted if $destRes is negative which indicates a stage not allowed for use. If "versioningWS" is version 2, moving can take place of versions.
-                                                       $workspaceAccessBlocked['dest1']='Could not insert record from table "'.$table.'" in destination PID "'.$resolvedPid.'" ';
-                                               } elseif ($destRes==1 && $WSversion['uid'])     {
-                                                       $workspaceAccessBlocked['dest2']='Could not insert other versions in destination PID ';
-                                               }
 
-                                               if (!count($workspaceAccessBlocked))    {
-                                                       if ($WSversion['uid'] && !$recIsNewVersion && (int)$TCA[$table]['ctrl']['versioningWS']>=2)     { // If the move operation is done on a versioned record, which is NOT new/deletd placeholder and versioningWS is in version 2, then...
-                                                               $this->moveRecord_wsPlaceholders($table,$uid,$destPid,$WSversion['uid']);
+                                                               // Workspace destination check:
+                                                       if (!($destRes>0 || ($canMoveRecord && !$destRes)))     {       // All records can be inserted if $destRes is greater than zero. Only new versions can be inserted if $destRes is false. NO RECORDS can be inserted if $destRes is negative which indicates a stage not allowed for use. If "versioningWS" is version 2, moving can take place of versions.
+                                                               $workspaceAccessBlocked['dest1']='Could not insert record from table "'.$table.'" in destination PID "'.$resolvedPid.'" ';
+                                                       } elseif ($destRes==1 && $WSversion['uid'])     {
+                                                               $workspaceAccessBlocked['dest2']='Could not insert other versions in destination PID ';
+                                                       }
+
+                                                       if (!count($workspaceAccessBlocked))    {
+                                                               if ($WSversion['uid'] && !$recIsNewVersion && (int)$TCA[$table]['ctrl']['versioningWS']>=2)     { // If the move operation is done on a versioned record, which is NOT new/deletd placeholder and versioningWS is in version 2, then...
+                                                                       $this->moveRecord_wsPlaceholders($table,$uid,$destPid,$WSversion['uid']);
+                                                               } else {
+                                                                       $this->moveRecord_raw($table,$uid,$destPid);
+                                                               }
                                                        } else {
-                                                               $this->moveRecord_raw($table,$uid,$destPid);
+                                                               $this->newlog("Move attempt failed due to workspace restrictions: ".implode(' // ',$workspaceAccessBlocked),1);
                                                        }
-                                               } else {
-                                                       $this->newlog("Move attempt failed due to workspace restrictions: ".implode(' // ',$workspaceAccessBlocked),1);
+                                               } else {        // Live workspace - move it!
+                                                       $this->moveRecord_raw($table,$uid,$destPid);
                                                }
-                                       } else {        // Live workspace - move it!
-                                               $this->moveRecord_raw($table,$uid,$destPid);
+                                       } else {
+                                               $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to insert.",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
                                        }
                                } else {
-                                       $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to insert",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
+                                       $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so.",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
                                }
                        } else {
-                               $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
+                               $this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so. [".$this->BE_USER->errorMsg."]",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
                        }
                }
        }
 
        /**
         * Creates a move placeholder for workspaces.
-        * USE ONLY INTERNALLY 
+        * USE ONLY INTERNALLY
         * Moving placeholder: Can be done because the system sees it as a placeholder for NEW elements like t3ver_state=1
         * Moving original: Will either create the placeholder if it doesn't exist or move existing placeholder in workspace.
         *
         * @param       string          Table name to move
         * @param       integer         Record uid to move (online record)
         * @param       integer         Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
-        * @param       integer         UID of offline version of online record 
+        * @param       integer         UID of offline version of online record
         * @return      void
         * @see moveRecord()
         */
@@ -3291,7 +3410,7 @@ class t3lib_TCEmain       {
 
        /**
         * Moves a record without checking security of any sort.
-        * USE ONLY INTERNALLY 
+        * USE ONLY INTERNALLY
         *
         * @param       string          Table name to move
         * @param       integer         Record uid to move
@@ -3321,7 +3440,7 @@ class t3lib_TCEmain       {
                                $hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
                        }
                }
-               
+
                        // Timestamp field:
                $updateFields = array();
                if ($TCA[$table]['ctrl']['tstamp'])     {
@@ -3462,8 +3581,9 @@ class t3lib_TCEmain       {
 
                if ($conf['type'] == 'inline')  {
                        $foreign_table = $conf['foreign_table'];
+                       $moveChildrenWithParent = (!isset($conf['behaviour']['disableMovingChildrenWithParent']) || !$conf['behaviour']['disableMovingChildrenWithParent']);
 
-                       if ($foreign_table) {
+                       if ($foreign_table && $moveChildrenWithParent) {
                                $inlineType = $this->getInlineFieldType($conf);
                                if ($inlineType == 'list' || $inlineType == 'field') {
                                        $moveTable = $foreign_table;
@@ -3488,11 +3608,12 @@ class t3lib_TCEmain     {
         * @param       string          Table name
         * @param       integer         Record uid (to be localized)
         * @param       integer         Language ID (from sys_language table)
-        * @return      void
+        * @return      mixed           The uid (integer) of the new translated record or false (boolean) if something went wrong
         */
-       function localize($table,$uid,$language)        {
+       function localize($table, $uid, $language) {
                global $TCA;
 
+               $newId = false;
                $uid = intval($uid);
 
                if ($TCA[$table] && $uid)       {
@@ -3511,7 +3632,7 @@ class t3lib_TCEmain       {
                                                                                $Ttable = 'pages_language_overlay';
                                                                                t3lib_div::loadTCA($Ttable);
                                                                        } else {
-                                                                               $pass = !t3lib_BEfunc::getRecordsByField($table,$TCA[$table]['ctrl']['transOrigPointerField'],$uid,'AND pid='.intval($row['pid']).' AND '.$TCA[$table]['ctrl']['languageField'].'='.intval($langRec['uid']));
+                                                                               $pass = !t3lib_BEfunc::getRecordLocalization($table, $uid, $langRec['uid'], 'AND pid='.intval($row['pid']));
                                                                                $Ttable = $table;
                                                                        }
 
@@ -3549,11 +3670,12 @@ class t3lib_TCEmain     {
                                                                                if ($Ttable === $table) {
 
                                                                                                // Execute the copy:
-                                                                                       $this->copyRecord($table,$uid,-$uid,1,$overrideValues,implode(',',$excludeFields));
+                                                                                       $newId = $this->copyRecord($table, $uid, -$uid, 1, $overrideValues, implode(',', $excludeFields), $language);
                                                                                } else {
 
                                                                                                // Create new record:
                                                                                        $copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
+                                                                                       /* @var $copyTCE t3lib_TCEmain  */
                                                                                        $copyTCE->stripslashes_values = 0;
                                                                                        $copyTCE->cachedTSconfig = $this->cachedTSconfig;       // Copy forth the cached TSconfig
                                                                                        $copyTCE->dontProcessTransformations=1;         // Transformations should NOT be carried out during copy
@@ -3566,6 +3688,7 @@ class t3lib_TCEmain       {
                                                                                        if ($theNewSQLID)       {
                                                                                                        // If is by design that $Ttable is used and not $table! See "l10nmgr" extension. Could be debated, but this is what I chose for this "pseudo case"
                                                                                                $this->copyMappingArray[$Ttable][$uid] = $theNewSQLID;
+                                                                                               $newId = $theNewSQLID;
                                                                                        }
                                                                                }
                                                                        } else $this->newlog('Localization failed; There already was a localization for this language of the record!',1);
@@ -3576,11 +3699,106 @@ class t3lib_TCEmain    {
                                } else $this->newlog('Sys language UID "'.$language.'" not found valid!',1);
                        } else $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table!',1);
                }
+               return $newId;
        }
 
 
-
-
+       /**
+        * Performs localization or synchronization of child records.
+        *
+        * @param       string          $table: The table of the localized parent record
+        * @param       integer         $id: The uid of the localized parent record
+        * @param       mixed           $command: Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
+        * @return      void
+        */
+       protected function inlineLocalizeSynchronize($table, $id, $command) {
+                       // <field>, (localize | synchronize | <uid>): 
+               $parts = t3lib_div::trimExplode(',', $command);
+               $field = $parts[0];
+               $type = $parts[1];
+
+               if ($field && (t3lib_div::inList('localize,synchronize', $type) || t3lib_div::testInt($type)) && isset($GLOBALS['TCA'][$table]['columns'][$field]['config'])) {
+                       $config = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
+                       $foreignTable = $config['foreign_table'];
+                       $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
+
+                       if ($localizationMode=='select') {
+                               $parentRecord = t3lib_BEfunc::getRecordWSOL($table, $id);
+                               $language = intval($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
+                               $transOrigPointer = intval($parentRecord[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
+                               $childTransOrigPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
+
+                               if ($parentRecord && is_array($parentRecord) && $language>0 && $transOrigPointer) {
+                                       $inlineSubType = $this->getInlineFieldType($config);
+                                       $transOrigRecord = t3lib_BEfunc::getRecordWSOL($table, $transOrigPointer);
+
+                                       if ($inlineSubType!==false) {
+                                               $removeArray = array();
+                                                       // Fetch children from original language parent:
+                                                       // @var $dbAnalysisOriginal t3lib_loadDBGroup
+                                               $dbAnalysisOriginal = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                               $dbAnalysisOriginal->start($transOrigRecord[$field], $foreignTable, '', $transOrigRecord['uid'], $table, $config);
+                                               $elementsOriginal = array();
+                                               foreach ($dbAnalysisOriginal->itemArray as $item) {
+                                                       $elementsOriginal[$item['id']] = $item;
+                                               }
+                                               unset($dbAnalysisOriginal);
+                                                       // Fetch children from current localized parent:
+                                                       // @var $dbAnalysisCurrent t3lib_loadDBGroup
+                                               $dbAnalysisCurrent = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                               $dbAnalysisCurrent->start($parentRecord[$field], $foreignTable, '', $id, $table, $config);
+                                                       // Perform synchronization: Possibly removal of already localized records:
+                                               if ($type=='synchronize') {
+                                                       foreach ($dbAnalysisCurrent->itemArray as $index => $item) {
+                                                               $childRecord = t3lib_BEfunc::getRecordWSOL($item['table'], $item['id']);
+                                                               if (isset($childRecord[$childTransOrigPointerField]) && $childRecord[$childTransOrigPointerField]>0) {
+                                                                       $childTransOrigPointer = $childRecord[$childTransOrigPointerField];
+                                                                               // If snychronization is requested, child record was translated once, but original record does not exist anymore, remove it:
+                                                                       if (!isset($elementsOriginal[$childTransOrigPointer])) {
+                                                                               unset($dbAnalysisCurrent->itemArray[$index]);
+                                                                               $removeArray[$item['table']][$item['id']]['delete'] = 1;
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                                       // Perform synchronization/localization: Possibly add unlocalized records for original language: 
+                                               if (t3lib_div::testInt($type) && isset($elementsOriginal[$type])) {
+                                                       $item = $elementsOriginal[$type];
+                                                       $item['id'] = $this->localize($item['table'], $item['id'], $language);
+                                                       $dbAnalysisCurrent->itemArray[] = $item; 
+                                               } elseif (t3lib_div::inList('localize,synchronize', $type)) {
+                                                       foreach ($elementsOriginal as $originalId => $item) {
+                                                               $item['id'] = $this->localize($item['table'], $item['id'], $language);
+                                                               $dbAnalysisCurrent->itemArray[] = $item; 
+                                                       }
+                                               }
+                                                       // Store the new values, we will set up the uids for the subtype later on (exception keep localization from original record):
+                                               $value = implode(',', $dbAnalysisCurrent->getValueArray());
+                                               $this->registerDBList[$table][$id][$field] = $value;
+                                                       // Remove child records (if synchronization requested it):
+                                               if (is_array($removeArray) && count($removeArray)) {
+                                                       $tce = t3lib_div::makeInstance('t3lib_TCEmain');
+                                                       $tce->stripslashes_values = false;
+                                                       $tce->start(array(), $removeArray);
+                                                       $tce->process_cmdmap();
+                                                       unset($tce);
+                                               }
+                                                       // Handle, reorder and store relations:
+                                               if ($inlineSubType=='list') {
+                                                       $updateFields = array($field => $value);
+                                               } elseif ($inlineSubType=='field') {
+                                                       $dbAnalysisCurrent->writeForeignField($config, $id);
+                                                       $updateFields = array($field => $dbAnalysisCurrent->countItems(false));
+                                               }
+                                                       // Update field referencing to child records of localized parent record:
+                                               if (is_array($updateFields) && count($updateFields)) {
+                                                       $this->updateDB($table, $id, $updateFields);
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
 
 
 
@@ -3636,10 +3854,10 @@ class t3lib_TCEmain     {
                                        $this->deleteEl($table, $id);
                                } else $this->newlog('Stage of root point did not allow for deletion',1);
                        } elseif ((int)$delRec['t3ver_state']===3) {    // Placeholders for moving operations are deletable directly.
-                               
+
                                        // Get record which its a placeholder for and reset the t3ver_state of that:
                                if ($wsRec = t3lib_BEfunc::getWorkspaceVersionOfRecord($delRec['t3ver_wsid'], $table, $delRec['t3ver_move_id'], 'uid')) {
-                                               // clear the state flag of the workspace version of the 
+                                               // Clear the state flag of the workspace version of the record
                                        $updateFields = array();
                                        $updateFields['t3ver_state'] = 0;       // Setting placeholder state value for version (so it can know it is currently a new version...)
                                        $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($wsRec['uid']), $updateFields);
@@ -3720,103 +3938,108 @@ class t3lib_TCEmain   {
        function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)  {
                global $TCA;
 
+                       // Checking if there is anything else disallowing deleting the record by checking if editing is allowed
+               $mayEditAccess = $this->BE_USER->recordEditAccessInternals($table,$uid);
+
                $uid = intval($uid);
                if ($TCA[$table] && $uid)       {
-                       if ($noRecordCheck || $this->doesRecordExist($table,$uid,'delete'))     {
-                               $this->clear_cache($table,$uid);        // clear cache before deleting the record, else the correct page cannot be identified by clear_cache
-
-                               $propArr = $this->getRecordProperties($table, $uid);
-                               $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
-
-                               $deleteRow = $TCA[$table]['ctrl']['delete'];
-                               if ($deleteRow && !$forceHardDelete)    {
-                                       $value = $undeleteRecord ? 0 : 1;
-                                       $updateFields = array(
-                                               $deleteRow => $value
-                                       );
+                       if ($mayEditAccess)     {
+                               if ($noRecordCheck || $this->doesRecordExist($table,$uid,'delete'))     {
+                                       $this->clear_cache($table,$uid);        // clear cache before deleting the record, else the correct page cannot be identified by clear_cache
+
+                                       $propArr = $this->getRecordProperties($table, $uid);
+                                       $pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);
+
+                                       $deleteRow = $TCA[$table]['ctrl']['delete'];
+                                       if ($deleteRow && !$forceHardDelete)    {
+                                               $value = $undeleteRecord ? 0 : 1;
+                                               $updateFields = array(
+                                                       $deleteRow => $value
+                                               );
 
-                                       if ($TCA[$table]['ctrl']['tstamp']) {
-                                               $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
-                                       }
+                                               if ($TCA[$table]['ctrl']['tstamp']) {
+                                                       $updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
+                                               }
 
-                                               // If the table is sorted, then the sorting number is set very high
-                                       if ($TCA[$table]['ctrl']['sortby'] && !$undeleteRecord) {
-                                               $updateFields[$TCA[$table]['ctrl']['sortby']] = 1000000000;
-                                       }
+                                                       // If the table is sorted, then the sorting number is set very high
+                                               if ($TCA[$table]['ctrl']['sortby'] && !$undeleteRecord) {
+                                                       $updateFields[$TCA[$table]['ctrl']['sortby']] = 1000000000;
+                                               }
 
-                                               // before (un-)deleting this record, check for child records or references
-                                       $this->deleteRecord_procFields($table, $uid, $undeleteRecord);
-                                       $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
-                               } else {
+                                                       // before (un-)deleting this record, check for child records or references
+                                               $this->deleteRecord_procFields($table, $uid, $undeleteRecord);
+                                               $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
+                                       } else {
 
-                                               // Fetches all fields with flexforms and look for files to delete:
-                                       t3lib_div::loadTCA($table);
-                                       foreach($TCA[$table]['columns'] as $fieldName => $cfg)  {
-                                               $conf = $cfg['config'];
+                                                       // Fetches all fields with flexforms and look for files to delete:
+                                               t3lib_div::loadTCA($table);
+                                               foreach($TCA[$table]['columns'] as $fieldName => $cfg)  {
+                                                       $conf = $cfg['config'];
 
-                                               switch($conf['type'])   {
-                                                       case 'flex':
-                                                               $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
-                                                               $flexObj->traverseFlexFormXMLData($table,$fieldName,t3lib_BEfunc::getRecordRaw($table,'uid='.intval($uid)),$this,'deleteRecord_flexFormCallBack');
-                                                       break;
+                                                       switch($conf['type'])   {
+                                                               case 'flex':
+                                                                       $flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
+                                                                       $flexObj->traverseFlexFormXMLData($table,$fieldName,t3lib_BEfunc::getRecordRaw($table,'uid='.intval($uid)),$this,'deleteRecord_flexFormCallBack');
+                                                               break;
+                                                       }
                                                }
-                                       }
 
-                                               // Fetches all fields that holds references to files
-                                       $fileFieldArr = $this->extFileFields($table);
-                                       if (count($fileFieldArr))       {
-                                               $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',$fileFieldArr), $table, 'uid='.intval($uid));
-                                               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))        {
-                                                       $fArray = $fileFieldArr;
-                                                       foreach($fArray as $theField)   {       // MISSING: Support for MM file relations!
-                                                               $this->extFileFunctions($table,$theField,$row[$theField],'deleteAll');          // This deletes files that belonged to this record.
+                                                       // Fetches all fields that holds references to files
+                                               $fileFieldArr = $this->extFileFields($table);
+                                               if (count($fileFieldArr))       {
+                                                       $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',$fileFieldArr), $table, 'uid='.intval($uid));
+                                                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))        {
+                                                               $fArray = $fileFieldArr;
+                                                               foreach($fArray as $theField)   {       // MISSING: Support for MM file relations!
+                                                                       $this->extFileFunctions($table,$theField,$row[$theField],'deleteAll');          // This deletes files that belonged to this record.
+                                                               }
+                                                       } else {
+                                                               $this->log($table,$uid,3,0,100,'Delete: Zero rows in result when trying to read filenames from record which should be deleted');
                                                        }
-                                               } else {
-                                                       $this->log($table,$uid,3,0,100,'Delete: Zero rows in result when trying to read filenames from record which should be deleted');
                                                }
+
+                                                       // Delete the hard way...:
+                                               $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($uid));
                                        }
 
-                                               // Delete the hard way...:
-                                       $GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($uid));
-                               }
+                                       $state = $undeleteRecord ? 1 : 3;       // 1 means insert, 3 means delete
+                                       if (!$GLOBALS['TYPO3_DB']->sql_error()) {
+                                               if ($forceHardDelete) {
+                                                       $message = "Record '%s' (%s) was deleted unrecoverable from page '%s' (%s)";
+                                               }
+                                               else {
+                                                       $message = $state == 1 ?
+                                                               "Record '%s' (%s) was restored on page '%s' (%s)" :
+                                                               "Record '%s' (%s) was deleted from page '%s' (%s)";
+                                               }
+                                               $this->log($table, $uid, $state, 0, 0,
+                                                                       $message, 0,
+                                                                       array(
+                                                                               $propArr['header'],
+                                                                               $table.':'.$uid,
+                                                                               $pagePropArr['header'],
+                                                                               $propArr['pid']
+                                                                               ),
+                                                                       $propArr['pid']);
 
-                               $state = $undeleteRecord ? 1 : 3;       // 1 means insert, 3 means delete
-                               if (!$GLOBALS['TYPO3_DB']->sql_error()) {
-                                       if ($forceHardDelete) {
-                                               $message = "Record '%s' (%s) was deleted unrecoverable from page '%s' (%s)";
-                                       }
-                                       else {
-                                               $message = $state == 1 ?
-                                                       "Record '%s' (%s) was restored on page '%s' (%s)" :
-                                                       "Record '%s' (%s) was deleted from page '%s' (%s)";
+                                       } else {
+                                               $this->log($table,$uid,$state,0,100,$GLOBALS['TYPO3_DB']->sql_error());
                                        }
-                                       $this->log($table, $uid, $state, 0, 0,
-                                                               $message, 0,
-                                                               array(
-                                                                       $propArr['header'],
-                                                                       $table.':'.$uid,
-                                                                       $pagePropArr['header'],
-                                                                       $propArr['pid']
-                                                                       ),
-                                                               $propArr['pid']);
-
-                               } else {
-                                       $this->log($table,$uid,$state,0,100,$GLOBALS['TYPO3_DB']->sql_error());
-                               }
 
-                                       // Update reference index:
-                               $this->updateRefIndex($table,$uid);
+                                               // Update reference index:
+                                       $this->updateRefIndex($table,$uid);
 
-                                       // if there are entries in the updateRefIndexStack
-                               if (is_array($this->updateRefIndexStack[$table]) && is_array($this->updateRefIndexStack[$table][$uid])) {
-                                       while ($args = array_pop($this->updateRefIndexStack[$table][$uid])) {
-                                                       // $args[0]: table, $args[1]: uid
-                                               $this->updateRefIndex($args[0], $args[1]);
+                                               // if there are entries in the updateRefIndexStack
+                                       if (is_array($this->updateRefIndexStack[$table]) && is_array($this->updateRefIndexStack[$table][$uid])) {
+                                               while ($args = array_pop($this->updateRefIndexStack[$table][$uid])) {
+                                                               // $args[0]: table, $args[1]: uid
+                                                       $this->updateRefIndex($args[0], $args[1]);
+                                               }
+                                               unset($this->updateRefIndexStack[$table][$uid]);
                                        }
-                                       unset($this->updateRefIndexStack[$table][$uid]);
-                               }
 
-                       } else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions');
+                               } else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions');
+                       } else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions. ['.$this->BE_USER->errorMsg.']');
                }
        }
 
@@ -4245,7 +4468,7 @@ class t3lib_TCEmain       {
                                                                                if (!$swapIntoWS)       $swapVersion['t3ver_state'] = 0;
 
                                                                                        // Moving element.
-                                                                               if ((int)$TCA[$table]['ctrl']['versioningWS']>=2)       {               //  && $t3ver_state['swapVersion']==4   // Maybe we don't need this? 
+                                                                               if ((int)$TCA[$table]['ctrl']['versioningWS']>=2)       {               //  && $t3ver_state['swapVersion']==4   // Maybe we don't need this?
                                                                                        if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table,$id,'t3ver_state,pid,uid'.($TCA[$table]['ctrl']['sortby']?','.$TCA[$table]['ctrl']['sortby']:'')))        {
                                                                                                $movePlhID = $plhRec['uid'];
                                                                                                $movePlh['pid'] = $swapVersion['pid'];
@@ -4285,6 +4508,9 @@ class t3lib_TCEmain       {
                                                                                                $curVersion['t3ver_swapmode'] = $swapVersion['t3ver_swapmode'];
                                                                                }
 
+                                                                                       // Registering and swapping MM relations in current and swap records:
+                                                                               $this->version_remapMMForVersionSwap($table,$id,$swapWith);
+
                                                                                        // Execute swapping:
                                                                                $sqlErrors = array();
                                                                                $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($id),$swapVersion);
@@ -4299,7 +4525,6 @@ class t3lib_TCEmain       {
                                                                                        }
                                                                                }
                                                                                
-
                                                                                if (!count($sqlErrors)) {
                                                                                        
                                                                                                // If a moving operation took place...:
@@ -4374,7 +4599,7 @@ class t3lib_TCEmain       {
         */
        function version_clearWSID($table,$id,$flush=FALSE)     {
                global $TCA;
-               
+
                if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id))        {
                        $this->newlog('Attempt to reset workspace for record failed: '.$errorCode,1);
                } elseif ($this->checkRecordUpdateAccess($table,$id)) {
@@ -4395,7 +4620,7 @@ class t3lib_TCEmain       {
                                if ($flush || ((int)$wsRec['t3ver_state']==1 || (int)$wsRec['t3ver_state']==2)) {
                                        $this->deleteEl($table, $id, TRUE, TRUE);
                                }
-                               
+
                                        // Remove the move-placeholder if found for live record.
                                if ((int)$TCA[$table]['ctrl']['versioningWS']>=2)       {
                                        if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table,$liveRec['uid'],'uid'))   {
@@ -4413,9 +4638,10 @@ class t3lib_TCEmain      {
         * @param       integer         Record UID
         * @param       integer         Stage ID to set
         * @param       string          Comment that goes into log
+        * @param       boolean         Accumulate state changes in memory for compiled notification email?
         * @return      void
         */
-       function version_setStage($table,$id,$stageId,$comment='')      {
+       function version_setStage($table,$id,$stageId,$comment='',$accumulateForNotifEmail=FALSE)       {
                if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id))        {
                        $this->newlog('Attempt to set stage for record failed: '.$errorCode,1);
                } elseif ($this->checkRecordUpdateAccess($table,$id)) {
@@ -4431,7 +4657,12 @@ class t3lib_TCEmain      {
 $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stage'=>$stageId));
 
                                if ((int)$stat['stagechg_notification']>0)      {
-                                       $this->notifyStageChange($stat,$stageId,$table,$id,$comment);
+                                       if ($accumulateForNotifEmail)   {
+                                               $this->accumulateForNotifEmail[$stat['uid'].':'.$stageId.':'.$comment]['shared'] = array($stat,$stageId,$comment);
+                                               $this->accumulateForNotifEmail[$stat['uid'].':'.$stageId.':'.$comment]['elements'][] = $table.':'.$id;
+                                       } else {
+                                               $this->notifyStageChange($stat,$stageId,$table,$id,$comment);
+                                       }
                                }
                        } else $this->newlog('The member user tried to set a stage value "'.$stageId.'" that was not allowed',1);
                } else $this->newlog('Attempt to set stage for record failed because you do not have edit access',1);
@@ -4470,7 +4701,144 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                        $swapVersion[$field] = $tempValue;
                }
        }
+       
+       /**
+        * Swaps MM-relations for current/swap record, see version_swap()
+        *
+        * @param       string  Table for the two input records
+        * @param       integer Current record (about to go offline)
+        * @param       integer Swap record (about to go online)
+        * @return void
+        * @see version_swap()
+        */
+       function version_remapMMForVersionSwap($table,$id,$swapWith)    {
+               global $TCA;
+               
+                       // Actually, selecting the records fully is only need if flexforms are found inside... This could be optimized ...
+               $currentRec = t3lib_BEfunc::getRecord($table,$id);
+               $swapRec = t3lib_BEfunc::getRecord($table,$swapWith);
+               
+               $this->version_remapMMForVersionSwap_reg = array();
+               
+               foreach($TCA[$table]['columns'] as $field => $fConf) {
+                       $conf = $fConf['config'];
+                       
+                       if ($this->isReferenceField($conf))     {
+                               $allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
+                               $prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
+                               if ($conf['MM'])        {
+                                       
+                                       $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                       /* @var $dbAnalysis t3lib_loadDBGroup */
+                                       $dbAnalysis->start('', $allowedTables, $conf['MM'], $id, $table, $conf);
+                                       if (count($dbAnalysis->getValueArray($prependName)))    {       
+                                               $this->version_remapMMForVersionSwap_reg[$id][$field] = array($dbAnalysis, $conf['MM'], $prependName);
+                                       }
+                                                                               
+                                       $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                       /* @var $dbAnalysis t3lib_loadDBGroup */
+                                       $dbAnalysis->start('', $allowedTables, $conf['MM'], $swapWith, $table, $conf);
+                                       if (count($dbAnalysis->getValueArray($prependName)))    {       
+                                               $this->version_remapMMForVersionSwap_reg[$swapWith][$field] = array($dbAnalysis, $conf['MM'], $prependName);
+                                       }
+                               }
+                       } elseif($conf['type']=='flex') {
+
+                                       // Current record
+                               $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $currentRec, $table);
+                               $currentValueArray = t3lib_div::xml2array($currentRec[$field]);
+
+                               if (is_array($currentValueArray))       {
+                                       $this->checkValue_flex_procInData(
+                                               $currentValueArray['data'],
+                                               array(),        // Not used.
+                                               array(),        // Not used.
+                                               $dataStructArray,
+                                               array($table,$id,$field),       // Parameters.
+                                               'version_remapMMForVersionSwap_flexFormCallBack'
+                                       );
+                               }
+
+                                       // Swap record
+                               $dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $swapRec, $table);
+                               $currentValueArray = t3lib_div::xml2array($swapRec[$field]);
+
+                               if (is_array($currentValueArray))       {
+                                       $this->checkValue_flex_procInData(
+                                               $currentValueArray['data'],
+                                               array(),        // Not used.
+                                               array(),        // Not used.
+                                               $dataStructArray,
+                                               array($table,$swapWith,$field), // Parameters.
+                                               'version_remapMMForVersionSwap_flexFormCallBack'
+                                       );
+                               }
+                       }
+               }
+               
+                       // Execute:
+               $this->version_remapMMForVersionSwap_execSwap($table,$id,$swapWith);
+       }
+
+       /**
+        * Callback function for traversing the FlexForm structure in relation to ...
+        *
+        * @param       array           Array of parameters in num-indexes: table, uid, field
+        * @param       array           TCA field configuration (from Data Structure XML)
+        * @param       string          The value of the flexForm field
+        * @param       string          Not used.
+        * @param       string          Not used.
+        * @param       string          Path in flexforms
+        * @return      array           Result array with key "value" containing the value of the processing.
+        * @see version_remapMMForVersionSwap(), checkValue_flex_procInData_travDS()
+        */
+       function version_remapMMForVersionSwap_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2, $path) {
+
+                       // Extract parameters:
+               list($table, $uid, $field) = $pParams;
+
+               if ($this->isReferenceField($dsConf)) {
+                       $allowedTables = $dsConf['type']=='group' ? $dsConf['allowed'] : $dsConf['foreign_table'].','.$dsConf['neg_foreign_table'];
+                       $prependName = $dsConf['type']=='group' ? $dsConf['prepend_tname'] : $dsConf['neg_foreign_table'];
+                       if ($dsConf['MM'])      {
+                               $dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                               /* @var $dbAnalysis t3lib_loadDBGroup */
+                               $dbAnalysis->start('', $allowedTables, $dsConf['MM'], $uid, $table, $dsConf);                           
+                               $this->version_remapMMForVersionSwap_reg[$uid][$field.'/'.$path] = array($dbAnalysis, $dsConf['MM'], $prependName);
+                       }
+               }
+       }
 
+       /**
+        * Performing the remapping operations found necessary in version_remapMMForVersionSwap()
+        * It must be done in three steps with an intermediate "fake" uid. The UID can be something else than -$id (fx. 9999999+$id if you dare... :-)- as long as it is unique.
+        *
+        * @param       string  Table for the two input records
+        * @param       integer Current record (about to go offline)
+        * @param       integer Swap record (about to go online)
+        * @return void
+        * @see version_remapMMForVersionSwap()
+        */
+       function version_remapMMForVersionSwap_execSwap($table,$id,$swapWith)   {
+               
+               if (is_array($this->version_remapMMForVersionSwap_reg[$id]))    {
+                       foreach($this->version_remapMMForVersionSwap_reg[$id] as $field => $str)        {
+                               $str[0]->remapMM($str[1],$id,-$id,$str[2]);
+                       }
+               }
+
+               if (is_array($this->version_remapMMForVersionSwap_reg[$swapWith]))      {
+                       foreach($this->version_remapMMForVersionSwap_reg[$swapWith] as $field => $str)  {
+                               $str[0]->remapMM($str[1],$swapWith,$id,$str[2]);
+                       }
+               }
+
+               if (is_array($this->version_remapMMForVersionSwap_reg[$id]))    {
+                       foreach($this->version_remapMMForVersionSwap_reg[$id] as $field => $str)        {
+                               $str[0]->remapMM($str[1],-$id,$swapWith,$str[2]);
+                       }
+               }
+       }
 
 
 
@@ -4626,8 +4994,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                        // If a change has been done, set the new value(s)
                if ($set)       {
                        if ($conf['MM'])        {
-// FIXME $theUidToUpdate is undefined
-                               $dbAnalysis->writeMM($conf['MM'], $theUidToUpdate, $prependName);
+                               $dbAnalysis->writeMM($conf['MM'], $MM_localUid, $prependName);
                        } else {
                                $vArray = $dbAnalysis->getValueArray($prependName);
                                if ($conf['type']=='select')    {
@@ -4738,20 +5105,21 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                                }
 
                                        // Process the arguments with the defined function:
-                               $remapAction['args'][$remapAction['pos']['valueArray']] = call_user_func_array(
+                               $newValue = call_user_func_array(
                                        array($this, $remapAction['func']),
                                        $remapAction['args']
                                );
-
-                                       // @TODO: Add option to disable count-field
-                               $newVal = $this->checkValue_checkMax($tcaFieldConf, $remapAction['args'][$remapAction['pos']['valueArray']]);
-                               $this->updateDB($table,$id,array($field => implode(',', $newVal)));
-
+                                       // If array is returned, check for maxitems condition, if string is returned this was already done:
+                               if (is_array($newValue)) {
+                                       $newValue = implode(',', $this->checkValue_checkMax($tcaFieldConf, $newValue));
+                               }
+                                       // Update in database (list of children (csv) or number of relations (foreign_field)):
+                               $this->updateDB($table, $id, array($field => $newValue));
                                        // Process waiting Hook: processDatamap_afterDatabaseOperations:
                                if (isset($this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'])) {
                                        $hookArgs = $this->remapStackRecords[$table][$rawId]['processDatamap_afterDatabaseOperations'];
                                                // Update field with remapped data:
-                                       $hookArgs['fieldArray'][$field] = implode(',', $newVal);
+                                       $hookArgs['fieldArray'][$field] = $newValue;
                                                // Process waiting hook objects:
                                        $hookObjectsArr = $hookArgs['hookObjectsArr'];
                                        foreach($hookObjectsArr as $hookObj)    {
@@ -4912,7 +5280,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                }
                return $res;
        }
-
+       
        /**
         * Checks if a table is allowed on a certain page id according to allowed tables set for the page "doktype" and its [ctrl][rootLevel]-settings if any.
         *
@@ -5525,6 +5893,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
         */
        function updateRefIndex($table,$id)     {
                $refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
+               /* @var $refIndexObj t3lib_refindex */
                $result = $refIndexObj->updateRefIndexTable($table,$id);
        }
 
@@ -5583,18 +5952,18 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                                                $row =  $lookForLiveVersion;
                                        }
 
-                                               // If the record happends to be it self
+                                               // If the record should be inserted after itself, keep the current sorting information:
                                        if ($row['uid']==$uid)  {
                                                $sortNumber = $row[$sortRow];
                                        } else {
                                                $subres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                                                               $sortRow.',pid,uid',
-                                                                               $table,
-                                                                               'pid='.intval($row['pid']).' AND '.$sortRow.'>='.intval($row[$sortRow]).$this->deleteClause($table),
-                                                                               '',
-                                                                               $sortRow.' ASC',
-                                                                               '2'
-                                                                       );              // Fetches the next record in order to calculate the in between sortNumber
+                                                       $sortRow.',pid,uid',
+                                                       $table,
+                                                       'pid='.intval($row['pid']).' AND '.$sortRow.'>='.intval($row[$sortRow]).$this->deleteClause($table),
+                                                       '',
+                                                       $sortRow.' ASC',
+                                                       '2'
+                                               );              // Fetches the next record in order to calculate the in-between sortNumber
                                                if ($GLOBALS['TYPO3_DB']->sql_num_rows($subres)==2)     {       // There was a record afterwards
                                                        $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);                         // Forward to the second result...
                                                        $subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);       // There was a record afterwards
@@ -5605,6 +5974,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                                                } else {        // If after the last record in the list, we just add the sortInterval to the last sortvalue
                                                        $sortNumber = $row[$sortRow]+$this->sortIntervals;
                                                }
+                                               $GLOBALS['TYPO3_DB']->sql_free_result($subres);
                                        }
                                        return Array('pid' => $row['pid'], 'sortNumber' => $sortNumber);
                                } else {
@@ -5913,7 +6283,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
        function dbAnalysisStoreExec()  {
                reset($this->dbAnalysisStore);
                while(list($k,$v)=each($this->dbAnalysisStore)) {
-                       $id = $this->substNEWwithIDs[$v[2]];
+                       $id = t3lib_BEfunc::wsMapId($v[4],$this->substNEWwithIDs[$v[2]]);
                        if ($id)        {
                                $v[2] = $id;
                                $v[0]->writeMM($v[1],$v[2],$v[3]);
@@ -6098,7 +6468,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
         * @return      boolean         True if DB reference field (group/db or select with foreign-table)
         */
        function isReferenceField($conf)        {
-               return ($conf['type']=='group' && $conf['internal_type']=='db') ||      ($conf['type']=='select' && $conf['foreign_table']);
+               return ($conf['type']=='group' && $conf['internal_type']=='db' || $conf['type']=='select' && $conf['foreign_table']);
        }
 
        /**
@@ -6120,6 +6490,7 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                return false;
        }
 
+
        /**
         * Get modified header for a copied record
         *
@@ -6273,13 +6644,14 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
         *
         * @param       array           Workspace access array (from t3lib_userauthgroup::checkWorkspace())
         * @param       integer         New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
-        * @param       string          Table name of element
-        * @param       integer         Record uid of element
+        * @param       string          Table name of element (or list of element names if $id is zero)
+        * @param       integer         Record uid of element (if zero, then $table is used as reference to element(s) alone)
         * @param       string          User comment sent along with action
         * @return      void
         */
        function notifyStageChange($stat,$stageId,$table,$id,$comment)  {
                $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
+               $elementName = $id ? $table.':'.$id : $table;   // So, if $id is not set, then $table is taken to be the complete element name!
 
                if (is_array($workspaceRec))    {
 
@@ -6332,13 +6704,24 @@ $this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stag
                                break;
                        }
                        $emails = array_unique($emails);
-
-                               // Send email:
-                       if (count($emails))     {
-                               $message = sprintf('
+                       
+                               // Path to record is found:
+                       list($eTable,$eUid) = explode(':',$elementName);
+                       $eUid = intval($eUid);
+                       $rr = t3lib_BEfunc::getRecord($eTable,$eUid);
+                       $recTitle = t3lib_BEfunc::getRecordTitle($eTable,$rr);                  
+                       if ($eTable!='pages')   {
+                               t3lib_BEfunc::fixVersioningPid($eTable,$rr);
+                               $eUid=$rr['pid'];
+                       }
+                       $path = t3lib_BEfunc::getRecordPath($eUid,'',20);
+                       
+                               // ALternative messages:
+                       $TSConfig = $this->getTCEMAIN_TSconfig($eUid);
+                       $body = trim($TSConfig['notificationEmail_body']) ? trim($TSConfig['notificationEmail_body']) : '
 At the TYPO3 site "%s" (%s)
 in workspace "%s" (#%s)
-the stage has changed for the element "%s":
+the stage has changed for the element(s) "%11$s" (%s) at location "%10$s" in the page tree:
 
 ==> %s
 
@@ -6346,20 +6729,27 @@ User Comment:
 "%s"
 
 State was change by %s (username: %s)
-                               ',
+                       ';
+                       $subject = trim($TSConfig['notificationEmail_subject']) ? trim($TSConfig['notificationEmail_subject']) : 'TYPO3 Workspace Note: Stage Change for %s';
+                       
+                               // Send email:
+                       if (count($emails))     {
+                               $message = sprintf($body,
                                $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
                                t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir,
                                $workspaceRec['title'],
                                $workspaceRec['uid'],
-                               $table.':'.$id,
+                               $elementName,
                                $newStage,
                                $comment,
                                $this->BE_USER->user['realName'],
-                               $this->BE_USER->user['username']);
+                               $this->BE_USER->user['username'],
+                               $path,
+                               $recTitle);
 
                                t3lib_div::plainMailEncoded(
                                        implode(',',$emails),
-                                       'TYPO3 Workspace Note: Stage Change for '.$table.':'.$id,
+                                       sprintf($subject,$elementName),
                                        trim($message)
                                );
                        }