[BUGFIX] Missing column in t3lib_TCEmain::getPreviousLocalizedRecordUid
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_befunc.php
index 73e9aed..5fc8797 100644 (file)
 <?php
 /***************************************************************
 <?php
 /***************************************************************
-*  Copyright notice
-*
-*  (c) 1999-2010 Kasper Skårhøj (kasperYYYY@typo3.com)
-*  All rights reserved
-*
-*  This script is part of the TYPO3 project. The TYPO3 project is
-*  free software; you can redistribute it and/or modify
-*  it under the terms of the GNU General Public License as published by
-*  the Free Software Foundation; either version 2 of the License, or
-*  (at your option) any later version.
-*
-*  The GNU General Public License can be found at
-*  http://www.gnu.org/copyleft/gpl.html.
-*  A copy is found in the textfile GPL.txt and important notices to the license
-*  from the author is found in LICENSE.txt distributed with these scripts.
-*
-*
-*  This script is distributed in the hope that it will be useful,
-*  but WITHOUT ANY WARRANTY; without even the implied warranty of
-*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-*  GNU General Public License for more details.
-*
-*  This copyright notice MUST APPEAR in all copies of the script!
-***************************************************************/
-/**
- * Standard functions available for the TYPO3 backend.
- * You are encouraged to use this class in your own applications (Backend Modules)
- *
- * Call ALL methods without making an object!
- * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
- *
- * $Id$
- * Usage counts are based on search 22/2 2003 through whole backend source of typo3/
- * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
- * XHTML compliant
- *
- * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
- */
-/**
- * [CLASS/FUNCTION INDEX of SCRIPT]
- *
- *
- *
- *  185: class t3lib_BEfunc
- *
- *              SECTION: SQL-related, selecting records, searching
- *  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, 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
- *  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
- * 1105:     function storeHash($hash,$data,$ident)
- * 1125:     function getHash($hash)
+ *  Copyright notice
  *
  *
- *              SECTION: TypoScript related
- * 1161:     function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)
- * 1217:     function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')
- * 1272:     function implodeTSParams($p,$k='')
+ *  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
+ *  All rights reserved
  *
  *
- *              SECTION: Users / Groups related
- * 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)
+ *  This script is part of the TYPO3 project. The TYPO3 project is
+ *  free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
  *
  *
- *              SECTION: Output related
- * 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)
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *  A copy is found in the textfile GPL.txt and important notices to the license
+ *  from the author is found in LICENSE.txt distributed with these scripts.
  *
  *
- *              SECTION: Backend Modules API functions
- * 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
- * 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='')
+ *  This script is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
  *
  *
- *              SECTION: 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
- * 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: 99
- * (This index is automatically created/updated by the extension "extdeveval")
- *
- */
-
-
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
 
 /**
  * Standard functions available for the TYPO3 backend.
 
 /**
  * Standard functions available for the TYPO3 backend.
+ * You are encouraged to use this class in your own applications (Backend Modules)
  * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
  *
  * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
  *
- * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
+ * Call ALL methods without making an object!
+ * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
+ *
+ * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage t3lib
  */
 final class t3lib_BEfunc {
 
  * @package TYPO3
  * @subpackage t3lib
  */
 final class t3lib_BEfunc {
 
-
-
        /*******************************************
         *
         * SQL-related, selecting records, searching
        /*******************************************
         *
         * SQL-related, selecting records, searching
@@ -193,19 +47,17 @@ final class t3lib_BEfunc {
 
 
        /**
 
 
        /**
-        * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field is configured in $TCA for the tablename, $table
-        * This function should ALWAYS be called in the backend for selection on tables which are configured in TCA since it will ensure consistent selection of records, even if they are marked deleted (in which case the system must always treat them as non-existent!)
+        * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field is configured in $GLOBALS['TCA'] for the tablename, $table
+        * This function should ALWAYS be called in the backend for selection on tables which are configured in $GLOBALS['TCA'] since it will ensure consistent selection of records, even if they are marked deleted (in which case the system must always treat them as non-existent!)
         * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering on those fields as well in the backend you can use ->BEenableFields() though.
         * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering on those fields as well in the backend you can use ->BEenableFields() though.
-        * Usage: 71
         *
         *
-        * @param       string          Table name present in $TCA
+        * @param       string          Table name present in $GLOBALS['TCA']
         * @param       string          Table alias if any
         * @return      string          WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
         */
         * @param       string          Table alias if any
         * @return      string          WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
         */
-       public static function deleteClause($table,$tableAlias = '') {
-               global $TCA;
-               if ($TCA[$table]['ctrl']['delete']) {
-                       return ' AND '.($tableAlias ? $tableAlias : $table).'.'.$TCA[$table]['ctrl']['delete'].'=0';
+       public static function deleteClause($table, $tableAlias = '') {
+               if ($GLOBALS['TCA'][$table]['ctrl']['delete']) {
+                       return ' AND ' . ($tableAlias ? $tableAlias : $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
                } else {
                        return '';
                }
                } else {
                        return '';
                }
@@ -216,22 +68,21 @@ final class t3lib_BEfunc {
         * You can set $field to a list of fields (default is '*')
         * 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.
         * You can set $field to a list of fields (default is '*')
         * 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
+        * $table must be found in $GLOBALS['TCA']
         *
         *
-        * @param       string          Table name present in $TCA
+        * @param       string          Table name present in $GLOBALS['TCA']
         * @param       integer         UID of record
         * @param       string          List of fields to select
         * @param       string          Additional WHERE clause, eg. " AND blablabla = 0"
         * @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)
+        * @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
         */
-       public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
+       public static function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE) {
                if ($GLOBALS['TCA'][$table]) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                $fields,
                                $table,
                if ($GLOBALS['TCA'][$table]) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                $fields,
                                $table,
-                               'uid=' . intval($uid) . ($useDeleteClause ? self::deleteClause($table) : '') . $where
+                                       'uid=' . intval($uid) . ($useDeleteClause ? self::deleteClause($table) : '') . $where
                        );
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
                        );
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
@@ -244,20 +95,21 @@ final class t3lib_BEfunc {
        /**
         * Like getRecord(), but overlays workspace version if any.
         *
        /**
         * Like getRecord(), but overlays workspace version if any.
         *
-        * @param       string          Table name present in $TCA
+        * @param       string          Table name present in $GLOBALS['TCA']
         * @param       integer         UID of record
         * @param       string          List of fields to select
         * @param       string          Additional WHERE clause, eg. " AND blablabla = 0"
         * @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)
+        * @param       boolean         Use the deleteClause to check if a record is deleted (default TRUE)
+        * @param       boolean         If TRUE the function does not return a "pointer" row for moved records in a workspace
         * @return      array           Returns the row if found, otherwise nothing
         */
         * @return      array           Returns the row if found, otherwise nothing
         */
-       public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = true) {
+       public static function getRecordWSOL($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE, $unsetMovePointers = FALSE) {
                if ($fields !== '*') {
                if ($fields !== '*') {
-                       $internalFields = t3lib_div::uniqueList($fields.',uid,pid'.($table == 'pages' ? ',t3ver_swapmode' : ''));
+                       $internalFields = t3lib_div::uniqueList($fields . ',uid,pid');
                        $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
                        $row = self::getRecord($table, $uid, $internalFields, $where, $useDeleteClause);
-                       self::workspaceOL($table, $row);
+                       self::workspaceOL($table, $row, -99, $unsetMovePointers);
 
 
-                       if (is_array ($row)) {
+                       if (is_array($row)) {
                                foreach (array_keys($row) as $key) {
                                        if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
                                                unset ($row[$key]);
                                foreach (array_keys($row) as $key) {
                                        if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
                                                unset ($row[$key]);
@@ -265,8 +117,8 @@ final class t3lib_BEfunc {
                                }
                        }
                } else {
                                }
                        }
                } else {
-                       $row = self::getRecord($table, $uid, $fields, $where);
-                       self::workspaceOL($table, $row);
+                       $row = self::getRecord($table, $uid, $fields, $where, $useDeleteClause);
+                       self::workspaceOL($table, $row, -99, $unsetMovePointers);
                }
                return $row;
        }
                }
                return $row;
        }
@@ -274,10 +126,9 @@ final class t3lib_BEfunc {
        /**
         * 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.
        /**
         * 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
+        * $table does NOT need to be configured in $GLOBALS['TCA']
         * The query used is simply this:
         * $query = 'SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
         * The query used is simply this:
         * $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          Table name (not necessarily in TCA)
         * @param       string          WHERE clause
@@ -297,78 +148,44 @@ final class t3lib_BEfunc {
         * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
         * The records are returned in an array
         * If no records were selected, the function returns nothing
         * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
         * The records are returned in an array
         * If no records were selected, the function returns nothing
-        * Usage: 8
         *
         *
-        * @param       string          Table name present in $TCA
+        * @param       string          Table name present in $GLOBALS['TCA']
         * @param       string          Field to select on
         * @param       string          Value that $theField must match
         * @param       string          Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
         * @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          Field to select on
         * @param       string          Value that $theField must match
         * @param       string          Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
         * @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)
+        * @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)
         */
-       public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = true) {
-               global $TCA;
-               if (is_array($TCA[$theTable])) {
+       public static function getRecordsByField($theTable, $theField, $theValue, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '', $useDeleteClause = TRUE) {
+               if (is_array($GLOBALS['TCA'][$theTable])) {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                               '*',
-                                               $theTable,
-                                               $theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
-                                                       ($useDeleteClause ? self::deleteClause($theTable).' ' : '').
+                               '*',
+                               $theTable,
+                                       $theField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable) .
+                                                       ($useDeleteClause ? self::deleteClause($theTable) . ' ' : '') .
                                                        self::versioningPlaceholderClause($theTable) . ' ' .
                                                        self::versioningPlaceholderClause($theTable) . ' ' .
-                                                       $whereClause,   // whereClauseMightContainGroupOrderBy
-                                               $groupBy,
-                                               $orderBy,
-                                               $limit
-                                       );
+                                                       $whereClause, // whereClauseMightContainGroupOrderBy
+                               $groupBy,
+                               $orderBy,
+                               $limit
+                       );
                        $rows = array();
                        $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);
-                       if (count($rows))       return $rows;
+                       if (count($rows)) {
+                               return $rows;
+                       }
                }
        }
 
        /**
                }
        }
 
        /**
-        * Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
-        * Usage: 0
-        *
-        * @param       array           Array of search words
-        * @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
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.6, use $GLOBALS['TYPO3_DB']->searchQuery() directly!
-        */
-       public static function searchQuery($searchWords, $fields, $table = '') {
-               t3lib_div::logDeprecatedFunction();
-
-               return $GLOBALS['TYPO3_DB']->searchQuery($searchWords, $fields, $table);
-       }
-
-       /**
-        * Returns a WHERE clause that can find a value ($value) in a list field ($field)
-        * For instance a record in the database might contain a list of numbers, "34,234,5" (with no spaces between). This query would be able to select that record based on the value "34", "234" or "5" regardless of their positioni in the list (left, middle or right).
-        * Is nice to look up list-relations to records or files in TYPO3 database tables.
-        * Usage: 0
-        *
-        * @param       string          Table field name
-        * @param       string          Value to find in list
-        * @return      string          WHERE clause for a query
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.6, use $GLOBALS['TYPO3_DB']->listQuery() directly!
-        */
-       public static function listQuery($field, $value) {
-               t3lib_div::logDeprecatedFunction();
-
-               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
         *
         * @param       string          [tablename]_[uid] string to explode
         * @return      array
@@ -381,7 +198,6 @@ final class t3lib_BEfunc {
        /**
         * Returns a list of pure integers based on $in_list being a list of records with table-names prepended.
         * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
        /**
         * Returns a list of pure integers based on $in_list being a list of records with table-names prepended.
         * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
-        * Usage: 1 (t3lib_userauthgroup)
         *
         * @param       string          Input list
         * @param       string          Table name from which ids is returned
         *
         * @param       string          Input list
         * @param       string          Table name from which ids is returned
@@ -390,15 +206,17 @@ final class t3lib_BEfunc {
         */
        public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
                $list = Array();
         */
        public static function getSQLselectableList($in_list, $tablename, $default_tablename) {
                $list = Array();
-               if ((string)trim($in_list)!='') {
+               if ((string) trim($in_list) != '') {
                        $tempItemArray = explode(',', trim($in_list));
                        foreach ($tempItemArray as $key => $val) {
                                $val = strrev($val);
                                $parts = explode('_', $val, 2);
                        $tempItemArray = explode(',', trim($in_list));
                        foreach ($tempItemArray as $key => $val) {
                                $val = strrev($val);
                                $parts = explode('_', $val, 2);
-                               if ((string)trim($parts[0])!='') {
+                               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;
+                                       }
                                }
                        }
                }
                                }
                        }
                }
@@ -410,9 +228,8 @@ final class t3lib_BEfunc {
         * 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_ACCESS_TIME"] is used for date.
         * 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_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       string          $table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $GLOBALS['TCA'].
         * @param       boolean         $inv means that the query will select all records NOT VISIBLE records (inverted selection)
         * @return      string          WHERE clause part
         */
         * @param       boolean         $inv means that the query will select all records NOT VISIBLE records (inverted selection)
         * @return      string          WHERE clause part
         */
@@ -423,19 +240,19 @@ final class t3lib_BEfunc {
                if (is_array($ctrl)) {
                        if (is_array($ctrl['enablecolumns'])) {
                                if ($ctrl['enablecolumns']['disabled']) {
                if (is_array($ctrl)) {
                        if (is_array($ctrl['enablecolumns'])) {
                                if ($ctrl['enablecolumns']['disabled']) {
-                                       $field = $table.'.'.$ctrl['enablecolumns']['disabled'];
-                                       $query[] = $field.'=0';
-                                       $invQuery[] = $field.'!=0';
+                                       $field = $table . '.' . $ctrl['enablecolumns']['disabled'];
+                                       $query[] = $field . '=0';
+                                       $invQuery[] = $field . '<>0';
                                }
                                if ($ctrl['enablecolumns']['starttime']) {
                                }
                                if ($ctrl['enablecolumns']['starttime']) {
-                                       $field = $table.'.'.$ctrl['enablecolumns']['starttime'];
-                                       $query[] = '('.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
-                                       $invQuery[] = '('.$field.'!=0 AND '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
+                                       $field = $table . '.' . $ctrl['enablecolumns']['starttime'];
+                                       $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'];
-                                       $query[] = '('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_ACCESS_TIME'].')';
-                                       $invQuery[] = '('.$field.'!=0 AND '.$field.'<='.$GLOBALS['SIM_ACCESS_TIME'].')';
+                                       $field = $table . '.' . $ctrl['enablecolumns']['endtime'];
+                                       $query[] = '(' . $field . '=0 OR ' . $field . '>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
+                                       $invQuery[] = '(' . $field . '<>0 AND ' . $field . '<=' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
                                }
                        }
                }
                                }
                        }
                }
@@ -447,21 +264,21 @@ final class t3lib_BEfunc {
        /**
         * Fetches the localization for a given record.
         *
        /**
         * Fetches the localization for a given record.
         *
-        * @param       string          $table: Table name present in $TCA
+        * @param       string          $table: Table name present in $GLOBALS['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: '')
         * @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
+        * @return      mixed           Multidimensional array with selected records; if none exist, FALSE is returned
         */
        public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
         */
        public static function getRecordLocalization($table, $uid, $language, $andWhereClause = '') {
-               $recordLocalization = false;
+               $recordLocalization = FALSE;
                if (self::isTableLocalizable($table)) {
                        $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
                        $recordLocalization = self::getRecordsByField(
                                $table,
                                $tcaCtrl['transOrigPointerField'],
                                $uid,
                if (self::isTableLocalizable($table)) {
                        $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
                        $recordLocalization = self::getRecordsByField(
                                $table,
                                $tcaCtrl['transOrigPointerField'],
                                $uid,
-                               'AND '.$tcaCtrl['languageField'].'='.intval($language).($andWhereClause ? ' '.$andWhereClause : ''),
+                                       'AND ' . $tcaCtrl['languageField'] . '=' . intval($language) . ($andWhereClause ? ' ' . $andWhereClause : ''),
                                '',
                                '',
                                '1'
                                '',
                                '',
                                '1'
@@ -471,95 +288,6 @@ final class t3lib_BEfunc {
        }
 
 
        }
 
 
-
-
-
-
-
-
-
-
-       /*******************************************
-        *
-        * SQL-related, DEPRECATED functions
-        * (use t3lib_DB functions instead)
-        *
-        *******************************************/
-
-
-       /**
-        * Returns a SELECT query, selecting fields ($select) from two/three tables joined
-        * $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.
-        *
-        * @param       string          Field list for SELECT
-        * @param       string          Tablename, local table
-        * @param       string          Tablename, relation table
-        * @param       string          Tablename, foreign table
-        * @param       string          Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
-        * @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.
-        * @return      string          Full SQL query
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.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()
-        */
-       public static function mm_query($select, $local_table, $mm_table, $foreign_table, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '') {
-               t3lib_div::logDeprecatedFunction();
-
-               $query = $GLOBALS['TYPO3_DB']->SELECTquery(
-                                       $select,
-                                       $local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
-                                       $local_table.'.uid='.$mm_table.'.uid_local'.($foreign_table?' AND '.$foreign_table.'.uid='.$mm_table.'.uid_foreign':'').' '.
-                                               $whereClause,   // whereClauseMightContainGroupOrderBy
-                                       $groupBy,
-                                       $orderBy,
-                                       $limit
-                               );
-               return $query;
-       }
-
-       /**
-        * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
-        * 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
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.6, use $GLOBALS['TYPO3_DB']->exec_INSERTquery() directly!
-        */
-       public static function DBcompileInsert($table, $fields_values) {
-               t3lib_div::logDeprecatedFunction();
-
-               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.
-        * 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
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.6, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery() directly!
-        */
-       public static function DBcompileUpdate($table, $where, $fields_values) {
-               t3lib_div::logDeprecatedFunction();
-
-               return $GLOBALS['TYPO3_DB']->UPDATEquery($table, $where, $fields_values);
-       }
-
-
-
-
-
-
-
-
-
-
        /*******************************************
         *
         * Page tree, TCA related
        /*******************************************
         *
         * Page tree, TCA related
@@ -570,11 +298,10 @@ final class t3lib_BEfunc {
         * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
         * By default deleted pages are filtered.
         * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
         * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
         * By default deleted pages are filtered.
         * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
-        * 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 process if we meet a page, the user has no reading access to.
         *
         * @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 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!
+        * @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!)
         */
        public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
         * @return      array           Root line array, all the way to the page tree root (or as far as $clause allows!)
         */
        public static function BEgetRootLine($uid, $clause = '', $workspaceOL = FALSE) {
@@ -616,8 +343,8 @@ final class t3lib_BEfunc {
                                        't3ver_oid' => $val['t3ver_oid'],
                                        't3ver_wsid' => $val['t3ver_wsid'],
                                        't3ver_state' => $val['t3ver_state'],
                                        't3ver_oid' => $val['t3ver_oid'],
                                        't3ver_wsid' => $val['t3ver_wsid'],
                                        't3ver_state' => $val['t3ver_state'],
-                                       't3ver_swapmode' => $val['t3ver_swapmode'],
-                                       't3ver_stage' => $val['t3ver_stage']
+                                       't3ver_stage' => $val['t3ver_stage'],
+                                       'backend_layout_next_level' => $val['backend_layout_next_level']
                                );
                                if (isset($val['_ORIG_pid'])) {
                                        $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
                                );
                                if (isset($val['_ORIG_pid'])) {
                                        $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
@@ -633,7 +360,7 @@ final class t3lib_BEfunc {
         *
         * @param       integer         $uid: 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 process if we meet a page, the user has no reading access to.
         *
         * @param       integer         $uid: 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 process if we meet a page, the user has no reading access to.
-        * @param       boolean         $workspaceOL: 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!
+        * @param       boolean         $workspaceOL: 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           Cached page record for the rootline
         * @see         BEgetRootLine
         */
         * @return      array           Cached page record for the rootline
         * @see         BEgetRootLine
         */
@@ -645,11 +372,11 @@ final class t3lib_BEfunc {
                        $row = $getPageForRootline_cache[$ident];
                } else {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                        $row = $getPageForRootline_cache[$ident];
                } else {
                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                               'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,t3ver_stage',
+                               'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage,backend_layout_next_level',
                                'pages',
                                'pages',
-                               'uid=' . intval($uid) . ' ' .
-                                       self::deleteClause('pages') . ' ' .
-                                       $clause         // whereClauseMightContainGroupOrderBy
+                                       'uid=' . intval($uid) . ' ' .
+                                                       self::deleteClause('pages') . ' ' .
+                                                       $clause // whereClauseMightContainGroupOrderBy
                        );
 
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        );
 
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
@@ -675,13 +402,12 @@ final class t3lib_BEfunc {
         * @return      void
         */
        public static function openPageTree($pid, $clearExpansion) {
         * @return      void
         */
        public static function openPageTree($pid, $clearExpansion) {
-               global $BE_USER;
 
                        // Get current expansion data:
                if ($clearExpansion) {
                        $expandedPages = array();
                } else {
 
                        // Get current expansion data:
                if ($clearExpansion) {
                        $expandedPages = array();
                } else {
-                       $expandedPages = unserialize($BE_USER->uc['browseTrees']['browsePages']);
+                       $expandedPages = unserialize($GLOBALS['BE_USER']->uc['browseTrees']['browsePages']);
                }
 
                        // Get rootline:
                }
 
                        // Get rootline:
@@ -689,8 +415,8 @@ final class t3lib_BEfunc {
 
                        // First, find out what mount index to use (if more than one DB mount exists):
                $mountIndex = 0;
 
                        // 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) {
+               $mountKeys = array_flip($GLOBALS['BE_USER']->returnWebmounts());
+               foreach ($rL as $rLDat) {
                        if (isset($mountKeys[$rLDat['uid']])) {
                                $mountIndex = $mountKeys[$rLDat['uid']];
                                break;
                        if (isset($mountKeys[$rLDat['uid']])) {
                                $mountIndex = $mountKeys[$rLDat['uid']];
                                break;
@@ -698,20 +424,19 @@ final class t3lib_BEfunc {
                }
 
                        // Traverse rootline and open paths:
                }
 
                        // Traverse rootline and open paths:
-               foreach($rL as $rLDat) {
+               foreach ($rL as $rLDat) {
                        $expandedPages[$mountIndex][$rLDat['uid']] = 1;
                }
 
                        // Write back:
                        $expandedPages[$mountIndex][$rLDat['uid']] = 1;
                }
 
                        // Write back:
-               $BE_USER->uc['browseTrees']['browsePages'] = serialize($expandedPages);
-               $BE_USER->writeUC();
+               $GLOBALS['BE_USER']->uc['browseTrees']['browsePages'] = serialize($expandedPages);
+               $GLOBALS['BE_USER']->writeUC();
        }
 
        /**
         * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
         * Each part of the path will be limited to $titleLimit characters
         * Deleted pages are filtered out.
        }
 
        /**
         * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
         * Each part of the path will be limited to $titleLimit characters
         * Deleted pages are filtered out.
-        * Usage: 15
         *
         * @param       integer         Page uid for which to create record path
         * @param       string          $clause is additional where clauses, eg. "
         *
         * @param       integer         Page uid for which to create record path
         * @param       string          $clause is additional where clauses, eg. "
@@ -720,7 +445,9 @@ final class t3lib_BEfunc {
         * @return      mixed           Path of record (string) OR array with short/long title if $fullTitleLimit is set.
         */
        public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
         * @return      mixed           Path of record (string) OR array with short/long title if $fullTitleLimit is set.
         */
        public static function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit = 0) {
-               if (!$titleLimit) { $titleLimit = 1000; }
+               if (!$titleLimit) {
+                       $titleLimit = 1000;
+               }
 
                $loopCheck = 100;
                $output = $fullOutput = '/';
 
                $loopCheck = 100;
                $output = $fullOutput = '/';
@@ -735,9 +462,6 @@ final class t3lib_BEfunc {
                        if ($record['uid'] === 0) {
                                continue;
                        }
                        if ($record['uid'] === 0) {
                                continue;
                        }
-                       if ($record['_ORIG_pid'] && $record['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...
-                       }
                        $output = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
                        if ($fullTitleLimit) {
                                $fullOutput = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
                        $output = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $titleLimit) . $output;
                        if ($fullTitleLimit) {
                                $fullOutput = '/' . t3lib_div::fixed_lgd_cs(strip_tags($record['title']), $fullTitleLimit) . $fullOutput;
@@ -752,33 +476,66 @@ final class t3lib_BEfunc {
        }
 
        /**
        }
 
        /**
-        * Returns an array with the exclude-fields as defined in TCA
+        * Returns an array with the exclude-fields as defined in TCA and FlexForms
         * Used for listing the exclude-fields in be_groups forms
         * Used for listing the exclude-fields in be_groups forms
-        * Usage: 2 (t3lib_tceforms + t3lib_transferdata)
         *
         *
-        * @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 and from FlexForms (fieldname, table:extkey;sheetname;fieldname)
         */
        public static function getExcludeFields() {
         */
        public static function getExcludeFields() {
-               global $TCA;
-                       // All TCA keys:
-               $theExcludeArray = Array();
-               $tc_keys = array_keys($TCA);
-               foreach($tc_keys as $table) {
+                       // All TCA keys
+               $theExcludeArray = array();
+               $tc_keys = array_keys($GLOBALS['TCA']);
+               foreach ($tc_keys as $table) {
                                // Load table
                        t3lib_div::loadTCA($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) {
-                                       if ($TCA[$table]['columns'][$field]['exclude']) {
-                                                       // Get Human Readable names of fields and table:
-                                               $Fname = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
-                                                       // add entry:
-                                               $theExcludeArray[] = Array($Fname, $table.':'.$field);
+                               // All field names configured and not restricted to admins
+                       if (is_array($GLOBALS['TCA'][$table]['columns'])
+                                       && $GLOBALS['TCA'][$table]['ctrl']['adminOnly'] != 1
+                                       && $GLOBALS['TCA'][$table]['ctrl']['rootLevel'] != 1
+                                       ) {
+                               $f_keys = array_keys($GLOBALS['TCA'][$table]['columns']);
+                               foreach ($f_keys as $field) {
+                                       if ($GLOBALS['TCA'][$table]['columns'][$field]['exclude']) {
+                                                       // Get human readable names of fields and table
+                                               $Fname = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']) . ': ' . $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
+                                                       // Add entry
+                                               $theExcludeArray[] = array($Fname, $table . ':' . $field);
+                                       }
+                               }
+                       }
+                       // All FlexForm fields
+                       $flexFormArray = self::getRegisteredFlexForms($table);
+                       foreach ($flexFormArray as $tableField => $flexForms) {
+                                       // Prefix for field label, e.g. "Plugin Options:"
+                               $labelPrefix = '';
+                               if (!empty($GLOBALS['TCA'][$table]['columns'][$tableField]['label'])) {
+                                       $labelPrefix = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$tableField]['label']);
+                               }
+                                       // Get all sheets and title
+                               foreach ($flexForms as $extIdent => $extConf) {
+                                       $extTitle = $GLOBALS['LANG']->sl($extConf['title']);
+                                               // Get all fields in sheet
+                                       foreach ($extConf['ds']['sheets'] as $sheetName => $sheet) {
+                                               if (empty($sheet['ROOT']['el']) || !is_array($sheet['ROOT']['el'])) {
+                                                       continue;
+                                               }
+                                               foreach ($sheet['ROOT']['el'] as $fieldName => $field) {
+                                                               // Use only excludeable fields
+                                                       if (empty($field['TCEforms']['exclude'])) {
+                                                               continue;
+                                                       }
+                                                       $fieldLabel = (!empty($field['TCEforms']['label']) ? $GLOBALS['LANG']->sl($field['TCEforms']['label']) : $fieldName);
+                                                       $fieldIdent = $table . ':' . $tableField . ';' . $extIdent . ';' . $sheetName . ';' . $fieldName;
+                                                       $theExcludeArray[] = array(trim($labelPrefix . ' ' . $extTitle, ': ') . ': ' . $fieldLabel, $fieldIdent);
+                                               }
                                        }
                                }
                        }
                }
                                        }
                                }
                        }
                }
+
+                       // Sort fields by label
+               usort($theExcludeArray, array(t3lib_TCEforms_Flexforms, 'compareArraysByFirstValue'));
+
                return $theExcludeArray;
        }
 
                return $theExcludeArray;
        }
 
@@ -786,10 +543,9 @@ final class t3lib_BEfunc {
         * Returns an array with explicit Allow/Deny fields.
         * Used for listing these field/value pairs in be_groups forms
         *
         * 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
+        * @return      array           Array with information from all of $GLOBALS['TCA']
         */
        public static function getExplicitAuthFieldValues() {
         */
        public static function getExplicitAuthFieldValues() {
-               global $TCA;
 
                        // Initialize:
                $adLabel = array(
 
                        // Initialize:
                $adLabel = array(
@@ -799,49 +555,49 @@ final class t3lib_BEfunc {
 
                        // All TCA keys:
                $allowDenyOptions = Array();
 
                        // All TCA keys:
                $allowDenyOptions = Array();
-               $tc_keys = array_keys($TCA);
-               foreach($tc_keys as $table)     {
+               $tc_keys = array_keys($GLOBALS['TCA']);
+               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'])) {
-                               $f_keys = array_keys($TCA[$table]['columns']);
-                               foreach($f_keys as $field) {
-                                       $fCfg = $TCA[$table]['columns'][$field]['config'];
-                                       if ($fCfg['type']=='select' && $fCfg['authMode'])       {
+                       if (is_array($GLOBALS['TCA'][$table]['columns'])) {
+                               $f_keys = array_keys($GLOBALS['TCA'][$table]['columns']);
+                               foreach ($f_keys as $field) {
+                                       $fCfg = $GLOBALS['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:
 
                                                        // 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']);
+                                                       $allowDenyOptions[$table . ':' . $field]['tableFieldLabel'] = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']) . ': ' . $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['columns'][$field]['label']);
 
                                                                // Check for items:
 
                                                                // Check for items:
-                                                       foreach($fCfg['items'] as $iVal) {
-                                                               if (strcmp($iVal[1], ''))       {       // Values '' is not controlled by this setting.
+                                                       foreach ($fCfg['items'] as $iVal) {
+                                                               if (strcmp($iVal[1], '')) { // Values '' is not controlled by this setting.
 
                                                                                // Find iMode:
                                                                        $iMode = '';
 
                                                                                // Find iMode:
                                                                        $iMode = '';
-                                                                       switch((string)$fCfg['authMode']) {
+                                                                       switch ((string) $fCfg['authMode']) {
                                                                                case 'explicitAllow':
                                                                                        $iMode = 'ALLOW';
                                                                                case 'explicitAllow':
                                                                                        $iMode = 'ALLOW';
-                                                                               break;
+                                                                                       break;
                                                                                case 'explicitDeny':
                                                                                        $iMode = 'DENY';
                                                                                case 'explicitDeny':
                                                                                        $iMode = 'DENY';
-                                                                               break;
+                                                                                       break;
                                                                                case 'individual':
                                                                                        if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
                                                                                                $iMode = 'ALLOW';
                                                                                        } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
                                                                                                $iMode = 'DENY';
                                                                                        }
                                                                                case 'individual':
                                                                                        if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
                                                                                                $iMode = 'ALLOW';
                                                                                        } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
                                                                                                $iMode = 'DENY';
                                                                                        }
-                                                                               break;
+                                                                                       break;
                                                                        }
 
                                                                                // Set iMode:
                                                                        if ($iMode) {
                                                                        }
 
                                                                                // Set iMode:
                                                                        if ($iMode) {
-                                                                               $allowDenyOptions[$table.':'.$field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
+                                                                               $allowDenyOptions[$table . ':' . $field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
                                                                        }
                                                                }
                                                        }
                                                                        }
                                                                }
                                                        }
@@ -857,36 +613,37 @@ final class t3lib_BEfunc {
        /**
         * Returns an array with system languages:
         *
        /**
         * Returns an array with system languages:
         *
-        * @return      array           Array with languages
+        * Since TYPO3 4.5 the flagIcon is not returned as a filename in "gfx/flags/*" anymore,
+        * but as a string <flags-xx>. The calling party should call
+        * t3lib_iconWorks::getSpriteIcon(<flags-xx>) to get an HTML which will represent
+        * the flag of this language.
+        *
+        * @return      array           Array with languages (title, uid, flagIcon)
         */
         */
-       public static function getSystemLanguages()     {
-
-                       // Initialize, add default language:
+       public static function getSystemLanguages() {
+               $languages = t3lib_div::makeInstance('t3lib_transl8tools')->getSystemLanguages();
                $sysLanguages = array();
                $sysLanguages = array();
-               $sysLanguages[] = array('Default language', 0);
-
-                       // Traverse languages
-               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,flag', 'sys_language', 'pid=0' . self::deleteClause('sys_language'));
-               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                       $sysLanguages[] = array(
-                               htmlspecialchars($row['title']) . ' [' . $row['uid'] . ']',
-                               $row['uid'],
-                               ($row['flag'] ? 'flags/' . $row['flag'] : '')
-                       );
+               foreach ($languages as $language) {
+                       if ($language['uid'] !== -1) {
+                               $sysLanguages[] = array(
+                                       0 => htmlspecialchars($language['title']) . ' [' . $language['uid'] . ']',
+                                       1 => $language['uid'],
+                                       2 => $language['flagIcon']
+                               );
+                       }
                }
                }
-               $GLOBALS['TYPO3_DB']->sql_free_result($res);
 
                return $sysLanguages;
        }
 
        /**
 
                return $sysLanguages;
        }
 
        /**
-        * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $TCA.
+        * Determines whether a table is localizable and has the languageField and transOrigPointerField set in $GLOBALS['TCA'].
         *
         * @param       string          $table: The table to check
         * @return      boolean         Whether a table is localizable
         */
        public static function isTableLocalizable($table) {
         *
         * @param       string          $table: The table to check
         * @return      boolean         Whether a table is localizable
         */
        public static function isTableLocalizable($table) {
-               $isLocalizable = false;
+               $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']);
                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']);
@@ -895,26 +652,26 @@ final class t3lib_BEfunc {
        }
 
        /**
        }
 
        /**
-        * Returns the value of the property localizationMode in the given $config array ($TCA[<table>]['columns'][<field>]['config']).
+        * Returns the value of the property localizationMode in the given $config array ($GLOBALS['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 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.
+        * If the table is not prepared for localization or not defined at all in $GLOBALS['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)
         *
         * @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
+        * @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 static function getInlineLocalizationMode($table, $fieldOrConfig) {
         */
        public static function getInlineLocalizationMode($table, $fieldOrConfig) {
-               $localizationMode = false;
+               $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($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)) {
+               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:
                        $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;
+                       if ($localizationMode == 'select' && !self::isTableLocalizable($config['foreign_table'])) {
+                               $localizationMode = FALSE;
                        }
                }
                return $localizationMode;
                        }
                }
                return $localizationMode;
@@ -923,15 +680,14 @@ final class t3lib_BEfunc {
        /**
         * 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.
        /**
         * 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)
-        * Usage: 21
+        * In any case ->isInWebMount must return TRUE for the user (regardless of $perms_clause)
         *
         * @param       integer         Page uid for which to check read-access
         *
         * @param       integer         Page uid for which to check read-access
-        * @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 $GLOBALS['BE_USER']->getPagePermsClause(1);
+        * @return      array           Returns page record if OK, otherwise FALSE.
         */
        public static function readPageAccess($id, $perms_clause) {
         */
        public static function readPageAccess($id, $perms_clause) {
-               if ((string)$id!='') {
+               if ((string) $id != '') {
                        $id = intval($id);
                        if (!$id) {
                                if ($GLOBALS['BE_USER']->isAdmin()) {
                        $id = intval($id);
                        if (!$id) {
                                if ($GLOBALS['BE_USER']->isAdmin()) {
@@ -951,12 +707,11 @@ final class t3lib_BEfunc {
                                }
                        }
                }
                                }
                        }
                }
-               return false;
+               return FALSE;
        }
 
        /**
         * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
        }
 
        /**
         * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
-        * Usage: 6
         *
         * @param       string          Table name (present in TCA)
         * @param       array           Record from $table
         *
         * @param       string          Table name (present in TCA)
         * @param       array           Record from $table
@@ -964,25 +719,23 @@ final class t3lib_BEfunc {
         * @return      array
         */
        public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
         * @return      array
         */
        public static function getTCAtypes($table, $rec, $useFieldNameAsKey = 0) {
-               global $TCA;
-
                t3lib_div::loadTCA($table);
                t3lib_div::loadTCA($table);
-               if ($TCA[$table])       {
+               if ($GLOBALS['TCA'][$table]) {
 
                                // Get type value:
                        $fieldValue = self::getTCAtypeValue($table, $rec);
 
                                // Get typesConf
 
                                // Get type value:
                        $fieldValue = self::getTCAtypeValue($table, $rec);
 
                                // Get typesConf
-                       $typesConf = $TCA[$table]['types'][$fieldValue];
+                       $typesConf = $GLOBALS['TCA'][$table]['types'][$fieldValue];
 
                                // Get fields list and traverse it
                        $fieldList = explode(',', $typesConf['showitem']);
                        $altFieldList = array();
 
                                // Traverse fields in types config and parse the configuration into a nice array:
 
                                // Get fields list and traverse it
                        $fieldList = explode(',', $typesConf['showitem']);
                        $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);
                                list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
-                               $defaultExtras = is_array($TCA[$table]['columns'][$pFieldName]) ? $TCA[$table]['columns'][$pFieldName]['defaultExtras'] : '';
+                               $defaultExtras = is_array($GLOBALS['TCA'][$table]['columns'][$pFieldName]) ? $GLOBALS['TCA'][$table]['columns'][$pFieldName]['defaultExtras'] : '';
                                $specConfParts = self::getSpecConfParts($pSpec, $defaultExtras);
 
                                $fieldList[$k] = array(
                                $specConfParts = self::getSpecConfParts($pSpec, $defaultExtras);
 
                                $fieldList[$k] = array(
@@ -1006,47 +759,93 @@ final class t3lib_BEfunc {
        }
 
        /**
        }
 
        /**
-        * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $TCA
-        * If no "type" field is configured in the "ctrl"-section of the $TCA for the table, zero is used.
-        * If zero is not an index in the "types" section of $TCA for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
-        * Usage: 7
+        * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $GLOBALS['TCA']
+        * If no "type" field is configured in the "ctrl"-section of the $GLOBALS['TCA'] for the table, zero is used.
+        * If zero is not an index in the "types" section of $GLOBALS['TCA'] for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
+        *
+        * Note: This method is very similar to t3lib_TCEforms::getRTypeNum(), however, it has two differences:
+        *       1) The method in TCEForms also takes care of localization (which is difficult to do here as the whole infrastructure for language overlays is only in TCEforms).
+        *       2) The $rec array looks different in TCEForms, as in there it's not the raw record but the t3lib_transferdata version of it, which changes e.g. how "select"
+        *          and "group" field values are stored, which makes different processing of the "foreign pointer field" type field variant necessary.
         *
         * @param       string          Table name present in TCA
         * @param       array           Record from $table
         * @return      string          Field value
         * @see getTCAtypes()
         */
         *
         * @param       string          Table name present in TCA
         * @param       array           Record from $table
         * @return      string          Field value
         * @see getTCAtypes()
         */
-       public static function getTCAtypeValue($table, $rec) {
-               global $TCA;
+       public static function getTCAtypeValue($table, $row) {
+
+               $typeNum = 0;
 
 
-                       // 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);
                t3lib_div::loadTCA($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;
-                       return $fieldValue;
+               if ($GLOBALS['TCA'][$table]) {
+                       $field = $GLOBALS['TCA'][$table]['ctrl']['type'];
+
+                       if (strpos($field, ':') !== FALSE) {
+                               list($pointerField, $foreignTableTypeField) = explode(':', $field);
+
+                               // Get field value from database if field is not in the $row array
+                               if (!isset($row[$pointerField])) {
+                                       $localRow = t3lib_BEfunc::getRecord($table, $row['uid'], $pointerField);
+                                       $foreignUid = $localRow[$pointerField];
+                               } else {
+                                       $foreignUid = $row[$pointerField];
+                               }
+
+                               if ($foreignUid) {
+                                       $fieldConfig = $GLOBALS['TCA'][$table]['columns'][$pointerField]['config'];
+                                       $relationType = $fieldConfig['type'];
+                                       if ($relationType === 'select') {
+                                               $foreignTable = $fieldConfig['foreign_table'];
+                                       } elseif ($relationType === 'group') {
+                                               $allowedTables = explode(',', $fieldConfig['allowed']);
+                                               $foreignTable = $allowedTables[0]; // Always take the first configured table.
+                                       } else {
+                                               throw new RuntimeException('TCA foreign field pointer fields are only allowed to be used with group or select field types.', 1325862240);
+                                       }
+
+                                       $foreignRow = t3lib_BEfunc::getRecord($foreignTable, $foreignUid, $foreignTableTypeField);
+
+                                       if ($foreignRow[$foreignTableTypeField]) {
+                                               $typeNum = $foreignRow[$foreignTableTypeField];
+                                       }
+                               }
+                       } else {
+                               $typeNum = $row[$field];
+                       }
+
+                       if (!strcmp($typeNum, '')) {  // If that value is an empty string, set it to "0" (zero)
+                               $typeNum = 0;
+                       }
+               }
+
+               // If current typeNum doesn't exist, set it to 0 (or to 1 for historical reasons, if 0 doesn't exist)
+               if (!$GLOBALS['TCA'][$table]['types'][$typeNum]) {
+                       $typeNum = $GLOBALS['TCA'][$table]['types']["0"] ? 0 : 1;
                }
                }
+
+               $typeNum = (string)$typeNum; // Force to string. Necessary for eg '-1' to be recognized as a type value.
+
+               return $typeNum;
        }
 
        /**
        }
 
        /**
-        * Parses a part of the field lists in the "types"-section of $TCA arrays, namely the "special configuration" at index 3 (position 4)
+        * Parses a part of the field lists in the "types"-section of $GLOBALS['TCA'] arrays, namely the "special configuration" at index 3 (position 4)
         * Elements are splitted by ":" and within those parts, parameters are splitted by "|".
         * Everything is returned in an array and you should rather see it visually than listen to me anymore now...  Check out example in Inside TYPO3
         * Elements are splitted by ":" and within those parts, parameters are splitted by "|".
         * Everything is returned in an array and you should rather see it visually than listen to me anymore now...  Check out example in Inside TYPO3
-        * Usage: 5
         *
         * @param       string          Content from the "types" configuration of TCA (the special configuration) - see description of function
         * @param       string          The ['defaultExtras'] value from field configuration
         * @return      array
         */
         *
         * @param       string          Content from the "types" configuration of TCA (the special configuration) - see description of function
         * @param       string          The ['defaultExtras'] value from field configuration
         * @return      array
         */
-       public static function getSpecConfParts($str, $defaultExtras)   {
+       public static function getSpecConfParts($str, $defaultExtras) {
 
                        // Add defaultExtras:
 
                        // Add defaultExtras:
-               $specConfParts = t3lib_div::trimExplode(':', $defaultExtras.':'.$str, 1);
+               $specConfParts = t3lib_div::trimExplode(':', $defaultExtras . ':' . $str, 1);
 
                $reg = array();
                if (count($specConfParts)) {
 
                $reg = array();
                if (count($specConfParts)) {
-                       foreach($specConfParts as $k2 => $v2) {
+                       foreach ($specConfParts as $k2 => $v2) {
                                unset($specConfParts[$k2]);
                                if (preg_match('/(.*)\[(.*)\]/', $v2, $reg)) {
                                        $specConfParts[trim($reg[1])] = array(
                                unset($specConfParts[$k2]);
                                if (preg_match('/(.*)\[(.*)\]/', $v2, $reg)) {
                                        $specConfParts[trim($reg[1])] = array(
@@ -1065,7 +864,6 @@ final class t3lib_BEfunc {
        /**
         * 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
        /**
         * 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
         *
         * @param       array           Array of "[key] = [value]" strings to convert.
         * @return      array
         *
         * @param       array           Array of "[key] = [value]" strings to convert.
         * @return      array
@@ -1075,7 +873,7 @@ final class t3lib_BEfunc {
                if (is_array($pArr)) {
                        foreach ($pArr as $k => $v) {
                                $parts = explode('=', $v, 2);
                if (is_array($pArr)) {
                        foreach ($pArr as $k => $v) {
                                $parts = explode('=', $v, 2);
-                               if (count($parts)==2) {
+                               if (count($parts) == 2) {
                                        $out[trim($parts[0])] = trim($parts[1]);
                                } else {
                                        $out[$k] = $v;
                                        $out[trim($parts[0])] = trim($parts[1]);
                                } else {
                                        $out[$k] = $v;
@@ -1088,42 +886,39 @@ final class t3lib_BEfunc {
        /**
         * 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.
        /**
         * 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
         * @param       string          Optional fieldname passed to hook object
         *
         * @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       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()
         */
        public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
         * @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()
         */
        public static function getFlexFormDS($conf, $row, $table, $fieldName = '', $WSOL = TRUE, $newRecordPidValue = 0) {
-               global $TYPO3_CONF_VARS;
-
                        // Get pointer field etc from TCA-config:
                        // Get pointer field etc from TCA-config:
-               $ds_pointerField =      $conf['ds_pointerField'];
-               $ds_array =             $conf['ds'];
-               $ds_tableField =        $conf['ds_tableField'];
-               $ds_searchParentField =         $conf['ds_pointerField_searchParent'];
+               $ds_pointerField = $conf['ds_pointerField'];
+               $ds_array = $conf['ds'];
+               $ds_tableField = $conf['ds_tableField'];
+               $ds_searchParentField = $conf['ds_pointerField_searchParent'];
 
                        // Find source value:
                $dataStructArray = '';
 
                        // Find source value:
                $dataStructArray = '';
-               if (is_array($ds_array))        {       // If there is a data source array, that takes precedence
+               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 a pointer field is set, take the value from that field in the $row array and use as key.
-                       if ($ds_pointerField)   {
+                       if ($ds_pointerField) {
 
                                        // Up to two pointer fields can be specified in a comma separated list.
                                $pointerFields = t3lib_div::trimExplode(',', $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)
+                               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]];
                                        }
                                } else {
@@ -1131,44 +926,50 @@ final class t3lib_BEfunc {
                                }
 
                                $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:') {
+                       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));
                                $file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer], 5));
                                if ($file && @is_file($file)) {
                                        $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
-                               } else $dataStructArray = 'The file "'.substr($ds_array[$srcPointer], 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]);
                        }
 
-               } elseif ($ds_pointerField) {   // If pointer field AND possibly a table/field is set:
+               } elseif ($ds_pointerField) { // If pointer field AND possibly a table/field is set:
                                // Value of field pointed to:
                        $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) {
                                // Value of field pointed to:
                        $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 = self::getRecord($table, $row['uid'], 'uid,' . $ds_searchParentField);     // Get the "pid" field - we cannot know that it is in the input record! ###NOTE_A###
+                               $rr = self::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) {
                                        self::workspaceOL($table, $rr);
                                if ($WSOL) {
                                        self::workspaceOL($table, $rr);
-                                       self::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!
+                                       self::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.
+                               $uidAcc = array(); // Used to avoid looping, if any should happen.
                                $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
                                $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
-                               while(!$srcPointer)             {
+                               while (!$srcPointer) {
 
                                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
 
                                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
-                                                                       'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
-                                                                       $table,
-                                                                       'uid=' . intval($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField]) . self::deleteClause($table)      ###NOTE_A###
-                                                               );
+                                               'uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''),
+                                               $table,
+                                                       'uid=' . intval($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField]) . self::deleteClause($table) ###NOTE_A###
+                                       );
                                        $newRecordPidValue = 0;
                                        $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
 
                                                // break if no result from SQL db or if looping...
                                        $newRecordPidValue = 0;
                                        $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                                        $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;
+                                       if (!is_array($rr) || isset($uidAcc[$rr['uid']])) {
+                                               break;
+                                       }
                                        $uidAcc[$rr['uid']] = 1;
 
                                        if ($WSOL) {
                                        $uidAcc[$rr['uid']] = 1;
 
                                        if ($WSOL) {
@@ -1181,27 +982,45 @@ final class t3lib_BEfunc {
 
                                // If there is a srcPointer value:
                        if ($srcPointer) {
 
                                // If there is a srcPointer value:
                        if ($srcPointer) {
-                               if (t3lib_div::testInt($srcPointer))    {       // If integer, then its a record we will look up:
+                               if (t3lib_utility_Math::canBeInterpretedAsInteger($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])) {
                                                $dataStructRec = self::getRecord($tName, $srcPointer);
                                                if ($WSOL) {
                                                        self::workspaceOL($tName, $dataStructRec);
                                                }
                                        list($tName, $fName) = explode(':', $ds_tableField, 2);
                                        if ($tName && $fName && is_array($GLOBALS['TCA'][$tName])) {
                                                $dataStructRec = self::getRecord($tName, $srcPointer);
                                                if ($WSOL) {
                                                        self::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:
+                                               if (strpos($dataStructRec[$fName], '<') === FALSE) {
+                                                       if (is_file(PATH_site . $dataStructRec[$fName])) {
+                                                                       // The value is a pointer to a file
+                                                               $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl(PATH_site . $dataStructRec[$fName]));
+                                                       } else {
+                                                               $dataStructArray = sprintf('File \'%s\' was not found', $dataStructRec[$fName]);
+                                                       }
+                                               } else {
+                                                               // No file pointer, handle as being XML (default behaviour)
+                                                       $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)) {
                                                $dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
                                        $file = t3lib_div::getFileAbsFileName($srcPointer);
                                        if ($file && @is_file($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
 
                        // 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) {
+               if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
+                       foreach ($GLOBALS['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);
                                $hookObj = t3lib_div::getUserObj($classRef);
                                if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
                                        $hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
@@ -1212,21 +1031,88 @@ final class t3lib_BEfunc {
                return $dataStructArray;
        }
 
                return $dataStructArray;
        }
 
+       /**
+        * Returns all registered FlexForm definitions with title and fields
+        *
+        * @param       string          The content table
+        * @return      array           The data structures with speaking extension title
+        * @see t3lib_BEfunc::getExcludeFields()
+        */
+       public static function getRegisteredFlexForms($table = 'tt_content') {
+               if (empty($table) || empty($GLOBALS['TCA'][$table]['columns'])) {
+                       return array();
+               }
 
 
 
 
+               $flexForms = array();
 
 
+               foreach ($GLOBALS['TCA'][$table]['columns'] as $tableField => $fieldConf) {
+                       if (!empty($fieldConf['config']['type']) && !empty($fieldConf['config']['ds']) && $fieldConf['config']['type'] == 'flex') {
+                               $flexForms[$tableField] = array();
 
 
+                               unset($fieldConf['config']['ds']['default']);
 
 
+                                       // Get pointer fields
+                               $pointerFields = (!empty($fieldConf['config']['ds_pointerField']) ? $fieldConf['config']['ds_pointerField'] : 'list_type,CType');
+                               $pointerFields = t3lib_div::trimExplode(',', $pointerFields);
 
 
+                                       // Get FlexForms
+                               foreach ($fieldConf['config']['ds'] as $flexFormKey => $dataStruct) {
+                                               // Get extension identifier (uses second value if it's not empty, "list" or "*", else first one)
+                                       $identFields = t3lib_div::trimExplode(',', $flexFormKey);
+                                       $extIdent = $identFields[0];
+                                       if (!empty($identFields[1]) && $identFields[1] != 'list' && $identFields[1] != '*') {
+                                               $extIdent = $identFields[1];
+                                       }
 
 
+                                               // Load external file references
+                                       if (!is_array($dataStruct)) {
+                                               $file = t3lib_div::getFileAbsFileName(str_ireplace('FILE:', '', $dataStruct));
+                                               if ($file && @is_file($file)) {
+                                                       $dataStruct = t3lib_div::getUrl($file);
+                                               }
+                                               $dataStruct = t3lib_div::xml2array($dataStruct);
+                                               if (!is_array($dataStruct)) {
+                                                       continue;
+                                               }
+                                       }
+                                               // Get flexform content
+                                       $dataStruct = t3lib_div::resolveAllSheetsInDS($dataStruct);
+                                       if (empty($dataStruct['sheets']) || !is_array($dataStruct['sheets'])) {
+                                               continue;
+                                       }
 
 
+                                               // Use DS pointer to get extension title from TCA
+                                       $title = $extIdent;
+                                       $keyFields = t3lib_div::trimExplode(',', $flexFormKey);
+                                       foreach ($pointerFields as $pointerKey => $pointerName) {
+                                               if (empty($keyFields[$pointerKey]) || $keyFields[$pointerKey] == '*' || $keyFields[$pointerKey] == 'list') {
+                                                       continue;
+                                               }
+                                               if (!empty($GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'])) {
+                                                       $items = $GLOBALS['TCA'][$table]['columns'][$pointerName]['config']['items'];
+                                                       if (!is_array($items)) {
+                                                               continue;
+                                                       }
+                                                       foreach ($items as $itemConf) {
+                                                               if (!empty($itemConf[0]) && !empty($itemConf[1]) && $itemConf[1] == $keyFields[$pointerKey]) {
+                                                                       $title = $itemConf[0];
+                                                                       break 2;
+                                                               }
+                                                       }
+                                               }
+                                       }
 
 
+                                       $flexForms[$tableField][$extIdent] = array(
+                                               'title' => $title,
+                                               'ds' => $dataStruct,
+                                       );
+                               }
+                       }
+               }
 
 
-
-
-
-
-
+               return $flexForms;
+       }
 
 
        /*******************************************
 
 
        /*******************************************
@@ -1239,7 +1125,6 @@ final class t3lib_BEfunc {
         * 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:
         * 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
         *
         * @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          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.
@@ -1247,23 +1132,12 @@ final class t3lib_BEfunc {
         * @return      void
         */
        public static function storeHash($hash, $data, $ident) {
         * @return      void
         */
        public static function storeHash($hash, $data, $ident) {
-               if (TYPO3_UseCachingFramework) {
-                       $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
-                               $hash,
-                               $data,
-                               array('ident_' . $ident),
-                               0 // unlimited lifetime
-                       );
-               } else {
-                       $insertFields = array(
-                               'hash' => $hash,
-                               'content' => $data,
-                               'ident' => $ident,
-                               'tstamp' => $GLOBALS['EXEC_TIME']
-                       );
-                       $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
-                       $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
-               }
+               $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set(
+                       $hash,
+                       $data,
+                       array('ident_' . $ident),
+                       0 // unlimited lifetime
+               );
        }
 
        /**
        }
 
        /**
@@ -1276,35 +1150,15 @@ final class t3lib_BEfunc {
         * @return      string
         */
        public static function getHash($hash, $expTime = 0) {
         * @return      string
         */
        public static function getHash($hash, $expTime = 0) {
-               $hashContent = null;
-               if (TYPO3_UseCachingFramework) {
-                       $contentHashCache = $GLOBALS['typo3CacheManager']->getCache('cache_hash');
-                       $cacheEntry = $contentHashCache->get($hash);
-
-                       if ($cacheEntry) {
-                               $hashContent = $cacheEntry;
-                       }
-               } else {
-                       $expTime = intval($expTime);
-                       if ($expTime) {
-                               $whereAdd = ' AND tstamp > '.(time()-$expTime);
-                       }
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
-                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
-
-                       $hashContent =  (is_array($row) ? $row['content'] : null);
+               $hashContent = NULL;
+               $cacheEntry = $GLOBALS['typo3CacheManager']->getCache('cache_hash')->get($hash);
+               if ($cacheEntry) {
+                       $hashContent = $cacheEntry;
                }
                return $hashContent;
        }
 
 
                }
                return $hashContent;
        }
 
 
-
-
-
-
-
-
        /*******************************************
         *
         * TypoScript related
        /*******************************************
         *
         * TypoScript related
@@ -1314,7 +1168,6 @@ final class t3lib_BEfunc {
        /**
         * Returns the Page TSconfig for page with id, $id
         * Requires class "t3lib_TSparser"
        /**
         * Returns the Page TSconfig for page with id, $id
         * Requires class "t3lib_TSparser"
-        * Usage: 26 (spec. in ext info_pagetsconfig)
         *
         * @param       integer         Page uid for which to create Page TSconfig
         * @param       array           If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
         *
         * @param       integer         Page uid for which to create Page TSconfig
         * @param       array           If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
@@ -1327,11 +1180,11 @@ final class t3lib_BEfunc {
                if (!is_array($rootLine)) {
                        $rootLine = self::BEgetRootLine($id, '', TRUE);
                }
                if (!is_array($rootLine)) {
                        $rootLine = self::BEgetRootLine($id, '', TRUE);
                }
-               ksort($rootLine);       // Order correctly
+               ksort($rootLine); // Order correctly
                $TSdataArray = array();
                $TSdataArray = array();
-               $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
-               foreach($rootLine as $k => $v) {
-                       $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);
                if ($returnPartArray) {
                }
                $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
                if ($returnPartArray) {
@@ -1377,8 +1230,6 @@ final class t3lib_BEfunc {
         * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
         * More documentation is needed.
         *
         * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
         * More documentation is needed.
         *
-        * Usage: 1 (ext. direct_mail)
-        *
         * @param       integer         Page id
         * @param       array           Page TS array to write
         * @param       string          Prefix for object paths
         * @param       integer         Page id
         * @param       array           Page TS array to write
         * @param       string          Prefix for object paths
@@ -1389,14 +1240,14 @@ final class t3lib_BEfunc {
         */
        public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
                $id = intval($id);
         */
        public static function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
                $id = intval($id);
-               if (is_array($pageTS) && $id>0) {
+               if (is_array($pageTS) && $id > 0) {
                        if (!is_array($impParams)) {
                                $impParams = self::implodeTSParams(self::getPagesTSconfig($id));
                        }
                        $set = array();
                        foreach ($pageTS as $f => $v) {
                        if (!is_array($impParams)) {
                                $impParams = self::implodeTSParams(self::getPagesTSconfig($id));
                        }
                        $set = array();
                        foreach ($pageTS as $f => $v) {
-                               $f = $TSconfPrefix.$f;
-                               if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
+                               $f = $TSconfPrefix . $f;
+                               if ((!isset($impParams[$f]) && trim($v)) || strcmp(trim($impParams[$f]), trim($v))) {
                                        $set[$f] = trim($v);
                                }
                        }
                                        $set[$f] = trim($v);
                                }
                        }
@@ -1409,15 +1260,15 @@ final class t3lib_BEfunc {
                                foreach ($set as $f => $v) {
                                        $inserted = 0;
                                        foreach ($TSlines as $ki => $kv) {
                                foreach ($set as $f => $v) {
                                        $inserted = 0;
                                        foreach ($TSlines as $ki => $kv) {
-                                               if (substr($kv, 0, strlen($f)+1)==$f.'=') {
-                                                       $TSlines[$ki] = $f.'='.$v;
+                                               if (substr($kv, 0, strlen($f) + 1) == $f . '=') {
+                                                       $TSlines[$ki] = $f . '=' . $v;
                                                        $inserted = 1;
                                                        break;
                                                }
                                        }
                                        if (!$inserted) {
                                                $TSlines = array_reverse($TSlines);
                                                        $inserted = 1;
                                                        break;
                                                }
                                        }
                                        if (!$inserted) {
                                                $TSlines = array_reverse($TSlines);
-                                               $TSlines[] = $f.'='.$v;
+                                               $TSlines[] = $f . '=' . $v;
                                                $TSlines = array_reverse($TSlines);
                                        }
                                }
                                                $TSlines = array_reverse($TSlines);
                                        }
                                }
@@ -1426,14 +1277,13 @@ final class t3lib_BEfunc {
                                        // store those changes
                                $TSconf = implode(LF, $TSlines);
 
                                        // store those changes
                                $TSconf = implode(LF, $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));
                        }
                }
        }
 
        /**
         * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
                        }
                }
        }
 
        /**
         * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
-        * Usage: 3
         *
         * @param       array           TypoScript structure
         * @param       string          Prefix string
         *
         * @param       array           TypoScript structure
         * @param       string          Prefix string
@@ -1446,7 +1296,7 @@ final class t3lib_BEfunc {
                                if (is_array($val)) {
                                        $implodeParams = array_merge($implodeParams, self::implodeTSParams($val, $k . $kb));
                                } else {
                                if (is_array($val)) {
                                        $implodeParams = array_merge($implodeParams, self::implodeTSParams($val, $k . $kb));
                                } else {
-                                       $implodeParams[$k.$kb] = $val;
+                                       $implodeParams[$k . $kb] = $val;
                                }
                        }
                }
                                }
                        }
                }
@@ -1454,12 +1304,6 @@ final class t3lib_BEfunc {
        }
 
 
        }
 
 
-
-
-
-
-
-
        /*******************************************
         *
         * Users / Groups related
        /*******************************************
         *
         * Users / Groups related
@@ -1469,7 +1313,6 @@ final class t3lib_BEfunc {
        /**
         * Returns an array with be_users records of all user NOT DELETED sorted by their username
         * Keys in the array is the be_users uid
        /**
         * Returns an array with be_users records of all user NOT DELETED sorted by their username
         * Keys in the array is the be_users uid
-        * Usage: 14 (spec. ext. "beuser" and module "web_perm")
         *
         * @param       string          Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
         * @param       string          Optional $where clause (fx. "AND username='pete'") can be used to limit query
         *
         * @param       string          Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
         * @param       string          Optional $where clause (fx. "AND username='pete'") can be used to limit query
@@ -1479,7 +1322,7 @@ final class t3lib_BEfunc {
                $be_user_Array = Array();
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 ' . $where . self::deleteClause('be_users'), '', 'username');
                $be_user_Array = Array();
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 ' . $where . self::deleteClause('be_users'), '', 'username');
-               while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                        $be_user_Array[$row['uid']] = $row;
                }
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
                        $be_user_Array[$row['uid']] = $row;
                }
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
@@ -1489,7 +1332,6 @@ final class t3lib_BEfunc {
 
        /**
         * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
 
        /**
         * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
-        * Usage: 8 (spec. ext. "beuser" and module "web_perm")
         *
         * @param       string          Field list
         * @param       string          WHERE clause
         *
         * @param       string          Field list
         * @param       string          WHERE clause
@@ -1499,7 +1341,7 @@ final class t3lib_BEfunc {
                $be_group_Array = Array();
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 ' . $where . self::deleteClause('be_groups'), '', 'title');
                $be_group_Array = Array();
 
                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 ' . $where . self::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;
                }
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
                        $be_group_Array[$row['uid']] = $row;
                }
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
@@ -1510,7 +1352,6 @@ final class t3lib_BEfunc {
        /**
         * Returns an array with be_groups records (like ->getGroupNames) but:
         * - if the current BE_USER is admin, then all groups are returned, otherwise only groups that the current user is member of (usergroup_cached_list) will be returned.
        /**
         * Returns an array with be_groups records (like ->getGroupNames) but:
         * - if the current BE_USER is admin, then all groups are returned, otherwise only groups that the current user is member of (usergroup_cached_list) will be returned.
-        * Usage: 2 (module "web_perm" and ext. taskcenter)
         *
         * @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
@@ -1518,7 +1359,7 @@ final class t3lib_BEfunc {
        public static 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 self::getGroupNames($fields, $exQ);
        }
                }
                return self::getGroupNames($fields, $exQ);
        }
@@ -1527,7 +1368,6 @@ final class t3lib_BEfunc {
         * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
         * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
         * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
         * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
         * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
-        * Usage: 8
         *
         * @param       array           User names
         * @param       array           Group names
         *
         * @param       array           User names
         * @param       array           Group names
@@ -1539,7 +1379,7 @@ final class t3lib_BEfunc {
                        foreach ($usernames as $uid => $row) {
                                $userN = $uid;
                                $set = 0;
                        foreach ($usernames as $uid => $row) {
                                $userN = $uid;
                                $set = 0;
-                               if ($row['uid']!=$GLOBALS['BE_USER']->user['uid']) {
+                               if ($row['uid'] != $GLOBALS['BE_USER']->user['uid']) {
                                        foreach ($groupArray as $v) {
                                                if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
                                                        $userN = $row['username'];
                                        foreach ($groupArray as $v) {
                                                if ($v && t3lib_div::inList($row['usergroup_cached_list'], $v)) {
                                                        $userN = $row['username'];
@@ -1551,7 +1391,9 @@ final class t3lib_BEfunc {
                                        $set = 1;
                                }
                                $usernames[$uid]['username'] = $userN;
                                        $set = 1;
                                }
                                $usernames[$uid]['username'] = $userN;
-                               if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
+                               if ($excludeBlindedFlag && !$set) {
+                                       unset($usernames[$uid]);
+                               }
                        }
                }
                return $usernames;
                        }
                }
                return $usernames;
@@ -1559,7 +1401,6 @@ final class t3lib_BEfunc {
 
        /**
         * Corresponds to blindUserNames but works for groups instead
 
        /**
         * Corresponds to blindUserNames but works for groups instead
-        * Usage: 2 (module web_perm)
         *
         * @param       array           Group names
         * @param       array           Group names (reference)
         *
         * @param       array           Group names
         * @param       array           Group names (reference)
@@ -1576,24 +1417,15 @@ final class t3lib_BEfunc {
                                        $set = 1;
                                }
                                $groups[$uid]['title'] = $groupN;
                                        $set = 1;
                                }
                                $groups[$uid]['title'] = $groupN;
-                               if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
+                               if ($excludeBlindedFlag && !$set) {
+                                       unset($groups[$uid]);
+                               }
                        }
                }
                return $groups;
        }
 
 
                        }
                }
                return $groups;
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
        /*******************************************
         *
         * Output related
        /*******************************************
         *
         * Output related
@@ -1602,86 +1434,84 @@ final class t3lib_BEfunc {
 
        /**
         * Returns the difference in days between input $tstamp and $EXEC_TIME
 
        /**
         * Returns the difference in days between input $tstamp and $EXEC_TIME
-        * Usage: 2 (class t3lib_BEfunc)
         *
         * @param       integer         Time stamp, seconds
         * @return      integer
         */
        public static function daysUntil($tstamp) {
         *
         * @param       integer         Time stamp, seconds
         * @return      integer
         */
        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));
        }
 
        /**
        }
 
        /**
-        * Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])
-        * Usage: 11
+        * Returns $tstamp formatted as "ddmmyy" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'])
         *
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
        public static function date($tstamp) {
         *
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
        public static function date($tstamp) {
-               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
+               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int) $tstamp);
        }
 
        /**
        }
 
        /**
-        * Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])
-        * Usage: 28
+        * Returns $tstamp formatted as "ddmmyy hhmm" (According to $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] AND $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'])
         *
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
        public static function datetime($value) {
         *
         * @param       integer         Time stamp, seconds
         * @return      string          Formatted time
         */
        public static function datetime($value) {
-               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
+               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
        }
 
        /**
         * Returns $value (in seconds) formatted as hh:mm:ss
         * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
        }
 
        /**
         * Returns $value (in seconds) formatted as hh:mm:ss
         * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
-        * Usage: 1 (class t3lib_BEfunc)
         *
         * @param       integer         Time stamp, seconds
         *
         * @param       integer         Time stamp, seconds
-        * @param       boolean         Output hh:mm:ss. If false: hh:mm
+        * @param       boolean         Output hh:mm:ss. If FALSE: hh:mm
         * @return      string          Formatted time
         */
        public static function time($value, $withSeconds = TRUE) {
         * @return      string          Formatted time
         */
        public static function time($value, $withSeconds = TRUE) {
-               $hh = floor($value/3600);
-               $min = floor(($value-$hh*3600)/60);
-               $sec = $value-$hh*3600-$min*60;
-               $l = sprintf('%02d', $hh).':'.sprintf('%02d', $min);
+               $hh = floor($value / 3600);
+               $min = floor(($value - $hh * 3600) / 60);
+               $sec = $value - $hh * 3600 - $min * 60;
+               $l = sprintf('%02d', $hh) . ':' . sprintf('%02d', $min);
                if ($withSeconds) {
                if ($withSeconds) {
-                       $l .= ':'.sprintf('%02d', $sec);
+                       $l .= ':' . sprintf('%02d', $sec);
                }
                return $l;
        }
 
        /**
         * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
                }
                return $l;
        }
 
        /**
         * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
-        * Usage: 15
         *
         * @param       integer         $seconds could be the difference of a certain timestamp and time()
         *
         * @param       integer         $seconds could be the difference of a certain timestamp and 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")
+        * @param       string          $labels should be something like ' min| hrs| days| yrs| min| hour| day| year'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
         * @return      string          Formatted time
         */
         * @return      string          Formatted time
         */
-       public static function calcAge($seconds, $labels = 'min|hrs|days|yrs') {
+       public static function calcAge($seconds, $labels = ' min| hrs| days| yrs| min| hour| day| year') {
                $labelArr = explode('|', $labels);
                $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]);
+               $absSeconds = abs($seconds);
+               $sign = ($seconds > 0 ? 1 : -1);
+               if ($seconds < 3600) {
+                       $val = round($absSeconds / 60);
+                       $seconds = ($sign * $val) . ($val == 1 ? $labelArr[4] : $labelArr[0]);
+               } elseif ($seconds < 24 * 3600) {
+                       $val = round($absSeconds / 3600);
+                       $seconds = ($sign * $val) . ($val == 1 ? $labelArr[5] : $labelArr[1]);
+               } elseif ($seconds < 365 * 24 * 3600) {
+                       $val = round($absSeconds / (24 * 3600));
+                       $seconds = ($sign * $val) . ($val == 1 ? $labelArr[6] : $labelArr[2]);
                } else {
                } else {
-                       $seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
+                       $val = round($absSeconds / (365 * 24 * 3600));
+                       $seconds = ($sign * $val) . ($val == 1 ? $labelArr[7] : $labelArr[3]);
                }
                }
-               return $prefix.$seconds;
+               return $seconds;
        }
 
        /**
         * Returns a formatted timestamp if $tstamp is set.
         * The date/datetime will be followed by the age in parenthesis.
        }
 
        /**
         * Returns a formatted timestamp if $tstamp is set.
         * The date/datetime will be followed by the age in parenthesis.
-        * Usage: 3
         *
         * @param       integer         Time stamp, seconds
         * @param       integer         1/-1 depending on polarity of age.
         *
         * @param       integer         Time stamp, seconds
         * @param       integer         1/-1 depending on polarity of age.
@@ -1690,82 +1520,61 @@ final class t3lib_BEfunc {
         */
        public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
                return $tstamp ?
         */
        public static function dateTimeAge($tstamp, $prefix = 1, $date = '') {
                return $tstamp ?
-                               ($date=='date' ? self::date($tstamp) : self::datetime($tstamp)) .
-                               ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_TIME'] - $tstamp), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) . ')'
+                               ($date == 'date' ? self::date($tstamp) : self::datetime($tstamp)) .
+                                               ' (' . self::calcAge($prefix * ($GLOBALS['EXEC_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)
-        * 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!
-        * Usage: 0
-        *
-        * @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
-        * @deprecated since TYPO3 3.6, this function will be removed in TYPO3 4.6 - The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
-        */
-       public static function titleAttrib($content = '', $hsc = 0) {
-               t3lib_div::logDeprecatedFunction();
-
-               global $CLIENT;
-               $attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
-               return strcmp($content, '')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
-       }
-
-       /**
         * Returns alt="" and title="" attributes with the value of $content.
         * Returns alt="" and title="" attributes with the value of $content.
-        * Usage: 7
         *
         * @param       string          Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
         * @return      string
         */
        public static function titleAltAttrib($content) {
                $out = '';
         *
         * @param       string          Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
         * @return      string
         */
        public static function titleAltAttrib($content) {
                $out = '';
-               $out.=' alt="'.htmlspecialchars($content).'"';
-               $out.=' title="'.htmlspecialchars($content).'"';
+               $out .= ' alt="' . htmlspecialchars($content) . '"';
+               $out .= ' title="' . htmlspecialchars($content) . '"';
                return $out;
        }
 
        /**
         * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field
                return $out;
        }
 
        /**
         * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field
-        * All $TYPO3_CONF_VARS['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
+        * All $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
         * Thumbsnails are linked to the show_item.php script which will display further details.
         * Thumbsnails are linked to the show_item.php script which will display further details.
-        * Usage: 7
         *
         * @param       array           $row is the database row from the table, $table.
         * @param       string          Table name for $row (present in TCA)
         * @param       string          $field is pointing to the field with the list of image files
         * @param       string          Back path prefix for image tag src="" field
         * @param       string          Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
         *
         * @param       array           $row is the database row from the table, $table.
         * @param       string          Table name for $row (present in TCA)
         * @param       string          $field is pointing to the field with the list of image files
         * @param       string          Back path prefix for image tag src="" field
         * @param       string          Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
-        * @param       string          Optional: $uploaddir is the directory relative to PATH_site where the image files from the $field value is found (Is by default set to the entry in $TCA for that field! so you don't have to!)
+        * @param       string          Optional: $uploaddir is the directory relative to PATH_site where the image files from the $field value is found (Is by default set to the entry in $GLOBALS['TCA'] for that field! so you don't have to!)
         * @param       boolean         If set, uploaddir is NOT prepended with "../"
         * @param       string          Optional: $tparams is additional attributes for the image tags
         * @param       integer         Optional: $size is [w]x[h] of the thumbnail. 56 is default.
         * @return      string          Thumbnail image tag.
         */
        public static function thumbCode($row, $table, $field, $backPath, $thumbScript = '', $uploaddir = NULL, $abs = 0, $tparams = '', $size = '') {
         * @param       boolean         If set, uploaddir is NOT prepended with "../"
         * @param       string          Optional: $tparams is additional attributes for the image tags
         * @param       integer         Optional: $size is [w]x[h] of the thumbnail. 56 is default.
         * @return      string          Thumbnail image tag.
         */
        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
                        // 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 = (is_null($uploaddir)) ? $GLOBALS['TCA'][$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
+               $uploaddir = preg_replace('#/$#', '', $uploaddir);
 
                        // Set thumbs-script:
                if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
                        $thumbScript = 'gfx/notfound_thumb.gif';
 
                        // Set thumbs-script:
                if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails']) {
                        $thumbScript = 'gfx/notfound_thumb.gif';
-               } elseif(!$thumbScript) {
+               } elseif (!$thumbScript) {
                        $thumbScript = 'thumbs.php';
                }
                        // Check and parse the size parameter
                $sizeParts = array();
                if ($size = trim($size)) {
                        $thumbScript = 'thumbs.php';
                }
                        // Check and parse the size parameter
                $sizeParts = array();
                if ($size = trim($size)) {
-                       $sizeParts = explode('x', $size.'x'.$size);
-                       if(!intval($sizeParts[0])) $size = '';
+                       $sizeParts = explode('x', $size . 'x' . $size);
+                       if (!intval($sizeParts[0])) {
+                               $size = '';
+                       }
                }
 
                        // Traverse files:
                }
 
                        // Traverse files:
@@ -1775,26 +1584,28 @@ final class t3lib_BEfunc {
                        if (trim($theFile)) {
                                $fI = t3lib_div::split_fileref($theFile);
                                $ext = $fI['fileext'];
                        if (trim($theFile)) {
                                $fI = t3lib_div::split_fileref($theFile);
                                $ext = $fI['fileext'];
-                                               // New 190201 start
+                                       // New 190201 start
                                $max = 0;
                                if (t3lib_div::inList('gif,jpg,png', $ext)) {
                                $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]);}
+                                       $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)) {
-                                       $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
-                               } 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);
+                               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
+                               } 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);
 
                                        if (!is_readable($theFile_abs)) {
                                                $flashMessage = t3lib_div::makeInstance(
                                                        't3lib_FlashMessage',
 
                                        if (!is_readable($theFile_abs)) {
                                                $flashMessage = t3lib_div::makeInstance(
                                                        't3lib_FlashMessage',
-                                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing_text') . ' <abbr title="' . $theFile_abs . '">' . $theFile . '</abbr>',
+                                                               $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing_text') . ' <abbr title="' . $theFile_abs . '">' . $theFile . '</abbr>',
                                                        $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing'),
                                                        t3lib_FlashMessage::ERROR
                                                );
                                                        $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:warning.file_missing'),
                                                        t3lib_FlashMessage::ERROR
                                                );
@@ -1802,18 +1613,24 @@ final class t3lib_BEfunc {
                                                continue;
                                        }
 
                                                continue;
                                        }
 
-                                       $check = basename($theFile_abs).':'.filemtime($theFile_abs).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
-                                       $params = '&file='.rawurlencode($theFile);
-                                       $params.= $size?'&size='.$size:'';
-                                       $params.= '&md5sum='.t3lib_div::shortMD5($check);
+                                       $check = basename($theFile_abs) . ':' . filemtime($theFile_abs) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
+                                       $params = '&file=' . rawurlencode($theFile);
+                                       $params .= $size ? '&size=' . $size : '';
+                                       $params .= '&md5sum=' . md5($check);
 
 
-                                       $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> ';
+                                       $url = $thumbScript . '?' . $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> ';
                                } else {
                                } else {
-                                       $icon = self::getFileIcon($ext);
-                                       $url = 'gfx/fileicons/'.$icon;
-                                       $thumbData.= '<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
+                                               // Icon
+                                       $theFile = ($abs ? '' : '../') . ($uploaddir ? $uploaddir . '/' : '') . trim($theFile);
+                                       $fileIcon = t3lib_iconWorks::getSpriteIconForFile(
+                                               strtolower($ext),
+                                               array('title' => htmlspecialchars(trim($theFile)))
+                                       );
+
+                                       $onClick = 'top.launchView(\'' . $theFile . '\',\'\',\'' . $backPath . '\');return false;';
+                                       $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
                                }
                        }
                }
                                }
                        }
                }
@@ -1822,7 +1639,6 @@ final class t3lib_BEfunc {
 
        /**
         * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
 
        /**
         * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
-        * Usage: 3
         *
         * @param       string          $thumbScript must point to "thumbs.php" relative to the script position
         * @param       string          $theFile must be the proper reference to the file thumbs.php should show
         *
         * @param       string          $thumbScript must point to "thumbs.php" relative to the script position
         * @param       string          $theFile must be the proper reference to the file thumbs.php should show
@@ -1831,19 +1647,18 @@ final class t3lib_BEfunc {
         * @return      string          Image tag
         */
        public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
         * @return      string          Image tag
         */
        public static function getThumbNail($thumbScript, $theFile, $tparams = '', $size = '') {
-               $check = basename($theFile).':'.filemtime($theFile).':'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
-               $params = '&file='.rawurlencode($theFile);
-               $params.= trim($size)?'&size='.trim($size):'';
-               $params.= '&md5sum='.t3lib_div::shortMD5($check);
+               $check = basename($theFile) . ':' . filemtime($theFile) . ':' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
+               $params = '&file=' . rawurlencode($theFile);
+               $params .= trim($size) ? '&size=' . trim($size) : '';
+               $params .= '&md5sum=' . md5($check);
 
 
-               $url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
-               $th = '<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
+               $url = $thumbScript . '?' . $params;
+               $th = '<img src="' . htmlspecialchars($url) . '" title="' . trim(basename($theFile)) . '"' . ($tparams ? " " . $tparams : "") . ' alt="" />';
                return $th;
        }
 
        /**
         * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
                return $th;
        }
 
        /**
         * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
-        * Usage: 8
         *
         * @param       array           Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
         * @param       string          $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
         *
         * @param       array           Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
         * @param       string          $perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
@@ -1851,192 +1666,235 @@ final class t3lib_BEfunc {
         * @return      string
         */
        public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
         * @return      string
         */
        public static function titleAttribForPages($row, $perms_clause = '', $includeAttrib = 1) {
-               global $TCA, $LANG;
                $parts = array();
                $parts = array();
-               $parts[] = 'id='.$row['uid'];
-               if ($row['alias'])      $parts[] = $LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
-               if ($row['pid']<0)      $parts[] = 'v#1.'.$row['t3ver_id'];
+               $parts[] = 'id=' . $row['uid'];
+               if ($row['alias']) {
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['alias']['label']) . ' ' . $row['alias'];
+               }
+               if ($row['pid'] < 0) {
+                       $parts[] = 'v#1.' . $row['t3ver_id'];
+               }
 
 
-               switch($row['t3ver_state']) {
+               switch ($row['t3ver_state']) {
                        case 1:
                        case 1:
-                               $parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
-                       break;
+                               $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
+                               break;
                        case 2:
                                $parts[] = 'Deleted element!';
                        case 2:
                                $parts[] = 'Deleted element!';
-                       break;
+                               break;
                        case 3:
                        case 3:
-                               $parts[] = 'NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
-                       break;
+                               $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
+                               break;
                        case 4:
                        case 4:
-                               $parts[] = 'OLD LOCATION (PNT) WSID#'.$row['t3ver_wsid'];
-                       break;
+                               $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
+                               break;
                        case -1:
                                $parts[] = 'New element!';
                        case -1:
                                $parts[] = 'New element!';
-                       break;
+                               break;
                }
 
                }
 
-               if ($row['doktype']=='3') {
-                       $parts[] = $LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
-               } elseif ($row['doktype']=='4') {
+               if ($row['doktype'] == t3lib_pageSelect::DOKTYPE_LINK) {
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
+               } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_SHORTCUT) {
                        if ($perms_clause) {
                                $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
                        } else {
                        if ($perms_clause) {
                                $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
                        } else {
-                               $lRec = self::getRecordWSOL('pages', intval($row['shortcut']), 'title');
-                               $label = $lRec['title'];
+                               $row['shortcut'] = intval($row['shortcut']);
+                               $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
+                               $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
                        }
                        if ($row['shortcut_mode'] != t3lib_pageSelect::SHORTCUT_MODE_NONE) {
                        }
                        if ($row['shortcut_mode'] != t3lib_pageSelect::SHORTCUT_MODE_NONE) {
-                               $label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
-                                                       $LANG->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
+                               $label .= ', ' . $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['shortcut_mode']['label']) . ' ' .
+                                               $GLOBALS['LANG']->sL(self::getLabelFromItemlist('pages', 'shortcut_mode', $row['shortcut_mode']));
                        }
                        }
-                       $parts[] = $LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
-               } elseif ($row['doktype']=='7') {
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
+               } elseif ($row['doktype'] == t3lib_pageSelect::DOKTYPE_MOUNTPOINT) {
                        if ($perms_clause) {
                                $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
                        } else {
                                $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
                                $label = $lRec['title'];
                        }
                        if ($perms_clause) {
                                $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
                        } else {
                                $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
                                $label = $lRec['title'];
                        }
-                       $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
                        if ($row['mount_pid_ol']) {
                        if ($row['mount_pid_ol']) {
-                               $parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
+                               $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['mount_pid_ol']['label']);
                        }
                }
                        }
                }
-               if ($row['nav_hide'])   $parts[] = rtrim($LANG->sL($TCA['pages']['columns']['nav_hide']['label']), ':');
-               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']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
-               if ($row['endtime'])    $parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
+               if ($row['nav_hide']) {
+                       $parts[] = rtrim($GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['nav_hide']['label']), ':');
+               }
+               if ($row['hidden']) {
+                       $parts[] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
+               }
+               if ($row['starttime']) {
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['starttime']['label']) . ' ' . self::dateTimeAge($row['starttime'], -1, 'date');
+               }
+               if ($row['endtime']) {
+                       $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['endtime']['label']) . ' ' . self::dateTimeAge($row['endtime'], -1, 'date');
+               }
                if ($row['fe_group']) {
                        $fe_groups = array();
                        foreach (t3lib_div::intExplode(',', $row['fe_group']) as $fe_group) {
                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(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
+                               if ($fe_group < 0) {
+                                       $fe_groups[] = $GLOBALS['LANG']->sL(self::getLabelFromItemlist('pages', 'fe_group', $fe_group));
                                } else {
                                        $lRec = self::getRecordWSOL('fe_groups', $fe_group, 'title');
                                        $fe_groups[] = $lRec['title'];
                                }
                        }
                        $label = implode(', ', $fe_groups);
                                } else {
                                        $lRec = self::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[] = $GLOBALS['LANG']->sL($GLOBALS['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;
        }
 
        /**
         * Returns title-attribute information for ANY record (from a table defined in TCA of course)
         * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
         * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
        }
 
        /**
         * Returns title-attribute information for ANY record (from a table defined in TCA of course)
         * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
         * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
-        * Usage: 10
         *
         * @param       array           Table row; $row is a row from the table, $table
         * @param       string          Table name
         * @return      string
         */
        public static function getRecordIconAltText($row, $table = 'pages') {
         *
         * @param       array           Table row; $row is a row from the table, $table
         * @param       string          Table name
         * @return      string
         */
        public static function getRecordIconAltText($row, $table = 'pages') {
-               if ($table=='pages') {
+               if ($table == 'pages') {
                        $out = self::titleAttribForPages($row, '', 0);
                } else {
                        $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
 
                        $out = self::titleAttribForPages($row, '', 0);
                } else {
                        $ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];
 
-                       $out = 'id='.$row['uid'];       // Uid is added
-                       if ($table=='pages' && $row['alias']) {
-                               $out.=' / '.$row['alias'];
+                       $out = 'id=' . $row['uid']; // Uid is added
+                       if ($table == 'pages' && $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'] && $row['pid'] < 0) {
+                               $out .= ' - v#1.' . $row['t3ver_id'];
                        }
                        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
                        }
                        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
-                               switch($row['t3ver_state']) {
+                               switch ($row['t3ver_state']) {
                                        case 1:
                                        case 1:
-                                               $out.= ' - PLH WSID#'.$row['t3ver_wsid'];
-                                       break;
+                                               $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
+                                               break;
                                        case 2:
                                        case 2:
-                                               $out.= ' - Deleted element!';
-                                       break;
+                                               $out .= ' - Deleted element!';
+                                               break;
                                        case 3:
                                        case 3:
-                                               $out.= ' - NEW LOCATION (PLH) WSID#'.$row['t3ver_wsid'];
-                                       break;
+                                               $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
+                                               break;
                                        case 4:
                                        case 4:
-                                               $out.= ' - OLD LOCATION (PNT)  WSID#'.$row['t3ver_wsid'];
-                                       break;
+                                               $out .= ' - OLD LOCATION (PNT)  WSID#' . $row['t3ver_wsid'];
+                                               break;
                                        case -1:
                                        case -1:
-                                               $out.= ' - New element!';
-                                       break;
+                                               $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']) {
                                        $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime') . ':' .
                        }
                        if ($ctrl['starttime']) {
                                if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME']) {
                                        $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime') . ':' .
-                                               self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' .
-                                               $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
+                                                       self::date($row[$ctrl['starttime']]) . ' (' . self::daysUntil($row[$ctrl['starttime']]) . ' ' .
+                                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
                                }
                        }
                        if ($row[$ctrl['endtime']]) {
                                $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime') . ': ' .
                                }
                        }
                        if ($row[$ctrl['endtime']]) {
                                $out .= ' - ' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime') . ': ' .
-                                       self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' .
-                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
+                                               self::date($row[$ctrl['endtime']]) . ' (' . self::daysUntil($row[$ctrl['endtime']]) . ' ' .
+                                               $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days') . ')';
                        }
                }
                return htmlspecialchars($out);
        }
 
        /**
                        }
                }
                return htmlspecialchars($out);
        }
 
        /**
-        * 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
+        * Returns the label of the first found entry in an "items" array from $GLOBALS['TCA'] (tablename = $table/fieldname = $col) where the value is $key
         *
         *
-        * @param       string          Table name, present in $TCA
-        * @param       string          Field name, present in $TCA
+        * @param       string          Table name, present in $GLOBALS['TCA']
+        * @param       string          Field name, present in $GLOBALS['TCA']
         * @param       string          items-array value to match
         * @return      string          Label for item entry
         */
        public static function getLabelFromItemlist($table, $col, $key) {
         * @param       string          items-array value to match
         * @return      string          Label for item entry
         */
        public static function getLabelFromItemlist($table, $col, $key) {
-               global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
 
                        // 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'])) {
-                               // Traverse the items-array...
-                       foreach ($TCA[$table]['columns'][$col]['config']['items'] as $k => $v) {
-                                       // ... and return the first found label where the value was equal to $key
-                               if (!strcmp($v[1], $key))       return $v[0];
+                       // Check, if there is an "items" array:
+               if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]) && is_array($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'])) {
+                               // Traverse the items-array...
+                       foreach ($GLOBALS['TCA'][$table]['columns'][$col]['config']['items'] as $k => $v) {
+                                       // ... and return the first found label where the value was equal to $key
+                               if (!strcmp($v[1], $key)) {
+                                       return $v[0];
+                               }
+                       }
+               }
+       }
+
+       /**
+        * Splits the given key with commas and returns the list of all the localized items labels, separated by a comma.
+        * NOTE: this does not take itemsProcFunc into account
+        *
+        * @static
+        * @param string $table Table name, present in TCA
+        * @param string $column Field name
+        * @param string $key Key or comma-separated list of keys.
+        * @return string Comma-separated list of localized labels
+        */
+       public static function getLabelsFromItemsList($table, $column, $key) {
+               $labels = array();
+               $values = t3lib_div::trimExplode(',', $key, TRUE);
+               if (count($values) > 0) {
+                               // Load full TCA for $table
+                       t3lib_div::loadTCA($table);
+                               // Check if there is an "items" array
+                       if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]) && is_array($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'])) {
+                                       // Loop on all selected values
+                               foreach ($values as $aValue) {
+                                       foreach ($GLOBALS['TCA'][$table]['columns'][$column]['config']['items'] as $itemConfiguration) {
+                                                       // Loop on all available items
+                                                       // Keep matches and move on to next value
+                                               if ($aValue == $itemConfiguration[1]) {
+                                                       $labels[] = $GLOBALS['LANG']->sL($itemConfiguration[0]);
+                                                       break;
+                                               }
+                                       }
+                               }
+
                        }
                }
                        }
                }
+               return implode(', ', $labels);
        }
 
        /**
         * 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 = '<strong>|</strong>' and the fieldname was 'not_found_field' then the return value would be '<strong>not_found_field</strong>'
        }
 
        /**
         * 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 = '<strong>|</strong>' and the fieldname was 'not_found_field' then the return value would be '<strong>not_found_field</strong>'
-        * Usage: 17
         *
         *
-        * @param       string          Table name, present in $TCA
+        * @param       string          Table name, present in $GLOBALS['TCA']
         * @param       string          Field name
         * @param       string          Wrap value - set function description
         * @return      string
         */
        public static function getItemLabel($table, $col, $printAllWrap = '') {
         * @param       string          Field name
         * @param       string          Wrap value - set function description
         * @return      string
         */
        public static function getItemLabel($table, $col, $printAllWrap = '') {
-               global $TCA;
                        // Load full TCA for $table
                t3lib_div::loadTCA($table);
                        // Check if column exists
                        // 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($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
                                // Re
                                // Re
-                       return $TCA[$table]['columns'][$col]['label'];
+                       return $GLOBALS['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];
                }
        }
 
        /**
         * Returns the "title"-value in record, $row, from table, $table
         * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
                }
        }
 
        /**
         * Returns the "title"-value in record, $row, from table, $table
         * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
-        * Usage: 26
         *
         * @param       string          Table name, present in TCA
         * @param       array           Row from table
         *
         * @param       string          Table name, present in TCA
         * @param       array           Row from table
@@ -2045,37 +1903,38 @@ final class t3lib_BEfunc {
         * @return      string
         */
        public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
         * @return      string
         */
        public static function getRecordTitle($table, $row, $prep = FALSE, $forceResult = TRUE) {
-               global $TCA;
-               if (is_array($TCA[$table]))     {
+               if (is_array($GLOBALS['TCA'][$table])) {
 
                                // If configured, call userFunc
 
                                // If configured, call userFunc
-                       if ($TCA[$table]['ctrl']['label_userFunc']) {
+                       if ($GLOBALS['TCA'][$table]['ctrl']['label_userFunc']) {
                                $params['table'] = $table;
                                $params['row'] = $row;
                                $params['title'] = '';
                                        //create NULL-reference
                                $null = NULL;
                                $params['table'] = $table;
                                $params['row'] = $row;
                                $params['title'] = '';
                                        //create NULL-reference
                                $null = NULL;
-                               t3lib_div::callUserFunction($TCA[$table]['ctrl']['label_userFunc'], $params, $null);
+                               t3lib_div::callUserFunction($GLOBALS['TCA'][$table]['ctrl']['label_userFunc'], $params, $null);
                                $t = $params['title'];
                        } else {
 
                                        // No userFunc: Build label
                                $t = $params['title'];
                        } else {
 
                                        // No userFunc: Build label
-                               $t = self::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);
+                               $t = self::getProcessedValue($table, $GLOBALS['TCA'][$table]['ctrl']['label'], $row[$GLOBALS['TCA'][$table]['ctrl']['label']], 0, 0, FALSE, $row['uid'], $forceResult);
+                               if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] || !strcmp($t, ''))) {
+                                       $altFields = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
                                        $tA = array();
                                        $tA = array();
-                                       if (!empty($t)) $tA[] = $t;
+                                       if (!empty($t)) {
+                                               $tA[] = $t;
+                                       }
                                        foreach ($altFields as $fN) {
                                                $t = trim(strip_tags($row[$fN]));
                                                if (strcmp($t, '')) {
                                        foreach ($altFields as $fN) {
                                                $t = trim(strip_tags($row[$fN]));
                                                if (strcmp($t, '')) {
-                                                       $t = self::getProcessedValue($table, $fN, $t, 0, 0, false, $row['uid']);
-                                                       if (!$TCA[$table]['ctrl']['label_alt_force']) {
+                                                       $t = self::getProcessedValue($table, $fN, $t, 0, 0, FALSE, $row['uid']);
+                                                       if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
                                                                break;
                                                        }
                                                        $tA[] = $t;
                                                }
                                        }
                                                                break;
                                                        }
                                                        $tA[] = $t;
                                                }
                                        }
-                                       if ($TCA[$table]['ctrl']['label_alt_force']) {
+                                       if ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
                                                $t = implode(', ', $tA);
                                        }
                                }
                                                $t = implode(', ', $tA);
                                        }
                                }
@@ -2105,27 +1964,29 @@ final class t3lib_BEfunc {
         */
        public static function getRecordTitlePrep($title, $titleLength = 0) {
                        // If $titleLength is not a valid positive integer, use BE_USER->uc['titleLen']:
         */
        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) {
+               if (!$titleLength || !t3lib_utility_Math::canBeInterpretedAsInteger($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) {
                        $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>';
+                       $title = '<span title="' . $titleOrig . '">' . $title . '</span>';
                }
                return $title;
        }
 
        /**
                }
                return $title;
        }
 
        /**
-        * Get a localized [No title] string, wrapped in <em>|</em> if $prep is true.
+        * 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) {
         *
         * @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>';
+               $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title', 1) . ']';
+               if ($prep) {
+                       $noTitle = '<em>' . $noTitle . '</em>';
+               }
                return $noTitle;
        }
 
                return $noTitle;
        }
 
@@ -2134,7 +1995,6 @@ final class t3lib_BEfunc {
         * 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
         * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
         * 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
         * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
-        * Usage: 24
         *
         * @param       string          Table name, present in TCA
         * @param       string          Field name, present in TCA
         *
         * @param       string          Table name, present in TCA
         * @param       string          Field name, present in TCA
@@ -2147,9 +2007,6 @@ final class t3lib_BEfunc {
         * @return      string
         */
        public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
         * @return      string
         */
        public static function getProcessedValue($table, $col, $value, $fixed_lgd_chars = 0, $defaultPassthrough = 0, $noRecordLookup = FALSE, $uid = 0, $forceResult = TRUE) {
-               global $TCA;
-               global $TYPO3_CONF_VARS;
-
                if ($col == 'uid') {
                                // no need to load TCA as uid is not in TCA-array
                        return $value;
                if ($col == 'uid') {
                                // no need to load TCA as uid is not in TCA-array
                        return $value;
@@ -2157,50 +2014,51 @@ final class t3lib_BEfunc {
                        // 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($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$col])) {
                                // Depending on the fields configuration, make a meaningful output value.
                                // Depending on the fields configuration, make a meaningful output value.
-                       $theColConf = $TCA[$table]['columns'][$col]['config'];
+                       $theColConf = $GLOBALS['TCA'][$table]['columns'][$col]['config'];
 
 
-                               /*****************
-                                *HOOK: pre-processing the human readable output from a record
-                                ****************/
-                       if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
+                       /*****************
+                        *HOOK: pre-processing the human readable output from a record
+                        ****************/
+                       if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
                                        // create NULL-reference
                                $null = NULL;
                                        // create NULL-reference
                                $null = NULL;
-                               foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
+                               foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
                                        t3lib_div::callUserFunction($_funcRef, $theColConf, $null);
                                }
                        }
 
                        $l = '';
                                        t3lib_div::callUserFunction($_funcRef, $theColConf, $null);
                                }
                        }
 
                        $l = '';
-                       switch((string)$theColConf['type']) {
+                       switch ((string) $theColConf['type']) {
                                case 'radio':
                                        $l = self::getLabelFromItemlist($table, $col, $value);
                                        $l = $GLOBALS['LANG']->sL($l);
                                case 'radio':
                                        $l = self::getLabelFromItemlist($table, $col, $value);
                                        $l = $GLOBALS['LANG']->sL($l);
-                               break;
+                                       break;
                                case 'select':
                                        if ($theColConf['MM']) {
                                                if ($uid) {
                                                                // Display the title of MM related records in lists
                                                        if ($noRecordLookup) {
                                                                $MMfield = $theColConf['foreign_table'] . '.uid';
                                case 'select':
                                        if ($theColConf['MM']) {
                                                if ($uid) {
                                                                // 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) {
+                                                       } else {
+                                                               $MMfields = array($theColConf['foreign_table'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
+                                                               foreach (t3lib_div::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
                                                                        $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
                                                                }
                                                                $MMfield = join(',', $MMfields);
                                                        }
 
                                                                        $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
                                                                }
                                                                $MMfield = join(',', $MMfields);
                                                        }
 
+                                                       /** @var $dbGroup t3lib_loadDBGroup */
                                                        $dbGroup = t3lib_div::makeInstance('t3lib_loadDBGroup');
                                                        $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
                                                        $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
 
                                                        $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) {
+                                                       if (is_array($selectUids) && count($selectUids) > 0) {
                                                                $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                                        'uid, ' . $MMfield,
                                                                        $theColConf['foreign_table'],
                                                                $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                                                                        'uid, ' . $MMfield,
                                                                        $theColConf['foreign_table'],
-                                                                       'uid IN (' . implode(',', $selectUids) . ')'
+                                                                               'uid IN (' . implode(',', $selectUids) . ')'
                                                                );
                                                                while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
                                                                        $mmlA[] = ($noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
                                                                );
                                                                while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
                                                                        $mmlA[] = ($noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult));
@@ -2219,9 +2077,9 @@ final class t3lib_BEfunc {
                                                        $l = 'N/A';
                                                }
                                        } else {
                                                        $l = 'N/A';
                                                }
                                        } else {
-                                               $l = self::getLabelFromItemlist($table, $col, $value);
-                                               $l = $GLOBALS['LANG']->sL($l);
-                                               if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']]) {
+                                               $l = self::getLabelsFromItemsList($table, $col, $value);
+
+                                               if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
                                                        if ($noRecordLookup) {
                                                                $l = $value;
                                                        } else {
                                                        if ($noRecordLookup) {
                                                                $l = $value;
                                                        } else {
@@ -2229,58 +2087,69 @@ final class t3lib_BEfunc {
                                                                $lA = array();
                                                                foreach ($rParts as $rVal) {
                                                                        $rVal = intval($rVal);
                                                                $lA = array();
                                                                foreach ($rParts as $rVal) {
                                                                        $rVal = intval($rVal);
-                                                                       if ($rVal>0) {
+                                                                       if ($rVal > 0) {
                                                                                $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
                                                                        } else {
                                                                                $r = self::getRecordWSOL($theColConf['neg_foreign_table'], -$rVal);
                                                                        }
                                                                        if (is_array($r)) {
                                                                                $r = self::getRecordWSOL($theColConf['foreign_table'], $rVal);
                                                                        } else {
                                                                                $r = self::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']) . self::getRecordTitle($rVal>0?$theColConf['foreign_table']:$theColConf['neg_foreign_table'], $r, FALSE, $forceResult);
+                                                                               $lA[] = $GLOBALS['LANG']->sL($rVal > 0 ? $theColConf['foreign_table_prefix'] : $theColConf['neg_foreign_table_prefix']) . self::getRecordTitle($rVal > 0 ? $theColConf['foreign_table'] : $theColConf['neg_foreign_table'], $r, FALSE, $forceResult);
                                                                        } else {
                                                                        } else {
-                                                                               $lA[] = $rVal?'['.$rVal.'!]':'';
+                                                                               $lA[] = $rVal ? '[' . $rVal . '!]' : '';
                                                                        }
                                                                }
                                                                $l = implode(', ', $lA);
                                                        }
                                                }
                                        }
                                                                        }
                                                                }
                                                                $l = implode(', ', $lA);
                                                        }
                                                }
                                        }
-                               break;
+                                       break;
                                case 'group':
                                        $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
                                case 'group':
                                        $l = implode(', ', t3lib_div::trimExplode(',', $value, 1));
-                               break;
+                                       break;
                                case 'check':
                                case 'check':
-                                       if (!is_array($theColConf['items']) || count($theColConf['items'])==1) {
+                                       if (!is_array($theColConf['items']) || count($theColConf['items']) == 1) {
                                                $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
                                        } else {
                                                $lA = Array();
                                                foreach ($theColConf['items'] as $key => $val) {
                                                $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xml:no');
                                        } else {
                                                $lA = Array();
                                                foreach ($theColConf['items'] as $key => $val) {
-                                                       if ($value & pow(2, $key))      {$lA[] = $GLOBALS['LANG']->sL($val[0]);}
+                                                       if ($value & pow(2, $key)) {
+                                                               $lA[] = $GLOBALS['LANG']->sL($val[0]);
+                                                       }
                                                }
                                                $l = implode(', ', $lA);
                                        }
                                                }
                                                $l = implode(', ', $lA);
                                        }
-                               break;
+                                       break;
                                case 'input':
                                case 'input':
+                                               // hide value 0 for dates, but show it for everything else
                                        if (isset($value)) {
                                                if (t3lib_div::inList($theColConf['eval'], 'date')) {
                                        if (isset($value)) {
                                                if (t3lib_div::inList($theColConf['eval'], 'date')) {
-                                                       $l = self::date($value) .
-                                                               ' (' .
-                                                               ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
-                                                               self::calcAge(abs($GLOBALS['EXEC_TIME'] - $value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')) .
-                                                               ')';
+                                                       if (!empty($value)) {
+                                                               $l = self::date($value) .
+                                                                       ' (' .
+                                                                       ($GLOBALS['EXEC_TIME'] - $value > 0 ? '-' : '') .
+                                                                       self::calcAge(abs($GLOBALS['EXEC_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 = self::time($value, FALSE);
+                                                       if (!empty($value)) {
+                                                               $l = self::time($value, FALSE);
+                                                       }
                                                } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
                                                } elseif (t3lib_div::inList($theColConf['eval'], 'timesec')) {
-                                                       $l = self::time($value);
+                                                       if (!empty($value)) {
+                                                               $l = self::time($value);
+                                                       }
                                                } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
                                                } elseif (t3lib_div::inList($theColConf['eval'], 'datetime')) {
-                                                       $l = self::datetime($value);
+                                                       if (!empty($value)) {
+                                                               $l = self::datetime($value);
+                                                       }
                                                } else {
                                                        $l = $value;
                                                }
                                        }
                                                } else {
                                                        $l = $value;
                                                }
                                        }
-                               break;
+                                       break;
                                case 'flex':
                                        $l = strip_tags($value);
                                case 'flex':
                                        $l = strip_tags($value);
-                               break;
+                                       break;
                                default:
                                        if ($defaultPassthrough) {
                                                $l = $value;
                                default:
                                        if ($defaultPassthrough) {
                                                $l = $value;
@@ -2289,25 +2158,25 @@ final class t3lib_BEfunc {
                                        } elseif ($value) {
                                                $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
                                        }
                                        } elseif ($value) {
                                                $l = t3lib_div::fixed_lgd_cs(strip_tags($value), 200);
                                        }
-                               break;
+                                       break;
                        }
 
                                // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
                        if (stristr($theColConf['eval'], 'password')) {
                        }
 
                                // If this field is a password field, then hide the password by changing it to a random number of asterisk (*)
                        if (stristr($theColConf['eval'], 'password')) {
-                               unset($l);
+                               $l = '';
                                $randomNumber = rand(5, 12);
                                $randomNumber = rand(5, 12);
-                               for ($i=0; $i < $randomNumber; $i++) {
+                               for ($i = 0; $i < $randomNumber; $i++) {
                                        $l .= '*';
                                }
                        }
 
                                        $l .= '*';
                                }
                        }
 
-                               /*****************
-                                *HOOK: post-processing the human readable output from a record
-                                ****************/
-                       if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
+                       /*****************
+                        *HOOK: post-processing the human readable output from a record
+                        ****************/
+                       if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
                                        // create NULL-reference
                                $null = NULL;
                                        // create NULL-reference
                                $null = NULL;
-                               foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
+                               foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
                                        $params = array(
                                                'value' => $l,
                                                'colConf' => $theColConf
                                        $params = array(
                                                'value' => $l,
                                                'colConf' => $theColConf
@@ -2326,7 +2195,6 @@ final class t3lib_BEfunc {
 
        /**
         * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
 
        /**
         * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
-        * Usage: 2
         *
         * @param       string          Table name, present in TCA
         * @param       string          Field name
         *
         * @param       string          Table name, present in TCA
         * @param       string          Field name
@@ -2338,14 +2206,13 @@ final class t3lib_BEfunc {
         * @see getProcessedValue()
         */
        public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
         * @see getProcessedValue()
         */
        public static function getProcessedValueExtra($table, $fN, $fV, $fixed_lgd_chars = 0, $uid = 0, $forceResult = TRUE) {
-               global $TCA;
                $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult);
                if (!isset($fVnew)) {
                $fVnew = self::getProcessedValue($table, $fN, $fV, $fixed_lgd_chars, 1, 0, $uid, $forceResult);
                if (!isset($fVnew)) {
-                       if (is_array($TCA[$table])) {
-                               if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate']) {
+                       if (is_array($GLOBALS['TCA'][$table])) {
+                               if ($fN == $GLOBALS['TCA'][$table]['ctrl']['tstamp'] || $fN == $GLOBALS['TCA'][$table]['ctrl']['crdate']) {
                                        $fVnew = self::datetime($fV);
                                        $fVnew = self::datetime($fV);
-                               } elseif ($fN=='pid'){
-                                       $fVnew = self::getRecordPath($fV, '1=1', 20);   // Fetches the path with no regard to the users permissions to select pages.
+                               } elseif ($fN == 'pid') {
+                                       $fVnew = self::getRecordPath($fV, '1=1', 20); // Fetches the path with no regard to the users permissions to select pages.
                                } else {
                                        $fVnew = $fV;
                                }
                                } else {
                                        $fVnew = $fV;
                                }
@@ -2356,7 +2223,6 @@ final class t3lib_BEfunc {
 
        /**
         * Returns file icon name (from $FILEICONS) for the fileextension $ext
 
        /**
         * Returns file icon name (from $FILEICONS) for the fileextension $ext
-        * Usage: 10
         *
         * @param       string          File extension, lowercase
         * @return      string          File icon filename
         *
         * @param       string          File extension, lowercase
         * @return      string          File icon filename
@@ -2369,39 +2235,51 @@ final class t3lib_BEfunc {
         * Returns fields for a table, $table, which would typically be interesting to select
         * This includes uid, the fields defined for title, icon-field.
         * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
         * Returns fields for a table, $table, which would typically be interesting to select
         * This includes uid, the fields defined for title, icon-field.
         * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
-        * Usage: 3
         *
         *
-        * @param       string          Table name, present in TCA
+        * @param       string          Table name, present in $GLOBALS['TCA']
         * @param       string          Table prefix
         * @param       array           Preset fields (must include prefix if that is used)
         * @return      string          List of fields.
         */
        public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
         * @param       string          Table prefix
         * @param       array           Preset fields (must include prefix if that is used)
         * @return      string          List of fields.
         */
        public static function getCommonSelectFields($table, $prefix = '', $fields = array()) {
-               global $TCA;
-               $fields[] = $prefix.'uid';
-               $fields[] = $prefix.$TCA[$table]['ctrl']['label'];
+               $fields[] = $prefix . 'uid';
+               if (isset($GLOBALS['TCA'][$table]['ctrl']['label']) && $GLOBALS['TCA'][$table]['ctrl']['label'] != '') {
+                       $fields[] = $prefix . $GLOBALS['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 ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
+                       $secondFields = t3lib_div::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
+                       foreach ($secondFields as $fieldN) {
+                               $fields[] = $prefix . $fieldN;
                        }
                }
                        }
                }
-               if ($TCA[$table]['ctrl']['versioningWS']) {
-                       $fields[] = $prefix.'t3ver_id';
-                       $fields[] = $prefix.'t3ver_state';
-                       $fields[] = $prefix.'t3ver_wsid';
-                       $fields[] = $prefix.'t3ver_count';
+               if ($GLOBALS['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 ($GLOBALS['TCA'][$table]['ctrl']['selicon_field']) {
+                       $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['selicon_field'];
+               }
+               if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
+                       $fields[] = $prefix . $GLOBALS['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'];
+               if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
+                       if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
+                               $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled'];
+                       }
+                       if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime']) {
+                               $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['starttime'];
+                       }
+                       if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime']) {
+                               $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['endtime'];
+                       }
+                       if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group']) {
+                               $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['fe_group'];
+                       }
                }
 
                return implode(',', array_unique($fields));
                }
 
                return implode(',', array_unique($fields));
@@ -2411,7 +2289,6 @@ final class t3lib_BEfunc {
         * Makes a form for configuration of some values based on configuration found in the array $configArray, with default values from $defaults and a data-prefix $dataPrefix
         * <form>-tags must be supplied separately
         * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3. That's were you can expect to find example, if anywhere.
         * Makes a form for configuration of some values based on configuration found in the array $configArray, with default values from $defaults and a data-prefix $dataPrefix
         * <form>-tags must be supplied separately
         * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3. That's were you can expect to find example, if anywhere.
-        * Usage: 1 (ext. direct_mail)
         *
         * @param       array           Field configuration code.
         * @param       array           Defaults
         *
         * @param       array           Field configuration code.
         * @param       array           Defaults
@@ -2424,56 +2301,49 @@ final class t3lib_BEfunc {
                        $lines = array();
                        foreach ($configArray as $fname => $config) {
                                if (is_array($config)) {
                        $lines = array();
                        foreach ($configArray as $fname => $config) {
                                if (is_array($config)) {
-                                       $lines[$fname] = '<strong>'.htmlspecialchars($config[1]).'</strong><br />';
-                                       $lines[$fname].=$config[2].'<br />';
-                                       switch($config[0]) {
+                                       $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
+                                       $lines[$fname] .= $config[2] . '<br />';
+                                       switch ($config[0]) {
                                                case 'string':
                                                case 'short':
                                                case 'string':
                                                case 'short':
-                                                       $formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
-                                               break;
+                                                       $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth($config[0] == 'short' ? 24 : 48) . ' />';
+                                                       break;
                                                case 'check':
                                                case 'check':
-                                                       $formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
-                                               break;
+                                                       $formEl = '<input type="hidden" name="' . $dataPrefix . '[' . $fname . ']" value="0" /><input type="checkbox" name="' . $dataPrefix . '[' . $fname . ']" value="1"' . ($params[$fname] ? ' checked="checked"' : '') . ' />';
+                                                       break;
                                                case 'comment':
                                                        $formEl = '';
                                                case 'comment':
                                                        $formEl = '';
-                                               break;
+                                                       break;
                                                case 'select':
                                                        $opt = array();
                                                        foreach ($config[3] as $k => $v) {
                                                case 'select':
                                                        $opt = array();
                                                        foreach ($config[3] as $k => $v) {
-                                                               $opt[] = '<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
+                                                               $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
                                                        }
                                                        }
-                                                       $formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('', $opt).'</select>';
-                                               break;
+                                                       $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
+                                                       break;
                                                default:
                                                        debug($config);
                                                default:
                                                        debug($config);
-                                               break;
+                                                       break;
                                        }
                                        }
-                                       $lines[$fname].=$formEl;
-                                       $lines[$fname].='<br /><br />';
+                                       $lines[$fname] .= $formEl;
+                                       $lines[$fname] .= '<br /><br />';
                                } else {
                                        $lines[$fname] = '<hr />';
                                } else {
                                        $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" />';
+               $out .= '<input type="submit" name="submit" value="Update configuration" />';
                return $out;
        }
 
 
                return $out;
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
        /*******************************************
         *
         * Backend Modules API functions
        /*******************************************
         *
         * Backend Modules API functions
@@ -2482,9 +2352,8 @@ final class t3lib_BEfunc {
 
        /**
         * Returns help-text icon if configured for.
 
        /**
         * Returns help-text icon if configured for.
-        * TCA_DESCR must be loaded prior to this function and $BE_USER must
+        * TCA_DESCR must be loaded prior to this function and $GLOBALS['BE_USER'] must
         * have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
         * have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
-        * Usage: 6
         *
         * Please note: since TYPO3 4.5 the UX team decided to not use CSH in its former way,
         * but to wrap the given text (where before the help icon was, and you could hover over it)
         *
         * Please note: since TYPO3 4.5 the UX team decided to not use CSH in its former way,
         * but to wrap the given text (where before the help icon was, and you could hover over it)
@@ -2494,55 +2363,83 @@ final class t3lib_BEfunc {
         * @param       string          Table name
         * @param       string          Field name
         * @param       string          Back path
         * @param       string          Table name
         * @param       string          Field name
         * @param       string          Back path
-        * @param       boolean         Force display of icon nomatter BE_USER setting for help
+        * @param       boolean         Force display of icon no matter BE_USER setting for help
         * @return      string          HTML content for a help icon/text
         */
        public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
         * @return      string          HTML content for a help icon/text
         */
        public static function helpTextIcon($table, $field, $BACK_PATH, $force = 0) {
-               global $TCA_DESCR, $BE_USER;
+               if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field]) && (isset($GLOBALS['BE_USER']->uc['edit_showFieldHelp']) || $force)) {
+                       return self::wrapInHelp($table, $field);
+               }
+       }
+
+       /**
+        * Returns CSH help text (description), if configured for, as an array (title, description)
+        *
+        * @param       string  Table name
+        * @param       string  Field name
+        * @return      array   With keys 'description' (raw, as available in locallang), 'title' (optional), 'moreInfo'
+        */
+       public static function helpTextArray($table, $field) {
+               if (!isset($GLOBALS['TCA_DESCR'][$table]['columns'])) {
+                       $GLOBALS['LANG']->loadSingleTableDescription($table);
+               }
+               $output = array(
+                       'description' => NULL,
+                       'title' => NULL,
+                       'moreInfo' => FALSE,
+               );
+               if (is_array($GLOBALS['TCA_DESCR'][$table]) && is_array($GLOBALS['TCA_DESCR'][$table]['columns'][$field])) {
+                       $data = $GLOBALS['TCA_DESCR'][$table]['columns'][$field];
 
 
-               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 = self::helpText($table, $field);
-                               $text = '<span class="typo3-csh-inline">' . $GLOBALS['LANG']->hscAndCharConv($text, FALSE) . '</span>';
+                               // add alternative title, if defined
+                       if ($data['alttitle']) {
+                               $output['title'] = $data['alttitle'];
+                       }
+
+                               // if we have more information to show
+                       if ($data['image_descr'] || $data['seeAlso'] || $data['details'] || $data['syntax']) {
+                               $output['moreInfo'] = TRUE;
+                       }
+
+                               // add description
+                       if ($data['description']) {
+                               $output['description'] = $data['description'];
                        }
                        }
-                       return '<a class="typo3-csh-link" href="#" rel="' . $table . '.' . $field . '">' . t3lib_iconWorks::getSpriteIcon('actions-system-help-open', array('class' => 'typo3-csh-icon')) . $text.'</a>';
                }
                }
+               return $output;
        }
 
        }
 
-
        /**
         * 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
-        * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
-        * Usage: 4
+        * $GLOBALS['TCA_DESCR'] must be loaded prior to this function and $GLOBALS['BE_USER'] must have "edit_showFieldHelp" set to "text",
+        * otherwise nothing is returned.
         *
         * @param       string          Table name
         * @param       string          Field name
         *
         * @param       string          Table name
         * @param       string          Field name
-        * @param       string          Back path, deprecated since TYPO3 4.5, will be removed in TYPO3 4.7, because not used at all
-        * @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
         */
-       public static function helpText($table, $field, $BACK_PATH = '', $styleAttrib = '') {
-               global $TCA_DESCR, $BE_USER;
-               $output = '';
+       public static function helpText($table, $field) {
+               $helpTextArray = self::helpTextArray($table, $field);
 
 
-               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 = t3lib_iconWorks::getSpriteIcon('actions-view-go-forward');
-                       }
-                               // add description text
-                       if ($data['description'] || $arrow) {
-                               $output = '<p class="t3-help-short">' . nl2br(htmlspecialchars($data['description'])) . $arrow . '</p>';
-                       }
+               $output = '';
 
 
-                               // put header before the rest of the text
-                       if ($data['alttitle']) {
-                               $output = '<h2 class="t3-row-header">' . $data['alttitle'] . '</h2>' . $output;
-                       }
+                       // put header before the rest of the text
+               if ($helpTextArray['title'] !== NULL) {
+                       $output .= '<h2 class="t3-row-header">' . $helpTextArray['title'] . '</h2>';
+               }
+                       // add the content
+               if ($helpTextArray['description'] !== NULL) {
+                       $output .= $helpTextArray['description'];
                }
                }
+                       // add see also arrow if we have more info
+               if ($helpTextArray['moreInfo']) {
+                       $arrow = t3lib_iconWorks::getSpriteIcon('actions-view-go-forward');
+               }
+                       // add description text
+               if ($helpTextArray['description'] || $arrow) {
+                       $output['description'] = '<p class="t3-help-short">' . nl2br(htmlspecialchars($helpTextArray['description'])) . $arrow . '</p>';
+               }
+
                return $output;
        }
 
                return $output;
        }
 
@@ -2558,71 +2455,87 @@ final class t3lib_BEfunc {
         * @return      string  the HTML code ready to render
         * @api public
         */
         * @return      string  the HTML code ready to render
         * @api public
         */
-       public static function wrapInHelp($table, $field, $text = '') {
-                       // get the help text that should be shown on hover
-               $GLOBALS['LANG']->loadSingleTableDescription($table);
-               $helpText = self::helpText($table, $field);
-               if ($helpText) {
-                               // if no text was given, just use the regular help icon
+       public static function wrapInHelp($table, $field, $text = '', array $overloadHelpText = array()) {
+                       // Initialize some variables
+               $helpText = '';
+               $abbrClassAdd = '';
+               $wrappedText = $text;
+               $hasHelpTextOverload = count($overloadHelpText) > 0;
+
+                       // Get the help text that should be shown on hover
+               if (!$hasHelpTextOverload) {
+                       $helpText = self::helpText($table, $field);
+               }
+
+                       // If there's a help text or some overload information, proceed with preparing an output
+               if (!empty($helpText) || $hasHelpTextOverload) {
+                               // If no text was given, just use the regular help icon
                        if ($text == '') {
                                $text = t3lib_iconWorks::getSpriteIcon('actions-system-help-open');
                        if ($text == '') {
                                $text = t3lib_iconWorks::getSpriteIcon('actions-system-help-open');
+                               $abbrClassAdd = '-icon';
                        }
                        }
-
-                       $helpText = '<div class="t3-help-inline">' . $helpText . '</div>';
-                       $text = '<abbr class="t3-help-teaser">' . $text . '</abbr>';
-
-                       $text = '<a class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '">' . $text . '</a>';
+                       $text = '<abbr class="t3-help-teaser' . $abbrClassAdd . '">' . $text . '</abbr>';
+                       $wrappedText = '<span class="t3-help-link" href="#" data-table="' . $table . '" data-field="' . $field . '"';
+                               // The overload array may provide a title and a description
+                               // If either one is defined, add them to the "data" attributes
+                       if ($hasHelpTextOverload) {
+                               if (isset($overloadHelpText['title'])) {