Fixed bug #10104: IRRE - Controll icons in header of newly created child elements...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_befunc.php
index 4c39276..d7bfad1 100755 (executable)
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
 /***************************************************************
 *  Copyright notice
 *
-*  (c) 1999-2004 Kasper Skaarhoj (kasper@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
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
  * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  * XHTML compliant
  *
  * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  * XHTML compliant
  *
- * @author     Kasper Skaarhoj <kasper@typo3.com>
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
  */
 /**
  * [CLASS/FUNCTION INDEX of SCRIPT]
  *
  *
  *
- *  162: class t3lib_BEfunc
+ *  185: class t3lib_BEfunc
  *
  *              SECTION: SQL-related, selecting records, searching
  *
  *              SECTION: SQL-related, selecting records, searching
- *  182:     function deleteClause($table)
- *  205:     function getRecord($table,$uid,$fields='*',$where='')
- *  227:     function getRecordRaw($table,$where='',$fields='*')
- *  249:     function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')
- *  281:     function searchQuery($searchWords,$fields,$table='')
- *  296:     function listQuery($field,$value)
- *  308:     function splitTable_Uid($str)
- *  323:     function getSQLselectableList($in_list,$tablename,$default_tablename)
- *  351:     function BEenableFields($table,$inv=0)
+ *  206:     function deleteClause($table,$tableAlias='')
+ *  230:     function getRecord($table,$uid,$fields='*',$where='',$useDeleteClause=true)
+ *  253:     function getRecordWSOL($table,$uid,$fields='*',$where='',$useDeleteClause=true)
+ *  286:     function getRecordRaw($table,$where='',$fields='*')
+ *  309:     function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='',$useDeleteClause=true)
+ *  342:     function searchQuery($searchWords,$fields,$table='')
+ *  357:     function listQuery($field,$value)
+ *  369:     function splitTable_Uid($str)
+ *  384:     function getSQLselectableList($in_list,$tablename,$default_tablename)
+ *  412:     function BEenableFields($table,$inv=0)
  *
  *
- *              SECTION: SQL-related, DEPRECIATED functions
- *  415:     function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
- *  437:     function DBcompileInsert($table,$fields_values)
- *  451:     function DBcompileUpdate($table,$where,$fields_values)
+ *              SECTION: SQL-related, DEPRECATED functions
+ *  476:     function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
+ *  498:     function DBcompileInsert($table,$fields_values)
+ *  512:     function DBcompileUpdate($table,$where,$fields_values)
  *
  *              SECTION: Page tree, TCA related
  *
  *              SECTION: Page tree, TCA related
- *  480:     function BEgetRootLine($uid,$clause='')
- *  526:     function openPageTree($pid,$clearExpansion)
- *  571:     function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)
- *  608:     function getExcludeFields()
- *  642:     function readPageAccess($id,$perms_clause)
- *  671:     function getTCAtypes($table,$rec,$useFieldNameAsKey=0)
- *  724:     function getTCAtypeValue($table,$rec)
- *  747:     function getSpecConfParts($str, $defaultExtras)
- *  777:     function getSpecConfParametersFromArray($pArr)
- *  803:     function getFlexFormDS($conf,$row,$table)
+ *  542:     function BEgetRootLine($uid,$clause='',$workspaceOL=FALSE)
+ *  598:     function openPageTree($pid,$clearExpansion)
+ *  643:     function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)
+ *  686:     function getExcludeFields()
+ *  716:     function getExplicitAuthFieldValues()
+ *  787:     function getSystemLanguages()
+ *  812:     function readPageAccess($id,$perms_clause)
+ *  843:     function getTCAtypes($table,$rec,$useFieldNameAsKey=0)
+ *  896:     function getTCAtypeValue($table,$rec)
+ *  919:     function getSpecConfParts($str, $defaultExtras)
+ *  950:     function getSpecConfParametersFromArray($pArr)
+ *  978:     function getFlexFormDS($conf,$row,$table,$fieldName='',$WSOL=TRUE)
  *
  *              SECTION: Caching related
  *
  *              SECTION: Caching related
- *  907:     function storeHash($hash,$data,$ident)
- *  927:     function getHash($hash,$expTime)
+ * 1105:     function storeHash($hash,$data,$ident)
+ * 1125:     function getHash($hash)
  *
  *              SECTION: TypoScript related
  *
  *              SECTION: TypoScript related
- *  963:     function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)
- * 1014:     function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')
- * 1069:     function implodeTSParams($p,$k='')
+ * 1161:     function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)
+ * 1217:     function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')
+ * 1272:     function implodeTSParams($p,$k='')
  *
  *              SECTION: Users / Groups related
  *
  *              SECTION: Users / Groups related
- * 1106:     function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='')
- * 1124:     function getGroupNames($fields='title,uid', $where='')
- * 1141:     function getListGroupNames($fields='title,uid')
- * 1160:     function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)
- * 1193:     function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)
+ * 1309:     function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='')
+ * 1327:     function getGroupNames($fields='title,uid', $where='')
+ * 1344:     function getListGroupNames($fields='title,uid')
+ * 1363:     function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)
+ * 1396:     function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)
  *
  *              SECTION: Output related
  *
  *              SECTION: Output related
- * 1236:     function daysUntil($tstamp)
- * 1248:     function date($tstamp)
- * 1259:     function datetime($value)
- * 1271:     function time($value)
- * 1287:     function calcAge($seconds,$labels)
- * 1313:     function dateTimeAge($tstamp,$prefix=1,$date='')
- * 1331:     function titleAttrib($content='',$hsc=0)
- * 1344:     function titleAltAttrib($content)
- * 1368:     function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir='',$abs=0,$tparams='',$size='')
- * 1436:     function getThumbNail($thumbScript,$theFile,$tparams='',$size='')
- * 1453:     function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)
- * 1511:     function getRecordIconAltText($row,$table='pages')
- * 1545:     function getLabelFromItemlist($table,$col,$key)
- * 1571:     function getItemLabel($table,$col,$printAllWrap='')
- * 1596:     function getRecordTitle($table,$row,$prep=0)
- * 1632:     function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0)
- * 1726:     function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0)
- * 1750:     function getFileIcon($ext)
- * 1764:     function getCommonSelectFields($table,$prefix)
- * 1790:     function makeConfigForm($configArray,$defaults,$dataPrefix)
+ * 1437:     function daysUntil($tstamp)
+ * 1449:     function date($tstamp)
+ * 1460:     function datetime($value)
+ * 1472:     function time($value)
+ * 1488:     function calcAge($seconds,$labels = 'min|hrs|days|yrs')
+ * 1514:     function dateTimeAge($tstamp,$prefix=1,$date='')
+ * 1532:     function titleAttrib($content='',$hsc=0)
+ * 1545:     function titleAltAttrib($content)
+ * 1569:     function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='')
+ * 1637:     function getThumbNail($thumbScript,$theFile,$tparams='',$size='')
+ * 1654:     function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)
+ * 1716:     function getRecordIconAltText($row,$table='pages')
+ * 1758:     function getLabelFromItemlist($table,$col,$key)
+ * 1784:     function getItemLabel($table,$col,$printAllWrap='')
+ * 1809:     function getRecordTitle($table,$row,$prep=0)
+ * 1847:     function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0)
+ * 2009:     function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0)
+ * 2033:     function getFileIcon($ext)
+ * 2047:     function getCommonSelectFields($table,$prefix='')
+ * 2090:     function makeConfigForm($configArray,$defaults,$dataPrefix)
  *
  *              SECTION: Backend Modules API functions
  *
  *              SECTION: Backend Modules API functions
- * 1865:     function helpTextIcon($table,$field,$BACK_PATH,$force=0)
- * 1886:     function helpText($table,$field,$BACK_PATH)
- * 1906:     function editOnClick($params,$backPath='',$requestUri='')
- * 1922:     function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='')
- * 1948:     function getModTSconfig($id,$TSref)
- * 1969:     function getFuncMenu($id,$elementName,$currentValue,$menuItems,$script='',$addparams='')
- * 1998:     function getFuncCheck($id,$elementName,$currentValue,$script='',$addparams='',$tagParams='')
- * 2018:     function getFuncInput($id,$elementName,$currentValue,$size=10,$script="",$addparams="")
- * 2034:     function unsetMenuItems($modTSconfig,$itemArray,$TSref)
- * 2057:     function getSetUpdateSignal($set='')
- * 2108:     function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')
+ * 2165:     function helpTextIcon($table,$field,$BACK_PATH,$force=0)
+ * 2187:     function helpText($table,$field,$BACK_PATH,$styleAttrib='')
+ * 2239:     function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='')
+ * 2277:     function editOnClick($params,$backPath='',$requestUri='')
+ * 2296:     function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE)
+ * 2328:     function getModTSconfig($id,$TSref)
+ * 2349:     function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')
+ * 2392:     function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='')
+ * 2417:     function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="")
+ * 2438:     function unsetMenuItems($modTSconfig,$itemArray,$TSref)
+ * 2461:     function getSetUpdateSignal($set='')
+ * 2512:     function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')
  *
  *              SECTION: Core
  *
  *              SECTION: Core
- * 2183:     function lockRecords($table='',$uid=0,$pid=0)
- * 2212:     function isRecordLocked($table,$uid)
- * 2252:     function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')
- * 2333:     function getTCEFORM_TSconfig($table,$row)
- * 2380:     function getTSconfig_pidValue($table,$uid,$pid)
- * 2408:     function getPidForModTSconfig($table,$uid,$pid)
- * 2424:     function getTSCpid($table,$uid,$pid)
- * 2440:     function firstDomainRecord($rootLine)
- * 2462:     function getDomainStartPage($domain, $path='')
- * 2492:     function RTEsetup($RTEprop,$table,$field,$type='')
- * 2510:     function &RTEgetObj()
- * 2549:     function isModuleSetInTBE_MODULES($modName)
+ * 2585:     function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl=172800)
+ * 2613:     function lockRecords($table='',$uid=0,$pid=0)
+ * 2642:     function isRecordLocked($table,$uid)
+ * 2682:     function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')
+ * 2763:     function getTCEFORM_TSconfig($table,$row)
+ * 2814:     function getTSconfig_pidValue($table,$uid,$pid)
+ * 2844:     function getPidForModTSconfig($table,$uid,$pid)
+ * 2860:     function getTSCpid($table,$uid,$pid)
+ * 2876:     function firstDomainRecord($rootLine)
+ * 2898:     function getDomainStartPage($domain, $path='')
+ * 2928:     function RTEsetup($RTEprop,$table,$field,$type='')
+ * 2947:     function &RTEgetObj()
+ * 2986:     function &softRefParserObj($spKey)
+ * 3018:     function explodeSoftRefParserList($parserList)
+ * 3050:     function isModuleSetInTBE_MODULES($modName)
+ * 3073:     function referenceCount($table,$ref,$msg='')
+ *
+ *              SECTION: Workspaces / Versioning
+ * 3132:     function selectVersionsOfRecord($table, $uid, $fields='*', $workspace=0)
+ * 3180:     function fixVersioningPid($table,&$rr,$ignoreWorkspaceMatch=FALSE)
+ * 3220:     function workspaceOL($table,&$row,$wsid=-99)
+ * 3268:     function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*')
+ * 3297:     function getLiveVersionOfRecord($table,$uid,$fields='*')
+ * 3319:     function isPidInVersionizedBranch($pid, $table='',$returnStage=FALSE)
+ * 3342:     function versioningPlaceholderClause($table)
+ * 3356:     function countVersionsOfRecordsOnPage($workspace,$pageId, $allTables=FALSE)
+ * 3391:     function wsMapId($table,$uid)
  *
  *              SECTION: Miscellaneous
  *
  *              SECTION: Miscellaneous
- * 2598:     function typo3PrintError($header,$text,$js='',$head=1)
- * 2644:     function getPathType_web_nonweb($path)
- * 2656:     function ADMCMD_previewCmds($pageinfo)
- * 2678:     function processParams($params)
- * 2704:     function getListOfBackendModules($name,$perms_clause,$backPath='',$script='index.php')
+ * 3421:     function typo3PrintError($header,$text,$js='',$head=1)
+ * 3465:     function TYPO3_copyRightNotice()
+ * 3489:     function displayWarningMessages()
+ * 3546:     function getPathType_web_nonweb($path)
+ * 3558:     function ADMCMD_previewCmds($pageinfo)
+ * 3580:     function processParams($params)
+ * 3606:     function getListOfBackendModules($name,$perms_clause,$backPath='',$script='index.php')
  *
  *
- * TOTAL FUNCTIONS: 80
+ * TOTAL FUNCTIONS: 99
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
 
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
 
+require_once (PATH_t3lib.'class.t3lib_loaddbgroup.php');
+
 
 /**
  * Standard functions available for the TYPO3 backend.
  * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
  *
 
 /**
  * Standard functions available for the TYPO3 backend.
  * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
  *
- * @author     Kasper Skaarhoj <kasper@typo3.com>
+ * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage t3lib
  */
  * @package TYPO3
  * @subpackage t3lib
  */
-class t3lib_BEfunc     {
+final class t3lib_BEfunc {
 
 
 
 
 
 
@@ -177,21 +200,22 @@ class t3lib_BEfunc        {
         * Usage: 71
         *
         * @param       string          Table name present in $TCA
         * Usage: 71
         *
         * @param       string          Table name present in $TCA
-        * @return      string          WHERE clause for filtering out deleted records, eg " AND NOT tablename.deleted"
+        * @param       string          Table alias if any
+        * @return      string          WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
         */
         */
-       function deleteClause($table)   {
+       public static function deleteClause($table,$tableAlias = '') {
                global $TCA;
                global $TCA;
-               if ($TCA[$table]['ctrl']['delete'])     {
-                       return ' AND NOT '.$table.'.'.$TCA[$table]['ctrl']['delete'];
+               if ($TCA[$table]['ctrl']['delete']) {
+                       return ' AND '.($tableAlias ? $tableAlias : $table).'.'.$TCA[$table]['ctrl']['delete'].'=0';
                } else {
                        return '';
                }
        }
 
        /**
                } else {
                        return '';
                }
        }
 
        /**
-        * Gets record with uid=$uid from $table
+        * Gets record with uid = $uid from $table
         * You can set $field to a list of fields (default is '*')
         * You can set $field to a list of fields (default is '*')
-        * Additional WHERE clauses can be added by $where (fx. ' AND blabla=1')
+        * Additional WHERE clauses can be added by $where (fx. ' AND blabla = 1')
         * Will automatically check if records has been deleted and if so, not return anything.
         * $table must be found in $TCA
         * Usage: 99
         * Will automatically check if records has been deleted and if so, not return anything.
         * $table must be found in $TCA
         * Usage: 99
@@ -199,36 +223,75 @@ class t3lib_BEfunc        {
         * @param       string          Table name present in $TCA
         * @param       integer         UID of record
         * @param       string          List of fields to select
         * @param       string          Table name present in $TCA
         * @param       integer         UID of record
         * @param       string          List of fields to select
-        * @param       string          Additional WHERE clause, eg. " AND blablabla=0"
+        * @param       string          Additional WHERE clause, eg. " AND blablabla = 0"
+        * @param       boolean         Use the deleteClause to check if a record is deleted (default true)
         * @return      array           Returns the row if found, otherwise nothing
         */
         * @return      array           Returns the row if found, otherwise nothing
         */
-       function getRecord($table,$uid,$fields='*',$where='')   {
-               if ($GLOBALS['TCA'][$table])    {
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid='.intval($uid).t3lib_BEfunc::deleteClause($table).$where);
-                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+       public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
+               if ($GLOBALS['TCA'][$table]) {
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                               $fields,
+                               $table,
+                               'uid='.intval($uid).($useDeleteClause ? t3lib_BEfunc::deleteClause($table) : '').$where
+                       );
+                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+                       if ($row) {
                                return $row;
                        }
                }
        }
 
        /**
                                return $row;
                        }
                }
        }
 
        /**
+        * Like getRecord(), but overlays workspace version if any.
+        *
+        * @param       string          Table name present in $TCA
+        * @param       integer         UID of record
+        * @param       string          List of fields to select
+        * @param       string          Additional WHERE clause, eg. " AND blablabla = 0"
+        * @param       boolean         Use the deleteClause to check if a record is deleted (default true)
+        * @return      array           Returns the row if found, otherwise nothing
+        */
+       public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
+               if ($fields !== '*') {
+                       $internalFields = t3lib_div::uniqueList($fields.',uid,pid'.($table == 'pages' ? ',t3ver_swapmode' : ''));
+                       $row = t3lib_BEfunc::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
+                       t3lib_BEfunc::workspaceOL($table, $row);
+
+                       if (is_array ($row)) {
+                               foreach (array_keys($row) as $key) {
+                                       if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
+                                               unset ($row[$key]);
+                                       }
+                               }
+                       }
+               } else {
+                       $row = t3lib_BEfunc::getRecord($table, $uid, $fields, $where);
+                       t3lib_BEfunc::workspaceOL($table, $row);
+               }
+               return $row;
+       }
+
+       /**
         * Returns the first record found from $table with $where as WHERE clause
         * This function does NOT check if a record has the deleted flag set.
         * $table does NOT need to be configured in $TCA
         * The query used is simply this:
         * Returns the first record found from $table with $where as WHERE clause
         * This function does NOT check if a record has the deleted flag set.
         * $table does NOT need to be configured in $TCA
         * The query used is simply this:
-        * $query='SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
+        * $query = 'SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
         * Usage: 5 (ext: sys_todos)
         *
         * @param       string          Table name (not necessarily in TCA)
         * @param       string          WHERE clause
         * @param       string          $fields is a list of fields to select, default is '*'
         * Usage: 5 (ext: sys_todos)
         *
         * @param       string          Table name (not necessarily in TCA)
         * @param       string          WHERE clause
         * @param       string          $fields is a list of fields to select, default is '*'
-        * @return      array           First row found, if any
+        * @return      array           First row found, if any, FALSE otherwise
         */
         */
-       function getRecordRaw($table,$where='',$fields='*')     {
-               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, $where);
-               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                       return $row;
+       public static function getRecordRaw($table, $where = '', $fields = '*') {
+               $row = FALSE;
+               if (FALSE !== ($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, $where, '', '', '1'))) {
+                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
                }
+               return $row;
        }
 
        /**
        }
 
        /**
@@ -244,23 +307,25 @@ class t3lib_BEfunc        {
         * @param       string          Optional GROUP BY field(s), if none, supply blank string.
         * @param       string          Optional ORDER BY field(s), if none, supply blank string.
         * @param       string          Optional LIMIT value ([begin,]max), if none, supply blank string.
         * @param       string          Optional GROUP BY field(s), if none, supply blank string.
         * @param       string          Optional ORDER BY field(s), if none, supply blank string.
         * @param       string          Optional LIMIT value ([begin,]max), if none, supply blank string.
+        * @param       boolean         Use the deleteClause to check if a record is deleted (default true)
         * @return      mixed           Multidimensional array with selected records (if any is selected)
         */
         * @return      mixed           Multidimensional array with selected records (if any is selected)
         */
-       function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')     {
+       public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true) {
                global $TCA;
                if (is_array($TCA[$theTable])) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                '*',
                                                $theTable,
                global $TCA;
                if (is_array($TCA[$theTable])) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                '*',
                                                $theTable,
-                                               $theField.'="'.$GLOBALS['TYPO3_DB']->quoteStr($theValue, $theTable).'"'.
-                                                       t3lib_BEfunc::deleteClause($theTable).' '.
+                                               $theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
+                                                       ($useDeleteClause ? t3lib_BEfunc::deleteClause($theTable).' ' : '').
+                                                       t3lib_BEfunc::versioningPlaceholderClause($theTable).' '.
                                                        $whereClause,   // whereClauseMightContainGroupOrderBy
                                                $groupBy,
                                                $orderBy,
                                                $limit
                                        );
                        $rows = array();
                                                        $whereClause,   // whereClauseMightContainGroupOrderBy
                                                $groupBy,
                                                $orderBy,
                                                $limit
                                        );
                        $rows = array();
-                       while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
+                       while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                                $rows[] = $row;
                        }
                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
                                $rows[] = $row;
                        }
                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
@@ -276,10 +341,10 @@ class t3lib_BEfunc        {
         * @param       array           Array of fields
         * @param       string          Table in which we are searching (for DBAL detection of quoteStr() method)
         * @return      string          WHERE clause for search
         * @param       array           Array of fields
         * @param       string          Table in which we are searching (for DBAL detection of quoteStr() method)
         * @return      string          WHERE clause for search
-        * @depreciated         Use $GLOBALS['TYPO3_DB']->searchQuery() directly!
+        * @deprecated since TYPO3 3.6 - Use $GLOBALS['TYPO3_DB']->searchQuery() directly!
         */
         */
-       function searchQuery($searchWords,$fields,$table='')    {
-               return $GLOBALS['TYPO3_DB']->searchQuery($searchWords,$fields,$table);
+       public static function searchQuery($searchWords, $fields, $table = '') {
+               return $GLOBALS['TYPO3_DB']->searchQuery($searchWords, $fields, $table);
        }
 
        /**
        }
 
        /**
@@ -291,23 +356,23 @@ class t3lib_BEfunc        {
         * @param       string          Table field name
         * @param       string          Value to find in list
         * @return      string          WHERE clause for a query
         * @param       string          Table field name
         * @param       string          Value to find in list
         * @return      string          WHERE clause for a query
-        * @depreciated         Use $GLOBALS['TYPO3_DB']->listQuery() directly!
+        * @deprecated since TYPO3 3.6 - Use $GLOBALS['TYPO3_DB']->listQuery() directly!
         */
         */
-       function listQuery($field,$value)       {
-               return $GLOBALS['TYPO3_DB']->listQuery($field,$value,'');
+       public static function listQuery($field, $value) {
+               return $GLOBALS['TYPO3_DB']->listQuery($field, $value, '');
        }
 
        /**
        }
 
        /**
-        * Makes an backwards explode on the $str and returns an array with ($table,$uid).
-        * Example: tt_content_45       =>      array('tt_content',45)
+        * Makes an backwards explode on the $str and returns an array with ($table, $uid).
+        * Example: tt_content_45 => array('tt_content', 45)
         * Usage: 1
         *
         * @param       string          [tablename]_[uid] string to explode
         * @return      array
         */
         * Usage: 1
         *
         * @param       string          [tablename]_[uid] string to explode
         * @return      array
         */
-       function splitTable_Uid($str)   {
-               list($uid,$table) = explode('_',strrev($str),2);
-               return array(strrev($table),strrev($uid));
+       public static function splitTable_Uid($str) {
+               list($uid, $table) = explode('_', strrev($str), 2);
+               return array(strrev($table), strrev($uid));
        }
 
        /**
        }
 
        /**
@@ -320,60 +385,86 @@ class t3lib_BEfunc        {
         * @param       string          $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
         * @return      string          List of ids
         */
         * @param       string          $default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
         * @return      string          List of ids
         */
-       function getSQLselectableList($in_list,$tablename,$default_tablename)   {
+       public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
                $list = Array();
                $list = Array();
-               if ((string)trim($in_list)!='') {
-                       $tempItemArray = explode(',',trim($in_list));
-                       while(list($key,$val)=each($tempItemArray))     {
+               if ((string)trim($in_list)!='') {
+                       $tempItemArray = explode(',', trim($in_list));
+                       while(list($key, $val) = each($tempItemArray)) {
                                $val = strrev($val);
                                $val = strrev($val);
-                               $parts = explode('_',$val,2);
-                               if ((string)trim($parts[0])!='')        {
+                               $parts = explode('_', $val, 2);
+                               if ((string)trim($parts[0])!='') {
                                        $theID = intval(strrev($parts[0]));
                                        $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
                                        $theID = intval(strrev($parts[0]));
                                        $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
-                                       if ($theTable==$tablename)      {$list[]=$theID;}
+                                       if ($theTable==$tablename)      {$list[] = $theID;}
                                }
                        }
                }
                                }
                        }
                }
-               return implode(',',$list);
+               return implode(',', $list);
        }
 
        /**
         * Backend implementation of enableFields()
         * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
         * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
        }
 
        /**
         * Backend implementation of enableFields()
         * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
         * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
-        * $GLOBALS["SIM_EXEC_TIME"] is used for date.
+        * $GLOBALS["SIM_ACCESS_TIME"] is used for date.
         * Usage: 5
         *
         * @param       string          $table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $TCA.
         * @param       boolean         $inv means that the query will select all records NOT VISIBLE records (inverted selection)
         * @return      string          WHERE clause part
         */
         * Usage: 5
         *
         * @param       string          $table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $TCA.
         * @param       boolean         $inv means that the query will select all records NOT VISIBLE records (inverted selection)
         * @return      string          WHERE clause part
         */
-       function BEenableFields($table,$inv=0)  {
+       public static function BEenableFields($table, $inv = 0) {
                $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
                $ctrl = $GLOBALS['TCA'][$table]['ctrl'];
-               $query=array();
-               $invQuery=array();
-               if (is_array($ctrl))    {
-                       if (is_array($ctrl['enablecolumns']))   {
-                               if ($ctrl['enablecolumns']['disabled']) {
+               $query = array();
+               $invQuery = array();
+               if (is_array($ctrl)) {
+                       if (is_array($ctrl['enablecolumns'])) {
+                               if ($ctrl['enablecolumns']['disabled']) {
                                        $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
                                        $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
-                                       $query[]='NOT '.$field;
-                                       $invQuery[]=$field;
+                                       $query[] = $field.'=0';
+                                       $invQuery[] = $field.'!=0';
                                }
                                }
-                               if ($ctrl['enablecolumns']['starttime'])        {
+                               if ($ctrl['enablecolumns']['starttime']) {
                                        $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
                                        $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
-                                       $query[]='('.$field.'<='.$GLOBALS['SIM_EXEC_TIME'].')';
-                                       $invQuery[]='('.$field.'!=0 AND '.$field.'>'.$GLOBALS['SIM_EXEC_TIME'].')';
+                                       $query[] = '('.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
+                                       $invQuery[] = '('.$field.'!=0 AND '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
                                }
                                }
-                               if ($ctrl['enablecolumns']['endtime'])  {
+                               if ($ctrl['enablecolumns']['endtime']) {
                                        $field = $table.'.'.$ctrl['enablecolumns']['endtime'];
                                        $field = $table.'.'.$ctrl['enablecolumns']['endtime'];
-                                       $query[]='('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_EXEC_TIME'].')';
-                                       $invQuery[]='('.$field.'!=0 AND '.$field.'<='.$GLOBALS['SIM_EXEC_TIME'].')';
+                                       $query[] = '('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
+                                       $invQuery[] = '('.$field.'!=0 AND '.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
                                }
                        }
                }
                                }
                        }
                }
-               $outQ = ' AND '.($inv ? '('.implode(' OR ',$invQuery).')' : implode(' AND ',$query));
+               $outQ = ($inv ? '(' . implode(' OR ', $invQuery) . ')' : implode(' AND ', $query));
 
 
-               return $outQ;
+               return $outQ ? ' AND ' . $outQ : '';
+       }
+
+       /**
+        * Fetches the localization for a given record.
+        *
+        * @param       string          $table: Table name present in $TCA
+        * @param       integer         $uid: The uid of the record
+        * @param       integer         $language: The uid of the language record in sys_language
+        * @param       string          $andWhereClause: Optional additional WHERE clause (default: '')
+        * @return      mixed           Multidimensional array with selected records; if none exist, false is returned
+        */
+       public function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
+               $recordLocalization = false;
+               if (self::isTableLocalizable($table)) {
+                       $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
+                       $recordLocalization = t3lib_BEfunc::getRecordsByField(
+                               $table,
+                               $tcaCtrl['transOrigPointerField'],
+                               $uid,
+                               'AND '.$tcaCtrl['languageField'].'='.intval($language).($andWhereClause ? ' '.$andWhereClause : ''),
+                               '',
+                               '',
+                               '1'
+                       );
+               }
+               return $recordLocalization;
        }
 
 
        }
 
 
@@ -387,7 +478,7 @@ class t3lib_BEfunc  {
 
        /*******************************************
         *
 
        /*******************************************
         *
-        * SQL-related, DEPRECIATED functions
+        * SQL-related, DEPRECATED functions
         * (use t3lib_DB functions instead)
         *
         *******************************************/
         * (use t3lib_DB functions instead)
         *
         *******************************************/
@@ -398,7 +489,6 @@ class t3lib_BEfunc  {
         * $local_table and $mm_table is mandatory. $foreign_table is optional.
         * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local  / [$mm_table].uid_foreign <--> [$foreign_table].uid
         * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
         * $local_table and $mm_table is mandatory. $foreign_table is optional.
         * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local  / [$mm_table].uid_foreign <--> [$foreign_table].uid
         * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
-        * DEPRECIATED - Use $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query() instead since that will return the result pointer while this returns the query. Using this function may make your application less fitted for DBAL later.
         *
         * @param       string          Field list for SELECT
         * @param       string          Tablename, local table
         *
         * @param       string          Field list for SELECT
         * @param       string          Tablename, local table
@@ -409,10 +499,10 @@ class t3lib_BEfunc        {
         * @param       string          Optional ORDER BY field(s), if none, supply blank string.
         * @param       string          Optional LIMIT value ([begin,]max), if none, supply blank string.
         * @return      string          Full SQL query
         * @param       string          Optional ORDER BY field(s), if none, supply blank string.
         * @param       string          Optional LIMIT value ([begin,]max), if none, supply blank string.
         * @return      string          Full SQL query
-        * @depreciated
+        * @deprecated since TYPO3 3.6 - Use $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query() instead since that will return the result pointer while this returns the query. Using this function may make your application less fitted for DBAL later.
         * @see t3lib_DB::exec_SELECT_mm_query()
         */
         * @see t3lib_DB::exec_SELECT_mm_query()
         */
-       function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')      {
+       public static function mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
                $query = $GLOBALS['TYPO3_DB']->SELECTquery(
                                        $select,
                                        $local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
                $query = $GLOBALS['TYPO3_DB']->SELECTquery(
                                        $select,
                                        $local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
@@ -427,28 +517,28 @@ class t3lib_BEfunc        {
 
        /**
         * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
 
        /**
         * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
-        * DEPRECIATED - $GLOBALS['TYPO3_DB']->INSERTquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_INSERTquery()
+        * DEPRECATED - $GLOBALS['TYPO3_DB']->INSERTquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_INSERTquery()
         *
         * @param       string          Table name
         * @param       array           Field values as key=>value pairs.
         * @return      string          Full SQL query for INSERT
         *
         * @param       string          Table name
         * @param       array           Field values as key=>value pairs.
         * @return      string          Full SQL query for INSERT
-        * @depreciated
+        * @deprecated since TYPO3 3.6
         */
         */
-       function DBcompileInsert($table,$fields_values) {
+       public static function DBcompileInsert($table, $fields_values) {
                return $GLOBALS['TYPO3_DB']->INSERTquery($table, $fields_values);
        }
 
        /**
         * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
                return $GLOBALS['TYPO3_DB']->INSERTquery($table, $fields_values);
        }
 
        /**
         * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
-        * DEPRECIATED - $GLOBALS['TYPO3_DB']->UPDATEquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery()
+        * DEPRECATED - $GLOBALS['TYPO3_DB']->UPDATEquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery()
         *
         * @param       string          Database tablename
         * @param       string          WHERE clause, eg. "uid=1"
         * @param       array           Field values as key=>value pairs.
         * @return      string          Full SQL query for UPDATE
         *
         * @param       string          Database tablename
         * @param       string          WHERE clause, eg. "uid=1"
         * @param       array           Field values as key=>value pairs.
         * @return      string          Full SQL query for UPDATE
-        * @depreciated
+        * @deprecated since TYPO3 3.6
         */
         */
-       function DBcompileUpdate($table,$where,$fields_values)  {
+       public static function DBcompileUpdate($table, $where, $fields_values) {
                return $GLOBALS['TYPO3_DB']->UPDATEquery($table, $where, $fields_values);
        }
 
                return $GLOBALS['TYPO3_DB']->UPDATEquery($table, $where, $fields_values);
        }
 
@@ -474,45 +564,64 @@ class t3lib_BEfunc        {
         * Usage: 1
         *
         * @param       integer         Page id for which to create the root line.
         * Usage: 1
         *
         * @param       integer         Page id for which to create the root line.
-        * @param       string          $clause can be used to select other criteria. It would typically be where-clauses that stops the proces if we meet a page, the user has no reading access to.
+        * @param       string          $clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
+        * @param       boolean         If true, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
         * @return      array           Root line array, all the way to the page tree root (or as far as $clause allows!)
         */
         * @return      array           Root line array, all the way to the page tree root (or as far as $clause allows!)
         */
-       function BEgetRootLine($uid,$clause='') {
+       public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
+               if (is_array($GLOBALS['T3_VAR']['BEgetRootLine_cache'][$uid][$clause][$workspaceOL?1:0])) {
+                       return $GLOBALS['T3_VAR']['BEgetRootLine_cache'][$uid][$clause][$workspaceOL?1:0];
+               }
+               $pid = $uid;
                $loopCheck = 100;
                $theRowArray = Array();
                $loopCheck = 100;
                $theRowArray = Array();
-               $output=Array();
-               while ($uid!=0 && $loopCheck>0) {
+               $output = Array();
+               while ($uid!=0 && $loopCheck>0) {
                        $loopCheck--;
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                        $loopCheck--;
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                                       'pid,uid,title,TSconfig,is_siteroot,storage_pid',
-                                                       'pages',
-                                                       'uid='.intval($uid).' '.
-                                                               t3lib_BEfunc::deleteClause('pages').' '.
-                                                               $clause         // whereClauseMightContainGroupOrderBy
-                                               );
-                       if ($GLOBALS['TYPO3_DB']->sql_error())  {
-                               debug($GLOBALS['TYPO3_DB']->sql_error(),1);
+                               'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,t3ver_stage',
+                               'pages',
+                               'uid='.intval($uid).' '.
+                                       t3lib_BEfunc::deleteClause('pages').' '.
+                                       $clause         // whereClauseMightContainGroupOrderBy
+                       );
+                       if ($GLOBALS['TYPO3_DB']->sql_error()) {
+                               debug($GLOBALS['TYPO3_DB']->sql_error(), 1);
                        }
                        }
-                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                               $uid = $row['pid'];
-                               $theRowArray[]=$row;
+                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                               if($workspaceOL)        t3lib_BEfunc::workspaceOL('pages', $row);
+                               if (is_array($row)) {
+                                       t3lib_BEfunc::fixVersioningPid('pages', $row);
+                                       $uid = $row['pid'];
+                                       $theRowArray[] = $row;
+                               } else break;
                        } else {
                                break;
                        }
                        } else {
                                break;
                        }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
                }
-               if ($uid==0) {$theRowArray[]=Array('uid'=>0,'title'=>'');}
-               if (is_array($theRowArray))     {
+               if ($uid==0) {$theRowArray[] = Array('uid'=>0, 'title'=>'');}
+               if (is_array($theRowArray)) {
                        reset($theRowArray);
                        reset($theRowArray);
-                       $c=count($theRowArray);
-                       while(list($key,$val)=each($theRowArray))       {
+                       $c = count($theRowArray);
+                       while(list($key, $val) = each($theRowArray)) {
                                $c--;
                                $output[$c]['uid'] = $val['uid'];
                                $c--;
                                $output[$c]['uid'] = $val['uid'];
+                               $output[$c]['pid'] = $val['pid'];
+                               if (isset($val['_ORIG_pid'])) $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
                                $output[$c]['title'] = $val['title'];
                                $output[$c]['TSconfig'] = $val['TSconfig'];
                                $output[$c]['is_siteroot'] = $val['is_siteroot'];
                                $output[$c]['storage_pid'] = $val['storage_pid'];
                                $output[$c]['title'] = $val['title'];
                                $output[$c]['TSconfig'] = $val['TSconfig'];
                                $output[$c]['is_siteroot'] = $val['is_siteroot'];
                                $output[$c]['storage_pid'] = $val['storage_pid'];
+                               $output[$c]['t3ver_oid'] = $val['t3ver_oid'];
+                               $output[$c]['t3ver_wsid'] = $val['t3ver_wsid'];
+                               $output[$c]['t3ver_state'] = $val['t3ver_state'];
+                               $output[$c]['t3ver_swapmode'] = $val['t3ver_swapmode'];
+                               $output[$c]['t3ver_stage'] = $val['t3ver_stage'];
                        }
                }
                        }
                }
+               $GLOBALS['T3_VAR']['BEgetRootLine_cache'][$pid][$clause][$workspaceOL?1:0] = $output;
+
                return $output;
        }
 
                return $output;
        }
 
@@ -523,11 +632,11 @@ class t3lib_BEfunc        {
         * @param       boolean         If set, then other open branches are closed.
         * @return      void
         */
         * @param       boolean         If set, then other open branches are closed.
         * @return      void
         */
-       function openPageTree($pid,$clearExpansion)     {
+       public static function openPageTree($pid, $clearExpansion) {
                global $BE_USER;
 
                        // Get current expansion data:
                global $BE_USER;
 
                        // Get current expansion data:
-               if ($clearExpansion)    {
+               if ($clearExpansion) {
                        $expandedPages = array();
                } else {
                        $expandedPages = unserialize($BE_USER->uc['browseTrees']['browsePages']);
                        $expandedPages = array();
                } else {
                        $expandedPages = unserialize($BE_USER->uc['browseTrees']['browsePages']);
@@ -539,15 +648,15 @@ class t3lib_BEfunc        {
                        // First, find out what mount index to use (if more than one DB mount exists):
                $mountIndex = 0;
                $mountKeys = array_flip($BE_USER->returnWebmounts());
                        // First, find out what mount index to use (if more than one DB mount exists):
                $mountIndex = 0;
                $mountKeys = array_flip($BE_USER->returnWebmounts());
-               foreach($rL as $rLDat)  {
-                       if (isset($mountKeys[$rLDat['uid']]))   {
+               foreach($rL as $rLDat) {
+                       if (isset($mountKeys[$rLDat['uid']])) {
                                $mountIndex = $mountKeys[$rLDat['uid']];
                                break;
                        }
                }
 
                        // Traverse rootline and open paths:
                                $mountIndex = $mountKeys[$rLDat['uid']];
                                break;
                        }
                }
 
                        // Traverse rootline and open paths:
-               foreach($rL as $rLDat)  {
+               foreach($rL as $rLDat) {
                        $expandedPages[$mountIndex][$rLDat['uid']] = 1;
                }
 
                        $expandedPages[$mountIndex][$rLDat['uid']] = 1;
                }
 
@@ -568,30 +677,39 @@ class t3lib_BEfunc        {
         * @param       integer         Title limit of Full title (typ. set to 1000 or so)
         * @return      mixed           Path of record (string) OR array with short/long title if $fullTitleLimit is set.
         */
         * @param       integer         Title limit of Full title (typ. set to 1000 or so)
         * @return      mixed           Path of record (string) OR array with short/long title if $fullTitleLimit is set.
         */
-       function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)   {
-               if (!$titleLimit) { $titleLimit=1000; }
+       public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
+               if (!$titleLimit) { $titleLimit = 1000; }
 
                $loopCheck = 100;
                $output = $fullOutput = '/';
 
                $loopCheck = 100;
                $output = $fullOutput = '/';
-               while ($uid!=0 && $loopCheck>0) {
+               while ($uid!=0 && $loopCheck>0) {
                        $loopCheck--;
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                        $loopCheck--;
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                               'pid,title',
+                                               'uid,pid,title,t3ver_oid,t3ver_wsid,t3ver_swapmode',
                                                'pages',
                                                'uid='.intval($uid).
                                                        t3lib_BEfunc::deleteClause('pages').
                                                        (strlen(trim($clause)) ? ' AND '.$clause : '')
                                        );
                                                'pages',
                                                'uid='.intval($uid).
                                                        t3lib_BEfunc::deleteClause('pages').
                                                        (strlen(trim($clause)) ? ' AND '.$clause : '')
                                        );
-                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                               $uid = $row['pid'];
-                               $output = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']),$titleLimit).$output;
-                               if ($fullTitleLimit)    $fullOutput = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']),$fullTitleLimit).$fullOutput;
+                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                               t3lib_BEfunc::workspaceOL('pages', $row);
+                               if (is_array($row)) {
+                                       t3lib_BEfunc::fixVersioningPid('pages', $row);
+
+                                       if ($row['_ORIG_pid'] && $row['t3ver_swapmode']>0)      {       // Branch points
+                                               $output = ' [#VEP#]'.$output;           // Adding visual token - Versioning Entry Point - that tells that THIS position was where the versionized branch got connected to the main tree. I will have to find a better name or something...
+                                       }
+                                       $uid = $row['pid'];
+                                       $output = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']), $titleLimit).$output;
+                                       if ($fullTitleLimit)    $fullOutput = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']), $fullTitleLimit).$fullOutput;
+                               } else break;
                        } else {
                                break;
                        }
                        } else {
                                break;
                        }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
 
                }
 
-               if ($fullTitleLimit)    {
+               if ($fullTitleLimit) {
                        return array($output, $fullOutput);
                } else {
                        return $output;
                        return array($output, $fullOutput);
                } else {
                        return $output;
@@ -605,23 +723,23 @@ class t3lib_BEfunc        {
         *
         * @return      array           Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries
         */
         *
         * @return      array           Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries
         */
-       function getExcludeFields()     {
+       public static function getExcludeFields() {
                global $TCA;
                        // All TCA keys:
                $theExcludeArray = Array();
                $tc_keys = array_keys($TCA);
                global $TCA;
                        // All TCA keys:
                $theExcludeArray = Array();
                $tc_keys = array_keys($TCA);
-               foreach($tc_keys as $table)     {
+               foreach($tc_keys as $table) {
                                // Load table
                        t3lib_div::loadTCA($table);
                                // All field names configured:
                                // Load table
                        t3lib_div::loadTCA($table);
                                // All field names configured:
-                       if (is_array($TCA[$table]['columns']))  {
+                       if (is_array($TCA[$table]['columns'])) {
                                $f_keys = array_keys($TCA[$table]['columns']);
                                $f_keys = array_keys($TCA[$table]['columns']);
-                               foreach($f_keys as $field)      {
-                                       if ($TCA[$table]['columns'][$field]['exclude']) {
+                               foreach($f_keys as $field) {
+                                       if ($TCA[$table]['columns'][$field]['exclude']) {
                                                        // Get Human Readable names of fields and table:
                                                        // Get Human Readable names of fields and table:
-                                               $Fname=$GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
+                                               $Fname = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
                                                        // add entry:
                                                        // add entry:
-                                               $theExcludeArray[] = Array($Fname , $table.':'.$field);
+                                               $theExcludeArray[] = Array($Fname, $table.':'.$field);
                                        }
                                }
                        }
                                        }
                                }
                        }
@@ -630,6 +748,140 @@ class t3lib_BEfunc        {
        }
 
        /**
        }
 
        /**
+        * Returns an array with explicit Allow/Deny fields.
+        * Used for listing these field/value pairs in be_groups forms
+        *
+        * @return      array           Array with information from all of $TCA
+        */
+       public static function getExplicitAuthFieldValues() {
+               global $TCA;
+
+                       // Initialize:
+               $adLabel = array(
+                       'ALLOW' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.allow'),
+                       'DENY' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.deny'),
+               );
+
+                       // All TCA keys:
+               $allowDenyOptions = Array();
+               $tc_keys = array_keys($TCA);
+               foreach($tc_keys as $table)     {
+
+                               // Load table
+                       t3lib_div::loadTCA($table);
+
+                               // All field names configured:
+                       if (is_array($TCA[$table]['columns'])) {
+                               $f_keys = array_keys($TCA[$table]['columns']);
+                               foreach($f_keys as $field) {
+                                       $fCfg = $TCA[$table]['columns'][$field]['config'];
+                                       if ($fCfg['type']=='select' && $fCfg['authMode'])       {
+
+                                                       // Check for items:
+                                               if (is_array($fCfg['items'])) {
+                                                               // Get Human Readable names of fields and table:
+                                                       $allowDenyOptions[$table.':'.$field]['tableFieldLabel'] = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
+
+                                                               // Check for items:
+                                                       foreach($fCfg['items'] as $iVal) {
+                                                               if (strcmp($iVal[1], ''))       {       // Values '' is not controlled by this setting.
+
+                                                                               // Find iMode:
+                                                                       $iMode = '';
+                                                                       switch((string)$fCfg['authMode']) {
+                                                                               case 'explicitAllow':
+                                                                                       $iMode = 'ALLOW';
+                                                                               break;
+                                                                               case 'explicitDeny':
+                                                                                       $iMode = 'DENY';
+                                                                               break;
+                                                                               case 'individual':
+                                                                                       if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
+                                                                                               $iMode = 'ALLOW';
+                                                                                       } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
+                                                                                               $iMode = 'DENY';
+                                                                                       }
+                                                                               break;
+                                                                       }
+
+                                                                               // Set iMode:
+                                                                       if ($iMode) {
+                                                                               $allowDenyOptions[$table.':'.$field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
+                                                                       }
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               return $allowDenyOptions;
+       }
+
+       /**
+        * Returns an array with system languages:
+        *
+        * @return      array           Array with languages
+        */
+       public static function getSystemLanguages()     {
+
+                       // Initialize, add default language:
+               $sysLanguages = array();
+               $sysLanguages[] = array('Default language', 0);
+
+                       // Traverse languages
+               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,flag', 'sys_language', 'pid=0'.t3lib_BEfunc::deleteClause('sys_language'));
+               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                       $sysLanguages[] = array($row['title'].' ['.$row['uid'].']', $row['uid'], ($row['flag'] ? 'flags/'.$row['flag'] : ''));
+               }
+               $GLOBALS['TYPO3_DB']->sql_free_result($res);
+
+               return $sysLanguages;
+       }
+
+       /**
+        * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $TCA.
+        *
+        * @param       string          $table: The table to check
+        * @return      boolean         Whether a table is localizable
+        */
+       public function isTableLocalizable($table) {
+               $isLocalizable = false;
+               if (isset($GLOBALS['TCA'][$table]['ctrl']) && is_array($GLOBALS['TCA'][$table]['ctrl'])) {
+                       $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
+                       $isLocalizable = (isset($tcaCtrl['languageField']) && $tcaCtrl['languageField'] && isset($tcaCtrl['transOrigPointerField']) && $tcaCtrl['transOrigPointerField']);
+               }
+               return $isLocalizable;
+       }
+
+       /**
+        * Returns the value of the property localizationMode in the given $config array ($TCA[<table>]['columns'][<field>]['config']).
+        * If the table is prepared for localization and no localizationMode is set, 'select' is returned by default.
+        * If the table is not prepared for localization or not defined at all in $TCA, false is returned.
+        *
+        * @param       string          $table: The name of the table to lookup in TCA
+        * @param       mixed           $fieldOrConfig: The fieldname (string) or the configuration of the field to check (array)
+        * @return      mixed           If table is localizable, the set localizationMode is returned (if property is not set, 'select' is returned by default); if table is not localizable, false is returned
+        */
+       public function getInlineLocalizationMode($table, $fieldOrConfig) {
+               $localizationMode = false;
+               if (is_array($fieldOrConfig) && count($fieldOrConfig)) {
+                       $config = $fieldOrConfig;
+               } elseif (is_string($fieldOrConfig) && isset($GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'])) {
+                       $config = $GLOBALS['TCA'][$table]['columns'][$fieldOrConfig]['config'];
+               }
+               if (is_array($config) && isset($config['type']) && $config['type']=='inline' && self::isTableLocalizable($table)) {
+                       $localizationMode = (isset($config['behaviour']['localizationMode']) && $config['behaviour']['localizationMode'] ? $config['behaviour']['localizationMode'] : 'select');
+                               // The mode 'select' is not possible when child table is not localizable at all:
+                       if ($localizationMode=='select' && !self::isTableLocalizable($config['foreign_table'])) {
+                               $localizationMode = false;
+                       }
+               }
+               return $localizationMode;
+       }
+
+       /**
         * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
         * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
         * In any case ->isInWebMount must return true for the user (regardless of $perms_clause)
         * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
         * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
         * In any case ->isInWebMount must return true for the user (regardless of $perms_clause)
@@ -639,20 +891,24 @@ class t3lib_BEfunc        {
         * @param       string          $perms_clause is typically a value generated with $BE_USER->getPagePermsClause(1);
         * @return      array           Returns page record if OK, otherwise false.
         */
         * @param       string          $perms_clause is typically a value generated with $BE_USER->getPagePermsClause(1);
         * @return      array           Returns page record if OK, otherwise false.
         */
-       function readPageAccess($id,$perms_clause)      {
-               if ((string)$id!='')    {
+       public static function readPageAccess($id, $perms_clause) {
+               if ((string)$id!='') {
                        $id = intval($id);
                        $id = intval($id);
-                       if (!$id)       {
-                               if ($GLOBALS['BE_USER']->isAdmin())     {
+                       if (!$id) {
+                               if ($GLOBALS['BE_USER']->isAdmin()) {
                                        $path = '/';
                                        $pageinfo['_thePath'] = $path;
                                        return $pageinfo;
                                }
                        } else {
                                        $path = '/';
                                        $pageinfo['_thePath'] = $path;
                                        return $pageinfo;
                                }
                        } else {
-                               $pageinfo = t3lib_BEfunc::getRecord('pages',$id,'*',($perms_clause ? ' AND '.$perms_clause : ''));
-                               if ($pageinfo['uid'] && $GLOBALS['BE_USER']->isInWebMount($id,$perms_clause))   {
-                                       list($pageinfo['_thePath'],$pageinfo['_thePathFull']) = t3lib_BEfunc::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
-                                       return $pageinfo;
+                               $pageinfo = t3lib_BEfunc::getRecord('pages', $id, '*', ($perms_clause ? ' AND '.$perms_clause : ''));
+                               if ($pageinfo['uid'] && $GLOBALS['BE_USER']->isInWebMount($id, $perms_clause)) {
+                                       t3lib_BEfunc::workspaceOL('pages', $pageinfo);
+                                       if (is_array($pageinfo)) {
+                                               t3lib_BEfunc::fixVersioningPid('pages', $pageinfo);
+                                               list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = t3lib_BEfunc::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
+                                               return $pageinfo;
+                                       }
                                }
                        }
                }
                                }
                        }
                }
@@ -668,14 +924,14 @@ class t3lib_BEfunc        {
         * @param       boolean         If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
         * @return      array
         */
         * @param       boolean         If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
         * @return      array
         */
-       function getTCAtypes($table,$rec,$useFieldNameAsKey=0)  {
+       public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
                global $TCA;
 
                t3lib_div::loadTCA($table);
                if ($TCA[$table])       {
 
                                // Get type value:
                global $TCA;
 
                t3lib_div::loadTCA($table);
                if ($TCA[$table])       {
 
                                // Get type value:
-                       $fieldValue = t3lib_BEfunc::getTCAtypeValue($table,$rec);
+                       $fieldValue = t3lib_BEfunc::getTCAtypeValue($table, $rec);
 
                                // Get typesConf
                        $typesConf = $TCA[$table]['types'][$fieldValue];
 
                                // Get typesConf
                        $typesConf = $TCA[$table]['types'][$fieldValue];
@@ -685,23 +941,23 @@ class t3lib_BEfunc        {
                        $altFieldList = array();
 
                                // Traverse fields in types config and parse the configuration into a nice array:
                        $altFieldList = array();
 
                                // Traverse fields in types config and parse the configuration into a nice array:
-                       foreach($fieldList as $k => $v) {
+                       foreach($fieldList as $k => $v) {
                                list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
                                $defaultExtras = is_array($TCA[$table]['columns'][$pFieldName]) ? $TCA[$table]['columns'][$pFieldName]['defaultExtras'] : '';
                                $specConfParts = t3lib_BEfunc::getSpecConfParts($pSpec, $defaultExtras);
 
                                list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
                                $defaultExtras = is_array($TCA[$table]['columns'][$pFieldName]) ? $TCA[$table]['columns'][$pFieldName]['defaultExtras'] : '';
                                $specConfParts = t3lib_BEfunc::getSpecConfParts($pSpec, $defaultExtras);
 
-                               $fieldList[$k]=array(
+                               $fieldList[$k] = array(
                                        'field' => $pFieldName,
                                        'title' => $pAltTitle,
                                        'palette' => $pPalette,
                                        'spec' => $specConfParts,
                                        'origString' => $v
                                );
                                        'field' => $pFieldName,
                                        'title' => $pAltTitle,
                                        'palette' => $pPalette,
                                        'spec' => $specConfParts,
                                        'origString' => $v
                                );
-                               if ($useFieldNameAsKey) {
+                               if ($useFieldNameAsKey) {
                                        $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
                                }
                        }
                                        $altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
                                }
                        }
-                       if ($useFieldNameAsKey) {
+                       if ($useFieldNameAsKey) {
                                $fieldList = $altFieldList;
                        }
 
                                $fieldList = $altFieldList;
                        }
 
@@ -721,12 +977,12 @@ class t3lib_BEfunc        {
         * @return      string          Field value
         * @see getTCAtypes()
         */
         * @return      string          Field value
         * @see getTCAtypes()
         */
-       function getTCAtypeValue($table,$rec)   {
+       public static function getTCAtypeValue($table, $rec) {
                global $TCA;
 
                        // If no field-value, set it to zero. If there is no type matching the field-value (which now may be zero...) test field-value '1' as default.
                t3lib_div::loadTCA($table);
                global $TCA;
 
                        // If no field-value, set it to zero. If there is no type matching the field-value (which now may be zero...) test field-value '1' as default.
                t3lib_div::loadTCA($table);
-               if ($TCA[$table])       {
+               if ($TCA[$table]) {
                        $field = $TCA[$table]['ctrl']['type'];
                        $fieldValue = $field ? ($rec[$field] ? $rec[$field] : 0) : 0;
                        if (!is_array($TCA[$table]['types'][$fieldValue]))      $fieldValue = 1;
                        $field = $TCA[$table]['ctrl']['type'];
                        $fieldValue = $field ? ($rec[$field] ? $rec[$field] : 0) : 0;
                        if (!is_array($TCA[$table]['types'][$fieldValue]))      $fieldValue = 1;
@@ -744,15 +1000,16 @@ class t3lib_BEfunc       {
         * @param       string          The ['defaultExtras'] value from field configuration
         * @return      array
         */
         * @param       string          The ['defaultExtras'] value from field configuration
         * @return      array
         */
-       function getSpecConfParts($str, $defaultExtras) {
+       public static function getSpecConfParts($str, $defaultExtras)   {
 
                        // Add defaultExtras:
                $specConfParts = t3lib_div::trimExplode(':', $defaultExtras.':'.$str, 1);
 
 
                        // Add defaultExtras:
                $specConfParts = t3lib_div::trimExplode(':', $defaultExtras.':'.$str, 1);
 
-               if (count($specConfParts))      {
-                       foreach($specConfParts as $k2 => $v2)   {
+               $reg = array();
+               if (count($specConfParts)) {
+                       foreach($specConfParts as $k2 => $v2) {
                                unset($specConfParts[$k2]);
                                unset($specConfParts[$k2]);
-                               if (ereg('(.*)\[(.*)\]',$v2,$reg))      {
+                               if (ereg('(.*)\[(.*)\]', $v2, $reg)) {
                                        $specConfParts[trim($reg[1])] = array(
                                                'parameters' => t3lib_div::trimExplode('|', $reg[2], 1)
                                        );
                                        $specConfParts[trim($reg[1])] = array(
                                                'parameters' => t3lib_div::trimExplode('|', $reg[2], 1)
                                        );
@@ -767,23 +1024,23 @@ class t3lib_BEfunc       {
        }
 
        /**
        }
 
        /**
-        * Takes an array of "[key]=[value]" strings and returns an array with the keys set as keys pointing to the value.
+        * Takes an array of "[key] = [value]" strings and returns an array with the keys set as keys pointing to the value.
         * Better see it in action! Find example in Inside TYPO3
         * Usage: 6
         *
         * Better see it in action! Find example in Inside TYPO3
         * Usage: 6
         *
-        * @param       array           Array of "[key]=[value]" strings to convert.
+        * @param       array           Array of "[key] = [value]" strings to convert.
         * @return      array
         */
         * @return      array
         */
-       function getSpecConfParametersFromArray($pArr)  {
-               $out=array();
-               if (is_array($pArr))    {
+       public static function getSpecConfParametersFromArray($pArr) {
+               $out = array();
+               if (is_array($pArr)) {
                        reset($pArr);
                        reset($pArr);
-                       while(list($k,$v)=each($pArr))  {
-                               $parts=explode('=',$v,2);
-                               if (count($parts)==2)   {
-                                       $out[trim($parts[0])]=trim($parts[1]);
+                       while(list($k, $v) = each($pArr)) {
+                               $parts = explode('=', $v, 2);
+                               if (count($parts)==2) {
+                                       $out[trim($parts[0])] = trim($parts[1]);
                                } else {
                                } else {
-                                       $out[$k]=$v;
+                                       $out[$k] = $v;
                                }
                        }
                }
                                }
                        }
                }
@@ -792,15 +1049,20 @@ class t3lib_BEfunc       {
 
        /**
         * Finds the Data Structure for a FlexForm field
 
        /**
         * Finds the Data Structure for a FlexForm field
+        * NOTE ON data structures for deleted records: This function may fail to deliver the data structure for a record for a few reasons: a) The data structure could be deleted (either with deleted-flagged or hard-deleted), b) the data structure is fetched using the ds_pointerField_searchParent in which case any deleted record on the route to the final location of the DS will make it fail. In theory, we can solve the problem in the case where records that are deleted-flagged keeps us from finding the DS - this is done at the markers ###NOTE_A### where we make sure to also select deleted records. However, we generally want the DS lookup to fail for deleted records since for the working website we expect a deleted-flagged record to be as inaccessible as one that is completely deleted from the DB. Any way we look at it, this may lead to integrity problems of the reference index and even lost files if attached. However, that is not really important considering that a single change to a data structure can instantly invalidate large amounts of the reference index which we do accept as a cost for the flexform features. Other than requiring a reference index update, deletion of/changes in data structure or the failure to look them up when completely deleting records may lead to lost files in the uploads/ folders since those are now without a proper reference.
         * Usage: 5
         *
         * @param       array           Field config array
         * @param       array           Record data
         * @param       string          The table name
         * Usage: 5
         *
         * @param       array           Field config array
         * @param       array           Record data
         * @param       string          The table name
+        * @param       string          Optional fieldname passed to hook object
+        * @param       boolean         Boolean; If set, workspace overlay is applied to records. This is correct behaviour for all presentation and export, but NOT if you want a true reflection of how things are in the live workspace.
+        * @param       integer         SPECIAL CASES: Use this, if the DataStructure may come from a parent record and the INPUT row doesn't have a uid yet (hence, the pid cannot be looked up). Then it is necessary to supply a PID value to search recursively in for the DS (used from TCEmain)
         * @return      mixed           If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
         * @see t3lib_TCEforms::getSingleField_typeFlex()
         */
         * @return      mixed           If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
         * @see t3lib_TCEforms::getSingleField_typeFlex()
         */
-       function getFlexFormDS($conf,$row,$table)       {
+       public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
+               global $TYPO3_CONF_VARS;
 
                        // Get pointer field etc from TCA-config:
                $ds_pointerField =      $conf['ds_pointerField'];
 
                        // Get pointer field etc from TCA-config:
                $ds_pointerField =      $conf['ds_pointerField'];
@@ -808,22 +1070,37 @@ class t3lib_BEfunc       {
                $ds_tableField =        $conf['ds_tableField'];
                $ds_searchParentField =         $conf['ds_pointerField_searchParent'];
 
                $ds_tableField =        $conf['ds_tableField'];
                $ds_searchParentField =         $conf['ds_pointerField_searchParent'];
 
-
                        // Find source value:
                        // Find source value:
-               $dataStructArray='';
+               $dataStructArray = '';
                if (is_array($ds_array))        {       // If there is a data source array, that takes precedence
                                // If a pointer field is set, take the value from that field in the $row array and use as key.
                        if ($ds_pointerField)   {
                if (is_array($ds_array))        {       // If there is a data source array, that takes precedence
                                // If a pointer field is set, take the value from that field in the $row array and use as key.
                        if ($ds_pointerField)   {
-                               $srcPointer = $row[$ds_pointerField];
+
+                                       // Up to two pointer fields can be specified in a comma separated list.
+                               $pointerFields = t3lib_div::trimExplode(',', $ds_pointerField);
+                               if(count($pointerFields) == 2) { // If we have two pointer fields, the array keys should contain both field values separated by comma. The asterisk "*" catches all values. For backwards compatibility, it's also possible to specify only the value of the first defined ds_pointerField.
+                                       if($ds_array[$row[$pointerFields[0]].','.$row[$pointerFields[1]]]) {    // Check if we have a DS for the combination of both pointer fields values
+                                               $srcPointer = $row[$pointerFields[0]].','.$row[$pointerFields[1]];
+                                       } elseif($ds_array[$row[$pointerFields[1]].',*']) {     // Check if we have a DS for the value of the first pointer field suffixed with ",*"
+                                               $srcPointer = $row[$pointerFields[1]].',*';
+                                       } elseif($ds_array['*,'.$row[$pointerFields[1]]]) {     // Check if we have a DS for the value of the second pointer field prefixed with "*,"
+                                               $srcPointer = '*,'.$row[$pointerFields[1]];
+                                       } elseif($ds_array[$row[$pointerFields[0]]]) {  // Check if we have a DS for just the value of the first pointer field (mainly for backwards compatibility)
+                                               $srcPointer = $row[$pointerFields[0]];
+                                       }
+                               } else {
+                                       $srcPointer = $row[$pointerFields[0]];
+                               }
+
                                $srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
                                $srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
-                       } else $srcPointer='default';
+                       } else $srcPointer = 'default';
 
                                // Get Data Source: Detect if it's a file reference and in that case read the file and parse as XML. Otherwise the value is expected to be XML.
 
                                // Get Data Source: Detect if it's a file reference and in that case read the file and parse as XML. Otherwise the value is expected to be XML.
-                       if (substr($ds_array[$srcPointer],0,5)=='FILE:')        {
-                               $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer],5));
-                               if ($file && @is_file($file))   {
+                       if (substr($ds_array[$srcPointer], 0, 5)=='FILE:') {
+                               $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
+                               if ($file && @is_file($file)) {
                                        $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
                                        $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
-                               } else $dataStructArray = 'The file "'.substr($dsSrc,5).'" in ds-array key "'.$srcPointer.'" was not found ("'.$file.'")';      // Error message.
+                               } else $dataStructArray = 'The file "'.substr($ds_array[$srcPointer], 5).'" in ds-array key "'.$srcPointer.'" was not found ("'.$file.'")';     // Error message.
                        } else {
                                $dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
                        }
                        } else {
                                $dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
                        }
@@ -833,40 +1110,66 @@ class t3lib_BEfunc       {
                        $srcPointer = $row[$ds_pointerField];
 
                                // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
                        $srcPointer = $row[$ds_pointerField];
 
                                // Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
-                       if ($ds_searchParentField && !$srcPointer)      {
-                               $rr = t3lib_BEfunc::getRecord($table,$row['uid'],$ds_searchParentField);        // Get the "pid" field - we cannot know that it is in the input record!
-                               $uidAcc=array();        // Used to avoid looping, if any should happen.
+                       if ($ds_searchParentField && !$srcPointer) {
+                               $rr = t3lib_BEfunc::getRecord($table, $row['uid'], 'uid,'.$ds_searchParentField);       // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
+                               if ($WSOL) {
+                                       t3lib_BEfunc::workspaceOL($table, $rr);
+                                       t3lib_BEfunc::fixVersioningPid($table, $rr, TRUE);      // Added "TRUE" 23/03/06 before 4.0. (Also to similar call below!).  Reason: When t3lib_refindex is scanning the system in Live workspace all Pages with FlexForms will not find their inherited datastructure. Thus all references from workspaces are removed! Setting TRUE means that versioning PID doesn't check workspace of the record. I can't see that this should give problems anywhere. See more information inside t3lib_refindex!
+                               }
+                               $uidAcc = array();      // Used to avoid looping, if any should happen.
                                $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
                                while(!$srcPointer)             {
                                $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
                                while(!$srcPointer)             {
+
                                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                                        'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
                                                                        $table,
                                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                                        'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
                                                                        $table,
-                                                                       'uid='.intval($rr[$ds_searchParentField]).t3lib_BEfunc::deleteClause($table)
+                                                                       'uid='.intval($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField]).t3lib_BEfunc::deleteClause($table)  ###NOTE_A###
                                                                );
                                                                );
+                                       $newRecordPidValue = 0;
                                        $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                                        $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
-                                       if (!is_array($rr) || isset($uidAcc[$rr['uid']]))       break;  // break if no result from SQL db or if looping...
-                                       $uidAcc[$rr['uid']]=1;
+                                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+
+                                               // break if no result from SQL db or if looping...
+                                       if (!is_array($rr) || isset($uidAcc[$rr['uid']]))       break;
+                                       $uidAcc[$rr['uid']] = 1;
 
 
+                                       if ($WSOL) {
+                                               t3lib_BEfunc::workspaceOL($table, $rr);
+                                               t3lib_BEfunc::fixVersioningPid($table, $rr, TRUE);
+                                       }
                                        $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
                                }
                        }
 
                                // If there is a srcPointer value:
                                        $srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
                                }
                        }
 
                                // If there is a srcPointer value:
-                       if ($srcPointer)        {
+                       if ($srcPointer) {
                                if (t3lib_div::testInt($srcPointer))    {       // If integer, then its a record we will look up:
                                if (t3lib_div::testInt($srcPointer))    {       // If integer, then its a record we will look up:
-                                       list($tName,$fName) = explode(':',$ds_tableField,2);
-                                       if ($tName && $fName && is_array($GLOBALS['TCA'][$tName]))      {
+                                       list($tName, $fName) = explode(':', $ds_tableField, 2);
+                                       if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
                                                $dataStructRec = t3lib_BEfunc::getRecord($tName, $srcPointer);
                                                $dataStructRec = t3lib_BEfunc::getRecord($tName, $srcPointer);
+                                               if ($WSOL) {
+                                                       t3lib_BEfunc::workspaceOL($tName, $dataStructRec);
+                                               }
                                                $dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
                                        } else $dataStructArray = 'No tablename ('.$tName.') or fieldname ('.$fName.') was found an valid!';
                                } else {        // Otherwise expect it to be a file:
                                        $file = t3lib_div::getFileAbsFileName($srcPointer);
                                                $dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
                                        } else $dataStructArray = 'No tablename ('.$tName.') or fieldname ('.$fName.') was found an valid!';
                                } else {        // Otherwise expect it to be a file:
                                        $file = t3lib_div::getFileAbsFileName($srcPointer);
-                                       if ($file && @is_file($file))   {
+                                       if ($file && @is_file($file)) {
                                                $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
                                                $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
-                                       } else $dataStructArray='The file "'.$srcPointer.'" was not found ("'.$file.'")';       // Error message.
+                                       } else $dataStructArray = 'The file "'.$srcPointer.'" was not found ("'.$file.'")';     // Error message.
                                }
                                }
-                       } else $dataStructArray='No source value in fieldname "'.$ds_pointerField.'"';  // Error message.
-               } else $dataStructArray='No proper configuration!';
+                       } else $dataStructArray = 'No source value in fieldname "'.$ds_pointerField.'"';        // Error message.
+               } else $dataStructArray = 'No proper configuration!';
+
+                       // Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
+               if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
+                               $hookObj = &t3lib_div::getUserObj($classRef);
+                               if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
+                                       $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
+                               }
+                       }
+               }
 
                return $dataStructArray;
        }
 
                return $dataStructArray;
        }
@@ -895,45 +1198,45 @@ class t3lib_BEfunc       {
         *******************************************/
 
        /**
         *******************************************/
 
        /**
-        * Stores the string value $data in the 'cache_hash' table with the hash key, $hash, and visual/symbolic identification, $ident
+        * Stores the string value $data in the 'cache_hash' cache with the
+        * hash key, $hash, and visual/symbolic identification, $ident
         * IDENTICAL to the function by same name found in t3lib_page:
         * Usage: 2
         *
         * IDENTICAL to the function by same name found in t3lib_page:
         * Usage: 2
         *
-        * @param       string          Hash key, 32 bytes hex
-        * @param       string          $data must be serialized before function call
-        * @param       string          Visual/symbolic identification (informational only)
+        * @param       string          32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
+        * @param       string          The data string. If you want to store an array, then just serialize it first.
+        * @param       string          $ident is just a textual identification in order to inform about the content!
         * @return      void
         */
         * @return      void
         */
-       function storeHash($hash,$data,$ident)  {
-               $insertFields = array(
-                       'hash' => $hash,
-                       'content' => $data,
-                       'ident' => $ident,
-                       'tstamp' => time()
+       public static function storeHash($hash, $data, $ident) {
+               $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
+                       $hash,
+                       $data,
+                       array('ident_' . $ident),
+                       0 // unlimited lifetime
                );
                );
-               $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash="'.$GLOBALS['TYPO3_DB']->quoteStr($hash, 'cache_hash').'"');
-               $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
        }
 
        /**
        }
 
        /**
-        * Retrieves the string content stored with hash key, $hash, in cache_hash
-        * IDENTICAL to the function by same name found in t3lib_page:
-        * Usage: 2
+        * Returns string value stored for the hash string in the cache "cache_hash"
+        * Can be used to retrieved a cached value
+        *
+        * IDENTICAL to the function by same name found in t3lib_page
         *
         *
-        * @param       string          Hash key, 32 bytes hex
-        * @param       integer         $expTime represents the expire time in seconds. For instance a value of 3600 would allow cached content within the last hour, otherwise nothing is returned.
+        * @param       string          The hash-string which was used to store the data value
         * @return      string
         */
         * @return      string
         */
-       function getHash($hash,$expTime)        {
-                       // if expTime is not set, the hash will never expire
-               $expTime = intval($expTime);
-               if ($expTime)   {
-                       $whereAdd = ' AND tstamp > '.(time()-$expTime);
-               }
-               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash="'.$GLOBALS['TYPO3_DB']->quoteStr($hash, 'cache_hash').'"'.$whereAdd);
-               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                       return $row['content'];
+       public static function getHash($hash) {
+               $hashContent = null;
+
+               $contentHashCache = $GLOBALS['typo3CacheManager']->getCache('cache_hash');
+               $cacheEntry = $contentHashCache->get($hash);
+
+               if ($cacheEntry) {
+                       $hashContent = $cacheEntry;
                }
                }
+
+               return $hashContent;
        }
 
 
        }
 
 
@@ -960,35 +1263,40 @@ class t3lib_BEfunc       {
         * @return      array           Page TSconfig
         * @see t3lib_TSparser
         */
         * @return      array           Page TSconfig
         * @see t3lib_TSparser
         */
-       function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)  {
-               $id=intval($id);
-               if (!is_array($rootLine))       {
-                       $rootLine = t3lib_BEfunc::BEgetRootLine($id,'');
+       public static function getPagesTSconfig($id, $rootLine = '', $returnPartArray = 0) {
+               $id = intval($id);
+               if (!is_array($rootLine)) {
+                       $rootLine = t3lib_BEfunc::BEgetRootLine($id, '', TRUE);
                }
                }
-               ksort($rootLine);       // Order correctly, changed 030102
-               reset($rootLine);
+               ksort($rootLine);       // Order correctly
                $TSdataArray = array();
                $TSdataArray = array();
-               $TSdataArray['defaultPageTSconfig']=$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];   // Setting default configuration:
-               while(list($k,$v)=each($rootLine))      {
-                       $TSdataArray['uid_'.$v['uid']]=$v['TSconfig'];
+               $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
+               foreach($rootLine as $k => $v) {
+                       $TSdataArray['uid_'.$v['uid']] = $v['TSconfig'];
                }
                $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
                }
                $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
-               if ($returnPartArray)   {
+               if ($returnPartArray) {
                        return $TSdataArray;
                }
 
                        // Parsing the user TS (or getting from cache)
                        return $TSdataArray;
                }
 
                        // Parsing the user TS (or getting from cache)
-               $userTS = implode($TSdataArray,chr(10).'[GLOBAL]'.chr(10));
+               $userTS = implode($TSdataArray, chr(10).'[GLOBAL]'.chr(10));
                $hash = md5('pageTS:'.$userTS);
                $hash = md5('pageTS:'.$userTS);
-               $cachedContent = t3lib_BEfunc::getHash($hash,0);
+               $cachedContent = t3lib_BEfunc::getHash($hash);
                $TSconfig = array();
                $TSconfig = array();
-               if (isset($cachedContent))      {
+               if (isset($cachedContent)) {
                        $TSconfig = unserialize($cachedContent);
                } else {
                        $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
                        $parseObj->parse($userTS);
                        $TSconfig = $parseObj->setup;
                        $TSconfig = unserialize($cachedContent);
                } else {
                        $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
                        $parseObj->parse($userTS);
                        $TSconfig = $parseObj->setup;
-                       t3lib_BEfunc::storeHash($hash,serialize($TSconfig),'PAGES_TSconfig');
+                       t3lib_BEfunc::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
+               }
+
+                       // get User TSconfig overlay
+               $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
+               if (is_array($userTSconfig)) {
+                       $TSconfig = t3lib_div::array_merge_recursive_overrule($TSconfig, $userTSconfig);
                }
                return $TSconfig;
        }
                }
                return $TSconfig;
        }
@@ -1011,47 +1319,47 @@ class t3lib_BEfunc      {
         * @internal
         * @see implodeTSParams(), getPagesTSconfig()
         */
         * @internal
         * @see implodeTSParams(), getPagesTSconfig()
         */
-       function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')   {
-               $id=intval($id);
-               if (is_array($pageTS) && $id>0) {
-                       if (!is_array($impParams))      {
+       public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
+               $id = intval($id);
+               if (is_array($pageTS) && $id>0) {
+                       if (!is_array($impParams)) {
                                $impParams =t3lib_BEfunc::implodeTSParams(t3lib_BEfunc::getPagesTSconfig($id));
                        }
                        reset($pageTS);
                                $impParams =t3lib_BEfunc::implodeTSParams(t3lib_BEfunc::getPagesTSconfig($id));
                        }
                        reset($pageTS);
-                       $set=array();
-                       while(list($f,$v)=each($pageTS))        {
+                       $set = array();
+                       while(list($f, $v) = each($pageTS)) {
                                $f = $TSconfPrefix.$f;
                                $f = $TSconfPrefix.$f;
-                               if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]),trim($v)))        {
-                                       $set[$f]=trim($v);
+                               if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
+                                       $set[$f] = trim($v);
                                }
                        }
                                }
                        }
-                       if (count($set))        {
+                       if (count($set)) {
                                        // Get page record and TS config lines
                                        // Get page record and TS config lines
-                               $pRec = t3lib_befunc::getRecord('pages',$id);
-                               $TSlines = explode(chr(10),$pRec['TSconfig']);
+                               $pRec = t3lib_befunc::getRecord('pages', $id);
+                               $TSlines = explode(chr(10), $pRec['TSconfig']);
                                $TSlines = array_reverse($TSlines);
                                        // Reset the set of changes.
                                reset($set);
                                $TSlines = array_reverse($TSlines);
                                        // Reset the set of changes.
                                reset($set);
-                               while(list($f,$v)=each($set))   {
+                               while(list($f, $v) = each($set)) {
                                        reset($TSlines);
                                        reset($TSlines);
-                                       $inserted=0;
-                                       while(list($ki,$kv)=each($TSlines))     {
-                                               if (substr($kv,0,strlen($f)+1)==$f.'=') {
-                                                       $TSlines[$ki]=$f.'='.$v;
-                                                       $inserted=1;
+                                       $inserted = 0;
+                                       while(list($ki, $kv) = each($TSlines)) {
+                                               if (substr($kv, 0, strlen($f)+1)==$f.'=') {
+                                                       $TSlines[$ki] = $f.'='.$v;
+                                                       $inserted = 1;
                                                        break;
                                                }
                                        }
                                                        break;
                                                }
                                        }
-                                       if (!$inserted) {
+                                       if (!$inserted) {
                                                $TSlines = array_reverse($TSlines);
                                                $TSlines = array_reverse($TSlines);
-                                               $TSlines[]=$f.'='.$v;
+                                               $TSlines[] = $f.'='.$v;
                                                $TSlines = array_reverse($TSlines);
                                        }
                                }
                                $TSlines = array_reverse($TSlines);
 
                                        // store those changes
                                                $TSlines = array_reverse($TSlines);
                                        }
                                }
                                $TSlines = array_reverse($TSlines);
 
                                        // store those changes
-                               $TSconf = implode(chr(10),$TSlines);
+                               $TSconf = implode(chr(10), $TSlines);
 
                                $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
                        }
 
                                $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
                        }
@@ -1066,15 +1374,15 @@ class t3lib_BEfunc      {
         * @param       string          Prefix string
         * @return      array           Imploded TypoScript objectstring/values
         */
         * @param       string          Prefix string
         * @return      array           Imploded TypoScript objectstring/values
         */
-       function implodeTSParams($p,$k='')      {
-               $implodeParams=array();
-               if (is_array($p))       {
+       public static function implodeTSParams($p, $k = '') {
+               $implodeParams = array();
+               if (is_array($p)) {
                        reset($p);
                        reset($p);
-                       while(list($kb,$val)=each($p))  {
-                               if (is_array($val))     {
-                                       $implodeParams = array_merge($implodeParams,t3lib_BEfunc::implodeTSParams($val,$k.$kb));
+                       while(list($kb, $val) = each($p)) {
+                               if (is_array($val)) {
+                                       $implodeParams = array_merge($implodeParams, t3lib_BEfunc::implodeTSParams($val, $k.$kb));
                                } else {
                                } else {
-                                       $implodeParams[$k.$kb]=$val;
+                                       $implodeParams[$k.$kb] = $val;
                                }
                        }
                }
                                }
                        }
                }
@@ -1103,13 +1411,15 @@ class t3lib_BEfunc      {
         * @param       string          Optional $where clause (fx. "AND username='pete'") can be used to limit query
         * @return      array
         */
         * @param       string          Optional $where clause (fx. "AND username='pete'") can be used to limit query
         * @return      array
         */
-       function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='') {
-               $be_user_Array=Array();
+       public static function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
+               $be_user_Array = Array();
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_users'), '', 'username');
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_users'), '', 'username');
-               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
-                       $be_user_Array[$row['uid']]=$row;
+               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                       $be_user_Array[$row['uid']] = $row;
                }
                }
+               $GLOBALS['TYPO3_DB']->sql_free_result($res);
+
                return $be_user_Array;
        }
 
                return $be_user_Array;
        }
 
@@ -1121,12 +1431,15 @@ class t3lib_BEfunc      {
         * @param       string          WHERE clause
         * @return      array
         */
         * @param       string          WHERE clause
         * @return      array
         */
-       function getGroupNames($fields='title,uid', $where='')  {
+       public static function getGroupNames($fields = 'title,uid', $where = '') {
                $be_group_Array = Array();
                $be_group_Array = Array();
+
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_groups'), '', 'title');
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_groups'), '', 'title');
-               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
+               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                        $be_group_Array[$row['uid']] = $row;
                }
                        $be_group_Array[$row['uid']] = $row;
                }
+               $GLOBALS['TYPO3_DB']->sql_free_result($res);
+
                return $be_group_Array;
        }
 
                return $be_group_Array;
        }
 
@@ -1138,12 +1451,12 @@ class t3lib_BEfunc      {
         * @param       string          Field list; $fields specify the fields selected (default: title,uid)
         * @return      array
         */
         * @param       string          Field list; $fields specify the fields selected (default: title,uid)
         * @return      array
         */
-       function getListGroupNames($fields='title,uid') {
-               $exQ=' AND hide_in_lists=0';
-               if (!$GLOBALS['BE_USER']->isAdmin())    {
+       public static function getListGroupNames($fields = 'title, uid') {
+               $exQ = ' AND hide_in_lists=0';
+               if (!$GLOBALS['BE_USER']->isAdmin()) {
                        $exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
                }
                        $exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
                }
-               return t3lib_BEfunc::getGroupNames($fields,$exQ);
+               return t3lib_BEfunc::getGroupNames($fields, $exQ);
        }
 
        /**
        }
 
        /**
@@ -1157,24 +1470,24 @@ class t3lib_BEfunc      {
         * @param       boolean         If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * @return      array           User names, blinded
         */
         * @param       boolean         If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * @return      array           User names, blinded
         */
-       function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)   {
-               if (is_array($usernames) && is_array($groupArray))      {
-                       while(list($uid,$row)=each($usernames)) {
-                               $userN=$uid;
-                               $set=0;
-                               if ($row['uid']!=$GLOBALS['BE_USER']->user['uid'])      {
+       public static function blindUserNames($usernames, $groupArray, $excludeBlindedFlag = 0) {
+               if (is_array($usernames) && is_array($groupArray)) {
+                       while(list($uid, $row) = each($usernames)) {
+                               $userN = $uid;
+                               $set = 0;
+                               if ($row['uid']!=$GLOBALS['BE_USER']->user['uid']) {
                                        reset($groupArray);
                                        reset($groupArray);
-                                       while(list(,$v)=each($groupArray))      {
-                                               if ($v && t3lib_div::inList($row['usergroup_cached_list'],$v))  {
+                                       while(list(,$v) = each($groupArray)) {
+                                               if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
                                                        $userN = $row['username'];
                                                        $userN = $row['username'];
-                                                       $set=1;
+                                                       $set = 1;
                                                }
                                        }
                                } else {
                                        $userN = $row['username'];
                                                }
                                        }
                                } else {
                                        $userN = $row['username'];
-                                       $set=1;
+                                       $set = 1;
                                }
                                }
-                               $usernames[$uid]['username']=$userN;
+                               $usernames[$uid]['username'] = $userN;
                                if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
                        }
                }
                                if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
                        }
                }
@@ -1190,16 +1503,16 @@ class t3lib_BEfunc      {
         * @param       boolean         If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * @return      array
         */
         * @param       boolean         If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * @return      array
         */
-       function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)     {
-               if (is_array($groups) && is_array($groupArray)) {
-                       while(list($uid,$row)=each($groups))    {
-                               $groupN=$uid;
-                               $set=0;
-                               if (t3lib_div::inArray($groupArray,$uid))       {
-                                       $groupN=$row['title'];
-                                       $set=1;
+       public static function blindGroupNames($groups, $groupArray, $excludeBlindedFlag = 0) {
+               if (is_array($groups) && is_array($groupArray)) {
+                       while(list($uid, $row) = each($groups)) {
+                               $groupN = $uid;
+                               $set = 0;
+                               if (t3lib_div::inArray($groupArray, $uid)) {
+                                       $groupN = $row['title'];
+                                       $set = 1;
                                }
                                }
-                               $groups[$uid]['title']=$groupN;
+                               $groups[$uid]['title'] = $groupN;
                                if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
                        }
                }
                                if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
                        }
                }
@@ -1224,8 +1537,6 @@ class t3lib_BEfunc        {
         *
         *******************************************/
 
         *
         *******************************************/
 
-
-
        /**
         * Returns the difference in days between input $tstamp and $EXEC_TIME
         * Usage: 2 (class t3lib_BEfunc)
        /**
         * Returns the difference in days between input $tstamp and $EXEC_TIME
         * Usage: 2 (class t3lib_BEfunc)
@@ -1233,7 +1544,7 @@ class t3lib_BEfunc        {
         * @param       integer         Time stamp, seconds
         * @return      integer
         */
         * @param       integer         Time stamp, seconds
         * @return      integer
         */
-       function daysUntil($tstamp)     {
+       public static function daysUntil($tstamp) {
                $delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
                return ceil($delta_t/(3600*24));
        }
                $delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
                return ceil($delta_t/(3600*24));
        }
@@ -1245,8 +1556,8 @@ class t3lib_BEfunc        {
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
-       function date($tstamp)  {
-               return Date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'],$tstamp);
+       public static function date($tstamp) {
+               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $tstamp);
        }
 
        /**
        }
 
        /**
@@ -1256,8 +1567,8 @@ class t3lib_BEfunc        {
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
-       function datetime($value)       {
-               return Date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],$value);
+       public static function datetime($value) {
+               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
        }
 
        /**
        }
 
        /**
@@ -1266,13 +1577,17 @@ class t3lib_BEfunc      {
         * Usage: 1 (class t3lib_BEfunc)
         *
         * @param       integer         Time stamp, seconds
         * Usage: 1 (class t3lib_BEfunc)
         *
         * @param       integer         Time stamp, seconds
+        * @param       boolean         Output hh:mm:ss. If false: hh:mm
         * @return      string          Formatted time
         */
         * @return      string          Formatted time
         */
-       function time($value)   {
+       public static function time($value, $withSeconds = TRUE) {
                $hh = floor($value/3600);
                $min = floor(($value-$hh*3600)/60);
                $sec = $value-$hh*3600-$min*60;
                $hh = floor($value/3600);
                $min = floor(($value-$hh*3600)/60);
                $sec = $value-$hh*3600-$min*60;
-               $l = sprintf('%02d',$hh).':'.sprintf('%02d',$min).':'.sprintf('%02d',$sec);
+               $l = sprintf('%02d', $hh).':'.sprintf('%02d', $min);
+               if ($withSeconds) {
+                       $l .= ':'.sprintf('%02d', $sec);
+               }
                return $l;
        }
 
                return $l;
        }
 
@@ -1284,18 +1599,18 @@ class t3lib_BEfunc      {
         * @param       string          $labels should be something like ' min| hrs| days| yrs'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
         * @return      string          Formatted time
         */
         * @param       string          $labels should be something like ' min| hrs| days| yrs'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
         * @return      string          Formatted time
         */
-       function calcAge($seconds,$labels)      {
-               $labelArr = explode('|',$labels);
-               $prefix='';
-               if ($seconds<0) {$prefix='-'; $seconds=abs($seconds);}
-               if ($seconds<3600)      {
-                       $seconds = round ($seconds/60).$labelArr[0];
-               } elseif ($seconds<24*3600)     {
-                       $seconds = round ($seconds/3600).$labelArr[1];
-               } elseif ($seconds<365*24*3600) {
-                       $seconds = round ($seconds/(24*3600)).$labelArr[2];
+       public static function calcAge($seconds, $labels = 'min|hrs|days|yrs') {
+               $labelArr = explode('|', $labels);
+               $prefix = '';
+               if ($seconds<0) {$prefix = '-'; $seconds = abs($seconds);}
+               if ($seconds<3600) {
+                       $seconds = round ($seconds/60).' '.trim($labelArr[0]);
+               } elseif ($seconds<24*3600) {
+                       $seconds = round ($seconds/3600).' '.trim($labelArr[1]);
+               } elseif ($seconds<365*24*3600) {
+                       $seconds = round ($seconds/(24*3600)).' '.trim($labelArr[2]);
                } else {
                } else {
-                       $seconds = round ($seconds/(365*24*3600)).$labelArr[3];
+                       $seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
                }
                return $prefix.$seconds;
        }
                }
                return $prefix.$seconds;
        }
@@ -1310,14 +1625,14 @@ class t3lib_BEfunc      {
         * @param       string          $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
         * @return      string
         */
         * @param       string          $date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
         * @return      string
         */
-       function dateTimeAge($tstamp,$prefix=1,$date='')        {
+       public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
                return $tstamp ?
                                ($date=='date' ? t3lib_BEfunc::date($tstamp) : t3lib_BEfunc::datetime($tstamp)).
                return $tstamp ?
                                ($date=='date' ? t3lib_BEfunc::date($tstamp) : t3lib_BEfunc::datetime($tstamp)).
-                               ' ('.t3lib_BEfunc::calcAge($prefix*(time()-$tstamp),$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')' : '';
+                               ' ('.t3lib_BEfunc::calcAge($prefix*(time()-$tstamp), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')' : '';
        }
 
        /**
        }
 
        /**
-        * Returns either title='' or alt='' attribute. This depends on the client browser and whether it supports title='' or not (which is the default)
+        * Returns either title = '' or alt = '' attribute. This depends on the client browser and whether it supports title = '' or not (which is the default)
         * If no $content is given only the attribute name is returned.
         * The returned attribute with content will have a leading space char.
         * Warning: Be careful to submit empty $content var - that will return just the attribute name!
         * If no $content is given only the attribute name is returned.
         * The returned attribute with content will have a leading space char.
         * Warning: Be careful to submit empty $content var - that will return just the attribute name!
@@ -1326,12 +1641,12 @@ class t3lib_BEfunc      {
         * @param       string          String to set as title-attribute. If no $content is given only the attribute name is returned.
         * @param       boolean         If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
         * @return      string
         * @param       string          String to set as title-attribute. If no $content is given only the attribute name is returned.
         * @param       boolean         If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
         * @return      string
-        * @depreciated         The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
+        * @deprecated since TYPO3 3.6 - The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
         */
         */
-       function titleAttrib($content='',$hsc=0)        {
+       public static function titleAttrib($content = '', $hsc = 0) {
                global $CLIENT;
                $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
                global $CLIENT;
                $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
-               return strcmp($content,'')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
+               return strcmp($content, '')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
        }
 
        /**
        }
 
        /**
@@ -1341,8 +1656,8 @@ class t3lib_BEfunc        {
         * @param       string          Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
         * @return      string
         */
         * @param       string          Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
         * @return      string
         */
-       function titleAltAttrib($content)       {
-               $out='';
+       public static function titleAltAttrib($content) {
+               $out = '';
                $out.=' alt="'.htmlspecialchars($content).'"';
                $out.=' title="'.htmlspecialchars($content).'"';
                return $out;
                $out.=' alt="'.htmlspecialchars($content).'"';
                $out.=' title="'.htmlspecialchars($content).'"';
                return $out;
@@ -1365,59 +1680,63 @@ class t3lib_BEfunc      {
         * @param       integer         Optional: $size is [w]x[h] of the thumbnail. 56 is default.
         * @return      string          Thumbnail image tag.
         */
         * @param       integer         Optional: $size is [w]x[h] of the thumbnail. 56 is default.
         * @return      string          Thumbnail image tag.
         */
-       function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='')    {
+       public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '') {
                global $TCA;
                        // Load table.
                t3lib_div::loadTCA($table);
 
                        // Find uploaddir automatically
                $uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
                global $TCA;
                        // Load table.
                t3lib_div::loadTCA($table);
 
                        // Find uploaddir automatically
                $uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
-               $uploaddir = preg_replace('#/$#','',$uploaddir);
+               $uploaddir = preg_replace('#/$#','', $uploaddir);
 
                        // Set thumbs-script:
 
                        // Set thumbs-script:
-               if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'])  {
-                       $thumbScript='gfx/notfound_thumb.gif';
-               } elseif(!$thumbScript) {
-                       $thumbScript='thumbs.php';
+               if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
+                       $thumbScript = 'gfx/notfound_thumb.gif';
+               } elseif(!$thumbScript) {
+                       $thumbScript = 'thumbs.php';
                }
                        // Check and parse the size parameter
                }
                        // Check and parse the size parameter
-               $sizeParts=array();
+               $sizeParts = array();
                if ($size = trim($size)) {
                        $sizeParts = explode('x', $size.'x'.$size);
                if ($size = trim($size)) {
                        $sizeParts = explode('x', $size.'x'.$size);
-                       if(!intval($sizeParts[0])) $size='';
+                       if(!intval($sizeParts[0])) $size = '';
                }
 
                        // Traverse files:
                $thumbs = explode(',', $row[$field]);
                }
 
                        // Traverse files:
                $thumbs = explode(',', $row[$field]);
-               $thumbData='';
-               while(list(,$theFile)=each($thumbs))    {
-                       if (trim($theFile))     {
+               $thumbData = '';
+               while(list(,$theFile) = each($thumbs)) {
+                       if (trim($theFile)) {
                                $fI = t3lib_div::split_fileref($theFile);
                                $ext = $fI['fileext'];
                                                // New 190201 start
                                $fI = t3lib_div::split_fileref($theFile);
                                $ext = $fI['fileext'];
                                                // New 190201 start
-                               $max=0;
-                               if (t3lib_div::inList('gif,jpg,png',$ext)) {
-                                       $imgInfo=@getimagesize(PATH_site.$uploaddir.'/'.$theFile);
-                                       if (is_array($imgInfo)) {$max = max($imgInfo[0],$imgInfo[1]);}
+                               $max = 0;
+                               if (t3lib_div::inList('gif,jpg,png', $ext)) {
+                                       $imgInfo = @getimagesize(PATH_site.$uploaddir.'/'.$theFile);
+                                       if (is_array($imgInfo)) {$max = max($imgInfo[0], $imgInfo[1]);}
                                }
                                        // use the original image if it's size fits to the thumbnail size
                                }
                                        // use the original image if it's size fits to the thumbnail size
-                               if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56))      {
-                                       $url = $uploaddir.'/'.trim($theFile);
-                                       $theFile = '../'.$url;
-                                       $onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
-                                       $thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="../'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
+                               if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56)) {
+                                       $theFile = $url = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
+                                       $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
+                                       $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
                                                // New 190201 stop
                                                // New 190201 stop
-                               } elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],$ext)) {
+                               } elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $ext)) {
+                                       $theFile_abs = PATH_site.($uploaddir?$uploaddir.'/':'').trim($theFile);
                                        $theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
                                        $theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
+
+                                       $check = basename($theFile_abs).':'.filemtime($theFile_abs).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
                                        $params = '&file='.rawurlencode($theFile);
                                        $params = '&file='.rawurlencode($theFile);
-                                       $params .= $size?'&size='.$size:'';
+                                       $params.= $size?'&size='.$size:'';
+                                       $params.= '&md5sum='.t3lib_div::shortMD5($check);
+
                                        $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
                                        $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
-                                       $onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
-                                       $thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
+                                       $onClick = 'top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
+                                       $thumbData.= '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
                                } else {
                                        $icon = t3lib_BEfunc::getFileIcon($ext);
                                        $url = 'gfx/fileicons/'.$icon;
                                } else {
                                        $icon = t3lib_BEfunc::getFileIcon($ext);
                                        $url = 'gfx/fileicons/'.$icon;
-                                       $thumbData.='<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
+                                       $thumbData.= '<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
                                }
                        }
                }
                                }
                        }
                }
@@ -1434,11 +1753,14 @@ class t3lib_BEfunc      {
         * @param       integer         $size is the size of the thumbnail send along to "thumbs.php"
         * @return      string          Image tag
         */
         * @param       integer         $size is the size of the thumbnail send along to "thumbs.php"
         * @return      string          Image tag
         */
-       function getThumbNail($thumbScript,$theFile,$tparams='',$size='')       {
+       public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
+               $check = basename($theFile).':'.filemtime($theFile).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
                $params = '&file='.rawurlencode($theFile);
                $params = '&file='.rawurlencode($theFile);
-               $params .= trim($size)?'&size='.trim($size):'';
+               $params.= trim($size)?'&size='.trim($size):'';
+               $params.= '&md5sum='.t3lib_div::shortMD5($check);
+
                $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
                $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
-               $th='<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
+               $th = '<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
                return $th;
        }
 
                return $th;
        }
 
@@ -1451,51 +1773,75 @@ class t3lib_BEfunc      {
         * @param       boolean         If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
         * @return      string
         */
         * @param       boolean         If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
         * @return      string
         */
-       function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)    {
-               global $TCA,$LANG;
-               $parts=array();
+       public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
+               global $TCA, $LANG;
+               $parts = array();
                $parts[] = 'id='.$row['uid'];
                $parts[] = 'id='.$row['uid'];
-               if ($row['alias'])      $parts[]=$LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
-               if ($row['doktype']=='3')       {
-                       $parts[]=$LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
-               } elseif ($row['doktype']=='4') {
-                       if ($perms_clause)      {
-                               $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']),$perms_clause,20);
+               if ($row['alias'])      $parts[] = $LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
+               if ($row['pid']<0)      $parts[] = 'v#1.'.$row['t3ver_id'];
+
+               switch($row['t3ver_state']) {
+                       case 1:
+                               $parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
+                       break;
+                       case 2:
+                               $parts[] = 'Deleted element!';
+                       break;
+                       case 3:
+                               $parts[] = 'NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
+                       break;
+                       case 4:
+                               $parts[] = 'OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
+                       break;
+                       case -1:
+                               $parts[] = 'New element!';
+                       break;
+               }
+
+               if ($row['doktype']=='3') {
+                       $parts[] = $LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
+               } elseif ($row['doktype']=='4') {
+                       if ($perms_clause) {
+                               $label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
                        } else {
                        } else {
-                               $lRec = t3lib_BEfunc::getRecord('pages',intval($row['shortcut']),'title');
+                               $lRec = t3lib_BEfunc::getRecordWSOL('pages', intval($row['shortcut']), 'title');
                                $label = $lRec['title'];
                        }
                                $label = $lRec['title'];
                        }
-                       if ($row['shortcut_mode']>0)    {
+                       if ($row['shortcut_mode']>0) {
                                $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
                                $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
-                                                       $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','shortcut_mode',$row['shortcut_mode']));
+                                                       $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
                        }
                        }
-                       $parts[]=$LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
-               } elseif ($row['doktype']=='7') {
-                       if ($perms_clause)      {
-                               $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']),$perms_clause,20);
+                       $parts[] = $LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
+               } elseif ($row['doktype']=='7') {
+                       if ($perms_clause) {
+                               $label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
                        } else {
                        } else {
-                               $lRec = t3lib_BEfunc::getRecord('pages',intval($row['mount_pid']),'title');
+                               $lRec = t3lib_BEfunc::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
                                $label = $lRec['title'];
                        }
                                $label = $lRec['title'];
                        }
-                       $parts[]=$LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
-                       if ($row['mount_pid_ol'])       {
+                       $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
+                       if ($row['mount_pid_ol']) {
                                $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
                        }
                }
                                $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
                        }
                }
-               if ($row['nav_hide'])   $parts[] = ereg_replace(':$','',$LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
+               if ($row['nav_hide'])   $parts[] = ereg_replace(':$', '', $LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
                if ($row['hidden'])     $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
                if ($row['hidden'])     $parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
-               if ($row['starttime'])  $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'],-1,'date');
-               if ($row['endtime'])    $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'],-1,'date');
-               if ($row['fe_group'])   {
-                       if ($row['fe_group']<0) {
-                               $label = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','fe_group',$row['fe_group']));
-                       } else {
-                               $lRec = t3lib_BEfunc::getRecord('fe_groups',$row['fe_group'],'title');
-                               $label = $lRec['title'];
+               if ($row['starttime'])  $parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'], -1, 'date');
+               if ($row['endtime'])    $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'], -1, 'date');
+               if ($row['fe_group']) {
+                       $fe_groups = array();
+                       foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
+                               if ($fe_group<0) {
+                                       $fe_groups[] = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages', 'fe_group', $fe_group));
+                               } else {
+                                       $lRec = t3lib_BEfunc::getRecordWSOL('fe_groups', $fe_group, 'title');
+                                       $fe_groups[] = $lRec['title'];
+                               }
                        }
                        }
+                       $label = implode(', ', $fe_groups);
                        $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
                }
                        $parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
                }
-               $out = htmlspecialchars(implode(' - ',$parts));
+               $out = htmlspecialchars(implode(' - ', $parts));
                return $includeAttrib ? 'title="'.$out.'"' : $out;
        }
 
                return $includeAttrib ? 'title="'.$out.'"' : $out;
        }
 
@@ -1509,25 +1855,48 @@ class t3lib_BEfunc      {
         * @param       string          Table name
         * @return      string
         */
         * @param       string          Table name
         * @return      string
         */
-       function getRecordIconAltText($row,$table='pages')      {
-               if ($table=='pages')    {
-                       $out = t3lib_BEfunc::titleAttribForPages($row,'',0);
+       public static function getRecordIconAltText($row, $table = 'pages') {
+               if ($table=='pages') {
+                       $out = t3lib_BEfunc::titleAttribForPages($row, '', 0);
                } else {
                        $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
 
                } else {
                        $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
 
-                       $out='id='.$row['uid']; // Uid is added
-                       if ($table=='pages' && $row['alias'])   {
+                       $out = 'id='.$row['uid'];       // Uid is added
+                       if ($table=='pages' && $row['alias']) {
                                $out.=' / '.$row['alias'];
                        }
                                $out.=' / '.$row['alias'];
                        }
+                       if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0) {
+                               $out.=' - v#1.'.$row['t3ver_id'];
+                       }
+                       if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
+                               switch($row['t3ver_state']) {
+                                       case 1:
+                                               $out.= ' - PLH WSID#'.$row['t3ver_wsid'];
+                                       break;
+                                       case 2:
+                                               $out.= ' - Deleted element!';
+                                       break;
+                                       case 3:
+                                               $out.= ' - NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
+                                       break;
+                                       case 4:
+                                               $out.= ' - OLD LOCATION (PNT)  WSID#'.$row['t3ver_wsid'];
+                                       break;
+                                       case -1:
+                                               $out.= ' - New element!';
+                                       break;
+                               }
+                       }
+
                        if ($ctrl['disabled'])  {               // Hidden ...
                                $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
                        }
                        if ($ctrl['disabled'])  {               // Hidden ...
                                $out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
                        }
-                       if ($ctrl['starttime']) {
-                               if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME'])   {
+                       if ($ctrl['starttime']) {
+                               if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
                                        $out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime').':'.t3lib_BEfunc::date($row[$ctrl['starttime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['starttime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
                                }
                        }
                                        $out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime').':'.t3lib_BEfunc::date($row[$ctrl['starttime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['starttime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
                                }
                        }
-                       if ($row[$ctrl['endtime']])     {
+                       if ($row[$ctrl['endtime']]) {
                                $out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime').': '.t3lib_BEfunc::date($row[$ctrl['endtime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['endtime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
                        }
                }
                                $out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime').': '.t3lib_BEfunc::date($row[$ctrl['endtime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['endtime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
                        }
                }
@@ -1535,7 +1904,7 @@ class t3lib_BEfunc        {
        }
 
        /**
        }
 
        /**
-        * Returns the label of the first found entry in an "items" array from $TCA (tablename=$table/fieldname=$col) where the value is $key
+        * Returns the label of the first found entry in an "items" array from $TCA (tablename = $table/fieldname = $col) where the value is $key
         * Usage: 9
         *
         * @param       string          Table name, present in $TCA
         * Usage: 9
         *
         * @param       string          Table name, present in $TCA
@@ -1543,25 +1912,25 @@ class t3lib_BEfunc      {
         * @param       string          items-array value to match
         * @return      string          Label for item entry
         */
         * @param       string          items-array value to match
         * @return      string          Label for item entry
         */
-       function getLabelFromItemlist($table,$col,$key) {
+       public static function getLabelFromItemlist($table, $col, $key) {
                global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
 
                        // Check, if there is an "items" array:
                global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
 
                        // Check, if there is an "items" array:
-               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items']))    {
+               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items'])) {
                                // Traverse the items-array...
                        reset($TCA[$table]['columns'][$col]['config']['items']);
                                // Traverse the items-array...
                        reset($TCA[$table]['columns'][$col]['config']['items']);
-                       while(list($k,$v)=each($TCA[$table]['columns'][$col]['config']['items']))       {
+                       while(list($k, $v) = each($TCA[$table]['columns'][$col]['config']['items'])) {
                                        // ... and return the first found label where the value was equal to $key
                                        // ... and return the first found label where the value was equal to $key
-                               if (!strcmp($v[1],$key))        return $v[0];
+                               if (!strcmp($v[1], $key))       return $v[0];
                        }
                }
        }
 
        /**
         * Returns the label-value for fieldname $col in table, $table
                        }
                }
        }
 
        /**
         * Returns the label-value for fieldname $col in table, $table
-        * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap='<b>|</b>' and the fieldname was 'not_found_field' then the return value would be '<b>not_found_field</b>'
+        * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap = '<b>|</b>' and the fieldname was 'not_found_field' then the return value would be '<b>not_found_field</b>'
         * Usage: 17
         *
         * @param       string          Table name, present in $TCA
         * Usage: 17
         *
         * @param       string          Table name, present in $TCA
@@ -1569,17 +1938,17 @@ class t3lib_BEfunc      {
         * @param       string          Wrap value - set function description
         * @return      string
         */
         * @param       string          Wrap value - set function description
         * @return      string
         */
-       function getItemLabel($table,$col,$printAllWrap='')     {
+       public static function getItemLabel($table, $col, $printAllWrap = '') {
                global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
                        // Check if column exists
                global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
                        // Check if column exists
-               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]))  {
+               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
                                // Re
                        return $TCA[$table]['columns'][$col]['label'];
                }
                                // Re
                        return $TCA[$table]['columns'][$col]['label'];
                }
-               if ($printAllWrap)      {
-                       $parts = explode('|',$printAllWrap);
+               if ($printAllWrap) {
+                       $parts = explode('|', $printAllWrap);
                        return $parts[0].$col.$parts[1];
                }
        }
                        return $parts[0].$col.$parts[1];
                }
        }
@@ -1592,31 +1961,94 @@ class t3lib_BEfunc      {
         * @param       string          Table name, present in TCA
         * @param       array           Row from table
         * @param       boolean         If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
         * @param       string          Table name, present in TCA
         * @param       array           Row from table
         * @param       boolean         If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
+        * @param       boolean         If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
         * @return      string
         */
         * @return      string
         */
-       function getRecordTitle($table,$row,$prep=0)    {
+       public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
                global $TCA;
                if (is_array($TCA[$table]))     {
                global $TCA;
                if (is_array($TCA[$table]))     {
-                       $t = $row[$TCA[$table]['ctrl']['label']];
-                       if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t,'')))   {
-                               $altFields=t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
-                               $tA=array();
-                               $tA[]=$t;
-                               while(list(,$fN)=each($altFields))      {
-                                       $t = $tA[] = trim(strip_tags($row[$fN]));
-                                       if (strcmp($t,'') && !$TCA[$table]['ctrl']['label_alt_force'])  break;
+
+                               // If configured, call userFunc
+                       if ($TCA[$table]['ctrl']['label_userFunc']) {
+                               $params['table'] = $table;
+                               $params['row'] = $row;
+                               $params['title'] = '';
+
+                               t3lib_div::callUserFunction($TCA[$table]['ctrl']['label_userFunc'], $params, $this);
+                               $t = $params['title'];
+                       } else {
+
+                                       // No userFunc: Build label
+                               $t = t3lib_BEfunc::getProcessedValue($table, $TCA[$table]['ctrl']['label'], $row[$TCA[$table]['ctrl']['label']], 0, 0, false, $row['uid'], $forceResult);
+                               if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
+                                       $altFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
+                                       $tA = array();
+                                       if (!empty($t)) $tA[] = $t;
+                                       foreach ($altFields as $fN) {
+                                               $t = trim(strip_tags($row[$fN]));
+                                               if (strcmp($t, '')) {
+                                                       $t = t3lib_BEfunc::getProcessedValue($table, $fN, $t, 0, 0, false, $row['uid']);
+                                                       if (!$TCA[$table]['ctrl']['label_alt_force']) {
+                                                               break;
+                                                       }
+                                                       $tA[] = $t;
+                                               }
+                                       }
+                                       if ($TCA[$table]['ctrl']['label_alt_force']) {
+                                               $t = implode(', ', $tA);
+                                       }
                                }
                                }
-                               if ($TCA[$table]['ctrl']['label_alt_force'])    $t=implode(', ',$tA);
                        }
                        }
-                       if ($prep)      {
-                               $t = htmlspecialchars(t3lib_div::fixed_lgd_cs($t,$GLOBALS['BE_USER']->uc['titleLen']));
-                               if (!strcmp(trim($t),''))       $t='<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>';
+
+                               // If the current result is empty, set it to '[No title]' (localized) and prepare for output if requested
+                       if ($prep || $forceResult) {
+                               if ($prep) {
+                                       $t = t3lib_BEfunc::getRecordTitlePrep($t);
+                               }
+                               if (!strcmp(trim($t), '')) {
+                                       $t = t3lib_BEfunc::getNoRecordTitle($prep);
+                               }
                        }
                        }
+
                        return $t;
                }
        }
 
        /**
                        return $t;
                }
        }
 
        /**
+        * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
+        * which offers a tooltip with the original title when moving mouse over it.
+        *
+        * @param       string          $title: The title string to be cropped
+        * @param       integer         $titleLength: Crop title after this length - if not set, BE_USER->uc['titleLen'] is used
+        * @return      string          The processed title string, wrapped in <span title="...">|</span> if cropped
+        */
+       public static function getRecordTitlePrep($title, $titleLength = 0) {
+                       // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
+               if (!$titleLength || !t3lib_div::testInt($titleLength) || $titleLength < 0) {
+                       $titleLength = $GLOBALS['BE_USER']->uc['titleLen'];
+               }
+               $titleOrig = htmlspecialchars($title);
+               $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($title, $titleLength));
+                       // If title was cropped, offer a tooltip:
+               if ($titleOrig != $title) {
+                       $title = '<span title="'.$titleOrig.'">'.$title.'</span>';
+               }
+               return $title;
+       }
+
+       /**
+        * Get a localized [No title] string, wrapped in <em>|</em> if $prep is true.
+        *
+        * @param       boolean         $prep: Wrap result in <em>|</em>
+        * @return      string          Localized [No title] string
+        */
+       public static function getNoRecordTitle($prep = FALSE) {
+               $noTitle = '['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1).']';
+               if ($prep) $noTitle = '<em>'.$noTitle.'</em>';
+               return $noTitle;
+       }
+
+       /**
         * Returns a human readable output of a value from a record
         * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
         * $table/$col is tablename and fieldname
         * Returns a human readable output of a value from a record
         * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
         * $table/$col is tablename and fieldname
@@ -1628,85 +2060,164 @@ class t3lib_BEfunc     {
         * @param       string          $value is the value of that field from a selected record
         * @param       integer         $fixed_lgd_chars is the max amount of characters the value may occupy
         * @param       boolean         $defaultPassthrough flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
         * @param       string          $value is the value of that field from a selected record
         * @param       integer         $fixed_lgd_chars is the max amount of characters the value may occupy
         * @param       boolean         $defaultPassthrough flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
+        * @param       boolean         If set, no records will be looked up, UIDs are just shown.
+        * @param       integer         uid of the current record
+        * @param       boolean         If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
         * @return      string
         */
         * @return      string
         */
-       function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0) {
+       public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
                global $TCA;
                global $TCA;
+               global $TYPO3_CONF_VARS;
+               
+               if ($col == 'uid') {
+                               // no need to load TCA as uid is not in TCA-array
+                       return $value;
+               }
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
                        // Check if table and field is configured:
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
                        // Check if table and field is configured:
-               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]))  {
+               if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col])) {
                                // Depending on the fields configuration, make a meaningful output value.
                        $theColConf = $TCA[$table]['columns'][$col]['config'];
                                // Depending on the fields configuration, make a meaningful output value.
                        $theColConf = $TCA[$table]['columns'][$col]['config'];
-                       $l='';
-                       switch((string)$theColConf['type'])     {
+
+                               /*****************
+                                *HOOK: pre-processing the human readable output from a record
+                                ****************/
+                       if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
+                                       t3lib_div::callUserFunction($_funcRef,$theColConf,$this);
+                               }
+                       }
+
+                       $l = '';
+                       switch((string)$theColConf['type']) {
                                case 'radio':
                                case 'radio':
-                                       $l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
+                                       $l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
+                                       $l = $GLOBALS['LANG']->sL($l);
                                break;
                                case 'select':
                                break;
                                case 'select':
-                                       if ($theColConf['MM'])  {
-                                               $l='N/A';
+                                       if ($theColConf['MM']) {
+                                               // Display the title of MM related records in lists
+                                               if ($noRecordLookup) {
+                                                       $MMfield = $theColConf['foreign_table'].'.uid';
+                                               } else  {
+                                                       $MMfields = array($theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label']);
+                                                       foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
+                                                               $MMfields[] = $theColConf['foreign_table'].'.'.$f;
+                                                       }
+                                                       $MMfield = join(',',$MMfields);
+                                               }
+
+                                               $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
+                                               $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
+                                               $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
+
+                                               if (is_array($selectUids) && count($selectUids)>0) {
+                                                       $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                                                               'uid, '.$MMfield,
+                                                               $theColConf['foreign_table'],
+                                                               'uid IN ('.implode(',', $selectUids).')'
+                                                       );
+                                                       while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
+                                                               $mmlA[] = ($noRecordLookup?$MMrow['uid']:t3lib_BEfunc::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
+                                                       }
+                                                       $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
+
+                                                       if (is_array($mmlA)) {
+                                                               $l = implode('; ', $mmlA);
+                                                       } else {
+                                                               $l = '';
+                                                       }
+                                               } else {
+                                                       $l = 'N/A';
+                                               }
                                        } else {
                                        } else {
-                                               $l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
-                                               $l=$GLOBALS['LANG']->sL($l);
-                                               if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']])  {
-                                                       $rParts = t3lib_div::trimExplode(',',$value,1);
-                                                       reset($rParts);
-                                                       $lA=array();
-                                                       while(list(,$rVal)=each($rParts))       {
-                                                               $rVal = intval($rVal);
-                                                               if ($rVal>0) {
-                                                                       $r=t3lib_BEfunc::getRecord($theColConf['foreign_table'],$rVal);
-                                                               } else {
-                                                                       $r=t3lib_BEfunc::getRecord($theColConf['neg_foreign_table'],-$rVal);
-                                                               }
-                                                               if (is_array($r))       {
-                                                                       $lA[]=$GLOBALS['LANG']->sL($rVal>0?$theColConf['foreign_table_prefix']:$theColConf['neg_foreign_table_prefix']).t3lib_BEfunc::getRecordTitle($rVal>0?$theColConf['foreign_table']:$theColConf['neg_foreign_table'],$r);
-                                                               } else {
-                                                                       $lA[]=$rVal?'['.$rVal.'!]':'';
+                                               $l = t3lib_BEfunc::getLabelFromItemlist($table, $col, $value);
+                                               $l = $GLOBALS['LANG']->sL($l);
+                                               if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
+                                                       if ($noRecordLookup) {
+                                                               $l = $value;
+                                                       } else {
+                                                               $rParts = t3lib_div::trimExplode(',', $value, 1);
+                                                               reset($rParts);
+                                                               $lA = array();
+                                                               while(list(,$rVal) = each($rParts)) {
+                                                                       $rVal = intval($rVal);
+                                                                       if ($rVal>0) {
+                                                                               $r = t3lib_BEfunc::getRecordWSOL($theColConf['foreign_table'], $rVal);
+                                                                       } else {
+                                                                               $r = t3lib_BEfunc::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
+                                                                       }
+                                                                       if (is_array($r)) {
+                                                                               $lA[] = $GLOBALS['LANG']->sL($rVal>0?$theColConf['foreign_table_prefix']:$theColConf['neg_foreign_table_prefix']).t3lib_BEfunc::getRecordTitle($rVal>0?$theColConf['foreign_table']:$theColConf['neg_foreign_table'], $r, FALSE, $forceResult);
+                                                                       } else {
+                                                                               $lA[] = $rVal?'['.$rVal.'!]':'';
+                                                                       }
                                                                }
                                                                }
+                                                               $l = implode(', ', $lA);
                                                        }
                                                        }
-                                                       $l=implode(',',$lA);
                                                }
                                        }
                                break;
                                                }
                                        }
                                break;
+                               case 'group':
+                                       $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
+                               break;
                                case 'check':
                                case 'check':
-                                       if (!is_array($theColConf['items']) || count($theColConf['items'])==1)  {
-                                               $l = $value ? 'Yes' : '';
+                                       if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
+                                               $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : '';
                                        } else {
                                                reset($theColConf['items']);
                                        } else {
                                                reset($theColConf['items']);
-                                               $lA=Array();
-                                               while(list($key,$val)=each($theColConf['items']))       {
-                                                       if ($value & pow(2,$key))       {$lA[]=$GLOBALS['LANG']->sL($val[0]);}
+                                               $lA = Array();
+                                               while(list($key, $val) = each($theColConf['items'])) {
+                                                       if ($value & pow(2, $key))      {$lA[] = $GLOBALS['LANG']->sL($val[0]);}
                                                }
                                                }
-                                               $l = implode($lA,', ');
+                                               $l = implode(', ', $lA);
                                        }
                                break;
                                case 'input':
                                        }
                                break;
                                case 'input':
-                                       if ($value)     {
-                                               if (t3lib_div::inList($theColConf['eval'],'date'))      {
+                                       if ($value) {
+                                               if (t3lib_div::inList($theColConf['eval'], 'date')) {
                                                        $l = t3lib_BEfunc::date($value).' ('.(time()-$value>0?'-':'').t3lib_BEfunc::calcAge(abs(time()-$value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')';
                                                        $l = t3lib_BEfunc::date($value).' ('.(time()-$value>0?'-':'').t3lib_BEfunc::calcAge(abs(time()-$value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')';
-                                               } elseif (t3lib_div::inList($theColConf['eval'],'time'))        {
+                                               } elseif (t3lib_div::inList($theColConf['eval'], 'time')) {
+                                                       $l = t3lib_BEfunc::time($value, FALSE);
+                                               } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
                                                        $l = t3lib_BEfunc::time($value);
                                                        $l = t3lib_BEfunc::time($value);
-                                               } elseif (t3lib_div::inList($theColConf['eval'],'datetime'))    {
+                                               } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
                                                        $l = t3lib_BEfunc::datetime($value);
                                                } else {
                                                        $l = $value;
                                                }
                                        }
                                break;
                                                        $l = t3lib_BEfunc::datetime($value);
                                                } else {
                                                        $l = $value;
                                                }
                                        }
                                break;
+                               case 'flex':
+                                       $l = strip_tags($value);
+                               break;
                                default:
                                default:
-                                       if ($defaultPassthrough)        {
-                                               $l=$value;
-                                       } elseif ($theColConf['MM'])    {
-                                               $l='N/A';
-                                       } elseif ($value)       {
-                                               $l=t3lib_div::fixed_lgd_cs(strip_tags($value),200);
+                                       if ($defaultPassthrough) {
+                                               $l = $value;
+                                       } elseif ($theColConf['MM']) {
+                                               $l = 'N/A';
+                                       } elseif ($value) {
+                                               $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
                                        }
                                break;
                        }
                                        }
                                break;
                        }
-                       if ($fixed_lgd_chars)   {
-                               return t3lib_div::fixed_lgd_cs($l,$fixed_lgd_chars);
+
+                               /*****************
+                                *HOOK: post-processing the human readable output from a record
+                                ****************/
+                       if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
+                       foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
+                                       $params = array(
+                                               'value' => $l,
+                                               'colConf' => $theColConf
+                                       );
+                                       $l = t3lib_div::callUserFunction($_funcRef, $params, $this);
+                               }
+                       }
+
+                       if ($fixed_lgd_chars) {
+                               return t3lib_div::fixed_lgd_cs($l, $fixed_lgd_chars);
                        } else {
                                return $l;
                        }
                        } else {
                                return $l;
                        }
@@ -1721,18 +2232,20 @@ class t3lib_BEfunc      {
         * @param       string          Field name
         * @param       string          Field value
         * @param       integer         $fixed_lgd_chars is the max amount of characters the value may occupy
         * @param       string          Field name
         * @param       string          Field value
         * @param       integer         $fixed_lgd_chars is the max amount of characters the value may occupy
+        * @param       integer         uid of the current record
+        * @param       boolean         If t3lib_BEfunc::getRecordTitle is used to process the value, this parameter is forwarded.
         * @return      string
         * @see getProcessedValue()
         */
         * @return      string
         * @see getProcessedValue()
         */
-       function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0)      {
+       public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
                global $TCA;
                global $TCA;
-               $fVnew = t3lib_BEfunc::getProcessedValue($table,$fN,$fV,$fixed_lgd_chars);
-               if (!isset($fVnew))     {
-                       if (is_array($TCA[$table]))     {
-                               if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
+               $fVnew = t3lib_BEfunc::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 0, 0, $uid, $forceResult);
+               if (!isset($fVnew)) {
+                       if (is_array($TCA[$table])) {
+                               if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
                                        $fVnew = t3lib_BEfunc::datetime($fV);
                                } elseif ($fN=='pid'){
                                        $fVnew = t3lib_BEfunc::datetime($fV);
                                } elseif ($fN=='pid'){
-                                       $fVnew = t3lib_BEfunc::getRecordPath($fV,'1',20);       // Fetches the path with no regard to the users permissions to select pages.
+                                       $fVnew = t3lib_BEfunc::getRecordPath($fV, '1=1', 20);   // Fetches the path with no regard to the users permissions to select pages.
                                } else {
                                        $fVnew = $fV;
                                }
                                } else {
                                        $fVnew = $fV;
                                }
@@ -1748,7 +2261,7 @@ class t3lib_BEfunc        {
         * @param       string          File extension, lowercase
         * @return      string          File icon filename
         */
         * @param       string          File extension, lowercase
         * @return      string          File icon filename
         */
-       function getFileIcon($ext)      {
+       public static function getFileIcon($ext) {
                return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
        }
 
                return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
        }
 
@@ -1760,21 +2273,38 @@ class t3lib_BEfunc      {
         *
         * @param       string          Table name, present in TCA
         * @param       string          Table prefix
         *
         * @param       string          Table name, present in TCA
         * @param       string          Table prefix
+        * @param       array           Preset fields (must include prefix if that is used)
         * @return      string          List of fields.
         */
         * @return      string          List of fields.
         */
-       function getCommonSelectFields($table,$prefix)  {
+       public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
                global $TCA;
                global $TCA;
-               $fields=array();
-               $fields[]=$prefix.'uid';
-               $fields[]=$prefix.$TCA[$table]['ctrl']['label'];
-               if ($TCA[$table]['ctrl']['label_alt'])  {
-                       $secondFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
-                       while(list(,$fieldN)=each($secondFields))       {
-                               $fields[]=$prefix.$fieldN;
+               $fields[] = $prefix.'uid';
+               $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
+
+               if ($TCA[$table]['ctrl']['label_alt']) {
+                       $secondFields = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['label_alt'], 1);
+                       foreach($secondFields as $fieldN) {
+                               $fields[] = $prefix.$fieldN;
                        }
                }
                        }
                }
-               if ($TCA[$table]['ctrl']['selicon_field'])      $fields[]=$prefix.$TCA[$table]['ctrl']['selicon_field'];
-               return implode(',',$fields);
+               if ($TCA[$table]['ctrl']['versioningWS']) {
+                       $fields[] = $prefix.'t3ver_id';
+                       $fields[] = $prefix.'t3ver_state';
+                       $fields[] = $prefix.'t3ver_wsid';
+                       $fields[] = $prefix.'t3ver_count';
+               }
+
+               if ($TCA[$table]['ctrl']['selicon_field'])      $fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
+               if ($TCA[$table]['ctrl']['typeicon_column'])    $fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];
+
+               if (is_array($TCA[$table]['ctrl']['enablecolumns']))            {
+                       if ($TCA[$table]['ctrl']['enablecolumns']['disabled'])  $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
+                       if ($TCA[$table]['ctrl']['enablecolumns']['starttime']) $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
+                       if ($TCA[$table]['ctrl']['enablecolumns']['endtime'])   $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
+                       if ($TCA[$table]['ctrl']['enablecolumns']['fe_group'])  $fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
+               }
+
+               return implode(',', array_unique($fields));
        }
 
        /**
        }
 
        /**
@@ -1788,16 +2318,16 @@ class t3lib_BEfunc      {
         * @param       string          Prefix for formfields
         * @return      string          HTML for a form.
         */
         * @param       string          Prefix for formfields
         * @return      string          HTML for a form.
         */
-       function makeConfigForm($configArray,$defaults,$dataPrefix)     {
+       public static function makeConfigForm($configArray, $defaults, $dataPrefix) {
                $params = $defaults;
                $params = $defaults;
-               if (is_array($configArray))     {
+               if (is_array($configArray)) {
                        reset($configArray);
                        reset($configArray);
-                       $lines=array();
-                       while(list($fname,$config)=each($configArray))  {
-                               if (is_array($config))  {
-                                       $lines[$fname]='<strong>'.htmlspecialchars($config[1]).'</strong><br />';
+                       $lines = array();
+                       while(list($fname, $config) = each($configArray)) {
+                               if (is_array($config)) {
+                                       $lines[$fname] = '<strong>'.htmlspecialchars($config[1]).'</strong><br />';
                                        $lines[$fname].=$config[2].'<br />';
                                        $lines[$fname].=$config[2].'<br />';
-                                       switch($config[0])      {
+                                       switch($config[0]) {
                                                case 'string':
                                                case 'short':
                                                        $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
                                                case 'string':
                                                case 'short':
                                                        $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
@@ -1810,11 +2340,11 @@ class t3lib_BEfunc      {
                                                break;
                                                case 'select':
                                                        reset($config[3]);
                                                break;
                                                case 'select':
                                                        reset($config[3]);
-                                                       $opt=array();
-                                                       while(list($k,$v)=each($config[3]))     {
-                                                               $opt[]='<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
+                                                       $opt = array();
+                                                       while(list($k, $v) = each($config[3])) {
+                                                               $opt[] = '<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
                                                        }
                                                        }
-                                                       $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('',$opt).'</select>';
+                                                       $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('', $opt).'</select>';
                                                break;
                                                default:
                                                        debug($config);
                                                break;
                                                default:
                                                        debug($config);
@@ -1823,13 +2353,13 @@ class t3lib_BEfunc      {
                                        $lines[$fname].=$formEl;
                                        $lines[$fname].='<br /><br />';
                                } else {
                                        $lines[$fname].=$formEl;
                                        $lines[$fname].='<br /><br />';
                                } else {
-                                       $lines[$fname]='<hr />';
+                                       $lines[$fname] = '<hr />';
                                        if ($config)    $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
                                        if ($config)    $lines[$fname].='<br />';
                                }
                        }
                }
                                        if ($config)    $lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
                                        if ($config)    $lines[$fname].='<br />';
                                }
                        }
                }
-               $out = implode('',$lines);
+               $out = implode('', $lines);
                $out.='<input type="submit" name="submit" value="Update configuration" />';
                return $out;
        }
                $out.='<input type="submit" name="submit" value="Update configuration" />';
                return $out;
        }
@@ -1863,66 +2393,57 @@ class t3lib_BEfunc      {
         * @param       boolean         Force display of icon nomatter BE_USER setting for help
         * @return      string          HTML content for a help icon/text
         */
         * @param       boolean         Force display of icon nomatter BE_USER setting for help
         * @return      string          HTML content for a help icon/text
         */
-       function helpTextIcon($table,$field,$BACK_PATH,$force=0)        {
-               global $TCA_DESCR,$BE_USER;
-               if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && ($BE_USER->uc['edit_showFieldHelp']=='icon' || $force))  {
-                       $onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
-                       return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
-                                       '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.
-                                       '</a>';
+       public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
+               global $TCA_DESCR, $BE_USER;
+
+               $onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
+               if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && (isset($BE_USER->uc['edit_showFieldHelp']) || $force)) {
+                       if ($BE_USER->uc['edit_showFieldHelp'] == 'icon') {
+                               $text = t3lib_BEfunc::helpText($table, $field, $BACK_PATH, '');
+                               $text = '<span class="typo3-csh-inline">'.$GLOBALS['LANG']->hscAndCharConv($text, false).'</span>';
+                       }
+                       return '<a class="typo3-csh-link" href="#" onclick="'.htmlspecialchars($onClick).'"><img'.t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/helpbubble.gif', 'width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.$text.'</a>';
                }
        }
 
                }
        }
 
+
        /**
         * Returns CSH help text (description), if configured for.
        /**
         * Returns CSH help text (description), if configured for.
-        * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text", otherwise nothing is returned
+        * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text",
+        * otherwise nothing is returned
         * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
         * Usage: 4
         *
         * @param       string          Table name
         * @param       string          Field name
         * @param       string          Back path
         * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
         * Usage: 4
         *
         * @param       string          Table name
         * @param       string          Field name
         * @param       string          Back path
-        * @param       string          Additional style-attribute content for wrapping table
+        * @param       string          DEPRECATED: Additional style-attribute content for wrapping table (now: only in function cshItem needed)
         * @return      string          HTML content for help text
         */
         * @return      string          HTML content for help text
         */
-       function helpText($table,$field,$BACK_PATH,$styleAttrib='')     {
-               global $TCA_DESCR,$BE_USER;
-               if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && $BE_USER->uc['edit_showFieldHelp']=='text')      {
-                       $fDat = $TCA_DESCR[$table]['columns'][$field];
-
-                               // Get Icon:
-                       $editIcon = t3lib_BEfunc::helpTextIcon(
-                                                                       $table,
-                                                                       $field,
-                                                                       $BACK_PATH,
-                                                                       TRUE
-                                                               );
-                               // Add title?
-                       $onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
-                       $text =
-                                       ($fDat['alttitle'] ? '<h4><a href="#" onclick="'.htmlspecialchars($onClick).'">'.$fDat['alttitle'].'</a></h4>' : '').
-                                       $fDat['description'];
-
-                               // More information to get?
-                       if ($fDat['image_descr'] || $fDat['seeAlso'] || $fDat['details'] || $fDat['syntax'])    { // || $fDat['image'];
-                               $text.=' <a href="#" onclick="'.htmlspecialchars($onClick).'">'.
-                                               '<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/rel_db.gif','width="13" height="12"').' class="absmiddle typo3-csh-more" alt="" />'.
-                                               '</a>';
+       public static function helpText($table, $field, $BACK_PATH, $styleAttrib = '') {
+               global $TCA_DESCR, $BE_USER;
+               $output = '';
+
+               if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field])) {
+                       $data = $TCA_DESCR[$table]['columns'][$field];
+                               // add see also arrow
+                       if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
+                               $arrow = '<img'.t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/rel_db.gif', 'width="13" height="12"').' class="absmiddle" alt="" />';
+                       }
+                               // add description text
+                       if ($data['description'] || $arrow) {
+                               $output = '<span class="paragraph">'.nl2br(htmlspecialchars($data['description'])).$arrow.'</span>';
                        }
 
                        }
 
-                               // Additional styles?
-                       $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
-
-                               // Compile table with CSH information:
-                       return '<table border="0" cellpadding="2" cellspacing="0" class="typo3-csh-inline"'.$params.'>
-                                               <tr>
-                                                       <td valign="top" width="14">'.$editIcon.'</td>
-                                                       <td valign="top">'.$text.'</td>
-                                               </tr>
-                                       </table>';
+                               // put header before the rest of the text
+                       if ($data['alttitle']) {
+                               $output = '<span class="header">'.$data['alttitle'].'</span><br />'.$output;
+                       }
                }
                }
+               return $output;
        }
 
        }
 
+
        /**
         * API for getting CSH icons/text for use in backend modules.
         * TCA_DESCR will be loaded if it isn't already
        /**
         * API for getting CSH icons/text for use in backend modules.
         * TCA_DESCR will be loaded if it isn't already
@@ -1932,29 +2453,42 @@ class t3lib_BEfunc      {
         * @param       string          Field name (CSH locallang main key)
         * @param       string          Back path
         * @param       string          Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
         * @param       string          Field name (CSH locallang main key)
         * @param       string          Back path
         * @param       string          Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
-        * @param       boolean         If set, the full text will never be shown (only icon). Useful for places where it will break the page if the table with full text is shown.
+        * @param       boolean         If set, the full text will never be shown (only icon).
+        *                              Useful for places where it will break the page if the table with full text is shown.
         * @param       string          Additional style-attribute content for wrapping table (full text mode only)
         * @return      string          HTML content for help text
         * @see helpText(), helpTextIcon()
         */
         * @param       string          Additional style-attribute content for wrapping table (full text mode only)
         * @return      string          HTML content for help text
         * @see helpText(), helpTextIcon()
         */
-       function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='')        {
+       public static function cshItem($table, $field, $BACK_PATH, $wrap = '', $onlyIconMode = FALSE, $styleAttrib = '') {
                global $TCA_DESCR, $LANG, $BE_USER;
                global $TCA_DESCR, $LANG, $BE_USER;
-               if ($BE_USER->uc['edit_showFieldHelp']) {
+
+               if ($BE_USER->uc['edit_showFieldHelp']) {
                        $LANG->loadSingleTableDescription($table);
 
                        $LANG->loadSingleTableDescription($table);
 
-                       if (is_array($TCA_DESCR[$table]))       {
-                                       // Creating CSH icon and short description:
-                               $fullText = t3lib_BEfunc::helpText($table,$field,$BACK_PATH,$styleAttrib);
-                               $icon = t3lib_BEfunc::helpTextIcon($table,$field,$BACK_PATH,$onlyIconMode);
+                       if (is_array($TCA_DESCR[$table])) {
+                               // Creating CSH icon and short description:
+                               $fullText = t3lib_BEfunc::helpText($table, $field, $BACK_PATH, '');
+                               $icon = t3lib_BEfunc::helpTextIcon($table, $field, $BACK_PATH);
+
+                               if ($fullText && !$onlyIconMode && $BE_USER->uc['edit_showFieldHelp'] == 'text')        {
 
 
-                               if ($fullText && !$onlyIconMode)        {
-                                       $output = $fullText;
+                                       // Additional styles?
+                                       $params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';
+
+                                       // Compile table with CSH information:
+                                       $fullText = '<table border="0" cellpadding="0" cellspacing="0" class="typo3-csh-inline"'.$params.'>
+                                       <tr>
+                                       <td valign="top" width="14">'.$icon.'</td>
+                                       <td valign="top">'.$fullText.'</td>
+                                       </tr>
+                                       </table>';
+
+                                       $output = $LANG->hscAndCharConv($fullText, false);
                                } else {
                                } else {
-                                       #$output = '<span style="position:absolute; filter: alpha(opacity=50); -moz-opacity: 0.50;">'.$icon.'</span>';
                                        $output = $icon;
 
                                        $output = $icon;
 
-                                       if ($output && $wrap)   {
-                                               $wrParts = explode('|',$wrap);
+                                       if ($output && $wrap) {
+                                               $wrParts = explode('|', $wrap);
                                                $output = $wrParts[0].$output.$wrParts[1];
                                        }
                                }
                                                $output = $wrParts[0].$output.$wrParts[1];
                                        }
                                }
@@ -1969,14 +2503,15 @@ class t3lib_BEfunc      {
         * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
         * Usage: 35
         *
         * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
         * Usage: 35
         *
-        * @param       string          $params is parameters sent along to alt_doc.php. This requires a much more details description which you must seek in Inside TYPO3s documentation of the alt_doc.php API. And example could be '&edit[pages][123]=edit' which will show edit form for page record 123.
+        * @param       string          $params is parameters sent along to alt_doc.php. This requires a much more details description which you must seek in Inside TYPO3s documentation of the alt_doc.php API. And example could be '&edit[pages][123] = edit' which will show edit form for page record 123.
         * @param       string          $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
         * @param       string          $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
         * @return      string
         * @param       string          $backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
         * @param       string          $requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
         * @return      string
+        * @see template::issueCommand()
         */
         */
-       function editOnClick($params,$backPath='',$requestUri='')       {
+       public static function editOnClick($params, $backPath = '', $requestUri = '') {
                $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
                $retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
-               return "document.location='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
+               return "window.location.href='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
        }
 
        /**
        }
 
        /**
@@ -1990,23 +2525,33 @@ class t3lib_BEfunc      {
         * @param       string          $anchor is optional anchor to the URL
         * @param       string          $altUrl is an alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
         * @param       string          Additional GET variables.
         * @param       string          $anchor is optional anchor to the URL
         * @param       string          $altUrl is an alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
         * @param       string          Additional GET variables.
+        * @param       boolean         If true, then the preview window will gain the focus.
         * @return      string
         */
         * @return      string
         */
-       function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='')        {
-               if ($altUrl)    {
+       public static function viewOnClick($id, $backPath = '', $rootLine = '', $anchor = '', $altUrl = '', $addGetVars = '', $switchFocus = TRUE) {
+               if ($altUrl) {
                        $url = $altUrl;
                } else {
                        $url = $altUrl;
                } else {
-                       if ($rootLine)  {
+
+                       $viewScriptPreviewEnabled  = '/' . TYPO3_mainDir . 'mod/user/ws/wsol_preview.php?id=';
+                       $viewScriptPreviewDisabled = '/index.php?id=';
+
+                               // check alternate Domains
+                       if ($rootLine)  {
                                $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
                                $parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
-                               if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path']))    {
+                               if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path']))    {
                                        $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
                                }
                        }
                                        $preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
                                }
                        }
-                       $preUrl = $preUrl_temp ? 'http://'.$preUrl_temp : $backPath.'..';
-                       $url = $preUrl.'/index.php?id='.$id.$addGetVars.$anchor;
+                       $preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
+
+                       $urlPreviewEnabled  = $preUrl . $viewScriptPreviewEnabled . $id . $addGetVars . $anchor;
+                       $urlPreviewDisabled = $preUrl . $viewScriptPreviewDisabled . $id . $addGetVars . $anchor;
                }
 
                }
 
-               return "previewWin=window.open('".$url."','newTypo3FrontendWindow','status=1,menubar=1,resizable=1,location=1,scrollbars=1,toolbar=1');previewWin.focus();";
+               return "previewWin=window.open(top.WorkspaceFrontendPreviewEnabled?'" .
+                       $urlPreviewDisabled . "':'" . $urlPreviewEnabled .
+                       "','newTYPO3frontendWindow');" . ( $switchFocus ? 'previewWin.focus();' : '');
        }
 
        /**
        }
 
        /**
@@ -2018,10 +2563,10 @@ class t3lib_BEfunc      {
         * @param       string          $TSref is an object string which determines the path of the TSconfig to return.
         * @return      array
         */
         * @param       string          $TSref is an object string which determines the path of the TSconfig to return.
         * @return      array
         */
-       function getModTSconfig($id,$TSref)     {
-               $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref,t3lib_BEfunc::getPagesTSconfig($id));
+       public static function getModTSconfig($id, $TSref) {
+               $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, t3lib_BEfunc::getPagesTSconfig($id));
                $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
                $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
-               $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions,$BE_USER_modOptions);
+               $modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
                return $modTSconfig;
        }
 
                return $modTSconfig;
        }
 
@@ -2039,22 +2584,25 @@ class t3lib_BEfunc      {
         * @param       string          $addParams is additional parameters to pass to the script.
         * @return      string          HTML code for selector box
         */
         * @param       string          $addParams is additional parameters to pass to the script.
         * @return      string          HTML code for selector box
         */
-       function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')        {
-               if (is_array($menuItems))       {
+       public static function getFuncMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
+               if (is_array($menuItems)) {
                        if (!is_array($mainParams)) {
                                $mainParams = array('id' => $mainParams);
                        }
                        if (!is_array($mainParams)) {
                                $mainParams = array('id' => $mainParams);
                        }
-                       $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
+                       $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
 
 
-                       if (!$script) { $script=basename(PATH_thisScript); }
+                       if (!$script) {
+                               $script = basename(PATH_thisScript);
+                               $mainParams.= (t3lib_div::_GET('M') ? '&M='.rawurlencode(t3lib_div::_GET('M')) : '');
+                       }
 
                        $options = array();
 
                        $options = array();
-                       foreach($menuItems as $value => $label) {
-                               $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue,$value)?' selected="selected"':'').'>'.
+                       foreach($menuItems as $value => $label) {
+                               $options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue, $value)?' selected="selected"':'').'>'.
                                                                t3lib_div::deHSCentities(htmlspecialchars($label)).
                                                                '</option>';
                        }
                                                                t3lib_div::deHSCentities(htmlspecialchars($label)).
                                                                '</option>';
                        }
-                       if (count($options))    {
+                       if (count($options)) {
                                $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
                                return '
 
                                $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
                                return '
 
@@ -2082,15 +2630,15 @@ class t3lib_BEfunc      {
         * @return      string          HTML code for checkbox
         * @see getFuncMenu()
         */
         * @return      string          HTML code for checkbox
         * @see getFuncMenu()
         */
-       function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='')    {
+       public static function getFuncCheck($mainParams, $elementName, $currentValue, $script = '', $addparams = '', $tagParams = '') {
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
-               $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
+               $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
 
                if (!$script) {basename(PATH_thisScript);}
                $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
 
                if (!$script) {basename(PATH_thisScript);}
                $onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
-               return '<input type="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
+               return '<input type="checkbox" class="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
        }
 
        /**
        }
 
        /**
@@ -2107,11 +2655,11 @@ class t3lib_BEfunc      {
         * @return      string          HTML code for input text field.
         * @see getFuncMenu()
         */
         * @return      string          HTML code for input text field.
         * @see getFuncMenu()
         */
-       function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="") {
+       public static function getFuncInput($mainParams, $elementName, $currentValue, $size = 10, $script = "", $addparams = "") {
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
-               $mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);
+               $mainParams = t3lib_div::implodeArrayForUrl('', $mainParams);
 
                if (!$script) {basename(PATH_thisScript);}
                $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
 
                if (!$script) {basename(PATH_thisScript);}
                $onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
@@ -2128,13 +2676,13 @@ class t3lib_BEfunc      {
         * @param       string          $TSref points to the "object string" in $modTSconfig
         * @return      array           The modified $itemArray is returned.
         */
         * @param       string          $TSref points to the "object string" in $modTSconfig
         * @return      array           The modified $itemArray is returned.
         */
-       function unsetMenuItems($modTSconfig,$itemArray,$TSref) {
+       public static function unsetMenuItems($modTSconfig, $itemArray, $TSref) {
                        // Getting TS-config options for this module for the Backend User:
                        // Getting TS-config options for this module for the Backend User:
-               $conf = $GLOBALS['BE_USER']->getTSConfig($TSref,$modTSconfig);
-               if (is_array($conf['properties']))      {
+               $conf = $GLOBALS['BE_USER']->getTSConfig($TSref, $modTSconfig);
+               if (is_array($conf['properties'])) {
                        reset($conf['properties']);
                        reset($conf['properties']);
-                       while(list($key,$val)=each($conf['properties']))        {
-                               if (!$val)      {
+                       while(list($key, $val) = each($conf['properties'])) {
+                               if (!$val) {
                                        unset($itemArray[$key]);
                                }
                        }
                                        unset($itemArray[$key]);
                                }
                        }
@@ -2146,44 +2694,91 @@ class t3lib_BEfunc      {
         * Call to update the page tree frame (or something else..?) after
         * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
         * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
         * Call to update the page tree frame (or something else..?) after
         * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
         * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
+        * please use the setUpdateSignal function instead now, as it allows you to add more parameters
         * Usage: 11
         *
         * @param       string          Whether to set or clear the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set.
         * @return      string          HTML code (<script> section)
         * Usage: 11
         *
         * @param       string          Whether to set or clear the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set.
         * @return      string          HTML code (<script> section)
+        * @see t3lib_BEfunc::getUpdateSignalCode()
+        * @see t3lib_BEfunc::setUpdateSignal()
+        * @deprecated  since TYPO3 4.2, please use the setUpdateSignal function instead, as it allows you to add more parameters
+        */
+       public static function getSetUpdateSignal($set = '') {
+                       // kept for backwards compatibility if $set is empty, use "getUpdateSignalCode()" instead
+               if ($set) {
+                       return t3lib_BEfunc::setUpdateSignal($set);
+               } else {
+                       return t3lib_BEfunc::getUpdateSignalCode();
+               }
+       }
+
+
+       /**
+        * Call to update the page tree frame (or something else..?) after
+        * use 'updatePageTree' as a first parameter will set the page tree to be updated.
+        * Usage: 10
+        *
+        * @param       string          Key to set the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set. If empty, all update signals will be removed.
+        * @param       mixed           Additional information for the update signal, used to only refresh a branch of the tree
+        * @return      void
+        * @see t3lib_BEfunc::getUpdateSignalCode()
         */
         */
-       function getSetUpdateSignal($set='')    {
+       public function setUpdateSignal($set = '', $params = '') {
                global $BE_USER;
                global $BE_USER;
-               $key = 't3lib_BEfunc::getSetUpdateSignal';
-               $out='';
-               if ($set)       {
-                       $modData=array();
-                       $modData['set']=$set;
-                       $BE_USER->pushModuleData($key,$modData);
+               $modData = $BE_USER->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
+
+               if ($set) {
+                       $modData[$set] = array(
+                               'set' => $set,
+                               'parameter' => $params);
+               } else {        // clear the module data
+                       $modData = array();
+               }
+               $BE_USER->pushModuleData('t3lib_BEfunc::getUpdateSignal', $modData);
+       }
+
+
+       /**
+        * Call to update the page tree frame (or something else..?) if this is set by the function
+        * setUpdateSignal(). It will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
+        * Usage: 1
+        *
+        * @return      string          HTML javascript code
+        * @see t3lib_BEfunc::setUpdateSignal()
+        */
+       public function getUpdateSignalCode() {
+               $signals = array();
+               $modData = $GLOBALS['BE_USER']->getModuleData('t3lib_BEfunc::getUpdateSignal', 'ses');
+               if (!count($modData)) {
+                       return '';
+               }
+
+                       // Hook: Allows to let TYPO3 execute your JS code
+               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'])) {
+                       $updateSignals = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['updateSignalHook'];
                } else {
                } else {
-                       $modData = $BE_USER->getModuleData($key,'ses');
-                       if (trim($modData['set']))      {
-                               $l=explode(',',$modData['set']);
-                               while(list(,$v)=each($l))       {
-                                       switch($v)      {
-                                               case 'updatePageTree':
-                                               case 'updateFolderTree':
-                                                       $out.='
-                                       <script type="text/javascript">
-                                       /*<![CDATA[*/
-                                                       if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav)  {
-                                                               top.content.nav_frame.refresh_nav();
-                                                       }
-                                       /*]]>*/
-                                       </script>';
-                                               break;
-                                       }
-                               }
-                               $modData=array();
-                               $modData['set']='';
-                               $BE_USER->pushModuleData($key,$modData);
+                       $updateSignals = array();
+               }
+
+                       // loop through all setUpdateSignals and get the JS code
+               foreach ($modData as $set => $val) {
+                       if (isset($updateSignals[$set])) {
+                               $params = array('set' => $set, 'parameter' => $val['parameter'], 'JScode' => '');
+                               $ref = NULL;
+                               t3lib_div::callUserFunction($updateSignals[$set], $params, $ref);
+                               $signals[] = $params['JScode'];
+                       } else if ($set == 'updatePageTree' || $set == 'updateFolderTree') {
+                               $signals[] = '
+                                       if (top && top.content && top.content.nav_frame && top.content.nav_frame.Tree) {
+                                               top.content.nav_frame.Tree.refresh();
+                                       }';
                        }
                }
                        }
                }
-               return $out;
+
+               $content = implode(chr(10), $signals);
+
+               t3lib_BEfunc::setUpdateSignal();        // for backwards compatibility, should be replaced
+               return $content;
        }
 
 
        }
 
 
@@ -2202,43 +2797,42 @@ class t3lib_BEfunc      {
         * @param       string          List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
         * @return      array           The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
         */
         * @param       string          List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
         * @return      array           The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
         */
-       function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')      {
+       public static function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type = '', $dontValidateList = '', $setDefaultList = '')  {
 
 
-               if ($modName && is_string($modName))    {
+               if ($modName && is_string($modName)) {
                                        // GETTING stored user-data from this module:
                                        // GETTING stored user-data from this module:
-                       $settings = $GLOBALS['BE_USER']->getModuleData($modName,$type);
+                       $settings = $GLOBALS['BE_USER']->getModuleData($modName, $type);
 
 
-                       $changed=0;
-                       if (!is_array($settings))       {
-                               $changed=1;
-                               $settings=array();
+                       $changed = 0;
+                       if (!is_array($settings)) {
+                               $changed = 1;
+                               $settings = array();
                        }
                        }
-                       if (is_array($MOD_MENU))        {
-                               reset($MOD_MENU);
-                               while(list($key,$var)=each($MOD_MENU))  {
+                       if (is_array($MOD_MENU)) {
+                               foreach ($MOD_MENU as $key=>$var) {
                                                // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
                                                // If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
-                                       if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key],$CHANGED_SETTINGS[$key]))   {
+                                       if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key], $CHANGED_SETTINGS[$key])) {
                                                $settings[$key] = (string)$CHANGED_SETTINGS[$key];
                                                $settings[$key] = (string)$CHANGED_SETTINGS[$key];
-                                               $changed=1;
+                                               $changed = 1;
                                        }
                                                // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
                                        }
                                                // If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
-                                       if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList,$key)))       {
+                                       if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList, $key))) {
                                                        // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
                                                        // If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
-                                               if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]]))      {
-                                                       $settings[$key]=(string)key($var);
-                                                       $changed=1;
+                                               if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]])) {
+                                                       $settings[$key] = (string)key($var);
+                                                       $changed = 1;
                                                }
                                        }
                                        if ($setDefaultList && !is_array($var)) {       // Sets default values (only strings/checkboxes, not menus)
                                                }
                                        }
                                        if ($setDefaultList && !is_array($var)) {       // Sets default values (only strings/checkboxes, not menus)
-                                               if (t3lib_div::inList($setDefaultList,$key) && !isset($settings[$key])) {
-                                                       $settings[$key]=$var;
+                                               if (t3lib_div::inList($setDefaultList, $key) && !isset($settings[$key])) {
+                                                       $settings[$key] = (string)$var;
                                                }
                                        }
                                }
                        } else {die ('No menu!');}
 
                                                }
                                        }
                                }
                        } else {die ('No menu!');}
 
-                       if ($changed)   {
-                               $GLOBALS['BE_USER']->pushModuleData($modName,$settings);
+                       if ($changed) {
+                               $GLOBALS['BE_USER']->pushModuleData($modName, $settings);
                        }
 
                        return  $settings;
                        }
 
                        return  $settings;
@@ -2263,7 +2857,36 @@ class t3lib_BEfunc       {
         *
         *******************************************/
 
         *
         *******************************************/
 
+       /**
+        * Set preview keyword, eg:
+        *      $previewUrl = t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.t3lib_BEfunc::compilePreviewKeyword('id='.$pageId.'&L='.$language.'&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS='.$this->workspace, $GLOBALS['BE_USER']->user['uid'], 120);
+        *
+        * todo for sys_preview:
+        * - Add a comment which can be shown to previewer in frontend in some way (plus maybe ability to write back, take other action?)
+        * - Add possibility for the preview keyword to work in the backend as well: So it becomes a quick way to a certain action of sorts?
+        *
+        * @param       string          Get variables to preview, eg. 'id=1150&L=0&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS=8'
+        * @param       string          32 byte MD5 hash keyword for the URL: "?ADMCMD_prev=[keyword]"
+        * @param       integer         Time-To-Live for keyword
+        * @param       integer         Which workspace to preview. Workspace UID, -1 or >0. If set, the getVars is ignored in the frontend, so that string can be empty
+        * @return      string          Returns keyword to use in URL for ADMCMD_prev=
+        */
+       public static function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl = 172800, $fullWorkspace = NULL) {
+               $field_array = array(
+                       'keyword' => md5(uniqid(microtime())),
+                       'tstamp' => time(),
+                       'endtime' => time()+$ttl,
+                       'config' => serialize(array(
+                               'fullWorkspace' => $fullWorkspace,
+                               'getVars' => $getVarsStr,
+                               'BEUSER_uid' => $beUserUid
+                       ))
+               );
+
+               $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_preview', $field_array);
 
 
+               return $field_array['keyword'];
+       }
 
        /**
         * Unlock or Lock a record from $table with $uid
 
        /**
         * Unlock or Lock a record from $table with $uid
@@ -2277,11 +2900,12 @@ class t3lib_BEfunc      {
         * @internal
         * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
         */
         * @internal
         * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
         */
-       function lockRecords($table='',$uid=0,$pid=0)   {
+       public static function lockRecords($table = '', $uid = 0, $pid = 0) {
                $user_id = intval($GLOBALS['BE_USER']->user['uid']);
                $user_id = intval($GLOBALS['BE_USER']->user['uid']);
-               if ($table && $uid)     {
+               if ($table && $uid) {
                        $fields_values = array(
                                'userid' => $user_id,
                        $fields_values = array(
                                'userid' => $user_id,
+                               'feuserid' => 0,
                                'tstamp' => $GLOBALS['EXEC_TIME'],
                                'record_table' => $table,
                                'record_uid' => $uid,
                                'tstamp' => $GLOBALS['EXEC_TIME'],
                                'record_table' => $table,
                                'record_uid' => $uid,
@@ -2306,30 +2930,49 @@ class t3lib_BEfunc      {
         * @internal
         * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
         */
         * @internal
         * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
         */
-       function isRecordLocked($table,$uid)    {
+       public static function isRecordLocked($table, $uid) {
                global $LOCKED_RECORDS;
                global $LOCKED_RECORDS;
-               if (!is_array($LOCKED_RECORDS)) {
+               if (!is_array($LOCKED_RECORDS)) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                        '*',
                                                        'sys_lockedrecords',
                                                        'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
                                                                AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
                                                );
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                        '*',
                                                        'sys_lockedrecords',
                                                        'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
                                                                AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
                                                );
-                       while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))       {
-                               $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]=$row;
-                               $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg']=sprintf(
-                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord'),
-                                       $row['username'],
-                                       t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
+                       while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                                       // Get the type of the user that locked this record:
+                               if ($row['userid']) {
+                                       $userTypeLabel = 'beUser';
+                               } elseif ($row['feuserid']) {
+                                       $userTypeLabel = 'feUser';
+                               } else {
+                                       $userTypeLabel = 'user';
+                               }
+                               $userType = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.' . $userTypeLabel);
+                                       // Get the username (if available):
+                               if ($row['username']) {
+                                       $userName = $row['username'];
+                               } else {
+                                       $userName = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.unknownUser');
+                               }
+
+                               $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']] = $row;
+                               $LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg'] = sprintf(
+                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecordUser'),
+                                       $userType,
+                                       $userName,
+                                       t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'], $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
                                );
                                );
-                               if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
-                                       $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg']=sprintf(
-                                               $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord_content'),
-                                               $row['username'],
-                                               t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
+                               if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']])) {
+                                       $LOCKED_RECORDS['pages:'.$row['record_pid']]['msg'] = sprintf(
+                                               $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecordUser_content'),
+                                               $userType,
+                                               $userName,
+                                               t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'], $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
                                        );
                                }
                        }
                                        );
                                }
                        }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
                }
                return $LOCKED_RECORDS[$table.':'.$uid];
        }
                }
                return $LOCKED_RECORDS[$table.':'.$uid];
        }
@@ -2346,37 +2989,39 @@ class t3lib_BEfunc      {
         * @internal
         * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
         */
         * @internal
         * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
         */
-       function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')     {
+       public static function exec_foreign_table_where_query($fieldValue, $field = '', $TSconfig = array(), $prefix = '') {
                global $TCA;
                global $TCA;
+
+               t3lib_div::loadTCA($foreign_table);
                $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
                $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
 
                $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
                $foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
                $rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];
 
                $fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
-               if (strstr($fTWHERE,'###REC_FIELD_'))   {
-                       $fTWHERE_parts = explode('###REC_FIELD_',$fTWHERE);
-                       while(list($kk,$vv)=each($fTWHERE_parts))       {
-                               if ($kk)        {
-                                       $fTWHERE_subpart = explode('###',$vv,2);
-                                       $fTWHERE_parts[$kk]=$TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
+               if (strstr($fTWHERE, '###REC_FIELD_')) {
+                       $fTWHERE_parts = explode('###REC_FIELD_', $fTWHERE);
+                       while(list($kk, $vv) = each($fTWHERE_parts)) {
+                               if ($kk) {
+                                       $fTWHERE_subpart = explode('###', $vv, 2);
+                                       $fTWHERE_parts[$kk] = $TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
                                }
                        }
                                }
                        }
-                       $fTWHERE = implode('',$fTWHERE_parts);
+                       $fTWHERE = implode('', $fTWHERE_parts);
                }
 
                }
 
-               $fTWHERE = str_replace('###CURRENT_PID###',intval($TSconfig['_CURRENT_PID']),$fTWHERE);
-               $fTWHERE = str_replace('###THIS_UID###',intval($TSconfig['_THIS_UID']),$fTWHERE);
-               $fTWHERE = str_replace('###THIS_CID###',intval($TSconfig['_THIS_CID']),$fTWHERE);
-               $fTWHERE = str_replace('###STORAGE_PID###',intval($TSconfig['_STORAGE_PID']),$fTWHERE);
-               $fTWHERE = str_replace('###SITEROOT###',intval($TSconfig['_SITEROOT']),$fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###',intval($TSconfig[$field]['PAGE_TSCONFIG_ID']),$fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###',$GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']),$fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###',$GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table),$fTWHERE);
+               $fTWHERE = str_replace('###CURRENT_PID###', intval($TSconfig['_CURRENT_PID']), $fTWHERE);
+               $fTWHERE = str_replace('###THIS_UID###', intval($TSconfig['_THIS_UID']), $fTWHERE);
+               $fTWHERE = str_replace('###THIS_CID###', intval($TSconfig['_THIS_CID']), $fTWHERE);
+               $fTWHERE = str_replace('###STORAGE_PID###', intval($TSconfig['_STORAGE_PID']), $fTWHERE);
+               $fTWHERE = str_replace('###SITEROOT###', intval($TSconfig['_SITEROOT']), $fTWHERE);
+               $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###', intval($TSconfig[$field]['PAGE_TSCONFIG_ID']), $fTWHERE);
+               $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###', $GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']), $fTWHERE);
+               $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###', $GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table), $fTWHERE);
 
                        // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
                $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
 
                        // rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
                $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
-               if ($rootLevel) {
+               if ($rootLevel) {
                        $queryParts = array(
                        $queryParts = array(
-                               'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
+                               'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table, $foreign_table.'.'),
                                'FROM' => $foreign_table,
                                'WHERE' => $foreign_table.'.pid=0 '.
                                                        t3lib_BEfunc::deleteClause($foreign_table).' '.
                                'FROM' => $foreign_table,
                                'WHERE' => $foreign_table.'.pid=0 '.
                                                        t3lib_BEfunc::deleteClause($foreign_table).' '.
@@ -2387,12 +3032,12 @@ class t3lib_BEfunc      {
                        );
                } else {
                        $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
                        );
                } else {
                        $pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
-                       if ($foreign_table!='pages')    {
+                       if ($foreign_table!='pages') {
                                $queryParts = array(
                                $queryParts = array(
-                                       'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
-                                       'FROM' => $foreign_table.',pages',
+                                       'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table, $foreign_table.'.'),
+                                       'FROM' => $foreign_table.', pages',
                                        'WHERE' => 'pages.uid='.$foreign_table.'.pid
                                        'WHERE' => 'pages.uid='.$foreign_table.'.pid
-                                                               AND NOT pages.deleted '.
+                                                               AND pages.deleted=0 '.
                                                                t3lib_BEfunc::deleteClause($foreign_table).
                                                                ' AND '.$pageClause.' '.
                                                                $wgolParts['WHERE'],
                                                                t3lib_BEfunc::deleteClause($foreign_table).
                                                                ' AND '.$pageClause.' '.
                                                                $wgolParts['WHERE'],
@@ -2402,9 +3047,9 @@ class t3lib_BEfunc        {
                                );
                        } else {
                                $queryParts = array(
                                );
                        } else {
                                $queryParts = array(
-                                       'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
+                                       'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table, $foreign_table.'.'),
                                        'FROM' => 'pages',
                                        'FROM' => 'pages',
-                                       'WHERE' => 'NOT pages.deleted
+                                       'WHERE' => 'pages.deleted=0
                                                                AND '.$pageClause.' '.
                                                                $wgolParts['WHERE'],
                                        'GROUPBY' => $wgolParts['GROUPBY'],
                                                                AND '.$pageClause.' '.
                                                                $wgolParts['WHERE'],
                                        'GROUPBY' => $wgolParts['GROUPBY'],
@@ -2427,37 +3072,40 @@ class t3lib_BEfunc      {
         * @return      array
         * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
         */
         * @return      array
         * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
         */
-       function getTCEFORM_TSconfig($table,$row) {
+       public static function getTCEFORM_TSconfig($table, $row) {
+               t3lib_BEfunc::fixVersioningPid($table, $row);
+
                $res = array();
                $res = array();
-               $typeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);
+               $typeVal = t3lib_BEfunc::getTCAtypeValue($table, $row);
 
                        // Get main config for the table
 
                        // Get main config for the table
-               list($TScID,$cPid) = t3lib_BEfunc::getTSCpid($table,$row['uid'],$row['pid']);
-
-               $rootLine = t3lib_BEfunc::BEgetRootLine($TScID,'');
-               if ($TScID>=0)  {
-                       $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table,t3lib_BEfunc::getPagesTSconfig($TScID,$rootLine));
-                       if (is_array($tempConf['properties']))  {
-                               while(list($key,$val)=each($tempConf['properties']))    {
-                                       if (is_array($val))     {
-                                               $fieldN = substr($key,0,-1);
+               list($TScID, $cPid) = t3lib_BEfunc::getTSCpid($table, $row['uid'], $row['pid']);
+
+               $rootLine = t3lib_BEfunc::BEgetRootLine($TScID, '', TRUE);
+               if ($TScID>=0) {
+                       $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table, t3lib_BEfunc::getPagesTSconfig($TScID, $rootLine));
+                       if (is_array($tempConf['properties'])) {
+                               while(list($key, $val) = each($tempConf['properties'])) {
+                                       if (is_array($val)) {
+                                              &