[BUGFIX] Catch exception in filelist when file is missing
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Utility / BackendUtility.php
index e76b550..66af510 100644 (file)
@@ -15,7 +15,7 @@ namespace TYPO3\CMS\Backend\Utility;
  *
  *  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
+ *  A copy is found in the text file GPL.txt and important notices to the license
  *  from the author is found in LICENSE.txt distributed with these scripts.
  *
  *
@@ -29,12 +29,14 @@ namespace TYPO3\CMS\Backend\Utility;
 
 use TYPO3\CMS\Backend\Utility\IconUtility;
 use TYPO3\CMS\Core\Messaging\FlashMessage;
+use TYPO3\CMS\Core\Resource\File;
 use TYPO3\CMS\Core\Resource\ProcessedFile;
 use TYPO3\CMS\Core\Resource\ResourceFactory;
 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 use TYPO3\CMS\Core\Utility\MathUtility;
+use TYPO3\CMS\Core\Versioning\VersionState;
 use TYPO3\CMS\Frontend\Page\PageRepository;
 
 /**
@@ -65,7 +67,7 @@ class BackendUtility {
         */
        static public function deleteClause($table, $tableAlias = '') {
                if ($GLOBALS['TCA'][$table]['ctrl']['delete']) {
-                       return ' AND ' . ($tableAlias ? $tableAlias : $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
+                       return ' AND ' . ($tableAlias ?: $table) . '.' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
                } else {
                        return '';
                }
@@ -87,7 +89,7 @@ class BackendUtility {
         */
        static public function getRecord($table, $uid, $fields = '*', $where = '', $useDeleteClause = TRUE) {
                if ($GLOBALS['TCA'][$table]) {
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid=' . intval($uid) . ($useDeleteClause ? self::deleteClause($table) : '') . $where);
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid=' . (int)$uid . ($useDeleteClause ? self::deleteClause($table) : '') . $where);
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
                        if ($row) {
@@ -215,7 +217,7 @@ class BackendUtility {
                                $val = strrev($val);
                                $parts = explode('_', $val, 2);
                                if ((string) trim($parts[0]) != '') {
-                                       $theID = intval(strrev($parts[0]));
+                                       $theID = (int)strrev($parts[0]);
                                        $theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
                                        if ($theTable == $tablename) {
                                                $list[] = $theID;
@@ -276,7 +278,7 @@ class BackendUtility {
                $recordLocalization = FALSE;
                if (self::isTableLocalizable($table)) {
                        $tcaCtrl = $GLOBALS['TCA'][$table]['ctrl'];
-                       $recordLocalization = self::getRecordsByField($table, $tcaCtrl['transOrigPointerField'], $uid, 'AND ' . $tcaCtrl['languageField'] . '=' . intval($language) . ($andWhereClause ? ' ' . $andWhereClause : ''), '', '', '1');
+                       $recordLocalization = self::getRecordsByField($table, $tcaCtrl['transOrigPointerField'], $uid, 'AND ' . $tcaCtrl['languageField'] . '=' . (int)$language . ($andWhereClause ? ' ' . $andWhereClause : ''), '', '', '1');
                }
                return $recordLocalization;
        }
@@ -359,7 +361,7 @@ class BackendUtility {
                if (is_array($getPageForRootline_cache[$ident])) {
                        $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_stage,backend_layout_next_level', 'pages', 'uid=' . intval($uid) . ' ' . self::deleteClause('pages') . ' ' . $clause);
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_stage,backend_layout_next_level', 'pages', 'uid=' . (int)$uid . ' ' . self::deleteClause('pages') . ' ' . $clause);
                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                        if ($row) {
                                $newLocation = FALSE;
@@ -465,12 +467,13 @@ class BackendUtility {
                // All TCA keys
                $tableNamesFromTca = array_keys($GLOBALS['TCA']);
                // Fetch translations for table names
+               $tableToTranslation = array();
                foreach ($tableNamesFromTca as $table) {
-                       $tableNamesFromTca[$table] = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']);
+                       $tableToTranslation[$table] = $GLOBALS['LANG']->sl($GLOBALS['TCA'][$table]['ctrl']['title']);
                }
                // Sort by translations
-               asort($tableNamesFromTca);
-               foreach ($tableNamesFromTca as $table => $translatedTable) {
+               asort($tableToTranslation);
+               foreach ($tableToTranslation as $table => $translatedTable) {
                        $excludeArrayTable = array();
 
                        // All field names configured and not restricted to admins
@@ -489,7 +492,7 @@ class BackendUtility {
                                }
                        }
                        // All FlexForm fields
-                       $flexFormArray = self::getRegisteredFlexForms($table);
+                       $flexFormArray = static::getRegisteredFlexForms($table);
                        foreach ($flexFormArray as $tableField => $flexForms) {
                                // Prefix for field label, e.g. "Plugin Options:"
                                $labelPrefix = '';
@@ -555,23 +558,23 @@ class BackendUtility {
                                                        // Check for items:
                                                        foreach ($fCfg['items'] as $iVal) {
                                                                // Values '' is not controlled by this setting.
-                                                               if (strcmp($iVal[1], '')) {
+                                                               if ((string)$iVal[1] !== '') {
                                                                        // Find iMode
                                                                        $iMode = '';
                                                                        switch ((string) $fCfg['authMode']) {
-                                                                       case 'explicitAllow':
-                                                                               $iMode = 'ALLOW';
-                                                                               break;
-                                                                       case 'explicitDeny':
-                                                                               $iMode = 'DENY';
-                                                                               break;
-                                                                       case 'individual':
-                                                                               if (!strcmp($iVal[4], 'EXPL_ALLOW')) {
+                                                                               case 'explicitAllow':
                                                                                        $iMode = 'ALLOW';
-                                                                               } elseif (!strcmp($iVal[4], 'EXPL_DENY')) {
+                                                                                       break;
+                                                                               case 'explicitDeny':
                                                                                        $iMode = 'DENY';
-                                                                               }
-                                                                               break;
+                                                                                       break;
+                                                                               case 'individual':
+                                                                                       if ($iVal[4] === 'EXPL_ALLOW') {
+                                                                                               $iMode = 'ALLOW';
+                                                                                       } elseif ($iVal[4] === 'EXPL_DENY') {
+                                                                                               $iMode = 'DENY';
+                                                                                       }
+                                                                                       break;
                                                                        }
                                                                        // Set iMode
                                                                        if ($iMode) {
@@ -679,7 +682,7 @@ class BackendUtility {
         */
        static public function readPageAccess($id, $perms_clause) {
                if ((string) $id != '') {
-                       $id = intval($id);
+                       $id = (int)$id;
                        if (!$id) {
                                if ($GLOBALS['BE_USER']->isAdmin()) {
                                        $path = '/';
@@ -692,7 +695,7 @@ class BackendUtility {
                                        self::workspaceOL('pages', $pageinfo);
                                        if (is_array($pageinfo)) {
                                                self::fixVersioningPid('pages', $pageinfo);
-                                               list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
+                                               list($pageinfo['_thePath'], $pageinfo['_thePathFull']) = self::getRecordPath((int)$pageinfo['uid'], $perms_clause, 15, 1000);
                                                return $pageinfo;
                                        }
                                }
@@ -791,7 +794,7 @@ class BackendUtility {
                                $typeNum = $row[$field];
                        }
                        // If that value is an empty string, set it to "0" (zero)
-                       if (!strcmp($typeNum, '')) {
+                       if (empty($typeNum)) {
                                $typeNum = 0;
                        }
                }
@@ -815,14 +818,14 @@ class BackendUtility {
         */
        static public function getSpecConfParts($str, $defaultExtras) {
                // Add defaultExtras:
-               $specConfParts = GeneralUtility::trimExplode(':', $defaultExtras . ':' . $str, 1);
+               $specConfParts = GeneralUtility::trimExplode(':', $defaultExtras . ':' . $str, TRUE);
                $reg = array();
                if (count($specConfParts)) {
                        foreach ($specConfParts as $k2 => $v2) {
                                unset($specConfParts[$k2]);
                                if (preg_match('/(.*)\\[(.*)\\]/', $v2, $reg)) {
                                        $specConfParts[trim($reg[1])] = array(
-                                               'parameters' => GeneralUtility::trimExplode('|', $reg[2], 1)
+                                               'parameters' => GeneralUtility::trimExplode('|', $reg[2], TRUE)
                                        );
                                } else {
                                        $specConfParts[trim($v2)] = 1;
@@ -932,7 +935,7 @@ class BackendUtility {
                                // Used to avoid looping, if any should happen.
                                $subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
                                while (!$srcPointer) {
-                                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''), $table, 'uid=' . intval(($newRecordPidValue ? $newRecordPidValue : $rr[$ds_searchParentField])) . self::deleteClause($table));
+                                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,' . $ds_pointerField . ',' . $ds_searchParentField . ($subFieldPointer ? ',' . $subFieldPointer : ''), $table, 'uid=' . (int)($newRecordPidValue ?: $rr[$ds_searchParentField]) . self::deleteClause($table));
                                        $newRecordPidValue = 0;
                                        $rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                                        $GLOBALS['TYPO3_DB']->sql_free_result($res);
@@ -1080,32 +1083,33 @@ class BackendUtility {
         *
         *******************************************/
        /**
-        * Stores the string value $data in the 'cache_hash' cache with the
-        * hash key, $hash, and visual/symbolic identification, $ident
+        * Stores $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 \TYPO3\CMS\Frontend\Page\PageRepository
         *
         * @param string $hash 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
-        * @param string $data The data string. If you want to store an array, then just serialize it first.
+        * @param mixed $data The data to store
         * @param string $ident $ident is just a textual identification in order to inform about the content!
         * @return      void
         */
        static public function storeHash($hash, $data, $ident) {
-               $GLOBALS['typo3CacheManager']->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), 0);
+               GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_hash')->set($hash, $data, array('ident_' . $ident), 0);
        }
 
        /**
-        * Returns string value stored for the hash string in the cache "cache_hash"
-        * Can be used to retrieved a cached value
+        * Returns data stored for the hash string in the cache "cache_hash"
+        * Can be used to retrieved a cached value, array or object
         *
         * IDENTICAL to the function by same name found in \TYPO3\CMS\Frontend\Page\PageRepository
         *
         * @param string $hash The hash-string which was used to store the data value
-        * @param integer $expTime Variabele is not used in the function
-        * @return string
+        * @param integer $expTime Variable is not used in the function
+        * @return mixed The "data" from the cache
         */
        static public function getHash($hash, $expTime = 0) {
                $hashContent = NULL;
-               $cacheEntry = $GLOBALS['typo3CacheManager']->getCache('cache_hash')->get($hash);
+               $cacheEntry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_hash')->get($hash);
                if ($cacheEntry) {
                        $hashContent = $cacheEntry;
                }
@@ -1126,109 +1130,55 @@ class BackendUtility {
         * @return array Page TSconfig
         * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
         */
-       static public function getPagesTSconfig($id, $rootLine = '', $returnPartArray = 0) {
-               $id = intval($id);
-               if (!is_array($rootLine)) {
-                       $rootLine = self::BEgetRootLine($id, '', TRUE);
-               }
-               // Order correctly
-               ksort($rootLine);
-               $TSdataArray = array();
-               // Setting default configuration
-               $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
-               foreach ($rootLine as $k => $v) {
-                       $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
-               }
-               $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
-               if ($returnPartArray) {
-                       return $TSdataArray;
-               }
-               // Parsing the page TS-Config (or getting from cache)
-               $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
-               if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions']) {
+       static public function getPagesTSconfig($id, $rootLine = NULL, $returnPartArray = FALSE) {
+               static $pagesTSconfig_cache = array();
+
+               $id = (int)$id;
+               if ($returnPartArray === FALSE
+                       && $rootLine === NULL
+                       && isset($pagesTSconfig_cache[$id])
+               ) {
+                       return $pagesTSconfig_cache[$id];
+               } else {
+                       $TSconfig = array();
+                       if (!is_array($rootLine)) {
+                               $useCacheForCurrentPageId = TRUE;
+                               $rootLine = self::BEgetRootLine($id, '', TRUE);
+                       } else {
+                               $useCacheForCurrentPageId = FALSE;
+                       }
+
+                       // Order correctly
+                       ksort($rootLine);
+                       $TSdataArray = array();
+                       // Setting default configuration
+                       $TSdataArray['defaultPageTSconfig'] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
+                       foreach ($rootLine as $k => $v) {
+                               $TSdataArray['uid_' . $v['uid']] = $v['TSconfig'];
+                       }
+                       $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
+                       if ($returnPartArray) {
+                               return $TSdataArray;
+                       }
+                       // Parsing the page TS-Config
+                       $pageTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
                        /* @var $parseObj \TYPO3\CMS\Backend\Configuration\TsConfigParser */
                        $parseObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Configuration\\TsConfigParser');
                        $res = $parseObj->parseTSconfig($pageTS, 'PAGES', $id, $rootLine);
                        if ($res) {
                                $TSconfig = $res['TSconfig'];
                        }
-               } else {
-                       $hash = md5('pageTS:' . $pageTS);
-                       $cachedContent = self::getHash($hash);
-                       $TSconfig = array();
-                       if (isset($cachedContent)) {
-                               $TSconfig = unserialize($cachedContent);
-                       } else {
-                               $parseObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
-                               $parseObj->parse($pageTS);
-                               $TSconfig = $parseObj->setup;
-                               self::storeHash($hash, serialize($TSconfig), 'PAGES_TSconfig');
+                       // Get User TSconfig overlay
+                       $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
+                       if (is_array($userTSconfig)) {
+                               \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($TSconfig, $userTSconfig);
                        }
-               }
-               // Get User TSconfig overlay
-               $userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
-               if (is_array($userTSconfig)) {
-                       $TSconfig = GeneralUtility::array_merge_recursive_overrule($TSconfig, $userTSconfig);
-               }
-               return $TSconfig;
-       }
 
-       /**
-        * Updates Page TSconfig for a page with $id
-        * The function seems to take $pageTS as an array with properties and compare the values with those that already exists for the "object string", $TSconfPrefix, for the page, then sets those values which were not present.
-        * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
-        *
-        * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
-        * More documentation is needed.
-        *
-        * @param integer $id Page id
-        * @param array $pageTS Page TS array to write
-        * @param string $TSconfPrefix Prefix for object paths
-        * @param array $impParams [Description needed.]
-        * @return      void
-        * @internal
-        * @see implodeTSParams(), getPagesTSconfig()
-        */
-       static public function updatePagesTSconfig($id, $pageTS, $TSconfPrefix, $impParams = '') {
-               $id = intval($id);
-               if (is_array($pageTS) && $id > 0) {
-                       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))) {
-                                       $set[$f] = trim($v);
-                               }
-                       }
-                       if (count($set)) {
-                               // Get page record and TS config lines
-                               $pRec = self::getRecord('pages', $id);
-                               $TSlines = explode(LF, $pRec['TSconfig']);
-                               $TSlines = array_reverse($TSlines);
-                               // Reset the set of changes.
-                               foreach ($set as $f => $v) {
-                                       $inserted = 0;
-                                       foreach ($TSlines as $ki => $kv) {
-                                               if (substr($kv, 0, strlen($f) + 1) == $f . '=') {
-                                                       $TSlines[$ki] = $f . '=' . $v;
-                                                       $inserted = 1;
-                                                       break;
-                                               }
-                                       }
-                                       if (!$inserted) {
-                                               $TSlines = array_reverse($TSlines);
-                                               $TSlines[] = $f . '=' . $v;
-                                               $TSlines = array_reverse($TSlines);
-                                       }
-                               }
-                               $TSlines = array_reverse($TSlines);
-                               // Store those changes
-                               $TSconf = implode(LF, $TSlines);
-                               $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid=' . intval($id), array('TSconfig' => $TSconf));
+                       if ($useCacheForCurrentPageId) {
+                               $pagesTSconfig_cache[$id] = $TSconfig;
                        }
                }
+               return $TSconfig;
        }
 
        /**
@@ -1266,13 +1216,12 @@ class BackendUtility {
         * @return array
         */
        static public function getUserNames($fields = 'username,usergroup,usergroup_cached_list,uid', $where = '') {
-               $be_user_Array = array();
-               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 ' . $where . self::deleteClause('be_users'), '', 'username');
-               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                       $be_user_Array[$row['uid']] = $row;
-               }
-               $GLOBALS['TYPO3_DB']->sql_free_result($res);
-               return $be_user_Array;
+               return self::getRecordsSortedByTitle(
+                       GeneralUtility::trimExplode(',', $fields, TRUE),
+                       'be_users',
+                       'username',
+                       'AND pid=0 ' . $where
+               );
        }
 
        /**
@@ -1280,16 +1229,48 @@ class BackendUtility {
         *
         * @param string $fields Field list
         * @param string $where WHERE clause
-        * @return      array
+        * @return array
         */
        static public function getGroupNames($fields = 'title,uid', $where = '') {
-               $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)) {
-                       $be_group_Array[$row['uid']] = $row;
+               return self::getRecordsSortedByTitle(
+                       GeneralUtility::trimExplode(',', $fields, TRUE),
+                       'be_groups',
+                       'title',
+                       'AND pid=0 ' . $where
+               );
+       }
+
+       /**
+        * Returns an array of all non-deleted records of a table sorted by a given title field.
+        * The value of the title field will be replaced by the return value
+        * of self::getRecordTitle() before the sorting is performed.
+        *
+        * @param array $fields Fields to select
+        * @param string $table Table name
+        * @param string $titleField Field that will contain the record title
+        * @param string $where Additional where clause
+        * @return array Array of sorted records
+        */
+       static protected function getRecordsSortedByTitle(array $fields, $table, $titleField, $where = '') {
+               $fieldsIndex = array_flip($fields);
+               // Make sure the titleField is amongst the fields when getting sorted
+               $fieldsIndex[$titleField] = 1;
+
+               $result = array();
+               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, '1=1 ' . $where . self::deleteClause($table));
+               while ($record = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                       // store the uid, because it might be unset if it's not among the requested $fields
+                       $recordId = $record['uid'];
+                       $record[$titleField] = self::getRecordTitle($table, $record);
+
+                       // include only the requested fields in the result
+                       $result[$recordId] = array_intersect_key($record, $fieldsIndex);
                }
                $GLOBALS['TYPO3_DB']->sql_free_result($res);
-               return $be_group_Array;
+
+               // sort records by $sortField. This is not done in the query because the title might have been overwritten by
+               // self::getRecordTitle();
+               return \TYPO3\CMS\Core\Utility\ArrayUtility::sortArraysByKey($result, $titleField);
        }
 
        /**
@@ -1302,7 +1283,7 @@ class BackendUtility {
        static public 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'] ?: 0) . ')';
                }
                return self::getGroupNames($fields, $exQ);
        }
@@ -1391,7 +1372,7 @@ class BackendUtility {
         * @return string Formatted time
         */
        static public function date($tstamp) {
-               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int) $tstamp);
+               return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], (int)$tstamp);
        }
 
        /**
@@ -1499,17 +1480,35 @@ class BackendUtility {
                $sizeParts = array(64, 64);
                if ($size = trim($size)) {
                        $sizeParts = explode('x', $size . 'x' . $size);
-                       if (!intval($sizeParts[0])) {
+                       if (!(int)$sizeParts[0]) {
                                $size = '';
                        }
                }
                $thumbData = '';
                // FAL references
                if ($tcaConfig['type'] === 'inline') {
-                       $referenceUids = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'sys_file_reference', 'tablenames = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_file_reference') . ' AND fieldname=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($field, 'sys_file_reference') . ' AND uid_foreign=' . intval($row['uid']) . self::deleteClause('sys_file_reference') . self::versioningPlaceholderClause('sys_file_reference'));
+                       $sortingField = isset($tcaConfig['foreign_sortby']) ? $tcaConfig['foreign_sortby'] : '';
+                       $referenceUids = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
+                               'uid',
+                               'sys_file_reference',
+                               'tablenames = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_file_reference')
+                                       . ' AND fieldname=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($field, 'sys_file_reference')
+                                       . ' AND uid_foreign=' . (int)$row['uid']
+                                       . self::deleteClause('sys_file_reference')
+                                       . self::versioningPlaceholderClause('sys_file_reference'),
+                               '',
+                               $sortingField
+                       );
                        foreach ($referenceUids as $referenceUid) {
                                $fileReferenceObject = ResourceFactory::getInstance()->getFileReferenceObject($referenceUid['uid']);
                                $fileObject = $fileReferenceObject->getOriginalFile();
+
+                               if ($fileObject->isMissing()) {
+                                       $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
+                                       $thumbData .= $flashMessage->render();
+                                       continue;
+                               }
+
                                // Web image
                                if (GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileReferenceObject->getExtension())) {
                                        $imageUrl = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array(
@@ -1519,7 +1518,7 @@ class BackendUtility {
                                        $imgTag = '<img src="' . $imageUrl . '" alt="' . htmlspecialchars($fileReferenceObject->getName()) . '" />';
                                } else {
                                        // Icon
-                                       $imgTag = IconUtility::getSpriteIconForFile(strtolower($fileObject->getExtension()), array('title' => $fileObject->getName()));
+                                       $imgTag = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName()));
                                }
                                if ($linkInfoPopup) {
                                        $onClick = 'top.launchView(\'_FILE\',\'' . $fileObject->getUid() . '\',\'' . $backPath . '\'); return false;';
@@ -1540,19 +1539,31 @@ class BackendUtility {
                        foreach ($thumbs as $theFile) {
                                if ($theFile) {
                                        $fileName = trim($uploaddir . '/' . $theFile, '/');
-                                       $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
+                                       try {
+                                               /** @var File $fileObject */
+                                               $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($fileName);
+                                               if ($fileObject->isMissing()) {
+                                                       $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
+                                                       $thumbData .= $flashMessage->render();
+                                                       continue;
+                                               }
+                                       } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException $exception) {
+                                               /** @var \TYPO3\CMS\Core\Messaging\FlashMessage $flashMessage */
+                                               $flashMessage = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage',
+                                                       htmlspecialchars($exception->getMessage()),
+                                                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing', TRUE),
+                                                       \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR
+                                               );
+                                               $thumbData .= $flashMessage->render();
+                                               continue;
+                                       }
+
                                        $fileExtension = $fileObject->getExtension();
                                        if ($fileExtension == 'ttf' || GeneralUtility::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'], $fileExtension)) {
                                                $imageUrl = $fileObject->process(ProcessedFile::CONTEXT_IMAGEPREVIEW, array(
                                                        'width' => $sizeParts[0],
                                                        'height' => $sizeParts[1]
                                                ))->getPublicUrl(TRUE);
-                                               if (!$fileObject->checkActionPermission('read')) {
-                                                       /** @var \TYPO3\CMS\Core\Messaging\FlashMessage $flashMessage */
-                                                       $flashMessage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing_text') . ' <abbr title="' . htmlspecialchars($fileObject->getName()) . '">' . htmlspecialchars($fileObject->getName()) . '</abbr>', $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_missing'), FlashMessage::ERROR);
-                                                       $thumbData .= $flashMessage->render();
-                                                       continue;
-                                               }
                                                $image = '<img src="' . htmlspecialchars($imageUrl) . '" hspace="2" border="0" title="' . htmlspecialchars($fileObject->getName()) . '"' . $tparams . ' alt="" />';
                                                if ($linkInfoPopup) {
                                                        $onClick = 'top.launchView(\'_FILE\', \'' . $fileName . '\',\'\',\'' . $backPath . '\');return false;';
@@ -1562,7 +1573,7 @@ class BackendUtility {
                                                }
                                        } else {
                                                // Gets the icon
-                                               $fileIcon = IconUtility::getSpriteIconForFile($fileExtension, array('title' => $fileObject->getName()));
+                                               $fileIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName()));
                                                if ($linkInfoPopup) {
                                                        $onClick = 'top.launchView(\'_FILE\', \'' . $fileName . '\',\'\',\'' . $backPath . '\'); return false;';
                                                        $thumbData .= '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . $fileIcon . '</a> ';
@@ -1612,30 +1623,30 @@ class BackendUtility {
                if ($row['pid'] < 0) {
                        $parts[] = 'v#1.' . $row['t3ver_id'];
                }
-               switch ($row['t3ver_state']) {
-               case 1:
-                       $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
-                       break;
-               case 2:
-                       $parts[] = 'Deleted element!';
-                       break;
-               case 3:
-                       $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
-                       break;
-               case 4:
-                       $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
-                       break;
-               case -1:
-                       $parts[] = 'New element!';
-                       break;
+               switch (VersionState::cast($row['t3ver_state'])) {
+                       case new VersionState(VersionState::NEW_PLACEHOLDER):
+                               $parts[] = 'PLH WSID#' . $row['t3ver_wsid'];
+                               break;
+                       case new VersionState(VersionState::DELETE_PLACEHOLDER):
+                               $parts[] = 'Deleted element!';
+                               break;
+                       case new VersionState(VersionState::MOVE_PLACEHOLDER):
+                               $parts[] = 'NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
+                               break;
+                       case new VersionState(VersionState::MOVE_POINTER):
+                               $parts[] = 'OLD LOCATION (PNT) WSID#' . $row['t3ver_wsid'];
+                               break;
+                       case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
+                               $parts[] = 'New element!';
+                               break;
                }
                if ($row['doktype'] == PageRepository::DOKTYPE_LINK) {
                        $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['url']['label']) . ' ' . $row['url'];
                } elseif ($row['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
                        if ($perms_clause) {
-                               $label = self::getRecordPath(intval($row['shortcut']), $perms_clause, 20);
+                               $label = self::getRecordPath((int)$row['shortcut'], $perms_clause, 20);
                        } else {
-                               $row['shortcut'] = intval($row['shortcut']);
+                               $row['shortcut'] = (int)$row['shortcut'];
                                $lRec = self::getRecordWSOL('pages', $row['shortcut'], 'title');
                                $label = $lRec['title'] . ' (id=' . $row['shortcut'] . ')';
                        }
@@ -1645,9 +1656,9 @@ class BackendUtility {
                        $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['shortcut']['label']) . ' ' . $label;
                } elseif ($row['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
                        if ($perms_clause) {
-                               $label = self::getRecordPath(intval($row['mount_pid']), $perms_clause, 20);
+                               $label = self::getRecordPath((int)$row['mount_pid'], $perms_clause, 20);
                        } else {
-                               $lRec = self::getRecordWSOL('pages', intval($row['mount_pid']), 'title');
+                               $lRec = self::getRecordWSOL('pages', (int)$row['mount_pid'], 'title');
                                $label = $lRec['title'];
                        }
                        $parts[] = $GLOBALS['LANG']->sL($GLOBALS['TCA']['pages']['columns']['mount_pid']['label']) . ' ' . $label;
@@ -1707,22 +1718,22 @@ class BackendUtility {
                                $out .= ' - v#1.' . $row['t3ver_id'];
                        }
                        if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
-                               switch ($row['t3ver_state']) {
-                               case 1:
-                                       $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
-                                       break;
-                               case 2:
-                                       $out .= ' - Deleted element!';
-                                       break;
-                               case 3:
-                                       $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
-                                       break;
-                               case 4:
-                                       $out .= ' - OLD LOCATION (PNT)  WSID#' . $row['t3ver_wsid'];
-                                       break;
-                               case -1:
-                                       $out .= ' - New element!';
-                                       break;
+                               switch (VersionState::cast($row['t3ver_state'])) {
+                                       case new VersionState(VersionState::NEW_PLACEHOLDER):
+                                               $out .= ' - PLH WSID#' . $row['t3ver_wsid'];
+                                               break;
+                                       case new VersionState(VersionState::DELETE_PLACEHOLDER):
+                                               $out .= ' - Deleted element!';
+                                               break;
+                                       case new VersionState(VersionState::MOVE_PLACEHOLDER):
+                                               $out .= ' - NEW LOCATION (PLH) WSID#' . $row['t3ver_wsid'];
+                                               break;
+                                       case new VersionState(VersionState::MOVE_POINTER):
+                                               $out .= ' - OLD LOCATION (PNT)  WSID#' . $row['t3ver_wsid'];
+                                               break;
+                                       case new VersionState(VersionState::NEW_PLACEHOLDER_VERSION):
+                                               $out .= ' - New element!';
+                                               break;
                                }
                        }
                        // Hidden
@@ -1755,7 +1766,7 @@ class BackendUtility {
                        // 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)) {
+                               if ((string)$v[1] === (string)$key) {
                                        return $v[0];
                                }
                        }
@@ -1772,7 +1783,7 @@ class BackendUtility {
         * @return string Label for item entry
         */
        static public function getLabelFromItemListMerged($pageId, $table, $column, $key) {
-               $pageTsConfig = self::getPagesTSconfig($pageId);
+               $pageTsConfig = static::getPagesTSconfig($pageId);
                $label = '';
                if (is_array($pageTsConfig['TCEFORM.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.']) && is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.'])) {
                        if (is_array($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.']) && isset($pageTsConfig['TCEFORM.'][$table . '.'][$column . '.']['addItems.'][$key])) {
@@ -1836,7 +1847,7 @@ class BackendUtility {
                        return $GLOBALS['TCA'][$table]['columns'][$col]['label'];
                }
                if ($printAllWrap) {
-                       \TYPO3\CMS\Core\Utility\GeneralUtility::deprecationLog('The third parameter of getItemLabel() is deprecated with TYPO3 CMS 6.2 and will be removed two versions later.');
+                       GeneralUtility::deprecationLog('The third parameter of getItemLabel() is deprecated with TYPO3 CMS 6.2 and will be removed two versions later.');
                        $parts = explode('|', $printAllWrap);
                        return $parts[0] . $col . $parts[1];
                }
@@ -1850,7 +1861,7 @@ class BackendUtility {
         *
         * @param string $table Table name, present in TCA
         * @param array $row Row from table
-        * @param boolean $prep If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
+        * @param boolean $prep If set, result is prepared for output: The output is cropped to a limited length (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
         * @param boolean $forceResult If set, the function always returns an output. If no value is found for the title, '[No title]' is returned (localized).
         * @return string
         */
@@ -1870,15 +1881,15 @@ class BackendUtility {
                        } else {
                                // No userFunc: Build label
                                $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 = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
+                               if ($GLOBALS['TCA'][$table]['ctrl']['label_alt'] && ($GLOBALS['TCA'][$table]['ctrl']['label_alt_force'] || (string)$t === '')) {
+                                       $altFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], TRUE);
                                        $tA = array();
                                        if (!empty($t)) {
                                                $tA[] = $t;
                                        }
                                        foreach ($altFields as $fN) {
                                                $t = trim(strip_tags($row[$fN]));
-                                               if (strcmp($t, '')) {
+                                               if ((string)$t !== '') {
                                                        $t = self::getProcessedValue($table, $fN, $t, 0, 0, FALSE, $row['uid']);
                                                        if (!$GLOBALS['TCA'][$table]['ctrl']['label_alt_force']) {
                                                                break;
@@ -1896,7 +1907,7 @@ class BackendUtility {
                                if ($prep) {
                                        $t = self::getRecordTitlePrep($t);
                                }
-                               if (!strcmp(trim($t), '')) {
+                               if (trim($t) === '') {
                                        $t = self::getNoRecordTitle($prep);
                                }
                        }
@@ -1905,7 +1916,7 @@ class BackendUtility {
        }
 
        /**
-        * Crops a title string to a limited lenght and if it really was cropped, wrap it in a <span title="...">|</span>,
+        * Crops a title string to a limited length and if it really was cropped, wrap it in a <span title="...">|</span>,
         * which offers a tooltip with the original title when moving mouse over it.
         *
         * @param string $title The title string to be cropped
@@ -1933,7 +1944,7 @@ class BackendUtility {
         * @return string Localized [No title] string
         */
        static public function getNoRecordTitle($prep = FALSE) {
-               $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', 1) . ']';
+               $noTitle = '[' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.no_title', TRUE) . ']';
                if ($prep) {
                        $noTitle = '<em>' . $noTitle . '</em>';
                }
@@ -1977,35 +1988,43 @@ class BackendUtility {
                        }
                        $l = '';
                        switch ((string) $theColConf['type']) {
-                       case 'radio':
-                               $l = self::getLabelFromItemlist($table, $col, $value);
-                               $l = $GLOBALS['LANG']->sL($l);
-                               break;
-                       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'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
-                                                       foreach (GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f) {
-                                                               $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
-                                                       }
-                                                       $MMfield = join(',', $MMfields);
-                                               }
-                                               /** @var $dbGroup \TYPO3\CMS\Core\Database\RelationHandler */
-                                               $dbGroup = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\RelationHandler');
-                                               $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
-                                               $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
-                                               if (is_array($selectUids) && count($selectUids) > 0) {
-                                                       $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, ' . $MMfield, $theColConf['foreign_table'], 'uid IN (' . implode(',', $selectUids) . ')' . self::deleteClause($theColConf['foreign_table']));
-                                                       while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
-                                                               $mmlA[] = $noRecordLookup ? $MMrow['uid'] : self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult);
+                               case 'radio':
+                                       $l = self::getLabelFromItemlist($table, $col, $value);
+                                       $l = $GLOBALS['LANG']->sL($l);
+                                       break;
+                               case 'inline':
+                               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'] . '.' . $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label']);
+                                                               foreach (GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$theColConf['foreign_table']]['ctrl']['label_alt'], TRUE) as $f) {
+                                                                       $MMfields[] = $theColConf['foreign_table'] . '.' . $f;
+                                                               }
+                                                               $MMfield = join(',', $MMfields);
                                                        }
-                                                       $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
-                                                       if (is_array($mmlA)) {
-                                                               $l = implode('; ', $mmlA);
+                                                       /** @var $dbGroup \TYPO3\CMS\Core\Database\RelationHandler */
+                                                       $dbGroup = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Database\\RelationHandler');
+                                                       $dbGroup->start($value, $theColConf['foreign_table'], $theColConf['MM'], $uid, $table, $theColConf);
+                                                       $selectUids = $dbGroup->tableArray[$theColConf['foreign_table']];
+                                                       if (is_array($selectUids) && count($selectUids) > 0) {
+                                                               $MMres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, ' . $MMfield, $theColConf['foreign_table'], 'uid IN (' . implode(',', $selectUids) . ')' . self::deleteClause($theColConf['foreign_table']));
+                                                               while ($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres)) {
+                                                                       // Keep sorting of $selectUids
+                                                                       $mmlA[array_search($MMrow['uid'], $selectUids)] = $noRecordLookup ?
+                                                                               $MMrow['uid'] :
+                                                                               self::getRecordTitle($theColConf['foreign_table'], $MMrow, FALSE, $forceResult);
+                                                               }
+                                                               $GLOBALS['TYPO3_DB']->sql_free_result($MMres);
+                                                               ksort($mmlA);
+                                                               if (is_array($mmlA)) {
+                                                                       $l = implode('; ', $mmlA);
+                                                               } else {
+                                                                       $l = 'N/A';
+                                                               }
                                                        } else {
                                                                $l = 'N/A';
                                                        }
@@ -2013,119 +2032,119 @@ class BackendUtility {
                                                        $l = 'N/A';
                                                }
                                        } else {
-                                               $l = 'N/A';
-                                       }
-                               } else {
-                                       $l = self::getLabelsFromItemsList($table, $col, $value);
-                                       if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
-                                               if ($noRecordLookup) {
-                                                       $l = $value;
-                                               } else {
-                                                       $rParts = GeneralUtility::trimExplode(',', $value, 1);
-                                                       $lA = array();
-                                                       foreach ($rParts as $rVal) {
-                                                               $rVal = intval($rVal);
-                                                               if ($rVal > 0) {
-                                                                       $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);
-                                                               } else {
-                                                                       $lA[] = $rVal ? '[' . $rVal . '!]' : '';
+                                               $l = self::getLabelsFromItemsList($table, $col, $value);
+                                               if ($theColConf['foreign_table'] && !$l && $GLOBALS['TCA'][$theColConf['foreign_table']]) {
+                                                       if ($noRecordLookup) {
+                                                               $l = $value;
+                                                       } else {
+                                                               $rParts = GeneralUtility::trimExplode(',', $value, TRUE);
+                                                               $lA = array();
+                                                               foreach ($rParts as $rVal) {
+                                                                       $rVal = (int)$rVal;
+                                                                       if ($rVal > 0) {
+                                                                               $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);
+                                                                       } else {
+                                                                               $lA[] = $rVal ? '[' . $rVal . '!]' : '';
+                                                                       }
                                                                }
+                                                               $l = implode(', ', $lA);
                                                        }
-                                                       $l = implode(', ', $lA);
+                                               }
+                                               if (empty($l) && !empty($value)) {
+                                                       // Use plain database value when label is empty
+                                                       $l = $value;
                                                }
                                        }
-                               }
-                               break;
-                       case 'group':
-                               // resolve the titles for DB records
-                               if ($theColConf['internal_type'] === 'db') {
-                                       $finalValues = array();
-                                       $relationTableName = $theColConf['allowed'];
-                                       $explodedValues = GeneralUtility::trimExplode(',', $value, TRUE);
+                                       break;
+                               case 'group':
+                                       // resolve the titles for DB records
+                                       if ($theColConf['internal_type'] === 'db') {
+                                               $finalValues = array();
+                                               $relationTableName = $theColConf['allowed'];
+                                               $explodedValues = GeneralUtility::trimExplode(',', $value, TRUE);
 
-                                       foreach ($explodedValues as $explodedValue) {
+                                               foreach ($explodedValues as $explodedValue) {
 
-                                               if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
-                                                       $relationTableNameForField = $relationTableName;
-                                               } else {
-                                                       list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
+                                                       if (MathUtility::canBeInterpretedAsInteger($explodedValue)) {
+                                                               $relationTableNameForField = $relationTableName;
+                                                       } else {
+                                                               list($relationTableNameForField, $explodedValue) = self::splitTable_Uid($explodedValue);
+                                                       }
+
+                                                       $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
+                                                       $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
                                                }
 
-                                               $relationRecord = static::getRecordWSOL($relationTableNameForField, $explodedValue);
-                                               $finalValues[] = static::getRecordTitle($relationTableNameForField, $relationRecord);
+                                               $l = implode(', ', $finalValues);
+                                       } else {
+                                               $l = implode(', ', GeneralUtility::trimExplode(',', $value, TRUE));
                                        }
-
-                                       $l = implode(', ', $finalValues);
-                               } else {
-                                       $l = implode(', ', GeneralUtility::trimExplode(',', $value, TRUE));
-                               }
-                               break;
-                       case 'check':
-                               if (!is_array($theColConf['items']) || count($theColConf['items']) == 1) {
-                                       $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xlf:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xlf:no');
-                               } else {
-                                       $lA = array();
-                                       foreach ($theColConf['items'] as $key => $val) {
-                                               if ($value & pow(2, $key)) {
-                                                       $lA[] = $GLOBALS['LANG']->sL($val[0]);
+                                       break;
+                               case 'check':
+                                       if (!is_array($theColConf['items']) || count($theColConf['items']) == 1) {
+                                               $l = $value ? $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xlf:yes') : $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_common.xlf:no');
+                                       } else {
+                                               $lA = array();
+                                               foreach ($theColConf['items'] as $key => $val) {
+                                                       if ($value & pow(2, $key)) {
+                                                               $lA[] = $GLOBALS['LANG']->sL($val[0]);
+                                                       }
                                                }
+                                               $l = implode(', ', $lA);
                                        }
-                                       $l = implode(', ', $lA);
-                               }
-                               break;
-                       case 'input':
-                               // Hide value 0 for dates, but show it for everything else
-                               if (isset($value)) {
-                                       if (GeneralUtility::inList($theColConf['eval'], 'date')) {
-                                               // Handle native date field
-                                               if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
-                                                       $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
-                                                       $emptyValue = $dateTimeFormats['date']['empty'];
-                                                       $value = $value !== $emptyValue ? strtotime($value) : 0;
-                                               }
-                                               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.xlf:labels.minutesHoursDaysYears')) . ')';
-                                               }
-                                       } elseif (GeneralUtility::inList($theColConf['eval'], 'time')) {
-                                               if (!empty($value)) {
-                                                       $l = self::time($value, FALSE);
-                                               }
-                                       } elseif (GeneralUtility::inList($theColConf['eval'], 'timesec')) {
-                                               if (!empty($value)) {
-                                                       $l = self::time($value);
-                                               }
-                                       } elseif (GeneralUtility::inList($theColConf['eval'], 'datetime')) {
-                                               // Handle native date/time field
-                                               if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
-                                                       $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
-                                                       $emptyValue = $dateTimeFormats['datetime']['empty'];
-                                                       $value = $value !== $emptyValue ? strtotime($value) : 0;
-                                               }
-                                               if (!empty($value)) {
-                                                       $l = self::datetime($value);
+                                       break;
+                               case 'input':
+                                       // Hide value 0 for dates, but show it for everything else
+                                       if (isset($value)) {
+                                               if (GeneralUtility::inList($theColConf['eval'], 'date')) {
+                                                       // Handle native date field
+                                                       if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'date') {
+                                                               $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
+                                                               $emptyValue = $dateTimeFormats['date']['empty'];
+                                                               $value = $value !== $emptyValue ? strtotime($value) : 0;
+                                                       }
+                                                       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.xlf:labels.minutesHoursDaysYears')) . ')';
+                                                       }
+                                               } elseif (GeneralUtility::inList($theColConf['eval'], 'time')) {
+                                                       if (!empty($value)) {
+                                                               $l = self::time($value, FALSE);
+                                                       }
+                                               } elseif (GeneralUtility::inList($theColConf['eval'], 'timesec')) {
+                                                       if (!empty($value)) {
+                                                               $l = self::time($value);
+                                                       }
+                                               } elseif (GeneralUtility::inList($theColConf['eval'], 'datetime')) {
+                                                       // Handle native date/time field
+                                                       if (isset($theColConf['dbType']) && $theColConf['dbType'] === 'datetime') {
+                                                               $dateTimeFormats = $GLOBALS['TYPO3_DB']->getDateTimeFormats($table);
+                                                               $emptyValue = $dateTimeFormats['datetime']['empty'];
+                                                               $value = $value !== $emptyValue ? strtotime($value) : 0;
+                                                       }
+                                                       if (!empty($value)) {
+                                                               $l = self::datetime($value);
+                                                       }
+                                               } else {
+                                                       $l = $value;
                                                }
-                                       } else {
+                                       }
+                                       break;
+                               case 'flex':
+                                       $l = strip_tags($value);
+                                       break;
+                               default:
+                                       if ($defaultPassthrough) {
                                                $l = $value;
+                                       } elseif ($theColConf['MM']) {
+                                               $l = 'N/A';
+                                       } elseif ($value) {
+                                               $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
                                        }
-                               }
-                               break;
-                       case 'flex':
-                               $l = strip_tags($value);
-                               break;
-                       default:
-                               if ($defaultPassthrough) {
-                                       $l = $value;
-                               } elseif ($theColConf['MM']) {
-                                       $l = 'N/A';
-                               } elseif ($value) {
-                                       $l = GeneralUtility::fixed_lgd_cs(strip_tags($value), 200);
-                               }
-                               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')) {
@@ -2193,7 +2212,7 @@ class BackendUtility {
         * @return string File icon filename
         */
        static public function getFileIcon($ext) {
-               return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
+               return $GLOBALS['FILEICONS'][$ext] ?: $GLOBALS['FILEICONS']['default'];
        }
 
        /**
@@ -2212,7 +2231,7 @@ class BackendUtility {
                        $fields[] = $prefix . $GLOBALS['TCA'][$table]['ctrl']['label'];
                }
                if ($GLOBALS['TCA'][$table]['ctrl']['label_alt']) {
-                       $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], 1);
+                       $secondFields = GeneralUtility::trimExplode(',', $GLOBALS['TCA'][$table]['ctrl']['label_alt'], TRUE);
                        foreach ($secondFields as $fieldN) {
                                $fields[] = $prefix . $fieldN;
                        }
@@ -2267,27 +2286,26 @@ class BackendUtility {
                                        $lines[$fname] = '<strong>' . htmlspecialchars($config[1]) . '</strong><br />';
                                        $lines[$fname] .= $config[2] . '<br />';
                                        switch ($config[0]) {
-                                       case 'string':
+                                               case 'string':
 
-                                       case 'short':
-                                               $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(($config[0] == 'short' ? 24 : 48)) . ' />';
-                                               break;
-                                       case 'check':
-                                               $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 = '';
-                                               break;
-                                       case 'select':
-                                               $opt = array();
-                                               foreach ($config[3] as $k => $v) {
-                                                       $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
-                                               }
-                                               $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
-                                               break;
-                                       default:
-                                               debug($config);
-                                               break;
+                                               case 'short':
+                                                       $formEl = '<input type="text" name="' . $dataPrefix . '[' . $fname . ']" value="' . $params[$fname] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(($config[0] == 'short' ? 24 : 48)) . ' />';
+                                                       break;
+                                               case 'check':
+                                                       $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 = '';
+                                                       break;
+                                               case 'select':
+                                                       $opt = array();
+                                                       foreach ($config[3] as $k => $v) {
+                                                               $opt[] = '<option value="' . htmlspecialchars($k) . '"' . ($params[$fname] == $k ? ' selected="selected"' : '') . '>' . htmlspecialchars($v) . '</option>';
+                                                       }
+                                                       $formEl = '<select name="' . $dataPrefix . '[' . $fname . ']">' . implode('', $opt) . '</select>';
+                                                       break;
+                                               default:
+                                                       debug($config);
                                        }
                                        $lines[$fname] .= $formEl;
                                        $lines[$fname] .= '<br /><br />';
@@ -2490,11 +2508,11 @@ class BackendUtility {
         * It will detect the correct domain name if needed and provide the link with the right back path.
         * Also it will re-use any window already open.
         *
-        * @param integer $pageUid Page id
+        * @param integer $pageUid Page UID
         * @param string $backPath Must point back to TYPO3_mainDir (where the site is assumed to be one level above)
         * @param array $rootLine If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
         * @param string $anchorSection Optional anchor to the URL
-        * @param string $alternativeUrl An alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
+        * @param string $alternativeUrl An alternative URL that, if set, will ignore other parameters except $switchFocus: It will return the window.open command wrapped around this URL!
         * @param string $additionalGetVars Additional GET variables.
         * @param boolean $switchFocus If TRUE, then the preview window will gain the focus.
         * @return string
@@ -2504,7 +2522,11 @@ class BackendUtility {
                if ($alternativeUrl) {
                        $viewScript = $alternativeUrl;
                }
-               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])) {
+
+               if (
+                       isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
+                       && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'])
+               ) {
                        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['viewOnClickClass'] as $funcRef) {
                                $hookObj = GeneralUtility::getUserObj($funcRef);
                                if (method_exists($hookObj, 'preProcess')) {
@@ -2512,9 +2534,33 @@ class BackendUtility {
                                }
                        }
                }
+
+               if ($alternativeUrl) {
+                       $previewUrl = $viewScript;
+               } else {
+                       $previewUrl = self::createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript);
+               }
+
+               $onclickCode = 'var previewWin = window.open(\'' . $previewUrl . '\',\'newTYPO3frontendWindow\');' . ($switchFocus ? 'previewWin.focus();' : '');
+               return $onclickCode;
+       }
+
+       /**
+        * Creates the view-on-click preview URL without any alternative URL.
+        *
+        * @param integer $pageUid Page UID
+        * @param array $rootLine If rootline is supplied, the function will look for the first found domain record and use that URL instead
+        * @param string $anchorSection Optional anchor to the URL
+        * @param string $additionalGetVars Additional GET variables.
+        * @param string $viewScript The path to the script used to view the page
+        *
+        * @return string The preview URL
+        */
+       static protected function createPreviewUrl($pageUid, $rootLine, $anchorSection, $additionalGetVars, $viewScript) {
                // Look if a fixed preview language should be added:
                $viewLanguageOrder = $GLOBALS['BE_USER']->getTSConfigVal('options.view.languageOrder');
-               if (strlen($viewLanguageOrder)) {
+
+               if (strlen($viewLanguageOrder) > 0) {
                        $suffix = '';
                        // Find allowed languages (if none, all are allowed!)
                        if (!$GLOBALS['BE_USER']->user['admin'] && strlen($GLOBALS['BE_USER']->groupData['allowed_languages'])) {
@@ -2538,18 +2584,19 @@ class BackendUtility {
                        // Add it
                        $additionalGetVars .= $suffix;
                }
+
                // Check a mount point needs to be previewed
                $sys_page = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
                $sys_page->init(FALSE);
                $mountPointInfo = $sys_page->getMountPointInfo($pageUid);
+
                if ($mountPointInfo && $mountPointInfo['overlay']) {
                        $pageUid = $mountPointInfo['mount_pid'];
                        $additionalGetVars .= '&MP=' . $mountPointInfo['MPvar'];
                }
                $viewDomain = self::getViewDomain($pageUid, $rootLine);
-               $previewUrl = $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
-               $onclickCode = 'var previewWin = window.open(\'' . $previewUrl . '\',\'newTYPO3frontendWindow\');' . ($switchFocus ? 'previewWin.focus();' : '');
-               return $onclickCode;
+
+               return $viewDomain . $viewScript . $pageUid . $additionalGetVars . $anchorSection;
        }
 
        /**
@@ -2576,7 +2623,12 @@ class BackendUtility {
                        if ($page['url_scheme'] == \TYPO3\CMS\Core\Utility\HttpUtility::SCHEME_HTTPS || $page['url_scheme'] == 0 && GeneralUtility::getIndpEnv('TYPO3_SSL')) {
                                $protocol = 'https';
                        }
-                       $domainName = self::firstDomainRecord($rootLine);
+                       $previewDomainConfig = $GLOBALS['BE_USER']->getTSConfig('TCEMAIN.previewDomain', self::getPagesTSconfig($pageId));
+                       if ($previewDomainConfig['value']) {
+                               $domainName = $previewDomainConfig['value'];
+                       } else {
+                               $domainName = self::firstDomainRecord($rootLine);
+                       }
                        if ($domainName) {
                                $domain = $domainName;
                        } else {
@@ -2589,7 +2641,7 @@ class BackendUtility {
                                $domain = rtrim(GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), '/');
                        }
                        // Append port number if lockSSLPort is not the standard port 443
-                       $portNumber = intval($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']);
+                       $portNumber = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
                        if ($portNumber > 0 && $portNumber !== 443 && $portNumber < 65536 && $protocol === 'https') {
                                $domain .= ':' . strval($portNumber);
                        }
@@ -2606,10 +2658,13 @@ class BackendUtility {
         * @return array
         */
        static public function getModTSconfig($id, $TSref) {
-               $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, self::getPagesTSconfig($id));
+               $pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref, static::getPagesTSconfig($id));
                $BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
-               $modTSconfig = GeneralUtility::array_merge_recursive_overrule($pageTS_modOptions, $BE_USER_modOptions);
-               return $modTSconfig;
+               if (is_null($BE_USER_modOptions['value'])) {
+                       unset($BE_USER_modOptions['value']);
+               }
+               \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($pageTS_modOptions, $BE_USER_modOptions);
+               return $pageTS_modOptions;
        }
 
        /**
@@ -2629,21 +2684,21 @@ class BackendUtility {
                if (!is_array($menuItems) || count($menuItems) <= 1) {
                        return '';
                }
-
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
-               $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
                if (!$script) {
-                       $script = basename(PATH_thisScript);
-                       $mainParams .= GeneralUtility::_GET('M') ? '&M=' . rawurlencode(GeneralUtility::_GET('M')) : '';
+                       $scriptUrl = self::getModuleUrl(GeneralUtility::_GET('M'), $mainParams) . $addparams;
+               } else {
+                       $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
+                       $scriptUrl = $script . '?' . $mainParams . $addparams;
                }
                $options = array();
                foreach ($menuItems as $value => $label) {
-                       $options[] = '<option value="' . htmlspecialchars($value) . '"' . (!strcmp($currentValue, $value) ? ' selected="selected"' : '') . '>' . GeneralUtility::deHSCentities(htmlspecialchars($label)) . '</option>';
+                       $options[] = '<option value="' . htmlspecialchars($value) . '"' . ((string)$currentValue === (string)$value ? ' selected="selected"' : '') . '>' . htmlspecialchars($label, ENT_COMPAT, 'UTF-8', FALSE) . '</option>';
                }
                if (count($options)) {
-                       $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+this.options[this.selectedIndex].value,this);';
+                       $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+this.options[this.selectedIndex].value,this);';
                        return '
 
                                <!-- Function Menu of module -->
@@ -2672,12 +2727,13 @@ class BackendUtility {
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
-               $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
                if (!$script) {
-                       $script = basename(PATH_thisScript);
-                       $mainParams .= GeneralUtility::_GET('M') ? '&M=' . rawurlencode(GeneralUtility::_GET('M')) : '';
+                       $scriptUrl = self::getModuleUrl(GeneralUtility::_GET('M'), $mainParams) . $addparams;
+               } else {
+                       $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
+                       $scriptUrl = $script . '?' . $mainParams . $addparams;
                }
-               $onClick = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($script . '?' . $mainParams . $addparams . '&' . $elementName . '=') . '+(this.checked?1:0),this);';
+               $onClick = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+(this.checked?1:0),this);';
 
                return
                '<input' .
@@ -2708,12 +2764,13 @@ class BackendUtility {
                if (!is_array($mainParams)) {
                        $mainParams = array('id' => $mainParams);
                }
-               $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
                if (!$script) {
-                       $script = basename(PATH_thisScript);
-                       $mainParams .= GeneralUtility::_GET('M') ? '&M=' . rawurlencode(GeneralUtility::_GET('M')) : '';
+                       $scriptUrl = self::getModuleUrl(GeneralUtility::_GET('M'), $mainParams) . $addparams;
+               } else {
+                       $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
+                       $scriptUrl = $script . '?' . $mainParams . $addparams;
                }
-               $onChange = 'jumpToUrl(\'' . $script . '?' . $mainParams . $addparams . '&' . $elementName . '=\'+escape(this.value),this);';
+               $onChange = 'jumpToUrl(' . GeneralUtility::quoteJSvalue($scriptUrl . '&' . $elementName . '=') . '+escape(this.value),this);';
                return '<input type="text"' . $GLOBALS['TBE_TEMPLATE']->formWidth($size) . ' name="' . $elementName . '" value="' . htmlspecialchars($currentValue) . '" onchange="' . htmlspecialchars($onChange) . '" />';
        }
 
@@ -2791,25 +2848,24 @@ class BackendUtility {
                                $signals[] = $params['JScode'];
                        } else {
                                switch ($set) {
-                               case 'updatePageTree':
-                                       $signals[] = '
-                                                       if (top && top.TYPO3.Backend.NavigationContainer.PageTree) {
-                                                               top.TYPO3.Backend.NavigationContainer.PageTree.refreshTree();
-                                                       }
-                                               ';
-                                       break;
-                               case 'updateFolderTree':
-                                       $signals[] = '
-                                                       if (top && top.TYPO3.Backend.NavigationIframe) {
-                                                               top.TYPO3.Backend.NavigationIframe.refresh();
-                                                       }';
-                                       break;
-                               case 'updateModuleMenu':
-                                       $signals[] = '
-                                                       if (top && top.TYPO3.ModuleMenu.App) {
-                                                               top.TYPO3.ModuleMenu.App.refreshMenu();
-                                                       }';
-                                       break;
+                                       case 'updatePageTree':
+                                               $signals[] = '
+                                                               if (top && top.TYPO3.Backend.NavigationContainer.PageTree) {
+                                                                       top.TYPO3.Backend.NavigationContainer.PageTree.refreshTree();
+                                                               }
+                                                       ';
+                                               break;
+                                       case 'updateFolderTree':
+                                               $signals[] = '
+                                                               if (top && top.TYPO3.Backend.NavigationIframe) {
+                                                                       top.TYPO3.Backend.NavigationIframe.refresh();
+                                                               }';
+                                               break;
+                                       case 'updateModuleMenu':
+                                               $signals[] = '
+                                                               if (top && top.TYPO3.ModuleMenu.App) {
+                                                                       top.TYPO3.ModuleMenu.App.refreshMenu();
+                                                               }';
                                }
                        }
                }
@@ -2848,12 +2904,12 @@ class BackendUtility {
                                        if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key])) {
                                                if (is_array($CHANGED_SETTINGS[$key])) {
                                                        $serializedSettings = serialize($CHANGED_SETTINGS[$key]);
-                                                       if (strcmp($settings[$key], $serializedSettings)) {
+                                                       if ((string)$settings[$key] !== $serializedSettings) {
                                                                $settings[$key] = $serializedSettings;
                                                                $changed = 1;
                                                        }
                                                } else {
-                                                       if (strcmp($settings[$key], $CHANGED_SETTINGS[$key])) {
+                                                       if ((string)$settings[$key] !== (string)$CHANGED_SETTINGS[$key]) {
                                                                $settings[$key] = $CHANGED_SETTINGS[$key];
                                                                $changed = 1;
                                                        }
@@ -2893,21 +2949,48 @@ class BackendUtility {
         * @param array $urlParameters URL parameters that should be added as key value pairs
         * @param boolean/string $backPathOverride backpath that should be used instead of the global $BACK_PATH
         * @param boolean $returnAbsoluteUrl If set to TRUE, the URL returned will be absolute, $backPathOverride will be ignored in this case
-        * @return boolean/string Calculated URL or FALSE
+        * @return string Calculated URL
         */
        static public function getModuleUrl($moduleName, $urlParameters = array(), $backPathOverride = FALSE, $returnAbsoluteUrl = FALSE) {
-               if (!$GLOBALS['BE_USER']->check('modules', $moduleName)) {
-                       return FALSE;
-               }
                if ($backPathOverride === FALSE) {
-                       $backPath = $GLOBALS['BACK_PATH'];
+                       $backPath = isset($GLOBALS['BACK_PATH']) ? $GLOBALS['BACK_PATH'] : '';
                } else {
                        $backPath = $backPathOverride;
                }
-               $allUrlParameters = array();
-               $allUrlParameters['M'] = $moduleName;
-               $allUrlParameters = array_merge($allUrlParameters, $urlParameters);
-               $url = 'mod.php?' . GeneralUtility::implodeArrayForUrl('', $allUrlParameters, '', TRUE);
+               $urlParameters = array(
+                       'M' => $moduleName,
+                       'moduleToken' => \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('moduleCall', $moduleName)
+               ) + $urlParameters;
+               $url = 'mod.php?' . ltrim(GeneralUtility::implodeArrayForUrl('', $urlParameters, '', TRUE, TRUE), '&');
+               if ($returnAbsoluteUrl) {
+                       return GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $url;
+               } else {
+                       return $backPath . $url;
+               }
+       }
+
+       /**
+        * Returns the Ajax URL for a given AjaxID including a CSRF token.
+        *
+        * @param string $ajaxIdentifier Identifier of the AJAX callback
+        * @param array $urlParameters URL parameters that should be added as key value pairs
+        * @param bool/string $backPathOverride Backpath that should be used instead of the global $BACK_PATH
+        * @param bool $returnAbsoluteUrl If set to TRUE, the URL returned will be absolute, $backPathOverride will be ignored in this case
+        * @return string Calculated URL
+        */
+       static public function getAjaxUrl($ajaxIdentifier, array $urlParameters = array(), $backPathOverride = FALSE, $returnAbsoluteUrl = FALSE) {
+               if ($backPathOverride) {
+                       $backPath = $backPathOverride;
+               } else {
+                       $backPath = isset($GLOBALS['BACK_PATH']) ? $GLOBALS['BACK_PATH'] : '';
+               }
+               $additionalUrlParameters = array(
+                       'ajaxID' => $ajaxIdentifier
+               );
+               if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['AJAX'][$ajaxIdentifier]['csrfTokenCheck'])) {
+                       $additionalUrlParameters['ajaxToken'] = \TYPO3\CMS\Core\FormProtection\FormProtectionFactory::get()->generateToken('ajaxCall', $ajaxIdentifier);
+               }
+               $url = 'ajax.php?' . ltrim(GeneralUtility::implodeArrayForUrl('', ($additionalUrlParameters + $urlParameters), '', TRUE, TRUE), '&');
                if ($returnAbsoluteUrl) {
                        return GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $url;
                } else {
@@ -2925,7 +3008,7 @@ class BackendUtility {
         */
        static public function getListViewLink($urlParameters = array(), $linkTitle = '', $linkText = '') {
                $url = self::getModuleUrl('web_list', $urlParameters);
-               if (!ExtensionManagementUtility::isLoaded('recordlist') || $url === FALSE) {
+               if ($url === FALSE) {
                        return '';
                } else {
                        return '<a href="' . htmlspecialchars($url) . '" title="' . htmlspecialchars($linkTitle) . '">' . IconUtility::getSpriteIcon('actions-system-list-open') . htmlspecialchars($linkText) . '</a>';
@@ -2961,7 +3044,7 @@ class BackendUtility {
         */
        static public function lockRecords($table = '', $uid = 0, $pid = 0) {
                if (isset($GLOBALS['BE_USER']->user['uid'])) {
-                       $user_id = intval($GLOBALS['BE_USER']->user['uid']);
+                       $user_id = (int)$GLOBALS['BE_USER']->user['uid'];
                        if ($table && $uid) {
                                $fields_values = array(
                                        'userid' => $user_id,
@@ -2974,7 +3057,7 @@ class BackendUtility {
                                );
                                $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
                        } else {
-                               $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid=' . intval($user_id));
+                               $GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid=' . (int)$user_id);
                        }
                }
        }
@@ -2992,7 +3075,7 @@ class BackendUtility {
        static public function isRecordLocked($table, $uid) {
                if (!is_array($GLOBALS['LOCKED_RECORDS'])) {
                        $GLOBALS['LOCKED_RECORDS'] = array();
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_lockedrecords', 'sys_lockedrecords.userid<>' . intval($GLOBALS['BE_USER']->user['uid']) . '
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_lockedrecords', 'sys_lockedrecords.userid<>' . (int)$GLOBALS['BE_USER']->user['uid'] . '
                                                                AND sys_lockedrecords.tstamp > ' . ($GLOBALS['EXEC_TIME'] - 2 * 3600));
                        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                                // Get the type of the user that locked this record:
@@ -3035,28 +3118,7 @@ class BackendUtility {
                $foreign_table = $fieldValue['config'][$prefix . 'foreign_table'];
                $rootLevel = $GLOBALS['TCA'][$foreign_table]['ctrl']['rootLevel'];
                $fTWHERE = $fieldValue['config'][$prefix . 'foreign_table_where'];
-               if (strstr($fTWHERE, '###REC_FIELD_')) {
-                       $fTWHERE_parts = explode('###REC_FIELD_', $fTWHERE);
-                       foreach ($fTWHERE_parts as $kk => $vv) {
-                               if ($kk) {
-                                       $fTWHERE_subpart = explode('###', $vv, 2);
-                                       if (substr($fTWHERE_parts[0], -1) === '\'' && $fTWHERE_subpart[1][0] === '\'') {
-                                               $fTWHERE_parts[$kk] = $GLOBALS['TYPO3_DB']->quoteStr($TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]], $foreign_table) . $fTWHERE_subpart[1];
-                                       } else {
-                                               $fTWHERE_parts[$kk] = $GLOBALS['TYPO3_DB']->fullQuoteStr($TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]], $foreign_table) . $fTWHERE_subpart[1];
-                                       }
-                               }
-                       }
-                       $fTWHERE = implode('', $fTWHERE_parts);
-               }
-               $fTWHERE = str_replace('###CURRENT_PID###', intval($TSconfig['_CURRENT_PID']), $fTWHERE);
-               $fTWHERE = str_replace('###THIS_UID###', intval($TSconfig['_THIS_UID']), $fTWHERE);
-               $fTWHERE = str_replace('###THIS_CID###', intval($TSconfig['_THIS_CID']), $fTWHERE);
-               $fTWHERE = str_replace('###STORAGE_PID###', intval($TSconfig['_STORAGE_PID']), $fTWHERE);
-               $fTWHERE = str_replace('###SITEROOT###', intval($TSconfig['_SITEROOT']), $fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_ID###', intval($TSconfig[$field]['PAGE_TSCONFIG_ID']), $fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###', $GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']), $fTWHERE);
-               $fTWHERE = str_replace('###PAGE_TSCONFIG_STR###', $GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table), $fTWHERE);
+               $fTWHERE = static::replaceMarkersInWhereClause($fTWHERE, $foreign_table, $field, $TSconfig);
                $wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
                // rootLevel = -1 means that elements can be on the rootlevel OR on any page (pid!=-1)
                // rootLevel = 0 means that elements are not allowed on root level
@@ -3099,6 +3161,65 @@ class BackendUtility {
        }
 
        /**
+        * Replaces all special markers in a where clause.
+        * Special markers are:
+        * ###REC_FIELD_[field name]###
+        * ###THIS_UID### - is current element uid (zero if new).
+        * ###THIS_CID###
+        * ###CURRENT_PID### - is the current page id (pid of the record).
+        * ###STORAGE_PID###
+        * ###SITEROOT###
+        * ###PAGE_TSCONFIG_ID### - a value you can set from Page TSconfig dynamically.
+        * ###PAGE_TSCONFIG_IDLIST### - a value you can set from Page TSconfig dynamically.
+        * ###PAGE_TSCONFIG_STR### - a value you can set from Page TSconfig dynamically.
+        *
+        * @param string $whereClause Where clause with markers
+        * @param string $table Name of the table of the current record row
+        * @param string $field Field name
+        * @param array $tsConfig TSconfig array from which to get further configuration settings for the field name
+        * @return string
+        */
+       static public function replaceMarkersInWhereClause($whereClause, $table, $field = '', $tsConfig = array()) {
+               if (strstr($whereClause, '###REC_FIELD_')) {
+                       $whereClauseParts = explode('###REC_FIELD_', $whereClause);
+                       foreach ($whereClauseParts as $key => $value) {
+                               if ($key) {
+                                       $whereClauseSubarts = explode('###', $value, 2);
+                                       if (substr($whereClauseParts[0], -1) === '\'' && $whereClauseSubarts[1][0] === '\'') {
+                                               $whereClauseParts[$key] = $GLOBALS['TYPO3_DB']->quoteStr($tsConfig['_THIS_ROW'][$whereClauseSubarts[0]], $table) . $whereClauseSubarts[1];
+                                       } else {
+                                               $whereClauseParts[$key] = $GLOBALS['TYPO3_DB']->fullQuoteStr($tsConfig['_THIS_ROW'][$whereClauseSubarts[0]], $table) . $whereClauseSubarts[1];
+                                       }
+                               }
+                       }
+                       $whereClause = implode('', $whereClauseParts);
+               }
+               return str_replace (
+                       array (
+                               '###CURRENT_PID###',
+                               '###THIS_UID###',
+                               '###THIS_CID###',
+                               '###STORAGE_PID###',
+                               '###SITEROOT###',
+                               '###PAGE_TSCONFIG_ID###',
+                               '###PAGE_TSCONFIG_IDLIST###',
+                               '###PAGE_TSCONFIG_STR###'
+                       ),
+                       array(
+                               (int)$tsConfig['_CURRENT_PID'],
+                               (int)$tsConfig['_THIS_UID'],
+                               (int)$tsConfig['_THIS_CID'],
+                               (int)$tsConfig['_STORAGE_PID'],
+                               (int)$tsConfig['_SITEROOT'],
+                               (int)$tsConfig[$field]['PAGE_TSCONFIG_ID'],
+                               $GLOBALS['TYPO3_DB']->cleanIntList($tsConfig[$field]['PAGE_TSCONFIG_IDLIST']),
+                               $GLOBALS['TYPO3_DB']->quoteStr($tsConfig[$field]['PAGE_TSCONFIG_STR'], $table)
+                       ),
+                       $whereClause
+               );
+       }
+
+       /**
         * Returns TSConfig for the TCEFORM object in Page TSconfig.
         * Used in TCEFORMs
         *
@@ -3112,17 +3233,16 @@ class BackendUtility {
                $typeVal = self::getTCAtypeValue($table, $row);
                // Get main config for the table
                list($TScID, $cPid) = self::getTSCpid($table, $row['uid'], $row['pid']);
-               $rootLine = self::BEgetRootLine($TScID, '', TRUE);
                if ($TScID >= 0) {
-                       $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.' . $table, self::getPagesTSconfig($TScID, $rootLine));
+                       $tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.' . $table, self::getPagesTSconfig($TScID));
                        if (is_array($tempConf['properties'])) {
                                foreach ($tempConf['properties'] as $key => $val) {
                                        if (is_array($val)) {
                                                $fieldN = substr($key, 0, -1);
                                                $res[$fieldN] = $val;
                                                unset($res[$fieldN]['types.']);
-                                               if (strcmp($typeVal, '') && is_array($val['types.'][$typeVal . '.'])) {
-                                                       $res[$fieldN] = GeneralUtility::array_merge_recursive_overrule($res[$fieldN], $val['types.'][$typeVal . '.']);
+                                               if ((string)$typeVal !== '' && is_array($val['types.'][$typeVal . '.'])) {
+                                                       \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($res[$fieldN], $val['types.'][$typeVal . '.']);
                                                }
                                        }
                                }
@@ -3133,12 +3253,13 @@ class BackendUtility {
                $res['_THIS_CID'] = $row['cid'];
                // So the row will be passed to foreign_table_where_query()
                $res['_THIS_ROW'] = $row;
+               $rootLine = self::BEgetRootLine($TScID, '', TRUE);
                foreach ($rootLine as $rC) {
                        if (!$res['_STORAGE_PID']) {
-                               $res['_STORAGE_PID'] = intval($rC['storage_pid']);
+                               $res['_STORAGE_PID'] = (int)$rC['storage_pid'];
                        }
                        if (!$res['_SITEROOT']) {
-                               $res['_SITEROOT'] = $rC['is_siteroot'] ? intval($rC['uid']) : 0;
+                               $res['_SITEROOT'] = $rC['is_siteroot'] ? (int)$rC['uid'] : 0;
                        }
                }
                return $res;
@@ -3160,7 +3281,7 @@ class BackendUtility {
        static public function getTSconfig_pidValue($table, $uid, $pid) {
                // If pid is an integer this takes precedence in our lookup.
                if (MathUtility::canBeInterpretedAsInteger($pid)) {
-                       $thePidValue = intval($pid);
+                       $thePidValue = (int)$pid;
                        // If ref to another record, look that record up.
                        if ($thePidValue < 0) {
                                $pidRec = self::getRecord($table, abs($thePidValue), 'pid');
@@ -3229,13 +3350,11 @@ class BackendUtility {
         * @return string Domain name, if found.
         */
        static public function firstDomainRecord($rootLine) {
-               if (ExtensionManagementUtility::isLoaded('cms')) {
-                       foreach ($rootLine as $row) {
-                               $dRec = self::getRecordsByField('sys_domain', 'pid', $row['uid'], ' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
-                               if (is_array($dRec)) {
-                                       $dRecord = reset($dRec);
-                                       return rtrim($dRecord['domainName'], '/');
-                               }
+               foreach ($rootLine as $row) {
+                       $dRec = self::getRecordsByField('sys_domain', 'pid', $row['uid'], ' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
+                       if (is_array($dRec)) {
+                               $dRecord = reset($dRec);
+                               return rtrim($dRecord['domainName'], '/');
                        }
                }
        }
@@ -3248,21 +3367,19 @@ class BackendUtility {
         * @return array Domain record, if found
         */
        static public function getDomainStartPage($domain, $path = '') {
-               if (ExtensionManagementUtility::isLoaded('cms')) {
-                       $domain = explode(':', $domain);
-                       $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
-                       // Path is calculated.
-                       $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
-                       // Stuff
-                       $domain .= $path;
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
-                               pages.uid=sys_domain.pid
-                               AND sys_domain.hidden=0
-                               AND (sys_domain.domainName=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain') . ' OR sys_domain.domainName=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(($domain . '/'), 'sys_domain') . ')' . self::deleteClause('pages'), '', '', '1');
-                       $result = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
-                       return $result;
-               }
+               $domain = explode(':', $domain);
+               $domain = strtolower(preg_replace('/\\.$/', '', $domain[0]));
+               // Path is calculated.
+               $path = trim(preg_replace('/\\/[^\\/]*$/', '', $path));
+               // Stuff
+               $domain .= $path;
+               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
+                       pages.uid=sys_domain.pid
+                       AND sys_domain.hidden=0
+                       AND (sys_domain.domainName=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain') . ' OR sys_domain.domainName=' . $GLOBALS['TYPO3_DB']->fullQuoteStr(($domain . '/'), 'sys_domain') . ')' . self::deleteClause('pages'), '', '', '1');
+               $result = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+               $GLOBALS['TYPO3_DB']->sql_free_result($res);
+               return $result;
        }
 
        /**
@@ -3280,10 +3397,10 @@ class BackendUtility {
                $thisFieldConf = $RTEprop['config.'][$table . '.'][$field . '.'];
                if (is_array($thisFieldConf)) {
                        unset($thisFieldConf['types.']);
-                       $thisConfig = GeneralUtility::array_merge_recursive_overrule($thisConfig, $thisFieldConf);
+                       \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($thisConfig, $thisFieldConf);
                }
                if ($type && is_array($RTEprop['config.'][$table . '.'][$field . '.']['types.'][$type . '.'])) {
-                       $thisConfig = GeneralUtility::array_merge_recursive_overrule($thisConfig, $RTEprop['config.'][$table . '.'][$field . '.']['types.'][$type . '.']);
+                       \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($thisConfig, $RTEprop['config.'][$table . '.'][$field . '.']['types.'][$type . '.']);
                }
                return $thisConfig;
        }
@@ -3364,12 +3481,12 @@ class BackendUtility {
                        return FALSE;
                }
                // Otherwise parse the list:
-               $keyList = GeneralUtility::trimExplode(',', $parserList, 1);
+               $keyList = GeneralUtility::trimExplode(',', $parserList, TRUE);
                $output = array();
                foreach ($keyList as $val) {
                        $reg = array();
                        if (preg_match('/^([[:alnum:]_-]+)\\[(.*)\\]$/', $val, $reg)) {
-                               $output[$reg[1]] = GeneralUtility::trimExplode(';', $reg[2], 1);
+                               $output[$reg[1]] = GeneralUtility::trimExplode(';', $reg[2], TRUE);
                        } else {
                                $output[$val] = '';
                        }
@@ -3388,7 +3505,7 @@ class BackendUtility {
                foreach ($GLOBALS['TBE_MODULES'] as $mkey => $list) {
                        $loaded[$mkey] = 1;
                        if (!is_array($list) && trim($list)) {
-                               $subList = GeneralUtility::trimExplode(',', $list, 1);
+                               $subList = GeneralUtility::trimExplode(',', $list, TRUE);
                                foreach ($subList as $skey) {
                                        $loaded[$mkey . '_' . $skey] = 1;
                                }
@@ -3411,13 +3528,13 @@ class BackendUtility {
                        // Look up the path:
                        if ($table == '_FILE') {
                                if (GeneralUtility::isFirstPartOfStr($ref, PATH_site)) {
-                                       $ref = substr($ref, strlen(PATH_site));
+                                       $ref = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($ref);
                                        $condition = 'ref_string=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($ref, 'sys_refindex');
                                } else {
                                        return '';
                                }
                        } else {
-                               $condition = 'ref_uid=' . intval($ref);
+                               $condition = 'ref_uid=' . (int)$ref;
                        }
                        $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', 'sys_refindex', 'ref_table=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_refindex') . ' AND ' . $condition . ' AND deleted=0');
                }
@@ -3434,7 +3551,7 @@ class BackendUtility {
         */
        static public function translationCount($table, $ref, $msg = '') {
                if (empty($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) && $GLOBALS['TCA'][$table]['ctrl']['languageField'] && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] && !$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) {
-                       $where = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . intval($ref) . ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '<>0';
+                       $where = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'] . '=' . (int)$ref . ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['languageField'] . '<>0';
                        if (!empty($GLOBALS['TCA'][$table]['ctrl']['delete'])) {
                                $where .= ' AND ' . $GLOBALS['TCA'][$table]['ctrl']['delete'] . '=0';
                        }
@@ -3469,7 +3586,7 @@ class BackendUtility {
                                $outputRows[] = $row;
                        } else {
                                // Select UID version:
-                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid=' . intval($uid) . ($includeDeletedRecords ? '' : self::deleteClause($table)));
+                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid=' . (int)$uid . ($includeDeletedRecords ? '' : self::deleteClause($table)));
                                // Add rows to output array:
                                if ($res) {
                                        $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
@@ -3482,7 +3599,7 @@ class BackendUtility {
                                }
                        }
                        // Select all offline versions of record:
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'pid=-1 AND uid<>' . intval($uid) . ' AND t3ver_oid=' . intval($uid) . ($workspace != 0 ? ' AND t3ver_wsid=' . intval($workspace) : '') . ($includeDeletedRecords ? '' : self::deleteClause($table)), '', 't3ver_id DESC');
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'pid=-1 AND uid<>' . (int)$uid . ' AND t3ver_oid=' . (int)$uid . ($workspace != 0 ? ' AND t3ver_wsid=' . (int)$workspace : '') . ($includeDeletedRecords ? '' : self::deleteClause($table)), '', 't3ver_id DESC');
                        // Add rows to output array:
                        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                                $outputRows[] = $row;
@@ -3527,7 +3644,7 @@ class BackendUtility {
                                        }
                                }
                                // If ID of current online version is found, look up the PID value of that:
-                               if ($oid && ($ignoreWorkspaceMatch || !strcmp((int) $wsid, $GLOBALS['BE_USER']->workspace))) {
+                               if ($oid && ($ignoreWorkspaceMatch || (int)$wsid === (int)$GLOBALS['BE_USER']->workspace)) {
                                        $oidRec = self::getRecord($table, $oid, 'pid');
                                        if (is_array($oidRec)) {
                                                $rr['_ORIG_pid'] = $rr['pid'];
@@ -3576,16 +3693,16 @@ class BackendUtility {
                                // If version was found, swap the default record with that one.
                                if (is_array($wsAlt)) {
                                        // Check if this is in move-state:
-                                       if ($previewMovePlaceholders && !$movePldSwap && ($table == 'pages' || (int) $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) && $unsetMovePointers) {
+                                       if ($previewMovePlaceholders && !$movePldSwap && ($table == 'pages' || (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) && $unsetMovePointers) {
                                                // Only for WS ver 2... (moving)
                                                // If t3ver_state is not found, then find it... (but we like best if it is here...)
                                                if (!isset($wsAlt['t3ver_state'])) {
                                                        $stateRec = self::getRecord($table, $wsAlt['uid'], 't3ver_state');
-                                                       $state = $stateRec['t3ver_state'];
+                                                       $versionState = VersionState::cast($stateRec['t3ver_state']);
                                                } else {
-                                                       $state = $wsAlt['t3ver_state'];
+                                                       $versionState = VersionState::cast($wsAlt['t3ver_state']);
                                                }
-                                               if ((int) $state === 4) {
+                                               if ($versionState->equals(VersionState::MOVE_POINTER)) {
                                                        // TODO: Same problem as frontend in versionOL(). See TODO point there.
                                                        $row = FALSE;
                                                        return;
@@ -3612,14 +3729,15 @@ class BackendUtility {
                                        $row['_MOVE_PLH_uid'] = $orig_uid;
                                        $row['_MOVE_PLH_pid'] = $orig_pid;
                                        // For display; To make the icon right for the placeholder vs. the original
-                                       $row['t3ver_state'] = 3;
+                                       $row['t3ver_state'] = (string)new VersionState(VersionState::MOVE_PLACEHOLDER);
                                }
                        }
                }
        }
 
        /**
-        * Checks if record is a move-placeholder (t3ver_state==3) and if so it will set $row to be the pointed-to live record (and return TRUE)
+        * Checks if record is a move-placeholder (t3ver_state==VersionState::MOVE_PLACEHOLDER) and if so
+        * it will set $row to be the pointed-to live record (and return TRUE)
         *
         * @param string $table Table name
         * @param array $row Row (passed by reference) - must be online record!
@@ -3628,18 +3746,18 @@ class BackendUtility {
         */
        static public function movePlhOL($table, &$row) {
                // Only for WS ver 2... (moving)
-               if ($table == 'pages' || (int) $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
+               if ($table == 'pages' || (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
                        // If t3ver_move_id or t3ver_state is not found, then find it... (but we like best if it is here...)
                        if (!isset($row['t3ver_move_id']) || !isset($row['t3ver_state'])) {
                                $moveIDRec = self::getRecord($table, $row['uid'], 't3ver_move_id, t3ver_state');
                                $moveID = $moveIDRec['t3ver_move_id'];
-                               $state = $moveIDRec['t3ver_state'];
+                               $versionState = VersionState::cast($moveIDRec['t3ver_state']);
                        } else {
                                $moveID = $row['t3ver_move_id'];
-                               $state = $row['t3ver_state'];
+                               $versionState = VersionState::cast($row['t3ver_state']);
                        }
                        // Find pointed-to record.
-                       if ((int) $state === 3 && $moveID) {
+                       if ($versionState->equals(VersionState::MOVE_PLACEHOLDER) && $moveID) {
                                if ($origRow = self::getRecord($table, $moveID, implode(',', array_keys($row)))) {
                                        $row = $origRow;
                                        return TRUE;
@@ -3662,7 +3780,7 @@ class BackendUtility {
                if (ExtensionManagementUtility::isLoaded('version')) {
                        if ($workspace !== 0 && $GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
                                // Select workspace version of record:
-                               $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow($fields, $table, 'pid=-1 AND ' . 't3ver_oid=' . intval($uid) . ' AND ' . 't3ver_wsid=' . intval($workspace) . self::deleteClause($table));
+                               $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow($fields, $table, 'pid=-1 AND ' . 't3ver_oid=' . (int)$uid . ' AND ' . 't3ver_wsid=' . (int)$workspace . self::deleteClause($table));
                                if (is_array($row)) {
                                        return $row;
                                }
@@ -3713,8 +3831,8 @@ class BackendUtility {
         */
        static public function versioningPlaceholderClause($table) {
                if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
-                       $currentWorkspace = intval($GLOBALS['BE_USER']->workspace);
-                       return ' AND (' . $table . '.t3ver_state <= 0 OR ' . $table . '.t3ver_wsid = ' . $currentWorkspace . ')';
+                       $currentWorkspace = (int)$GLOBALS['BE_USER']->workspace;
+                       return ' AND (' . $table . '.t3ver_state <= ' . new VersionState(VersionState::DEFAULT_STATE) . ' OR ' . $table . '.t3ver_wsid = ' . $currentWorkspace . ')';
                }
        }
 
@@ -3731,7 +3849,7 @@ class BackendUtility {
                        if (is_null($workspaceId)) {
                                $workspaceId = $GLOBALS['BE_USER']->workspace;
                        }
-                       $workspaceId = intval($workspaceId);
+                       $workspaceId = (int)$workspaceId;
                        $pidOperator = $workspaceId === 0 ? '!=' : '=';
                        $whereClause = ' AND ' . $table . '.t3ver_wsid=' . $workspaceId . ' AND ' . $table . '.pid' . $pidOperator . '-1';
                }
@@ -3752,7 +3870,7 @@ class BackendUtility {
                                if ($tableName != 'pages' && $cfg['ctrl']['versioningWS']) {
                                        // Select all records from this table in the database from the workspace
                                        // This joins the online version with the offline version as tables A and B
-                                       $output[$tableName] = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('B.uid as live_uid, A.uid as offline_uid', $tableName . ' A,' . $tableName . ' B', 'A.pid=-1' . ' AND B.pid=' . intval($pageId) . ' AND A.t3ver_wsid=' . intval($workspace) . ' AND A.t3ver_oid=B.uid' . self::deleteClause($tableName, 'A') . self::deleteClause($tableName, 'B'));
+                                       $output[$tableName] = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('B.uid as live_uid, A.uid as offline_uid', $tableName . ' A,' . $tableName . ' B', 'A.pid=-1' . ' AND B.pid=' . (int)$pageId . ' AND A.t3ver_wsid=' . (int)$workspace . ' AND A.t3ver_oid=B.uid' . self::deleteClause($tableName, 'A') . self::deleteClause($tableName, 'B'));
                                        if (!is_array($output[$tableName]) || !count($output[$tableName])) {
                                                unset($output[$tableName]);
                                        }
@@ -3787,9 +3905,14 @@ class BackendUtility {
         */
        static public function getMovePlaceholder($table, $uid, $fields = '*') {
                $workspace = $GLOBALS['BE_USER']->workspace;
-               if ($workspace !== 0 && $GLOBALS['TCA'][$table] && (int) $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
+               if ($workspace !== 0 && $GLOBALS['TCA'][$table] && (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
                        // Select workspace version of record:
-                       $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow($fields, $table, 'pid<>-1 AND ' . 't3ver_state=3 AND ' . 't3ver_move_id=' . intval($uid) . ' AND ' . 't3ver_wsid=' . intval($workspace) . self::deleteClause($table));
+                       $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
+                               $fields,
+                               $table,
+                               'pid<>-1 AND t3ver_state=' . new VersionState(VersionState::MOVE_PLACEHOLDER) . ' AND t3ver_move_id='
+                                       . (int)$uid . ' AND t3ver_wsid=' . (int)$workspace . self::deleteClause($table)
+                       );
                        if (is_array($row)) {
                                return $row;
                        }
@@ -3844,141 +3967,12 @@ class BackendUtility {
         * These warnings are only displayed to admin users
         *
         * @return string Rendered messages as HTML
+        * @deprecated since 6.2 and is removed two versions later. This was transferred to ext:aboutmodules, do not use any longer!
+        * @see \TYPO3\CMS\Aboutmodules\Controller\ModulesController
         */
        static public function displayWarningMessages() {
-               if ($GLOBALS['BE_USER']->isAdmin()) {
-                       // Array containing warnings that must be displayed
-                       $warnings = array();
-                       // If this file exists and it isn't older than one hour, the Install Tool is enabled
-                       $enableInstallToolFile = PATH_site . 'typo3conf/ENABLE_INSTALL_TOOL';
-                       // Cleanup command, if set
-                       $cmd = GeneralUtility::_GET('adminWarning_cmd');
-                       switch ($cmd) {
-                       case 'remove_ENABLE_INSTALL_TOOL':
-                               if (unlink($enableInstallToolFile)) {
-                                       unset($enableInstallToolFile);
-                               }
-                               break;
-                       }
-                       // Check if the Install Tool Password is still default: joh316
-                       if ($GLOBALS['TYPO3_CONF_VARS']['BE']['installToolPassword'] == md5('joh316')) {
-                               $url = 'install/index.php?redirect_url=index.php' . urlencode('?TYPO3_INSTALL[type]=about');
-                               $warnings['install_password'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.install_password'), '<a href="' . $url . '">', '</a>');
-                       }
-                       // Check if there is still a default user 'admin' with password 'password' (MD5sum = 5f4dcc3b5aa765d61d8327deb882cf99)
-                       $where_clause = 'username=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('admin', 'be_users') . ' AND password=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('5f4dcc3b5aa765d61d8327deb882cf99', 'be_users') . self::deleteClause('be_users');
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, username, password', 'be_users', $where_clause);
-                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                               $url = 'alt_doc.php?returnUrl=' . urlencode('mod.php?M=help_AboutmodulesAboutmodules') . '&edit[be_users][' . $row['uid'] . ']=edit';
-                               $warnings['backend_admin'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.backend_admin'), '<a href="' . htmlspecialchars($url) . '">', '</a>');
-                       }
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
-                       // Check whether the file ENABLE_INSTALL_TOOL contains the string "KEEP_FILE" which permanently unlocks the install tool
-                       if (is_file($enableInstallToolFile) && trim(file_get_contents($enableInstallToolFile)) === 'KEEP_FILE') {
-                               $url = GeneralUtility::getIndpEnv('TYPO3_REQUEST_SCRIPT') . '?adminWarning_cmd=remove_ENABLE_INSTALL_TOOL';
-                               $warnings['install_enabled'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.install_enabled'), '<span style="white-space:nowrap;">' . $enableInstallToolFile . '</span>');
-                               $warnings['install_enabled'] .= ' <a href="' . $url . '">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.install_enabled_cmd') . '</a>';
-                       }
-                       // Check if the encryption key is empty
-                       if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] == '') {
-                               $url = 'install/index.php?redirect_url=index.php' . urlencode('?TYPO3_INSTALL[type]=config#set_encryptionKey');
-                               $warnings['install_encryption'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.install_encryption'), '<a href="' . $url . '">', '</a>');
-                       }
-                       // Check if parts of fileDenyPattern were removed which is dangerous on Apache
-                       $defaultParts = GeneralUtility::trimExplode('|', FILE_DENY_PATTERN_DEFAULT, TRUE);
-                       $givenParts = GeneralUtility::trimExplode('|', $GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'], TRUE);
-                       $result = array_intersect($defaultParts, $givenParts);
-                       if ($defaultParts !== $result) {
-                               $warnings['file_deny_pattern'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_deny_pattern_partsNotPresent'), '<br /><pre>' . htmlspecialchars(FILE_DENY_PATTERN_DEFAULT) . '</pre><br />');
-                       }
-                       // Check if fileDenyPattern allows to upload .htaccess files which is dangerous on Apache
-                       if ($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'] != FILE_DENY_PATTERN_DEFAULT && GeneralUtility::verifyFilenameAgainstDenyPattern('.htaccess')) {
-                               $warnings['file_deny_htaccess'] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.file_deny_htaccess');
-                       }
-                       // Check if there are still updates to perform
-                       if (!GeneralUtility::compat_version(TYPO3_branch)) {
-                               $url = 'install/index.php?redirect_url=index.php' . urlencode('?TYPO3_INSTALL[type]=update');
-                               $warnings['install_update'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.install_update'), '<a href="' . $url . '">', '</a>');
-                       }
-                       // Check if sys_refindex is empty
-                       $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', 'sys_refindex');
-                       $registry = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Registry');
-                       $lastRefIndexUpdate = $registry->get('core', 'sys_refindex_lastUpdate');
-                       if (!$count && $lastRefIndexUpdate) {
-                               $url =  static::getModuleUrl('system_dbint') . '&id=0&SET[function]=refindex';
-                               $warnings['backend_reference'] = sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.backend_reference_index'), '<a href="' . $url . '">', '</a>', self::dateTime($lastRefIndexUpdate));
-                       }
-                       // Check for memcached if configured
-                       $memCacheUse = FALSE;
-                       if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'])) {
-                               foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'] as $table => $conf) {
-                                       if (is_array($conf)) {
-                                               foreach ($conf as $key => $value) {
-                                                       if (!is_array($value) && $value === 'TYPO3\\CMS\\Core\\Cache\\Backend\\MemcachedBackend') {
-                                                               $servers = $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations'][$table]['options']['servers'];
-                                                               $memCacheUse = TRUE;
-                                                               break;
-                                                       }
-                                               }
-                                       }
-                               }
-                               if ($memCacheUse) {
-                                       $failed = array();
-                                       $defaultPort = ini_get('memcache.default_port');
-                                       if (function_exists('memcache_connect')) {
-                                               if (is_array($servers)) {
-                                                       foreach ($servers as $testServer) {
-                                                               $configuredServer = $testServer;
-                                                               if (substr($testServer, 0, 7) == 'unix://') {
-                                                                       $host = $testServer;
-                                                                       $port = 0;
-                                                               } else {
-                                                                       if (substr($testServer, 0, 6) === 'tcp://') {
-                                                                               $testServer = substr($testServer, 6);
-                                                                       }
-                                                                       if (strstr($testServer, ':') !== FALSE) {
-                                                                               list($host, $port) = explode(':', $testServer, 2);
-                                                                       } else {
-                                                                               $host = $testServer;
-                                                                               $port = $defaultPort;
-                                                                       }
-                                                               }
-                                                               $memcache_obj = @memcache_connect($host, $port);
-                                                               if ($memcache_obj != NULL) {
-                                                                       memcache_close($memcache_obj);
-                                                               } else {
-                                                                       $failed[] = $configuredServer;
-                                                               }
-                                                       }
-                                               }
-                                       }
-                                       if (count($failed) > 0) {
-                                               $warnings['memcached'] = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.memcache_not_usable') . '<br/>' . implode(', ', $failed);
-                                       }
-                               }
-                       }
-                       // Hook for additional warnings
-                       if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['displayWarningMessages'])) {
-                               foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['displayWarningMessages'] as $classRef) {
-                                       $hookObj = GeneralUtility::getUserObj($classRef);
-                                       if (method_exists($hookObj, 'displayWarningMessages_postProcess')) {
-                                               $hookObj->displayWarningMessages_postProcess($warnings);
-                                       }
-                               }
-                       }
-                       if (count($warnings)) {
-                               if (count($warnings) > 1) {
-                                       $securityWarnings = '<ul><li>' . implode('</li><li>', $warnings) . '</li></ul>';
-                               } else {
-                                       $securityWarnings = '<p>' . implode('', $warnings) . '</p>';
-                               }
-                               $securityMessage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', $securityWarnings, $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:warning.header'), FlashMessage::ERROR);
-                               $content = '<div style="margin: 20px 0px;">' . $securityMessage->render() . '</div>';
-                               unset($warnings);
-                               return $content;
-                       }
-               }
-               return '<p>&nbsp;</p>';
+               GeneralUtility::logDeprecatedFunction();
+               return '';
        }
 
        /**
@@ -4043,14 +4037,13 @@ class BackendUtility {
                        $interface = $GLOBALS['BE_USER']->uc['interfaceSetup'];
                }
                switch ($interface) {
-               case 'frontend':
-                       $script = '../.';
-                       break;
-               case 'backend':
+                       case 'frontend':
+                               $script = '../.';
+                               break;
+                       case 'backend':
 
-               default:
-                       $script = 'backend.php';
-                       break;
+                       default:
+                               $script = 'backend.php';
                }
                return $script;
        }
@@ -4105,6 +4098,3 @@ class BackendUtility {
        }
 
 }
-
-
-?>