[BUGFIX] Throw HttpStatusExceptions in tslib_fe
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / class.tslib_fe.php
index 158da87..89e06a1 100644 (file)
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
-*  (c) 1999-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
+*  (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
  * The class is instantiated as $GLOBALS['TSFE'] in index_ts.php.
  * The use of this class should be inspired by the order of function calls as found in index_ts.php.
  *
- * $Id$
- * Revised for TYPO3 3.6 June/2003 by Kasper Skaarhoj
+ * Revised for TYPO3 3.6 June/2003 by Kasper Skårhøj
  * XHTML compliant
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  */
 
 /**
  * (This index is automatically created/updated by the extension "extdeveval")
  *
  */
-
-require_once (PATH_t3lib.'class.t3lib_lock.php');
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
 /**
  * Main frontend class, instantiated in the index_ts.php script as the global object TSFE
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage tslib
  */
- class tslib_fe        {
+ class tslib_fe {
 
                // CURRENT PAGE:
        var $id='';                                                     // The page id (int)
        var $type='';                                           // RO The type (int)
        var $idParts=array();                           // Loaded with the id, exploded by ','
        var $cHash='';                                          // The submitted cHash
-       var $no_cache='';                                       // Page will not be cached. Write only true. Never clear value (some other code might have reasons to set it true)
+       var $no_cache='';                                       // Page will not be cached. Write only TRUE. Never clear value (some other code might have reasons to set it TRUE)
        var $rootLine='';                                       // The rootLine (all the way to tree root, not only the current site!) (array)
        var $page='';                                           // The pagerecord (array)
        var $contentPid=0;                                      // This will normally point to the same value as id, but can be changed to point to another page from which content will then be displayed instead.
-       protected $originalShortcutPage = null; // gets set when we are processing a page of type shortcut in the early stages opf init.php when we do not know about languages yet, used later in init.php to determine the correct shortcut in case a translation changes the shortcut target (array)
+       protected $originalShortcutPage = NULL; // gets set when we are processing a page of type shortcut in the early stages opf init.php when we do not know about languages yet, used later in init.php to determine the correct shortcut in case a translation changes the shortcut target (array)
 
        /**
         * sys_page-object, pagefunctions
@@ -253,6 +230,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        var $beUserLogin='';                            // Flag that indicates if a Backend user is logged in!
        var $workspacePreview='';                       // Integer, that indicates which workspace is being previewed.
        var $loginAllowedInBranch = TRUE;       // Shows whether logins are allowed in branch
+       var $loginAllowedInBranch_mode = '';    // Shows specific mode (all or groups)
        var $ADMCMD_preview_BEUSER_uid = 0;     // Integer, set to backend user ID to initialize when keyword-based preview is used.
 
                // PREVIEW
@@ -274,7 +252,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @var t3lib_TStemplate
         */
        var $tmpl='';
-       var $cacheTimeOutDefault='';            // Is set to the time-to-live time of cached pages. If false, default is 60*60*24, which is 24 hours.
+       var $cacheTimeOutDefault = FALSE;               // Is set to the time-to-live time of cached pages. If FALSE, default is 60*60*24, which is 24 hours.
        var $cacheContentFlag = 0;                      // Set internally if cached content is fetched from the database
        var $cacheExpires=0;                            // Set to the expire time of cached content
        var $isClientCachable=FALSE;            // Set if cache headers allowing caching are sent.
@@ -419,6 +397,11 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        var $pages_lockObj;                                     // Locking object for accessing "cache_pages"
 
        /**
+        * @var t3lib_PageRenderer
+        */
+       protected $pageRenderer;
+
+       /**
         * the page cache object, use this to save pages to the cache and to
         * retrieve them again
         *
@@ -427,6 +410,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        protected $pageCache;
        protected $pageCacheTags = array();
 
+               // caches the timestamp until a cache entry for this page is valid
+       protected $getCacheTimeoutCache = NULL;
 
        /**
         * Class constructor
@@ -445,7 +430,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         * @see index_ts.php
         */
-       function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='')   {
+       function __construct($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='')        {
 
                        // Setting some variables:
                $this->TYPO3_CONF_VARS = $TYPO3_CONF_VARS;
@@ -457,7 +442,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $GLOBALS['TT']->setTSlogMessage($warning,2);
                        } else {
                                $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "'.t3lib_div::getIndpEnv('TYPO3_REQUEST_URL').'"';
-                               $this->no_cache = $no_cache ? 1 : 0;
+                               $this->disableCache();
                        }
                        t3lib_div::sysLog($warning, 'cms', 2);
                }
@@ -478,18 +463,9 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        }
                }
 
-               $this->initCaches();
-       }
-
-       /**
-        * Connect to MySQL database
-        * May exit after outputting an error message or some JavaScript redirecting to the install tool.
-        *
-        * @return      void
-        * @deprecated since TYPO3 3.8 - Use connectToDB() instead!
-        */
-       function connectToMySQL()       {
-               $this->connectToDB();
+               if (TYPO3_UseCachingFramework) {
+                       $this->initCaches();
+               }
        }
 
        /**
@@ -499,46 +475,31 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function connectToDB()  {
-               if ($GLOBALS['TYPO3_DB']->sql_pconnect(TYPO3_db_host, TYPO3_db_username, TYPO3_db_password))    {
-                       if (!TYPO3_db)  {
-                               $this->printError('No database selected','Database Error');
-                                       // Redirects to the Install Tool:
-                               echo '<script type="text/javascript">
-                                               /*<![CDATA[*/
-                                       window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
-                                               /*]]>*/
-                                       </script>';
-                               exit;
-                       } elseif (!$GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db))       {
-                               if ($this->checkPageUnavailableHandler())       {
-                                       $this->pageUnavailableAndExit('Cannot connect to the current database, "'.TYPO3_db.'"');
+               if (!TYPO3_db) {
+                               // jump into Install Tool 1-2-3 mode, if no DB name is defined (fresh installation)
+                       t3lib_utility_Http::redirect(TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316');
+               }
+
+                       // sql_pconnect() can throw an Exception in case of some failures, or it returns FALSE
+               $link = $GLOBALS['TYPO3_DB']->sql_pconnect(TYPO3_db_host, TYPO3_db_username, TYPO3_db_password);
+               if ($link !== FALSE) {
+                               // Connection to DB server ok, now select the database
+                       if (!$GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db)) {
+                               $message = 'Cannot connect to the configured database "'.TYPO3_db.'"';
+                               if ($this->checkPageUnavailableHandler()) {
+                                       $this->pageUnavailableAndExit($message);
                                } else {
-                                       $message = 'Cannot connect to the current database, "'.TYPO3_db.'"';
                                        t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                       header('HTTP/1.0 503 Service Temporarily Unavailable');
-                                       $this->printError($message, 'Database Error');
-                                       exit;
+                                       throw new t3lib_error_http_ServiceUnavailableException($message, 1301648782);
                                }
                        }
                } else {
-                       if (!TYPO3_db)  {
-                                       // Redirects to the Install Tool:
-                               echo '<script type="text/javascript">
-                                               /*<![CDATA[*/
-                                       window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
-                                               /*]]>*/
-                                       </script>';
-                               exit;
-                       }
-
-                       if ($this->checkPageUnavailableHandler())       {
-                               $this->pageUnavailableAndExit('The current username, password or host was not accepted when the connection to the database was attempted to be established!');
+                       $message = 'The current username, password or host was not accepted when the connection to the database was attempted to be established!';
+                       if ($this->checkPageUnavailableHandler()) {
+                               $this->pageUnavailableAndExit($message);
                        } else {
-                               $message = 'The current username, password or host was not accepted when the connection to the database was attempted to be established!';
                                t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                               header('HTTP/1.0 503 Service Temporarily Unavailable');
-                               $this->printError($message, 'Database Error');
-                               exit;
+                               throw new t3lib_error_http_ServiceUnavailableException('Database Error: ' . $message, 1301648945);
                        }
                }
 
@@ -567,7 +528,19 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                }
        }
 
-
+       /**
+        * Gets instance of PageRenderer
+        *
+        * @return      t3lib_PageRenderer
+        */
+       public function getPageRenderer() {
+               if (!isset($this->pageRenderer)) {
+                       $this->pageRenderer = t3lib_div::makeInstance('t3lib_PageRenderer');
+                       $this->pageRenderer->setTemplateFile(PATH_tslib . 'templates/tslib_page_frontend.html');
+                       $this->pageRenderer->setBackPath(TYPO3_mainDir);
+               }
+               return $this->pageRenderer;
+       }
 
 
 
@@ -591,66 +564,33 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         ********************************************/
 
        /**
-        * Include files necessary for the TYPO3 caching framework. This method will
-        * go away when autoloading is implemented.
-        *
-        * @return      void
-        */
-       protected function includeCaches() {
-               $GLOBALS['TT']->push('Including the Caching System','');
-
-               t3lib_div::requireOnce(PATH_t3lib . 'class.t3lib_cache.php');
-
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/backend/interfaces/interface.t3lib_cache_backend_backend.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/frontend/interfaces/interface.t3lib_cache_frontend_frontend.php');
-
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/backend/class.t3lib_cache_backend_abstractbackend.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/frontend/class.t3lib_cache_frontend_abstractfrontend.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/class.t3lib_cache_exception.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/class.t3lib_cache_factory.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/class.t3lib_cache_manager.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/frontend/class.t3lib_cache_frontend_variablefrontend.php');
-
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_classalreadyloaded.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_duplicateidentifier.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_invalidbackend.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_invalidcache.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_invaliddata.php');
-               t3lib_div::requireOnce(PATH_t3lib . 'cache/exception/class.t3lib_cache_exception_nosuchcache.php');
-
-               $GLOBALS['TT']->pull();
-       }
-
-       /**
         * Initializes the caching system.
         *
         * @return      void
         */
        protected function initCaches() {
-               $this->includeCaches();
+               if (TYPO3_UseCachingFramework) {
+                       $GLOBALS['TT']->push('Initializing the Caching System','');
 
-               $GLOBALS['TT']->push('Initializing the Caching System','');
+                       t3lib_cache::initializeCachingFramework();
 
-               $GLOBALS['typo3CacheManager'] = t3lib_div::makeInstance('t3lib_cache_Manager');
-               $GLOBALS['typo3CacheFactory'] = t3lib_div::makeInstance('t3lib_cache_Factory');
-               $GLOBALS['typo3CacheFactory']->setCacheManager($GLOBALS['typo3CacheManager']);
-
-               try {
-                       $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
-                               'cache_pages'
-                       );
-               } catch(t3lib_cache_exception_NoSuchCache $e) {
-                       t3lib_cache::initPageCache();
+                       try {
+                               $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
+                                       'cache_pages'
+                               );
+                       } catch(t3lib_cache_exception_NoSuchCache $e) {
+                               t3lib_cache::initPageCache();
 
-                       $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
-                               'cache_pages'
-                       );
-               }
+                               $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
+                                       'cache_pages'
+                               );
+                       }
 
-               t3lib_cache::initPageSectionCache();
-               t3lib_cache::initContentHashCache();
+                       t3lib_cache::initPageSectionCache();
+                       t3lib_cache::initContentHashCache();
 
-               $GLOBALS['TT']->pull();
+                       $GLOBALS['TT']->pull();
+               }
        }
 
        /**
@@ -662,7 +602,6 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                $this->fe_user = t3lib_div::makeInstance('tslib_feUserAuth');
 
                $this->fe_user->lockIP = $this->TYPO3_CONF_VARS['FE']['lockIP'];
-               $this->fe_user->lockHashKeyWords = $this->TYPO3_CONF_VARS['FE']['lockHashKeyWords'];
                $this->fe_user->checkPid = $this->TYPO3_CONF_VARS['FE']['checkFeUserPid'];
                $this->fe_user->lifetime = intval($this->TYPO3_CONF_VARS['FE']['lifetime']);
                $this->fe_user->checkPid_value = $GLOBALS['TYPO3_DB']->cleanIntList(t3lib_div::_GP('pid'));     // List of pid's acceptable
@@ -731,7 +670,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        // Clean up.
                $gr_array = array_unique($gr_array);    // Make unique...
                sort($gr_array);        // sort
-               if (count($gr_array))   {
+               if (count($gr_array) && !$this->loginAllowedInBranch_mode)      {
                        $this->gr_list.=','.implode(',',$gr_array);
                }
 
@@ -755,7 +694,6 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * 2) Using hook which enables features like those provided from "simulatestatic" or "realurl" extension (AKA "Speaking URLs")
         *
         * @return      void
-        * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&cHash=4ad9d7acb4
         */
        function checkAlternativeIdMethods()    {
                $this->siteScript = t3lib_div::getIndpEnv('TYPO3_SITE_SCRIPT');
@@ -799,23 +737,23 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                if ($this->beUserLogin || $this->doWorkspacePreview())  {
 
                                // Backend user preview features:
-                       if ($this->beUserLogin && ($GLOBALS['BE_USER']->frontendEdit instanceof t3lib_frontendedit)) {
-                               $this->fePreview = $GLOBALS['BE_USER']->frontendEdit->extGetFeAdminValue('preview') ? true : false;
+                       if ($this->beUserLogin && ($GLOBALS['BE_USER']->adminPanel instanceof tslib_AdminPanel)) {
+                               $this->fePreview = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview') ? TRUE : FALSE;
 
                                        // If admin panel preview is enabled...
                                if ($this->fePreview)   {
                                        $fe_user_OLD_USERGROUP = $this->fe_user->user['usergroup'];
 
-                                       $this->showHiddenPage = $GLOBALS['BE_USER']->frontendEdit->extGetFeAdminValue('preview', 'showHiddenPages');
-                                       $this->showHiddenRecords = $GLOBALS['BE_USER']->frontendEdit->extGetFeAdminValue('preview', 'showHiddenRecords');
+                                       $this->showHiddenPage = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
+                                       $this->showHiddenRecords = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
                                                // simulate date
-                                       $simTime = $GLOBALS['BE_USER']->frontendEdit->extGetFeAdminValue('preview', 'simulateDate');
+                                       $simTime = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
                                        if ($simTime)   {
                                                $GLOBALS['SIM_EXEC_TIME'] = $simTime;
                                                $GLOBALS['SIM_ACCESS_TIME'] = $simTime - ($simTime % 60);
                                        }
                                                // simulate user
-                                       $simUserGroup = $GLOBALS['BE_USER']->frontendEdit->extGetFeAdminValue('preview', 'simulateUserGroup');
+                                       $simUserGroup = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
                                        $this->simUserGroup = $simUserGroup;
                                        if ($simUserGroup)      $this->fe_user->user['usergroup']=$simUserGroup;
                                        if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
@@ -861,7 +799,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                                // If the front-end is showing a preview, caching MUST be disabled.
                        if ($this->fePreview)   {
-                               $this->set_no_cache();
+                               $this->disableCache();
                        }
                }
                $GLOBALS['TT']->pull();
@@ -886,10 +824,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
                if (!$this->loginAllowedInBranch)       {       // Logins are not allowed:
                        if ($this->isUserOrGroupSet())  {       // Only if there is a login will we run this...
-
-                                       // Clear out user and group:
-                               unset($this->fe_user->user);
-                               $this->gr_list = '0,-1';
+                               if ($this->loginAllowedInBranch_mode=='all')    {
+                                               // Clear out user and group:
+                                       unset($this->fe_user->user);
+                                       $this->gr_list = '0,-1';
+                               } else {
+                                       $this->gr_list = '0,-2';
+                               }
 
                                        // Fetching the id again, now with the preview settings reset.
                                $this->fetch_the_id();
@@ -972,14 +913,12 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                if ($theFirstPage)      {
                                        $this->id = $theFirstPage['uid'];
                                } else {
-                                       if ($this->checkPageUnavailableHandler())       {
-                                               $this->pageUnavailableAndExit('No pages are found on the rootlevel!');
+                                       $message = 'No pages are found on the rootlevel!';
+                                       if ($this->checkPageUnavailableHandler()) {
+                                               $this->pageUnavailableAndExit($message);
                                        } else {
-                                               $message = 'No pages are found on the rootlevel!';
                                                t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                               header('HTTP/1.0 503 Service Temporarily Unavailable');
-                                               $this->printError($message);
-                                               exit;
+                                               throw new t3lib_error_http_ServiceUnavailableException($message, 1301648975);
                                        }
                                }
                        }
@@ -1001,6 +940,23 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound]);
                }
 
+               if ($this->page['url_scheme'] > 0) {
+                       $newUrl = '';
+                       $requestUrlScheme = parse_url(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'), PHP_URL_SCHEME);
+                       if ((int) $this->page['url_scheme'] === t3lib_utility_http::SCHEME_HTTP && $requestUrlScheme == 'https') {
+                               $newUrl = 'http://' . substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'), 8);
+                       } elseif ((int) $this->page['url_scheme'] === t3lib_utility_http::SCHEME_HTTPS && $requestUrlScheme == 'http') {
+                               $newUrl = 'https://' . substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'), 7);
+                       }
+                       if ($newUrl !== '') {
+                               if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+                                       $headerCode = t3lib_utility_Http::HTTP_STATUS_303;
+                               } else {
+                                       $headerCode = t3lib_utility_Http::HTTP_STATUS_301;
+                               }
+                               t3lib_utility_http::redirect($newUrl, $headerCode);
+                       }
+               }
                        // set no_cache if set
                if ($this->page['no_cache'])    {
                        $this->set_no_cache();
@@ -1047,34 +1003,30 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                }
                        }
                                // If still no page...
-                       if (!count($this->page))        {
-                               if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'])      {
-                                       $this->pageNotFoundAndExit('The requested page does not exist!');
+                       if (!count($this->page)) {
+                               $message = 'The requested page does not exist!';
+                               if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
+                                       $this->pageNotFoundAndExit($message);
                                } else {
-                                       $message = 'The requested page does not exist!';
-                                       header('HTTP/1.0 404 Page Not Found');
                                        t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                       $this->printError($message);
-                                       exit;
+                                       throw new t3lib_error_http_PageNotFoundException($message, 1301648780);
                                }
                        }
                }
 
                        // Spacer is not accessible in frontend
-               if ($this->page['doktype'] == 199)      {
-                       if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'])      {
-                               $this->pageNotFoundAndExit('The requested page does not exist!');
+               if ($this->page['doktype'] == t3lib_pageSelect::DOKTYPE_SPACER) {
+                       $message = 'The requested page does not exist!';
+                       if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
+                               $this->pageNotFoundAndExit($message);
                        } else {
-                               $message = 'The requested page does not exist!';
-                               header('HTTP/1.0 404 Page Not Found');
                                t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                               $this->printError($message);
-                               exit;
+                               throw new t3lib_error_http_PageNotFoundException($message, 1301648781);
                        }
                }
 
                        // Is the ID a link to another page??
-               if ($this->page['doktype']==4)  {
+               if ($this->page['doktype'] == t3lib_pageSelect::DOKTYPE_SHORTCUT) {
                        $this->MP = '';         // We need to clear MP if the page is a shortcut. Reason is if the short cut goes to another page, then we LEAVE the rootline which the MP expects.
 
                                // saving the page so that we can check later - when we know
@@ -1098,15 +1050,14 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $this->versioningWorkspaceId = $ws;
                                $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
                        }
-                       if (!count($this->rootLine))    {
-                               if ($this->checkPageUnavailableHandler())       {
-                                       $this->pageUnavailableAndExit('The requested page didn\'t have a proper connection to the tree-root!');
+                       if (!count($this->rootLine)) {
+                               $message = 'The requested page didn\'t have a proper connection to the tree-root!';
+                               if ($this->checkPageUnavailableHandler()) {
+                                       $this->pageUnavailableAndExit($message);
                                } else {
-                                       $message = 'The requested page didn\'t have a proper connection to the tree-root! <br /><br />('.$this->sys_page->error_getRootLine.')';
-                                       header('HTTP/1.0 503 Service Temporarily Unavailable');
-                                       t3lib_div::sysLog(str_replace('<br /><br />','',$message), 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                       $this->printError($message);
-                                       exit;
+                                       $rootline = '('.$this->sys_page->error_getRootLine.')';
+                                       t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
+                                       throw new t3lib_error_http_ServiceUnavailableException($message . '<br /><br />' . $rootline, 1301648167);
                                }
                        }
                        $this->fePreview = 1;
@@ -1114,15 +1065,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
                if ($this->checkRootlineForIncludeSection())    {
-                       if (!count($this->rootLine))    {
-                               if ($this->checkPageUnavailableHandler())       {
-                                       $this->pageUnavailableAndExit('The requested page was not accessible!');
+                       if (!count($this->rootLine)) {
+                               $message = 'The requested page was not accessible!';
+                               if ($this->checkPageUnavailableHandler()) {
+                                       $this->pageUnavailableAndExit($message);
                                } else {
-                                       $message = 'The requested page was not accessible!';
-                                       header('HTTP/1.0 503 Service Temporarily Unavailable');
                                        t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                       $this->printError($message);
-                                       exit;
+                                       throw new t3lib_error_http_ServiceUnavailableException($message, 1301648234);
                                }
                        } else {
                                $el = reset($this->rootLine);
@@ -1137,7 +1086,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
         *
         * @param       integer         The value of the "shortcut" field from the pages record
-        * @param       integer         The shortcut mode: 1 and 2 will select either first subpage or random subpage; the default is the page pointed to by $SC
+        * @param       integer         The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC
         * @param       integer         The current page UID of the page which is a shortcut
         * @param       integer         Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
         * @param       array           An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
@@ -1150,42 +1099,56 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        // Find $page record depending on shortcut mode:
                switch($mode)   {
-                       case 1:
-                       case 2:
-                               $pageArray = $this->sys_page->getMenu($idArray[0]?$idArray[0]:$thisUid,'*','sorting','AND pages.doktype<199 AND pages.doktype!=6');
+                       case t3lib_pageSelect::SHORTCUT_MODE_FIRST_SUBPAGE:
+                       case t3lib_pageSelect::SHORTCUT_MODE_RANDOM_SUBPAGE:
+                               $pageArray = $this->sys_page->getMenu(($idArray[0] ? $idArray[0] : $thisUid), '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . t3lib_pageSelect::DOKTYPE_BE_USER_SECTION);
                                $pO = 0;
-                               if ($mode==2 && count($pageArray))      {       // random
-                                       $this->make_seed();
+                               if ($mode == t3lib_pageSelect::SHORTCUT_MODE_RANDOM_SUBPAGE && count($pageArray)) {
                                        $randval = intval(rand(0,count($pageArray)-1));
                                        $pO = $randval;
                                }
                                $c = 0;
-                               reset($pageArray);
-                               while(list(,$pV)=each($pageArray))      {
+                               foreach ($pageArray as $pV) {
                                        if ($c==$pO)    {
                                                $page = $pV;
                                                break;
                                        }
                                        $c++;
                                }
+                               if (count($page) == 0) {
+                                       $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. '
+                                               . 'However, this page has no accessible subpages.';
+                                       throw new t3lib_error_http_PageNotFoundException($message, 1301648328);
+                               }
+                       break;
+                       case t3lib_pageSelect::SHORTCUT_MODE_PARENT_PAGE:
+                               $parent = $this->sys_page->getPage($thisUid);
+                               $page = $this->sys_page->getPage($parent['pid']);
+                               if (count($page) == 0) {
+                                       $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. '
+                                               . 'However, the parent page is not accessible.';
+                                       throw new t3lib_error_http_PageNotFoundException($message, 1301648358);
+                               }
                        break;
                        default:
                                $page = $this->sys_page->getPage($idArray[0]);
+                               if (count($page) == 0) {
+                                       $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
+                                       throw new t3lib_error_http_PageNotFoundException($message, 1301648404);
+                               }
                        break;
                }
 
                        // Check if short cut page was a shortcut itself, if so look up recursively:
-               if ($page['doktype']==4)        {
+               if ($page['doktype'] == t3lib_pageSelect::DOKTYPE_SHORTCUT) {
                        if (!in_array($page['uid'],$pageLog) && $itera>0)       {
                                $pageLog[] = $page['uid'];
                                $page = $this->getPageShortcut($page['shortcut'],$page['shortcut_mode'],$page['uid'],$itera-1,$pageLog);
                        } else {
                                $pageLog[] = $page['uid'];
                                $message = 'Page shortcuts were looping in uids '.implode(',',$pageLog).'...!';
-                               header('HTTP/1.0 500 Internal Server Error');
                                t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                               $this->printError($message);
-                               exit;
+                               throw new RuntimeException($message, 1294587212);
                        }
                }
                        // Return resulting page:
@@ -1208,7 +1171,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
                                $removeTheRestFlag=1;
                        }
-                       if ($this->rootLine[$a]['doktype']==6)  {
+                       if ($this->rootLine[$a]['doktype'] == t3lib_pageSelect::DOKTYPE_BE_USER_SECTION) {
                                if ($this->beUserLogin) {       // If there is a backend user logged in, check if he has read access to the page:
                                        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($this->id).' AND '.$GLOBALS['BE_USER']->getPagePermsClause(1));     // versionOL()?
                                        list($isPage) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
@@ -1227,12 +1190,12 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
        /**
         * Checks page record for enableFields
-        * Returns true if enableFields does not disable the page record.
+        * Returns TRUE if enableFields does not disable the page record.
         * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
         *
         * @param       array           The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
         * @param       boolean         Bypass group-check
-        * @return      boolean         True, if record is viewable.
+        * @return      boolean         TRUE, if record is viewable.
         * @see tslib_cObj::getTreeList(), checkPagerecordForIncludeSection()
         */
        function checkEnableFields($row,$bypassGroupCheck=FALSE)        {
@@ -1248,7 +1211,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         *
         * @param       array           The page record to evaluate (needs field: fe_group)
         * @param       mixed           List of group id's (comma list or array). Default is $this->gr_list
-        * @return      boolean         True, if group access is granted.
+        * @return      boolean         TRUE, if group access is granted.
         * @access private
         */
        function checkPageGroupAccess($row, $groupList=NULL) {
@@ -1258,6 +1221,19 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                if(!is_array($groupList)) {
                        $groupList = explode(',', $groupList);
                }
+
+                       // If the actual page has no fe_group, check the rootline for
+                       // inherited fe_group due to extendToSubpage-property
+               if (intval($row['fe_group']) === 0) {
+                       $rootLine = $this->sys_page->getRootLine($row['uid']);
+                       foreach ($rootLine as $pageConf) {
+                               if ($pageConf['fe_group'] != '' && $pageConf['extendToSubpages'] == 1) {
+                                       $row['fe_group'] = $pageConf['fe_group'];
+                                       break;
+                               }
+                       }
+               }
+
                $pageGroupList = explode(',', $row['fe_group'] ? $row['fe_group'] : 0);
                return count(array_intersect($groupList, $pageGroupList)) > 0;
        }
@@ -1266,7 +1242,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * Checks page record for include section
         *
         * @param       array           The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
-        * @return      boolean         Returns true if either extendToSubpages is not checked or if the enableFields does not disable the page record.
+        * @return      boolean         Returns TRUE if either extendToSubpages is not checked or if the enableFields does not disable the page record.
         * @access private
         * @see checkEnableFields(), tslib_cObj::getTreeList(), checkRootlineForIncludeSection()
         */
@@ -1275,9 +1251,9 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        }
 
        /**
-        * Checks if logins are allowed in the current branch of the page tree. Traverses the full root line and returns TRUE if logins are OK, otherwise false (and then the login user must be unset!)
+        * Checks if logins are allowed in the current branch of the page tree. Traverses the full root line and returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
         *
-        * @return      boolean         returns TRUE if logins are OK, otherwise false (and then the login user must be unset!)
+        * @return      boolean         returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
         */
        function checkIfLoginAllowedInBranch()  {
 
@@ -1292,7 +1268,15 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        if ($this->rootLine[$a]['fe_login_mode'] > 0)   {
 
                                        // Determine state from value:
-                               $disable = (int)$this->rootLine[$a]['fe_login_mode'] === 1 ? TRUE : FALSE;
+                               if ((int)$this->rootLine[$a]['fe_login_mode'] === 1)    {
+                                       $disable = TRUE;
+                                       $this->loginAllowedInBranch_mode = 'all';
+                               } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3)      {
+                                       $disable = TRUE;
+                                       $this->loginAllowedInBranch_mode = 'groups';
+                               } else {
+                                       $disable = FALSE;
+                               }
                        }
                }
 
@@ -1330,7 +1314,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
        /**
         * This checks if there are ARGV-parameters in the QUERY_STRING and if so, those are used for the id
-        * $this->id must be 'false' in order for any processing to happen in here
+        * $this->id must be 'FALSE' in order for any processing to happen in here
         * If an id/alias value is extracted from the QUERY_STRING it is set in $this->id
         *
         * @return      void
@@ -1340,7 +1324,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                if (!$this->id) {
                        list($theAlias) = explode('&',t3lib_div::getIndpEnv('QUERY_STRING'));
                        $theAlias = trim($theAlias);
-                       $this->id = ($theAlias != '' && strpos($theAlias, '=') === false) ? $theAlias : 0;
+                       $this->id = ($theAlias != '' && strpos($theAlias, '=') === FALSE) ? $theAlias : 0;
                }
        }
 
@@ -1357,9 +1341,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                // Checks if the $domain-startpage is in the rootLine. This is necessary so that references to page-id's from other domains are not possible.
                if ($domainStartPage && is_array($this->rootLine)) {
-                       reset ($this->rootLine);
                        $idFound = 0;
-                       while(list($key,$val)=each($this->rootLine)) {
+                       foreach ($this->rootLine as $key => $val) {
                                if ($val['uid']==$domainStartPage)      {
                                        $idFound=1;
                                        break;
@@ -1396,7 +1379,11 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $host = explode('.',t3lib_div::getIndpEnv('HTTP_HOST'));
                        while(count($host))     {
                                $pageUid = $this->sys_page->getDomainStartPage(implode('.',$host),t3lib_div::getIndpEnv('SCRIPT_NAME'),t3lib_div::getIndpEnv('REQUEST_URI'));
-                               if ($pageUid)   return $pageUid; else array_shift($host);
+                               if ($pageUid) {
+                                       return $pageUid;
+                               } else {
+                                       array_shift($host);
+                               }
                        }
                        return $pageUid;
                } else {
@@ -1434,7 +1421,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
         * and devIPMask must not match the current visitor's IP address.
         *
-        * @return      boolean         True/false whether the pageUnavailable_handler should be used.
+        * @return      boolean         TRUE/FALSE whether the pageUnavailable_handler should be used.
         */
        function checkPageUnavailableHandler()  {
                if($this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling'] &&
@@ -1450,7 +1437,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        /**
         * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
         *
-        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
+        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->t3lib_message_ErrorPageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
         * @param       string          If set, this is passed directly to the PHP function, header()
         * @param       string          If set, error messages will also mention this as the reason for the page-not-found.
         * @return      void            (The function exits!)
@@ -1462,7 +1449,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        /**
         * Page not found handler. Acts a wrapper for the pageErrorHandler method.
         *
-        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
+        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->t3lib_message_ErrorPageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
         * @param       string          If set, this is passed directly to the PHP function, header()
         * @param       string          If set, error messages will also mention this as the reason for the page-not-found.
         * @return      void            (The function exits!)
@@ -1475,7 +1462,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * Generic error page handler.
         * Exits.
         *
-        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
+        * @param       mixed           Which type of handling; If a true PHP-boolean or TRUE then a ->t3lib_message_ErrorPageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
         * @param       string          If set, this is passed directly to the PHP function, header()
         * @param       string          If set, error messages will also mention this as the reason for the page-not-found.
         * @return      void            (The function exits!)
@@ -1492,7 +1479,11 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        // Create response:
                if (gettype($code)=='boolean' || !strcmp($code,1))      {       // Simply boolean; Just shows TYPO3 error page with reason:
-                       $this->printError('The page did not exist or was inaccessible.'.($reason ? ' Reason: '.htmlspecialchars($reason) : ''));
+                       $title = 'Page Not Found';
+                       $message = 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . htmlspecialchars($reason) : '');
+                       $messagePage = t3lib_div::makeInstance('t3lib_message_ErrorpageMessage', $message, $title);
+                       $messagePage->output();
+                       exit;
                } elseif (t3lib_div::isFirstPartOfStr($code,'USER_FUNCTION:')) {
                        $funcRef = trim(substr($code,14));
                        $params = array(
@@ -1509,20 +1500,23 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $fileContent = str_replace('###REASON###', htmlspecialchars($reason), $fileContent);
                                echo $fileContent;
                        } else {
-                               $this->printError('Configuration Error: 404 page "'.$readFile.'" could not be found.');
+                               throw new RuntimeException('Configuration Error: 404 page "' . $readFile.'" could not be found.', 1294587214);
                        }
                } elseif (t3lib_div::isFirstPartOfStr($code,'REDIRECT:')) {
-                       header('Location: '.t3lib_div::locationHeaderUrl(substr($code,9)));
-                       exit;
+                       t3lib_utility_Http::redirect(substr($code, 9));
                } elseif (strlen($code))        {
                                // Check if URL is relative
                        $url_parts = parse_url($code);
                        if ($url_parts['host'] == '')   {
                                $url_parts['host'] = t3lib_div::getIndpEnv('HTTP_HOST');
-                               $code = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
-                               $checkBaseTag = false;
+                               if ($code{0} === '/') {
+                                       $code = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
+                               } else {
+                                       $code = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
+                               }
+                               $checkBaseTag = FALSE;
                        } else {
-                               $checkBaseTag = true;
+                               $checkBaseTag = TRUE;
                        }
 
                                // Check recursion
@@ -1530,9 +1524,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                if ($reason == '') {
                                        $reason = 'Page cannot be found.';
                                }
-                               $reason.= chr(10) . chr(10) . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
-                               $this->printError('Reason: '.nl2br(htmlspecialchars($reason)));
-                               exit();
+                               $reason.= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
+                               throw new RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
                        }
 
                                // Prepare headers
@@ -1543,12 +1536,12 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $res = t3lib_div::getURL($code, 1, $headerArr);
 
                                // Header and content are separated by an empty line
-                       list($header, $content) = preg_split("/[\r\n\r\n]/", $res, 2);
-                       $content.= "\r\n";
+                       list($header, $content) = explode(CRLF . CRLF, $res, 2);
+                       $content.= CRLF;
 
-                       if (false === $res) {
+                       if (FALSE === $res) {
                                        // Last chance -- redirect
-                               header('Location: '.t3lib_div::locationHeaderUrl($code));
+                               t3lib_utility_Http::redirect($code);
                        } else {
 
                                $forwardHeaders = array(        // Forward these response headers to the client
@@ -1566,7 +1559,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                if ($checkBaseTag)      {
 
                                                // If content already has <base> tag, we do not need to do anything
-                                       if (false === stristr($content, '<base '))      {
+                                       if (FALSE === stristr($content, '<base '))      {
 
                                                        // Generate href for base tag
                                                $base = $url_parts['scheme'] . '://';
@@ -1583,7 +1576,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                                $base.= preg_replace('/(.*\/)[^\/]*/', '${1}', $url_parts['path']);
 
                                                        // Put it into content (generate also <head> if necessary)
-                                               $replacement = chr(10) . '<base href="' . htmlentities($base) . '" />' . chr(10);
+                                               $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
                                                if (stristr($content, '<head>'))        {
                                                        $content = preg_replace('/(<head>)/i', '\1' . $replacement, $content);
                                                } else {
@@ -1594,7 +1587,10 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                echo $content;  // Output the content
                        }
                } else {
-                       $this->printError($reason ? 'Reason: '.htmlspecialchars($reason) : 'Page cannot be found.');
+                       $title = 'Page Not Found';
+                       $message = ($reason ? 'Reason: ' . htmlspecialchars($reason) : 'Page cannot be found.');
+                       $messagePage = t3lib_div::makeInstance('t3lib_message_ErrorpageMessage', $message, $title);
+                       $messagePage->output();
                }
                exit();
        }
@@ -1625,6 +1621,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         * @access private
         * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @todo        Deprecated but still used in the Core!
         */
        function idPartsAnalyze($str)   {
                $GET_VARS = '';
@@ -1698,22 +1695,24 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                        if (@is_file(PATH_site.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate'])) {
                                                $message = t3lib_div::getUrl(PATH_site.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate']);
                                        } else {
-                                               $message = '<b>ERROR!</b><br>Template File "'.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate'].'" configured with $TYPO3_CONF_VARS["FE"]["workspacePreviewLogoutTemplate"] not found. Please contact webmaster about this problem.';
+                                               $message = '<strong>ERROR!</strong><br>Template File "'.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate'].'" configured with $TYPO3_CONF_VARS["FE"]["workspacePreviewLogoutTemplate"] not found. Please contact webmaster about this problem.';
                                        }
                                } else {
                                        $message = 'You logged out from Workspace preview mode. Click this link to <a href="%1$s">go back to the website</a>';
                                }
+
+                               $returnUrl = t3lib_div::sanitizeLocalUrl(t3lib_div::_GET('returnUrl'));
                                die(sprintf($message,
-                                       htmlspecialchars(ereg_replace('\&?ADMCMD_prev=[[:alnum:]]+','',t3lib_div::_GET('returnUrl')))
+                                       htmlspecialchars(preg_replace('/\&?ADMCMD_prev=[[:alnum:]]+/', '', $returnUrl))
                                        ));
                        }
 
                                // Look for keyword configuration record:
-                       list($previewData) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
+                       $previewData = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
                                '*',
                                'sys_preview',
                                'keyword='.$GLOBALS['TYPO3_DB']->fullQuoteStr($inputCode, 'sys_preview').
-                                       ' AND endtime>'.time()
+                                       ' AND endtime>' . $GLOBALS['EXEC_TIME']
                        );
 
                                // Get: Backend login status, Frontend login status
@@ -1742,9 +1741,9 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                                                        // Return preview keyword configuration:
                                                return $previewConfig;
-                                       } else die(htmlspecialchars('Request URL did not match "'.t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.$inputCode.'"'));    // This check is to prevent people from setting additional GET vars via realurl or other URL path based ways of passing parameters.
-                               } else die('POST requests are incompatible with keyword preview.');
-                       } else die('ADMCMD command could not be executed! (No keyword configuration found)');
+                                       } else throw new Exception(htmlspecialchars('Request URL did not match "' . t3lib_div::getIndpEnv('TYPO3_SITE_URL') . 'index.php?ADMCMD_prev=' . $inputCode . '"', 1294585190));        // This check is to prevent people from setting additional GET vars via realurl or other URL path based ways of passing parameters.
+                               } else throw new Exception('POST requests are incompatible with keyword preview.', 1294585191);
+                       } else throw new Exception('ADMCMD command could not be executed! (No keyword configuration found)', 1294585192);
                }
        }
 
@@ -1756,14 +1755,10 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         * @see ADMCMD_preview(), index_ts.php
         */
-       function ADMCMD_preview_postInit($previewConfig){
-               if (is_array($previewConfig))   {
-
-                               // Clear cookies:
-                       unset($_COOKIE['be_typo_user']);
-                       $this->ADMCMD_preview_BEUSER_uid = $previewConfig['BEUSER_uid'];
-
-               } else die('Error in preview configuration.');
+       function ADMCMD_preview_postInit(array $previewConfig){
+                       // Clear cookies:
+               unset($_COOKIE['be_typo_user']);
+               $this->ADMCMD_preview_BEUSER_uid = $previewConfig['BEUSER_uid'];
        }
 
 
@@ -1789,10 +1784,15 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @see reqCHash()
         */
        function makeCacheHash()        {
+               // No need to test anything if caching was already disabled.
+               if ($this->no_cache && !$this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
+                       return;
+               }
+
                $GET = t3lib_div::_GET();
                if ($this->cHash && is_array($GET))     {
                        $this->cHash_array = t3lib_div::cHashParams(t3lib_div::implodeArrayForUrl('',$GET));
-                       $cHash_calc = t3lib_div::shortMD5(serialize($this->cHash_array));
+                       $cHash_calc = t3lib_div::calculateCHash($this->cHash_array);
 
                        if ($cHash_calc!=$this->cHash)  {
                                if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
@@ -1861,7 +1861,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        if (!is_array($cc)) {
                                $key = $this->id.'::'.$this->MP;
-                               $isLocked = $this->acquirePageGenerationLock($this->pagesection_lockObj, $key); // Returns true if the lock is active now
+                               $isLocked = $this->acquirePageGenerationLock($this->pagesection_lockObj, $key); // Returns TRUE if the lock is active now
 
                                if (!$isLocked) {
                                                // Lock is no longer active, the data in "cache_pagesection" is now ready
@@ -1913,8 +1913,16 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                                        // Release this lock
                                                $this->releasePageGenerationLock($this->pages_lockObj);
 
+                                                       // Call hook when a page is retrieved from cache:
+                                               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache']))  {
+                                                       $_params = array('pObj' => &$this, 'cache_pages_row' => &$row);
+                                                       foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] as $_funcRef)   {
+                                                               t3lib_div::callUserFunction($_funcRef,$_params,$this);
+                                                       }
+                                               }
+
                                                $this->config = (array)unserialize($row['cache_data']);         // Fetches the lowlevel config stored with the cached data
-                                               $this->content = $row['HTML'];  // Getting the content
+                                               $this->content = (TYPO3_UseCachingFramework ? $row['content'] : $row['HTML']);  // Getting the content
                                                $this->tempContent = $row['temp_content'];      // Flag for temp content
                                                $this->cacheContentFlag = 1;    // Setting flag, so we know, that some cached content has been loaded
                                                $this->cacheExpires = $row['expires'];
@@ -1923,7 +1931,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                                        $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
                                                        $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
 
-                                                       $this->content.= chr(10).'<!-- Cached page generated '.date($dateFormat.' '.$timeFormat, $row['tstamp']).'. Expires '.Date($dateFormat.' '.$timeFormat, $row['expires']).' -->';
+                                                       $this->content.= LF.'<!-- Cached page generated '.date($dateFormat.' '.$timeFormat, $row['tstamp']).'. Expires '.Date($dateFormat.' '.$timeFormat, $row['expires']).' -->';
                                                }
                                        }
                                $GLOBALS['TT']->pull();
@@ -1940,11 +1948,31 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      array           Cached row, if any. Otherwise void.
         */
        function getFromCache_queryRow() {
-               $GLOBALS['TT']->push('Cache Query', '');
-               $cachedPage = $this->pageCache->get($this->newHash);
-               $GLOBALS['TT']->pull();
+               if (TYPO3_UseCachingFramework) {
+                       $GLOBALS['TT']->push('Cache Query', '');
+                       $row = $this->pageCache->get($this->newHash);
+                       $GLOBALS['TT']->pull();
+               } else {
+                       $GLOBALS['TT']->push('Cache Query','');
+                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
+                               'S.*',
+                               'cache_pages S,pages P',
+                               'S.hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages').'
+                                       AND S.page_id=P.uid
+                                       AND S.expires > '.intval($GLOBALS['ACCESS_TIME']).'
+                                       AND P.deleted=0
+                                       AND P.hidden=0
+                                       AND P.starttime<='.intval($GLOBALS['ACCESS_TIME']).'
+                                       AND (P.endtime=0 OR P.endtime>'.intval($GLOBALS['ACCESS_TIME']).')'
+                       );
+                       $GLOBALS['TT']->pull();
 
-               return $cachedPage;
+                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                               $this->pageCachePostProcess($row,'get');
+                       }
+                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+               }
+               return $row;
        }
 
        /**
@@ -1991,7 +2019,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                'type' => intval($this->type),
                                'gr_list' => (string)$this->gr_list,
                                'MP' => (string)$this->MP,
-                               'cHash' => $this->cHash_array
+                               'cHash' => $this->cHash_array,
+                               'domainStartPage' => $this->domainStartPage,
                        )
                );
 
@@ -2013,7 +2042,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                'type' => intval($this->type),
                                'gr_list' => (string)$this->gr_list,
                                'MP' => (string)$this->MP,
-                               'cHash' => $this->cHash_array
+                               'cHash' => $this->cHash_array,
+                               'domainStartPage' => $this->domainStartPage,
                        )
                );
 
@@ -2026,7 +2056,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function getConfigArray()       {
-               $setStatPageName = false;
+               $setStatPageName = FALSE;
 
                if (!is_array($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {       // If config is not set by the cache (which would be a major mistake somewhere) OR if INTincScripts-include-scripts have been registered, then we must parse the template in order to get it
                                $GLOBALS['TT']->push('Parse template','');
@@ -2045,14 +2075,14 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $this->pSetup = $this->tmpl->setup[$this->sPre.'.'];
 
                                if (!is_array($this->pSetup))   {
-                                       if ($this->checkPageUnavailableHandler())       {
-                                               $this->pageUnavailableAndExit('The page is not configured! [type= '.$this->type.']['.$this->sPre.']');
+                                       $message = 'The page is not configured! [type='.$this->type.']['.$this->sPre.'].';
+                                       if ($this->checkPageUnavailableHandler()) {
+                                               $this->pageUnavailableAndExit($message);
                                        } else {
-                                               $message = 'The page is not configured! [type= '.$this->type.']['.$this->sPre.']';
-                                               header('HTTP/1.0 503 Service Temporarily Unavailable');
+                                               $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' .
+                                                              $this->type . ' configured.';
                                                t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                               $this->printError($message);
-                                               exit;
+                                               throw new t3lib_error_http_ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
                                        }
                                } else {
                                        $this->config['config'] = array();
@@ -2067,7 +2097,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                        }
 
                                        if ($this->config['config']['typolinkEnableLinksAcrossDomains']) {
-                                               $this->config['config']['typolinkCheckRootline'] = true;
+                                               $this->config['config']['typolinkCheckRootline'] = TRUE;
                                        }
 
                                                // Set default values for removeDefaultJS, inlineStyle2TempFile and minifyJS so CSS and JS are externalized/minified if compatversion is higher than 4.0
@@ -2092,6 +2122,16 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                                        $this->config['FEData'] = $this->tmpl->setup['FEData'];
                                        $this->config['FEData.'] = $this->tmpl->setup['FEData.'];
+
+                                               // class for render Header and Footer parts
+                                       $template = '';
+                                       if ($this->pSetup['pageHeaderFooterTemplateFile']) {
+                                               $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
+                                               if ($file) {
+                                                       $this->setTemplateFile($file);
+                                               }
+                                       }
+
                                }
                                $GLOBALS['TT']->pull();
                        } else {
@@ -2099,10 +2139,8 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                        $this->pageUnavailableAndExit('No TypoScript template found!');
                                } else {
                                        $message = 'No TypoScript template found!';
-                                       header('HTTP/1.0 503 Service Temporarily Unavailable');
                                        t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                                       $this->printError($message);
-                                       exit;
+                                       throw new t3lib_error_http_ServiceUnavailableException($message, 1294587218);
                                }
                        }
                }
@@ -2116,8 +2154,17 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                }
 
                        // No cache
-               if ($this->config['config']['no_cache'])        { $this->set_no_cache(); }              // Set $this->no_cache true if the config.no_cache value is set!
+               if ($this->config['config']['no_cache'])        { $this->set_no_cache(); }              // Set $this->no_cache TRUE if the config.no_cache value is set!
+
+                       // merge GET with defaultGetVars
+               if (!empty($this->config['config']['defaultGetVars.'])) {
+                       $modifiedGetVars = t3lib_div::array_merge_recursive_overrule(
+                               t3lib_div::removeDotsFromTS($this->config['config']['defaultGetVars.']),
+                               t3lib_div::_GET()
+                       );
 
+                       t3lib_div::_GETset($modifiedGetVars);
+               }
 
                        // Hook for postProcessing the configuration array
                if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'])) {
@@ -2149,16 +2196,14 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         *******************************************/
 
        /**
-        * Get the compressed $TCA array for use in the front-end
-        * A compressed $TCA array holds only the ctrl- and feInterface-part for each table. But the column-definitions are omitted in order to save some memory and be more efficient.
+        * Get the compressed $GLOBALS['TCA'] array for use in the front-end
+        * A compressed $GLOBALS['TCA'] array holds only the ctrl- and feInterface-part for each table. But the column-definitions are omitted in order to save some memory and be more efficient.
         * Operates on the global variable, $TCA
         *
         * @return      void
         * @see includeTCA()
         */
        function getCompressedTCarray() {
-               global $TCA;
-
                $GLOBALS['TT']->push('Get Compressed TC array');
                if (!$this->TCAloaded)  {
                                // Create hash string for storage / retrieval of cached content:
@@ -2170,24 +2215,24 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        if ($this->TYPO3_CONF_VARS['EXT']['extCache'] != 0) {
                                // Try to fetch if cache is enabled
-                               list($TCA, $this->TCAcachedExtras) = unserialize($this->sys_page->getHash($tempHash));
+                               list($GLOBALS['TCA'], $this->TCAcachedExtras) = unserialize($this->sys_page->getHash($tempHash));
                        }
 
                                // If no result, create it:
-                       if (!is_array($TCA))    {
+                       if (!is_array($GLOBALS['TCA'])) {
                                $this->includeTCA(0);
                                $newTc = Array();
                                $this->TCAcachedExtras = array();       // Collects other information
 
-                               foreach($TCA as $key => $val)           {
+                               foreach($GLOBALS['TCA'] as $key => $val) {
                                        $newTc[$key]['ctrl'] = $val['ctrl'];
                                        $newTc[$key]['feInterface'] = $val['feInterface'];
 
                                                // Collect information about localization exclusion of fields:
                                        t3lib_div::loadTCA($key);
-                                       if (is_array($TCA[$key]['columns']))    {
+                                       if (is_array($GLOBALS['TCA'][$key]['columns'])) {
                                                $this->TCAcachedExtras[$key]['l10n_mode'] = array();
-                                               foreach($TCA[$key]['columns'] as $fN => $fV)    {
+                                               foreach($GLOBALS['TCA'][$key]['columns'] as $fN => $fV) {
                                                        if ($fV['l10n_mode'])   {
                                                                $this->TCAcachedExtras[$key]['l10n_mode'][$fN] = $fV['l10n_mode'];
                                                        }
@@ -2195,7 +2240,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                        }
                                }
 
-                               $TCA = $newTc;
+                               $GLOBALS['TCA'] = $newTc;
                                // Store it in cache if cache is enabled
                                if ($this->TYPO3_CONF_VARS['EXT']['extCache'] != 0) {
                                        $this->sys_page->storeHash($tempHash, serialize(array($newTc,$this->TCAcachedExtras)), 'SHORT_TC');
@@ -2212,14 +2257,15 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * full TCA for the table, use t3lib_div::loadTCA($tableName) after calling
         * this function.
         *
-        * @param       boolean         Probably, keep hands of this value. Just don't set it. (This may affect the first-ever time this function is called since if you set it to zero/false any subsequent call will still trigger the inclusion; In other words, this value will be set in $this->TCAloaded after inclusion and therefore if its false, another inclusion will be possible on the next call. See ->getCompressedTCarray())
+        * @param       boolean         Probably, keep hands of this value. Just don't set it. (This may affect the first-ever time this function is called since if you set it to zero/FALSE any subsequent call will still trigger the inclusion; In other words, this value will be set in $this->TCAloaded after inclusion and therefore if its FALSE, another inclusion will be possible on the next call. See ->getCompressedTCarray())
         * @return      void
         * @see getCompressedTCarray()
         */
-       function includeTCA($TCAloaded=1)       {
-               global $TCA, $PAGES_TYPES, $LANG_GENERAL_LABELS, $TBE_MODULES;
+       function includeTCA($TCAloaded = 1) {
+                       // do not remove this global declaration - it's used inside the ext_tables.php files
+               global $TCA;
                if (!$this->TCAloaded)  {
-                       $TCA = Array();
+                       $GLOBALS['TCA'] = array();
                        include (TYPO3_tables_script ? PATH_typo3conf.TYPO3_tables_script : PATH_t3lib.'stddb/tables.php');
                                // Extension additions
                        if ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE']) {
@@ -2245,6 +2291,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         */
        function settingLanguage()      {
 
+               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess']))   {
+                       $_params = array();
+                       foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] as $_funcRef)   {
+                               t3lib_div::callUserFunction($_funcRef, $_params, $this);
+                       }
+               }
+
                        // Get values from TypoScript:
                $this->sys_language_uid = $this->sys_language_content = intval($this->config['config']['sys_language_uid']);
                list($this->sys_language_mode,$sys_language_content) = t3lib_div::trimExplode(';', $this->config['config']['sys_language_mode']);
@@ -2310,14 +2363,12 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        // Updating content of the two rootLines IF the language key is set!
                if ($this->sys_language_uid && is_array($this->tmpl->rootLine)) {
-                       reset($this->tmpl->rootLine);
-                       while(list($rLk)=each($this->tmpl->rootLine))   {
+                       foreach ($this->tmpl->rootLine as $rLk => $value) {
                                $this->tmpl->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->tmpl->rootLine[$rLk]);
                        }
                }
                if ($this->sys_language_uid && is_array($this->rootLine))       {
-                       reset($this->rootLine);
-                       while(list($rLk)=each($this->rootLine)) {
+                       foreach ($this->rootLine as $rLk => $value) {
                                $this->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->rootLine[$rLk]);
                        }
                }
@@ -2344,6 +2395,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        list($tN,$fN) = explode(':',$TF);
                        $this->TCAcachedExtras[$tN]['l10n_mode'][$fN] = 'exclude';
                }
+
+               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess']))  {
+                       $_params = array();
+                       foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] as $_funcRef)  {
+                               t3lib_div::callUserFunction($_funcRef, $_params, $this);
+                       }
+               }
        }
 
        /**
@@ -2355,7 +2413,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
 
                        // Setting locale
                if ($this->config['config']['locale_all'])      {
-                       # Change by Rene Fritz, 22/10 2002
+                       # Change by René Fritz, 22/10 2002
                        # there's a problem that PHP parses float values in scripts wrong if the locale LC_NUMERIC is set to something with a comma as decimal point
                        # this does not work in php 4.2.3
                        #setlocale('LC_ALL',$this->config['config']['locale_all']);
@@ -2364,7 +2422,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        # so we set all except LC_NUMERIC
                        $locale = setlocale(LC_COLLATE, $this->config['config']['locale_all']);
                        if ($locale) {
-                               setlocale(LC_CTYPE, $this->config['config']['locale_all']);
+
+                                       // PHP fatals with uppercase I characters in method names with turkish locale LC_CTYPE
+                                       // @see http://bugs.php.net/bug.php?id=35050
+                               if (substr($this->config['config']['locale_all'], 0, 2) != 'tr') {
+                                       setlocale(LC_CTYPE, $this->config['config']['locale_all']);
+                               }
+
                                setlocale(LC_MONETARY, $this->config['config']['locale_all']);
                                setlocale(LC_TIME, $this->config['config']['locale_all']);
 
@@ -2436,7 +2500,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        // Hook for processing data submission to extensions:
                if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission']))  {
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $_classRef)  {
-                               $_procObj = &t3lib_div::getUserObj($_classRef);
+                               $_procObj = t3lib_div::getUserObj($_classRef);
                                $_procObj->checkDataSubmission($this);
                        }
                }
@@ -2448,7 +2512,6 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         *
         * @return      void
         * @see tslib_feTCE
-        * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=342&cHash=fdf55adb3b
         */
        function fe_tce()       {
                $fe_tce = t3lib_div::makeInstance('tslib_feTCE');
@@ -2499,7 +2562,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                                $EMAIL_VARS[$fieldKey] = $res;  // Set value if OK
                                        } elseif ($integrityCheck)      {       // Otherwise abort:
                                                $GLOBALS['TT']->setTSlogMessage('"Formmail" discovered a field ('.$fieldKey.') which could not be decoded to a valid string. Sending formmail aborted due to security reasons!',3);
-                                               return false;
+                                               return FALSE;
                                        } else {
                                                $GLOBALS['TT']->setTSlogMessage('"Formmail" discovered a field ('.$fieldKey.') which could not be decoded to a valid string. The security level accepts this, but you should consider a correct coding though!',2);
                                        }
@@ -2515,7 +2578,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        // Hook for preprocessing of the content for formmails:
                if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass']))    {
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass'] as $_classRef)    {
-                               $_procObj = &t3lib_div::getUserObj($_classRef);
+                               $_procObj = t3lib_div::getUserObj($_classRef);
                                $EMAIL_VARS = $_procObj->sendFormmail_preProcessVariables($EMAIL_VARS,$this);
                        }
                }
@@ -2577,28 +2640,33 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        function jumpUrl()      {
                if ($this->jumpurl)     {
                        if (t3lib_div::_GP('juSecure')) {
+                               $locationData = (string)t3lib_div::_GP('locationData');
+                               $mimeType = (string)t3lib_div::_GP('mimeType');  // Need a type cast here because mimeType is optional!
+
                                $hArr = array(
                                        $this->jumpurl,
-                                       t3lib_div::_GP('locationData'),
-                                       $this->TYPO3_CONF_VARS['SYS']['encryptionKey']
+                                       $locationData,
+                                       $mimeType
                                );
-                               $calcJuHash=t3lib_div::shortMD5(serialize($hArr));
-                               $locationData = t3lib_div::_GP('locationData');
-                               $juHash = t3lib_div::_GP('juHash');
-                               if ($juHash == $calcJuHash)     {
+                               $calcJuHash = t3lib_div::hmac(serialize($hArr));
+                               $juHash = (string)t3lib_div::_GP('juHash');
+                               if ($juHash === $calcJuHash)    {
                                        if ($this->locDataCheck($locationData)) {
                                                $this->jumpurl = rawurldecode($this->jumpurl);  // 211002 - goes with cObj->filelink() rawurlencode() of filenames so spaces can be allowed.
-                                               if (@is_file($this->jumpurl))   {
-                                                       $mimeType = t3lib_div::_GP('mimeType');
-                                                       $mimeType = $mimeType ? $mimeType : 'application/octet-stream';
-                                                       header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
-                                                       header('Content-Type: '.$mimeType);
-                                                       header('Content-Disposition: attachment; filename='.basename($this->jumpurl));
-                                                       readfile($this->jumpurl);
-                                                       exit;
-                                               } else die('jumpurl Secure: "'.$this->jumpurl.'" was not a valid file!');
-                                       } else die('jumpurl Secure: locationData, '.$locationData.', was not accessible.');
-                               } else die('jumpurl Secure: Calculated juHash did not match the submitted juHash.');
+                                                       // Deny access to files that match TYPO3_CONF_VARS[SYS][fileDenyPattern] and whose parent directory is typo3conf/ (there could be a backup file in typo3conf/ which does not match against the fileDenyPattern)
+                                               $absoluteFileName = t3lib_div::getFileAbsFileName(t3lib_div::resolveBackPath($this->jumpurl), FALSE);
+                                               if (t3lib_div::isAllowedAbsPath($absoluteFileName) && t3lib_div::verifyFilenameAgainstDenyPattern($absoluteFileName) && !t3lib_div::isFirstPartOfStr($absoluteFileName, PATH_site . 'typo3conf')) {
+                                                       if (@is_file($absoluteFileName)) {
+                                                               $mimeType = $mimeType ? $mimeType : 'application/octet-stream';
+                                                               header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+                                                               header('Content-Type: '.$mimeType);
+                                                               header('Content-Disposition: attachment; filename="'.basename($absoluteFileName) . '"');
+                                                               readfile($absoluteFileName);
+                                                               exit;
+                                                       } else throw new Exception('jumpurl Secure: "' . $this->jumpurl . '" was not a valid file!', 1294585193);
+                                               } else throw new Exception('jumpurl Secure: The requested file was not allowed to be accessed through jumpUrl (path or file not allowed)!', 1294585194);
+                                       } else throw new Exception('jumpurl Secure: locationData, ' . $locationData . ', was not accessible.', 1294585195);
+                               } else throw new Exception('jumpurl Secure: Calculated juHash did not match the submitted juHash.', 1294585196);
                        } else {
                                $TSConf = $this->getPagesTSconfig();
                                if ($TSConf['TSFE.']['jumpUrl_transferSession'])        {
@@ -2609,23 +2677,21 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                if ($TSConf['TSFE.']['jumpURL_HTTPStatusCode']) {
                                        switch (intval($TSConf['TSFE.']['jumpURL_HTTPStatusCode'])){
                                                case 301:
-                                                       header(t3lib_div::HTTP_STATUS_301);
+                                                       $statusCode = t3lib_utility_Http::HTTP_STATUS_301;
                                                        break;
                                                case 302:
-                                                       header(t3lib_div::HTTP_STATUS_302);
-                                                       break;
-                                               case 303:
-                                                       header(t3lib_div::HTTP_STATUS_303);
+                                                       $statusCode = t3lib_utility_Http::HTTP_STATUS_302;
                                                        break;
                                                case 307:
-                                                       header(t3lib_div::HTTP_STATUS_307);
+                                                       $statusCode = t3lib_utility_Http::HTTP_STATUS_307;
                                                        break;
+                                               case 303:
                                                default:
+                                                       $statusCode = t3lib_utility_Http::HTTP_STATUS_303;
                                                        break;
                                        }
                                }
-                               header('Location: '.$this->jumpurl);
-                               exit;
+                               t3lib_utility_Http::redirect($this->jumpurl, $statusCode);
                        }
                }
        }
@@ -2674,7 +2740,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         *******************************************/
 
        /**
-        * Returns true if the page should be generated
+        * Returns TRUE if the page should be generated
         * That is if jumpurl is not set and the cacheContentFlag is not set.
         *
         * @return      boolean
@@ -2690,7 +2756,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function tempPageCacheContent() {
-               $this->tempContent = false;
+               $this->tempContent = FALSE;
 
                if (!$this->no_cache)   {
                        $seconds = 30;
@@ -2725,7 +2791,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $padSuffix = '<!--pad-->';      // prevent any trims
                        $padSize = 768 - strlen($padSuffix) - strlen($temp_content);
                        if ($padSize > 0) {
-                               $temp_content = str_pad($temp_content, $padSize, "\n") . $padSuffix;
+                               $temp_content = str_pad($temp_content, $padSize, LF) . $padSuffix;
                        }
 
                        if (!$this->headerNoCache() && $cachedRow = $this->getFromCache_queryRow())     {
@@ -2747,21 +2813,17 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function realPageCacheContent() {
-               $cache_timeout = $this->get_cache_timeout();            // seconds until a cached page is too old
-               $timeOutTime = $GLOBALS['EXEC_TIME']+$cache_timeout;
-               if ($this->config['config']['cache_clearAtMidnight'])   {
-                       $midnightTime = mktime (0,0,0,date('m',$timeOutTime),date('d',$timeOutTime),date('Y',$timeOutTime));
-                       if ($midnightTime > $GLOBALS['EXEC_TIME'])      {               // If the midnight time of the expire-day is greater than the current time, we may set the timeOutTime to the new midnighttime.
-                               $timeOutTime = $midnightTime;
-                       }
-               }
-               $this->tempContent = false;
+                       // seconds until a cached page is too old
+               $cacheTimeout = $this->get_cache_timeout();
+               $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
+               $this->tempContent = FALSE;
+
                $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
 
                        // Hook for cache post processing (eg. writing static files!)
                if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache']))    {
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] as $_classRef)    {
-                               $_procObj = &t3lib_div::getUserObj($_classRef);
+                               $_procObj = t3lib_div::getUserObj($_classRef);
                                $_procObj->insertPageIncache($this,$timeOutTime);
                        }
                }
@@ -2777,35 +2839,55 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @see realPageCacheContent(), tempPageCacheContent()
         */
        function setPageCacheContent($content, $data, $expirationTstamp) {
-               $this->clearPageCacheContent();
-
-               $cacheData = array(
-                       'hash'         => $this->newHash,
-                       'page_id'      => $this->id,
-                       'HTML'         => $content,
-                       'temp_content' => $this->tempContent,
-                       'cache_data'   => serialize($data),
-                       'expires'      => $expirationTstamp,
-                       'tstamp'       => $GLOBALS['EXEC_TIME']
-               );
 
-               $this->cacheExpires = $expirationTstamp;
+               if (TYPO3_UseCachingFramework) {
+                       $cacheData = array(
+                               'identifier'    => $this->newHash,
+                               'page_id'               => $this->id,
+                               'content'                       => $content,
+                               'temp_content'  => $this->tempContent,
+                               'cache_data'    => serialize($data),
+                               'expires'               => $expirationTstamp,
+                               'tstamp'                => $GLOBALS['EXEC_TIME']
+                       );
 
-               $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
+                       $this->cacheExpires = $expirationTstamp;
 
-               if ($this->page_cache_reg1) {
-                       $reg1 = intval($this->page_cache_reg1);
+                       $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
 
-                       $cacheData['reg1']     = $reg1;
-                       $this->pageCacheTags[] = 'reg1_' . $reg1;
-               }
+                       if ($this->page_cache_reg1) {
+                               $reg1 = intval($this->page_cache_reg1);
 
-               $this->pageCache->set(
-                       $cacheData['hash'],
-                       $cacheData,
-                       $this->pageCacheTags,
-                       $cacheData['expires'] - $GLOBALS['EXEC_TIME']
-               );
+                               $cacheData['reg1']     = $reg1;
+                               $this->pageCacheTags[] = 'reg1_' . $reg1;
+                       }
+
+                       $this->pageCache->set(
+                               $this->newHash,
+                               $cacheData,
+                               $this->pageCacheTags,
+                               $expirationTstamp - $GLOBALS['EXEC_TIME']
+                       );
+               } else {
+                       $this->clearPageCacheContent();
+                       $insertFields = array(
+                               'hash' => $this->newHash,
+                               'page_id' => $this->id,
+                               'HTML' => $content,
+                               'temp_content' => $this->tempContent,
+                               'cache_data' => serialize($data),
+                               'expires' => $expirationTstamp,
+                               'tstamp' => $GLOBALS['EXEC_TIME']
+                       );
+
+                       $this->cacheExpires = $expirationTstamp;
+
+                       if ($this->page_cache_reg1)     {
+                               $insertFields['reg1'] = intval($this->page_cache_reg1);
+                       }
+                       $this->pageCachePostProcess($insertFields,'set');
+                       $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_pages', $insertFields);
+               }
        }
 
        /**
@@ -2814,7 +2896,34 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function clearPageCacheContent() {
-               $this->pageCache->remove($this->newHash);
+               if (TYPO3_UseCachingFramework) {
+                       $this->pageCache->remove($this->newHash);
+               } else {
+                       $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages'));
+               }
+       }
+
+       /**
+        * Post processing page cache rows for both get and set.
+        *
+        * @param       array           Input "cache_pages" row, passed by reference!
+        * @param       string          Type of operation, either "get" or "set"
+        * @return      void
+        */
+       function pageCachePostProcess(&$row,$type)      {
+
+               if ($this->TYPO3_CONF_VARS['FE']['pageCacheToExternalFiles'])   {
+                       $cacheFileName = PATH_site.'typo3temp/cache_pages/'.$row['hash']{0}.$row['hash']{1}.'/'.$row['hash'].'.html';
+                       switch((string)$type)   {
+                               case 'get':
+                                       $row['HTML'] = @is_file($cacheFileName) ? t3lib_div::getUrl($cacheFileName) : '<!-- CACHING ERROR, sorry -->';
+                               break;
+                               case 'set':
+                                       t3lib_div::writeFileToTypo3tempDir($cacheFileName, $row['HTML']);
+                                       $row['HTML'] = '';
+                               break;
+                       }
+               }
        }
 
        /**
@@ -2824,10 +2933,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * @return      void
         */
        function clearPageCacheContent_pidList($pidList) {
-               $pageIds = t3lib_div::trimExplode(',', $pidList);
-
-               foreach ($pageIds as $pageId) {
-                       $this->pageCache->flushByTag('pageId_' . (int) $pageId);
+               if (TYPO3_UseCachingFramework) {
+                       $pageIds = t3lib_div::trimExplode(',', $pidList);
+                       foreach ($pageIds as $pageId) {
+                               $this->pageCache->flushByTag('pageId_' . (int) $pageId);
+                       }
+               } else {
+                       $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($pidList).')');
                }
        }
 
@@ -2850,13 +2962,13 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         *
         * @param       t3lib_lock      Reference to a locking object
         * @param       string          String to identify the lock in the system
-        * @return      boolean         Returns true if the lock could be obtained, false otherwise (= process had to wait for existing lock to be released)
+        * @return      boolean         Returns TRUE if the lock could be obtained, FALSE otherwise (= process had to wait for existing lock to be released)
         * @see releasePageGenerationLock()
         */
        function acquirePageGenerationLock(&$lockObj, $key)     {
                if ($this->no_cache || $this->headerNoCache()) {
                        t3lib_div::sysLog('Locking: Page is not cached, no locking required', 'cms', t3lib_div::SYSLOG_SEVERITY_INFO);
-                       return true;    // No locking is needed if caching is disabled
+                       return TRUE;    // No locking is needed if caching is disabled
                }
 
                try {
@@ -2864,10 +2976,10 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                                $lockObj = t3lib_div::makeInstance('t3lib_lock', $key, $this->TYPO3_CONF_VARS['SYS']['lockingMode']);
                        }
 
-                       $success = false;
+                       $success = FALSE;
                        if (strlen($key)) {
-                                       // true = Page could get locked without blocking
-                                       // false = Page could get locked but process was blocked before
+                                       // TRUE = Page could get locked without blocking
+                                       // FALSE = Page could get locked but process was blocked before
                                $success = $lockObj->acquire();
                                if ($lockObj->getLockStatus()) {
                                        $lockObj->sysLog('Acquired lock');
@@ -2875,7 +2987,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        }
                } catch (Exception $e) {
                        t3lib_div::sysLog('Locking: Failed to acquire lock: '.$e->getMessage(), 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
-                       $success = false;       // If locking fails, return with false and continue without locking
+                       $success = FALSE;       // If locking fails, return with FALSE and continue without locking
                }
 
                return $success;
@@ -2885,19 +2997,19 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
         * Release the page generation lock
         *
         * @param       t3lib_lock      Reference to a locking object
-        * @return      boolean         Returns true on success, false otherwise
+        * @return      boolean         Returns TRUE on success, FALSE otherwise
         * @see acquirePageGenerationLock()
         */
        function releasePageGenerationLock(&$lockObj) {
-               $success = false;
+               $success = FALSE;
                        // If lock object is set and was acquired (may also happen if no_cache was enabled during runtime), release it:
                if (is_object($lockObj) && $lockObj instanceof t3lib_lock && $lockObj->getLockStatus()) {
                        $success = $lockObj->release();
                        $lockObj->sysLog('Released lock');
-                       $lockObj = null;
+                       $lockObj = NULL;
                        // Otherwise, if caching is disabled, no locking is required:
                } elseif ($this->no_cache || $this->headerNoCache()) {
-                       $success = true;
+                       $success = TRUE;
                }
                return $success;
        }
@@ -2947,7 +3059,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                $this->newHash = $this->getHash();      // Same codeline as in getFromCache(). But $this->all has been changed by t3lib_TStemplate::start() in the meantime, so this must be called again!
                $this->config['hash_base'] = $this->hash_base;  // For cache management informational purposes.
 
-               if (!is_object($this->pages_lockObj) || $this->pages_lockObj->getLockStatus()==false) {
+               if (!is_object($this->pages_lockObj) || $this->pages_lockObj->getLockStatus()==FALSE) {
                                // Here we put some temporary stuff in the cache in order to let the first hit generate the page. The temporary cache will expire after a few seconds (typ. 30) or will be cleared by the rendered page, which will also clear and rewrite the cache.
                        $this->tempPageCacheContent();
                }
@@ -3048,7 +3160,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        // Hook for indexing pages
                if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'])) {
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'] as $_classRef) {
-                               $_procObj = &t3lib_div::getUserObj($_classRef);
+                               $_procObj = t3lib_div::getUserObj($_classRef);
                                $_procObj->hook_indexContent($this);
                        }
                }
@@ -3058,7 +3170,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $this->realPageCacheContent();
                } elseif ($this->tempContent)   {               // If there happens to be temporary content in the cache and the cache was not cleared due to new content, put it in... ($this->no_cache=0)
                        $this->clearPageCacheContent();
-                       $this->tempContent = false;
+                       $this->tempContent = FALSE;
                }
 
                        // Release open locks
@@ -3089,12 +3201,12 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
                        $this->INTincScript_process($INTiS_config);
                                // Check if there were new items added to INTincScript during the previous execution:
                        $INTiS_config = array_diff_assoc($this->config['INTincScript'], $INTiS_config);
-                       $reprocess = (count($INTiS_config) ? true : false);
+                       $reprocess = (count($INTiS_config) ? TRUE : FALSE);
                } while($reprocess);
 
                $GLOBALS['TT']->push('Substitute header section');
                $this->INTincScript_loadJSCode();
-               $this->content = str_replace('<!--HD_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset(implode(chr(10),$this->additionalHeaderData),'HD'), $this->content);
+               $this->content = str_replace('<!--HD_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset(implode(LF,$this->additionalHeaderData),'HD'), $this->content);
                $this->content = str_replace('<!--TDS_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset($this->divSection,'TDS'), $this->content);
                $this->setAbsRefPrefix();
                $GLOBALS['TT']->pull();
@@ -3110,7 +3222,7 @@ require_once (PATH_t3lib.'class.t3lib_lock.php');
        protected function INTincScript_includeLibs($INTiS_config) {
                foreach($INTiS_config as $INTiS_cPart) {
                        if (isset($INTiS_cPart['conf']['includeLibs']) && $INTiS_cPart['conf']['includeLibs']) {
-                               $INTiS_resourceList = t3lib_div::trimExplode(',', $INTiS_cPart['conf']['includeLibs'], true);
+                               $INTiS_resourceList = t3lib_div::trimExplode(',', $INTiS_cPart['conf']['includeLibs'], TRUE);
                                $this->includeLibraries($INTiS_resourceList);
                        }
                }
@@ -3187,7 +3299,7 @@ if (version == "n3") {
 <script type="text/javascript">
        /*<![CDATA[*/
 <!--
-'.implode(chr(10),$this->additionalJavaScript).'
+'.implode(LF,$this->additionalJavaScript).'
 '.trim($this->JSCode).'
 // -->
        /*]]>*/
@@ -3198,7 +3310,7 @@ if (version == "n3") {
 <style type="text/css">
        /*<![CDATA[*/
 <!--
-'.implode(chr(10),$this->additionalCSS).'
+'.implode(LF,$this->additionalCSS).'
 // -->
        /*]]>*/
 </style>';
@@ -3208,7 +3320,7 @@ if (version == "n3") {
        /**
         * Determines if there are any INTincScripts to include
         *
-        * @return      boolean         Returns true if scripts are found (and not jumpurl)
+        * @return      boolean         Returns TRUE if scripts are found (and not jumpurl)
         */
        function isINTincScript()       {
                return  (is_array($this->config['INTincScript']) && !$this->jumpurl);
@@ -3229,7 +3341,7 @@ if (version == "n3") {
         * @return      string          Keyword: "all", "cached" or "output"
         */
        function doLocalAnchorFix()     {
-               return $this->config['config']['prefixLocalAnchors'];
+               return (isset($this->config['config']['prefixLocalAnchors'])) ? $this->config['config']['prefixLocalAnchors'] : NULL;
        }
 
 
@@ -3257,7 +3369,7 @@ if (version == "n3") {
         * Determines if content should be outputted.
         * Outputting content is done only if jumpUrl is NOT set.
         *
-        * @return      boolean         Returns true if $this->jumpurl is not set.
+        * @return      boolean         Returns TRUE if $this->jumpurl is not set.
         */
        function isOutputting() {
 
@@ -3265,7 +3377,9 @@ if (version == "n3") {
                $enableOutput = (!$this->jumpurl);
 
                        // Call hook for possible disabling of output:
-               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])) {
+               if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])
+                       && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])) {
+
                        $_params = array('pObj' => &$this, 'enableOutput' => &$enableOutput);
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'] as $_funcRef)  {
                                t3lib_div::callUserFunction($_funcRef,$_params,$this);
@@ -3282,23 +3396,23 @@ if (version == "n3") {
         *
         * @return      void
         */
-       function processOutput()        {
+       function processOutput() {
 
                        // Set header for charset-encoding unless disabled
-               if (!$this->config['config']['disableCharsetHeader'])   {
+               if (empty($this->config['config']['disableCharsetHeader'])) {
                        $headLine = 'Content-Type: text/html; charset='.trim($this->metaCharset);
                        header($headLine);
                }
 
                        // Set cache related headers to client (used to enable proxy / client caching!)
-               if ($this->config['config']['sendCacheHeaders'])        {
+               if (!empty($this->config['config']['sendCacheHeaders'])) {
                        $this->sendCacheHeaders();
                }
 
                        // Set headers, if any
-               if ($this->config['config']['additionalHeaders'])       {
+               if (!empty($this->config['config']['additionalHeaders'])) {
                        $headerArray = explode('|', $this->config['config']['additionalHeaders']);
-                       while(list(,$headLine)=each($headerArray))      {
+                       foreach ($headerArray as $headLine) {
                                $headLine = trim($headLine);
                                header($headLine);
                        }
@@ -3310,7 +3424,7 @@ if (version == "n3") {
                }
 
                        // Make substitution of eg. username/uid in content only if cache-headers for client/proxy caching is NOT sent!
-               if (!$this->isClientCachable)   {
+               if (!$this->isClientCachable) {
                        $this->contentStrReplace();
                }
 
@@ -3321,30 +3435,30 @@ if (version == "n3") {
                        $GLOBALS['TT']->pull();
                }
                        // XHTML-clean the code, if flag set
-               if ($this->doXHTML_cleaning() == 'output')              {
+               if ($this->doXHTML_cleaning() == 'output') {
                        $GLOBALS['TT']->push('XHTML clean, output','');
                                $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
                                $this->content = $XHTML_clean->XHTML_clean($this->content);
                        $GLOBALS['TT']->pull();
                }
                        // Fix local anchors in links, if flag set
-               if ($this->doLocalAnchorFix() == 'output')              {
+               if ($this->doLocalAnchorFix() == 'output') {
                        $GLOBALS['TT']->push('Local anchor fix, output','');
                                $this->prefixLocalAnchorsWithScript();
                        $GLOBALS['TT']->pull();
                }
 
                        // Hook for post-processing of page content before output:
-               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output']))       {
+               if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'])) {
                        $_params = array('pObj' => &$this);
-                       foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] as $_funcRef)        {
+                       foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] as $_funcRef) {
                                t3lib_div::callUserFunction($_funcRef,$_params,$this);
                        }
                }
 
                        // Send content-lenght header.
                        // Notice that all HTML content outside the length of the content-length header will be cut off! Therefore content of unknown length from included PHP-scripts and if admin users are logged in (admin panel might show...) or if debug mode is turned on, we disable it!
-               if ($this->config['config']['enableContentLengthHeader'] &&
+               if (!empty($this->config['config']['enableContentLengthHeader']) &&
                        !$this->isEXTincScript() &&
                        !$this->beUserLogin  &&
                        !$this->TYPO3_CONF_VARS['FE']['debug'] &&
@@ -3368,7 +3482,7 @@ if (version == "n3") {
                $doCache = $this->isStaticCacheble();
 
                        // This variable will be TRUE unless cache headers are configured to be sent ONLY if a branch does not allow logins and logins turns out to be allowed anyway...
-               $loginsDeniedCfg = !$this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch'] || !$this->loginAllowedInBranch;
+               $loginsDeniedCfg = (empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch));
 
                        // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
                if ($doCache
@@ -3451,12 +3565,12 @@ if (version == "n3") {
                if ($this->fe_user->user['uid'])        {
 
                                // User name:
-                       $token = trim($this->config['config']['USERNAME_substToken']);
+                       $token = (isset($this->config['config']['USERNAME_substToken'])) ? trim($this->config['config']['USERNAME_substToken']) : '';
                        $search[] = ($token ? $token : '<!--###USERNAME###-->');
                        $replace[] = $this->fe_user->user['username'];
 
                                // User uid (if configured):
-                       $token = trim($this->config['config']['USERUID_substToken']);
+                       $token = (isset($this->config['config']['USERUID_substToken'])) ? trim($this->config['config']['USERUID_substToken']) : '';
                        if ($token) {
                                $search[] = $token;
                                $replace[] = $this->fe_user->user['uid'];
@@ -3491,11 +3605,11 @@ if (version == "n3") {
        /**
         * Determines if any EXTincScripts should be included
         *
-        * @return      boolean         True, if external php scripts should be included (set by PHP_SCRIPT_EXT cObjects)
+        * @return      boolean         TRUE, if external php scripts should be included (set by PHP_SCRIPT_EXT cObjects)
         * @see tslib_cObj::PHP_SCRIPT
         */
        function isEXTincScript()       {
-               return is_array($this->config['EXTincScript']);
+               return (isset($this->config['EXTincScript']) && is_array($this->config['EXTincScript']));
        }
 
        /**
@@ -3514,21 +3628,25 @@ if (version == "n3") {
         * @access private
         */
        function setParseTime() {
-                       // Compensates for the time consumed with Back end user initialization.
-               $this->scriptParseTime = $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_end'])
-                                                               - $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_start'])
-                                                               - ($GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'])-$GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_start']));
-       }
+        // Compensates for the time consumed with Back end user initialization.
+        $microtime_start            = (isset($GLOBALS['TYPO3_MISC']['microtime_start'])) ? $GLOBALS['TYPO3_MISC']['microtime_start'] : NULL;
+        $microtime_end              = (isset($GLOBALS['TYPO3_MISC']['microtime_end'])) ? $GLOBALS['TYPO3_MISC']['microtime_end'] : NULL;
+        $microtime_BE_USER_start    = (isset($GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'])) ? $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] : NULL;
+        $microtime_BE_USER_end      = (isset($GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'])) ? $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] : NULL;
+
+        $this->scriptParseTime = $GLOBALS['TT']->getMilliseconds($microtime_end) - $GLOBALS['TT']->getMilliseconds($microtime_start)
+                                - ($GLOBALS['TT']->getMilliseconds($microtime_BE_USER_end) - $GLOBALS['TT']->getMilliseconds($microtime_BE_USER_start));
+    }
 
        /**
         * Initialize file-based statistics handling: Check filename and permissions, and create the logfile if it does not exist yet.
         * This function should be called with care because it might overwrite existing settings otherwise.
         *
-        * @return      boolean         True if statistics are enabled (will require some more processing after charset handling is initialized)
+        * @return      boolean         TRUE if statistics are enabled (will require some more processing after charset handling is initialized)
         * @access private
         */
        protected function statistics_init()    {
-               $setStatPageName = false;
+               $setStatPageName = FALSE;
                $theLogFile = $this->TYPO3_CONF_VARS['FE']['logfile_dir'].strftime($this->config['config']['stat_apache_logfile']);
 
                        // Add PATH_site left to $theLogFile if the path is not absolute yet
@@ -3545,7 +3663,7 @@ if (version == "n3") {
 
                                if (@is_file($theLogFile) && @is_writable($theLogFile)) {
                                        $this->config['stat_vars']['logFile'] = $theLogFile;
-                                       $setStatPageName = true;        // Set page name later on
+                                       $setStatPageName = TRUE;        // Set page name later on
                                } else {
                                        $GLOBALS['TT']->setTSlogMessage('Could not set logfile path. Check filepath and permissions.',3);
                                }
@@ -3627,13 +3745,13 @@ if (version == "n3") {
         * @return      void
         */
        function statistics()   {
-               if ($this->config['config']['stat'] &&
+               if (!empty($this->config['config']['stat']) &&
                                (!strcmp('',$this->config['config']['stat_typeNumList']) || t3lib_div::inList(str_replace(' ','',$this->config['config']['stat_typeNumList']), $this->type)) &&
-                               (!$this->config['config']['stat_excludeBEuserHits'] || !$this->beUserLogin) &&
-                               (!$this->config['config']['stat_excludeIPList'] || !t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'),str_replace(' ','',$this->config['config']['stat_excludeIPList'])))) {
+                               (empty($this->config['config']['stat_excludeBEuserHits']) || !$this->beUserLogin) &&
+                               (empty($this->config['config']['stat_excludeIPList']) || !t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'),str_replace(' ','',$this->config['config']['stat_excludeIPList'])))) {
 
                        $GLOBALS['TT']->push('Stat');
-                               if (t3lib_extMgm::isLoaded('sys_stat') && $this->config['config']['stat_mysql'])        {
+                               if (t3lib_extMgm::isLoaded('sys_stat') && !empty($this->config['config']['stat_mysql'])) {
 
                                                // Jumpurl:
                                        $sword = t3lib_div::_GP('sword');
@@ -3679,9 +3797,9 @@ if (version == "n3") {
                                        );
 
                                                // Hook for preprocessing the list of fields to insert into sys_stat:
-                                       if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass']))    {
+                                       if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass'])) {
                                                foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass'] as $_classRef)    {
-                                                       $_procObj = &t3lib_div::getUserObj($_classRef);
+                                                       $_procObj = t3lib_div::getUserObj($_classRef);
                                                        $insertFields = $_procObj->sysstat_preProcessFields($insertFields,$this);
                                                }
                                        }
@@ -3693,11 +3811,11 @@ if (version == "n3") {
                                }
 
                                        // Apache:
-                               if ($this->config['config']['stat_apache'] && $this->config['stat_vars']['pageName'])   {
+                               if (!empty($this->config['config']['stat_apache']) && !empty($this->config['stat_vars']['pageName'])) {
                                        if (@is_file($this->config['stat_vars']['logFile'])) {
                                                        // Build a log line (format is derived from the NCSA extended/combined log format)
                                                        // Log part 1: Remote hostname / address
-                                               $LogLine = (t3lib_div::getIndpEnv('REMOTE_HOST') && !$this->config['config']['stat_apache_noHost']) ? t3lib_div::getIndpEnv('REMOTE_HOST') : t3lib_div::getIndpEnv('REMOTE_ADDR');
+                                               $LogLine = (t3lib_div::getIndpEnv('REMOTE_HOST') && empty($this->config['config']['stat_apache_noHost'])) ? t3lib_div::getIndpEnv('REMOTE_HOST') : t3lib_div::getIndpEnv('REMOTE_ADDR');
                                                        // Log part 2: Fake the remote logname
                                                $LogLine.= ' -';
                                                        // Log part 3: Remote username
@@ -3709,14 +3827,14 @@ if (version == "n3") {
                                                        // Log part 6: Status and content length (ignores special content like admin panel!)
                                                $LogLine.= ' 200 '.strlen($this->content);
 
-                                               if (!$this->config['config']['stat_apache_notExtended']) {
+                                               if (empty($this->config['config']['stat_apache_notExtended'])) {
                                                        $referer = t3lib_div::getIndpEnv('HTTP_REFERER');
                                                        $LogLine.= ' "'.($referer ? $referer : '-').'" "'.t3lib_div::getIndpEnv('HTTP_USER_AGENT').'"';
                                                }
 
                                                $GLOBALS['TT']->push('Write to log file (fputs)');
                                                        $logfilehandle = fopen($this->config['stat_vars']['logFile'], 'a');
-                                                       fputs($logfilehandle, $LogLine.chr(10));
+                                                       fputs($logfilehandle, $LogLine.LF);
                                                        @fclose($logfilehandle);
                                                $GLOBALS['TT']->pull();
 
@@ -3735,26 +3853,15 @@ if (version == "n3") {
         * @return      void
         */
        function previewInfo()  {
-               if ($this->fePreview)   {
-                               if ($this->fePreview==2)        {
-                                       $onclickForStoppingPreview = 'document.location="'.t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev=LOGOUT&returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')).'";return false;';
-                                       $text = 'Preview of workspace "'.$this->whichWorkspace(TRUE).'" ('.$this->whichWorkspace().')';
-                                       $html = $this->doWorkspacePreview() ? '<br/><input name="_" type="submit" value="Stop preview" onclick="'.htmlspecialchars($onclickForStoppingPreview).'" />' : '';
-                               } else {
-                                       $text = 'PREVIEW!';
-                                       $html = '';
-                               }
-
-                               $stdMsg = '<div id="typo3-previewInfo" style="position: absolute; top: 20px; right: 20px; border: 2px solid #000; padding: 5px 5px; background: #f00; font: 1em Verdana; color: #000; font-weight: bold; z-index: 10001">'.htmlspecialchars($text).$html.'</div>';
-
-                               if ($this->fePreview==2)        {
-                                       $temp_content = $this->config['config']['message_preview_workspace'] ?
-                                               @sprintf($this->config['config']['message_preview_workspace'], $this->whichWorkspace(TRUE),$this->whichWorkspace()) :
-                                               $stdMsg;
-                               } else {
-                                       $temp_content = $this->config['config']['message_preview'] ? $this->config['config']['message_preview'] : $stdMsg;
+               if ($this->fePreview !== 0) {
+                       $previewInfo = '';
+                       if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_previewInfo']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_previewInfo'])) {
+                               $_params = array('pObj' => &$this);
+                               foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_previewInfo'] as $_funcRef) {
+                                       $previewInfo .= t3lib_div::callUserFunction($_funcRef,$_params,$this);
                                }
-                               echo $temp_content;
+                       }
+                       $this->content = str_ireplace('</body>',  $previewInfo . '</body>', $this->content);
                }
        }
 
@@ -3766,7 +3873,7 @@ if (version == "n3") {
        function hook_eofe()    {
 
                        // Call hook for end-of-frontend processing:
-               if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe']))    {
+               if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'])) {
                        $_params = array('pObj' => &$this);
                        foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'] as $_funcRef)     {
                                t3lib_div::callUserFunction($_funcRef,$_params,$this);
@@ -3780,7 +3887,7 @@ if (version == "n3") {
         * @return      string          HTML, a tag for a link to the backend.
         */
        function beLoginLinkIPList()    {
-               if ($this->config['config']['beLoginLinkIPList']) {
+               if (!empty($this->config['config']['beLoginLinkIPList'])) {
                        if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $this->config['config']['beLoginLinkIPList']))       {
                                $label = !$this->beUserLogin ? $this->config['config']['beLoginLinkIPList_login'] : $this->config['config']['beLoginLinkIPList_logout'];
                                if ($label)     {
@@ -3845,9 +3952,12 @@ if (version == "n3") {
         * @param       boolean         The "no_cache" status of the link.
         * @return      string          The body of the filename.
         * @see getSimulFileName(), t3lib_tstemplate::linkData(), tslib_frameset::frameParams()
-        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.6, please use the "simulatestatic" sysext directly
+        * @todo        Deprecated but still used in the Core!
         */
-       function makeSimulFileName($inTitle, $page, $type, $addParams = '', $no_cache = false) {
+       function makeSimulFileName($inTitle, $page, $type, $addParams = '', $no_cache = FALSE) {
+               t3lib_div::logDeprecatedFunction();
+
                if (t3lib_extMgm::isLoaded('simulatestatic')) {
                        $parameters = array(
                                'inTitle' => $inTitle,
@@ -3862,7 +3972,7 @@ if (version == "n3") {
                                $this
                        );
                } else {
-                       return false;
+                       return FALSE;
                }
        }
 
@@ -3872,9 +3982,11 @@ if (version == "n3") {
         * @param       string          Query string to analyse
         * @return      array           Two num keys returned, first is the parameters that MAY be encoded, second is the non-encodable parameters.
         * @see makeSimulFileName(), t3lib_tstemplate::linkData()
-        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.6, please use the "simulatestatic" sysext directly
         */
        function simulateStaticDocuments_pEnc_onlyP_proc($linkVars)     {
+               t3lib_div::logDeprecatedFunction();
+
                if (t3lib_extMgm::isLoaded('simulatestatic')) {
                        return t3lib_div::callUserFunction(
                                'EXT:simulatestatic/class.tx_simulatestatic.php:&tx_simulatestatic->processEncodedQueryString',
@@ -3882,7 +3994,7 @@ if (version == "n3") {
                                $this
                        );
                } else {
-                       return false;
+                       return FALSE;
                }
        }
 
@@ -3891,9 +4003,12 @@ if (version == "n3") {
         *
         * @return      string          The filename (without path)
         * @see makeSimulFileName(), publish.php
-        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.6, please use the "simulatestatic" sysext directly
+        * @todo        Deprecated but still used in the Core!
         */
        function getSimulFileName()     {
+               t3lib_div::logDeprecatedFunction();
+
                return $this->makeSimulFileName(
                        $this->page['title'],
                        ($this->page['alias'] ? $this->page['alias'] : $this->id),
@@ -3905,9 +4020,11 @@ if (version == "n3") {
         * Checks and sets replacement character for simulateStaticDocuments. Default is underscore.
         *
         * @return      void
-        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.6, please use the "simulatestatic" sysext directly
         */
        function setSimulReplacementChar() {
+               t3lib_div::logDeprecatedFunction();
+
                $replacement = $defChar = t3lib_div::compat_version('4.0') ? '-' : '_';
                if (isset($this->config['config']['simulateStaticDocuments_replacementChar'])) {
                        $replacement = trim($this->config['config']['simulateStaticDocuments_replacementChar']);
@@ -3926,9 +4043,11 @@ if (version == "n3") {
         * @param       integer         Number of characters in the string
         * @param       string          Character to put in the end of string to merge it with the next value.
         * @return      string          String
-        * @deprecated since TYPO3, 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
+        * @deprecated since TYPO3, 4.3, will be removed in TYPO3 4.6, please use the "simulatestatic" sysext directly
+        * @todo        Deprecated but still used in the Core!
         */
        function fileNameASCIIPrefix($inTitle,$titleChars,$mergeChar='.')       {
+               t3lib_div::logDeprecatedFunction();
                $out = $this->csConvObj->specCharsToASCII($this->renderCharset, $inTitle);
                        // Get replacement character
                $replacementChar = $this->config['config']['simulateStaticDocuments_replacementChar'];
@@ -3958,7 +4077,7 @@ if (version == "n3") {
                $n = $n + $offset;
                if ($offset > 0 && $n > $end)   {
                        $n = $start + ($n - $end - 1);
-               } else if ($offset < 0 && $n < $start)  {
+               } elseif ($offset < 0 && $n < $start)   {
                        $n = $end - ($start - $n - 1);
                }
                return chr($n);
@@ -3988,7 +4107,7 @@ if (version == "n3") {
                                        $out .= $this->encryptCharcode($charValue,0x2B,0x3A,$offset);
                                } elseif ($charValue >= 0x40 && $charValue <= 0x5A)     {       // A-Z @
                                        $out .= $this->encryptCharcode($charValue,0x40,0x5A,$offset);
-                               } else if ($charValue >= 0x61 && $charValue <= 0x7A)    {       // a-z
+                               } elseif ($charValue >= 0x61 && $charValue <= 0x7A)     {       // a-z
                                        $out .= $this->encryptCharcode($charValue,0x61,0x7A,$offset);
                                } else {
                                        $out .= $string{$i};
@@ -4027,20 +4146,27 @@ if (version == "n3") {
        }
 
        /**
-        * Encrypts a strings by XOR'ing all characters with the ASCII value of a character in $this->TYPO3_CONF_VARS['SYS']['encryptionKey']
-        * If $this->TYPO3_CONF_VARS['SYS']['encryptionKey'] is empty, 255 is used for XOR'ing. Using XOR means that the string can be decrypted by simply calling the function again - just like rot-13 works (but in this case for ANY byte value).
+        * Encrypts a strings by XOR'ing all characters with a key derived from the
+        * TYPO3 encryption key.
         *
-        * @param       string          Input string
-        * @return      string          Output string
+        * Using XOR means that the string can be decrypted by simply calling the
+        * function again - just like rot-13 works (but in this case for ANY byte
+        * value).
+        *
+        * @param string $string string to crypt, may be empty
+        *
+        * @return string binary crypt string, will have the same length as $string
         */
-       function roundTripCryptString($string)  {
+       protected function roundTripCryptString($string) {
                $out = '';
-               $strLen = strlen($string);
-               $cryptLen = strlen($this->TYPO3_CONF_VARS['SYS']['encryptionKey']);
 
-               for ($a=0; $a < $strLen; $a++)  {
-                       $xorVal = $cryptLen>0 ? ord($this->TYPO3_CONF_VARS['SYS']['encryptionKey']{($a%$cryptLen)}) : 255;
-                       $out.= chr(ord($string{$a}) ^ $xorVal);
+               $cleartextLength = strlen($string);
+               $key = sha1($this->TYPO3_CONF_VARS['SYS']['encryptionKey']);
+               $keyLength = strlen($key);
+
+               for ($a = 0; $a < $cleartextLength; $a++) {
+                       $xorVal = ord($key{($a % $keyLength)});
+                       $out .= chr(ord($string{$a}) ^ $xorVal);
                }
 
                return $out;
@@ -4050,7 +4176,7 @@ if (version == "n3") {
         * Checks if a PHPfile may be included.
         *
         * @param       string          Relative path to php file
-        * @return      boolean         Returns true if $GLOBALS['TYPO3_CONF_VARS']['FE']['noPHPscriptInclude'] is not set OR if the file requested for inclusion is found in one of the allowed paths.
+        * @return      boolean         Returns TRUE if $GLOBALS['TYPO3_CONF_VARS']['FE']['noPHPscriptInclude'] is not set OR if the file requested for inclusion is found in one of the allowed paths.
         * @see tslib_cObj::PHP_SCRIPT(), tslib_feTCE::includeScripts(), tslib_menu::includeMakeMenu()
         */
        function checkFileInclude($incFile)     {
@@ -4084,10 +4210,13 @@ if (version == "n3") {
                if ($this->absRefPrefix)        {
                        $this->content = str_replace('"media/', '"'.t3lib_extMgm::siteRelPath('cms').'tslib/media/', $this->content);
                        $this->content = str_replace('"typo3conf/ext/', '"'.$this->absRefPrefix.'typo3conf/ext/', $this->content);
-                       $this->content = str_replace('"typo3/contrib/', '"'.$this->absRefPrefix.'typo3/contrib/', $this->content);
+                       $this->content = str_replace('"' . TYPO3_mainDir . 'contrib/', '"' . $this->absRefPrefix . TYPO3_mainDir . 'contrib/', $this->content);
+                       $this->content = str_replace('"' . TYPO3_mainDir . 'ext/', '"' . $this->absRefPrefix . TYPO3_mainDir . 'ext/', $this->content);
+                       $this->content = str_replace('"' . TYPO3_mainDir . 'sysext/' , '"' . $this->absRefPrefix . TYPO3_mainDir . 'sysext/', $this->content);
                        $this->content = str_replace('"'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '"'.$this->absRefPrefix.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], $this->content);
+                       $this->content = str_replace('"' . $GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_imageStorageDir'], '"' . $this->absRefPrefix . $GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_imageStorageDir'], $this->content);
                        // Process additional directories
-                       $directories = t3lib_div::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
+                       $directories = t3lib_div::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], TRUE);
                        foreach ($directories as $directory) {
                                $this->content = str_replace('"' . $directory, '"' . $this->absRefPrefix . $directory, $this->content);
                        }
@@ -4119,22 +4248,29 @@ if (version == "n3") {
         * @param       string          Header string
         * @return      void
         * @see t3lib_timeTrack::debug_typo3PrintError()
+        * @see t3lib_message_ErrorPageMessage
+        * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7
         */
-       function printError($label,$header='Error!')    {
-               t3lib_timeTrack::debug_typo3PrintError($header,$label,0,t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
+       function printError($label,$header='Error!') {
+               t3lib_div::logDeprecatedFunction();
+               t3lib_timeTrack::debug_typo3PrintError($header, $label, 0, t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
        }
 
        /**
         * Logs access to deprecated TypoScript objects and properties.
+        *
         * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
+        * Note: The second parameter was introduced in TYPO3 4.5 and is not available in older versions
         *
-        * @param       string          Message string
+        * @param       string          Deprecated object or property
+        * @param       string          Message or additional information
         * @return      void
         * @see t3lib_div::deprecationLog(), t3lib_timeTrack::setTSlogMessage()
         */
-       function logDeprecatedTyposcript($msg) {
-               $GLOBALS['TT']->setTSlogMessage($msg . ' is deprecated.', 2);
-               t3lib_div::deprecationLog('TypoScript ' . $msg);
+       function logDeprecatedTyposcript($typoScriptProperty, $explanation = '') {
+               $explanationText = (strlen($explanation) ? ' - ' . $explanation : '');
+               $GLOBALS['TT']->setTSlogMessage($typoScriptProperty . ' is deprecated.' . $explanationText, 2);
+               t3lib_div::deprecationLog('TypoScript ' . $typoScriptProperty . ' is deprecated' . $explanationText);
        }
 
        /**
@@ -4145,12 +4281,15 @@ if (version == "n3") {
         * @access private
         */
        function updateMD5paramsRecord($hash)   {
-               $GLOBALS['TYPO3_DB']->exec_UPDATEquery('cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_md5params'), array('tstamp' => time()));
+               $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
+                       'cache_md5params',
+                       'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_md5params'), array('tstamp' => $GLOBALS['EXEC_TIME'])
+               );
        }
 
        /**
         * Pass the content through tidy - a little program that cleans up HTML-code.
-        * Requires $this->TYPO3_CONF_VARS['FE']['tidy'] to be true and $this->TYPO3_CONF_VARS['FE']['tidy_path'] to contain the filename/path of tidy including clean-up arguments for tidy. See default value in TYPO3_CONF_VARS in t3lib/config_default.php
+        * Requires $this->TYPO3_CONF_VARS['FE']['tidy'] to be TRUE and $this->TYPO3_CONF_VARS['FE']['tidy_path'] to contain the filename/path of tidy including clean-up arguments for tidy. See default value in TYPO3_CONF_VARS in t3lib/config_default.php
         *
         * @param       string          The page content to clean up. Will be written to a temporary file which "tidy" is then asked to clean up. File content is read back and returned.
         * @return      string          Returns the
@@ -4166,7 +4305,7 @@ if (version == "n3") {
 
                        exec ($this->TYPO3_CONF_VARS['FE']['tidy_path'].' '.$fname, $output);                   // run the $content through 'tidy', which formats the HTML to nice code.
                        @unlink ($fname);       // Delete the tempfile again
-                       $content = implode(chr(10),$output);
+                       $content = implode(LF,$output);
                        if (!trim($content))    {
                                $content = $oldContent; // Restore old content due empty return value.
                                $GLOBALS['TT']->setTSlogMessage('"tidy" returned an empty value!',2);
@@ -4209,9 +4348,9 @@ if (version == "n3") {
        }
 
        /**
-        * Returns true if workspace preview is enabled
+        * Returns TRUE if workspace preview is enabled
         *
-        * @return      boolean         Returns true if workspace preview is enabled
+        * @return      boolean         Returns TRUE if workspace preview is enabled
         */
        function doWorkspacePreview()   {
                return (string)$this->workspacePreview!=='';
@@ -4233,7 +4372,7 @@ if (version == "n3") {
                if ($returnTitle)       {
                        if ($ws===-1)   {
                                return 'Default Draft Workspace';
-                       } else {
+                       } elseif (t3lib_extMgm::isLoaded('workspaces')) {
                                $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('title', 'sys_workspace', 'uid='.intval($ws));
                                if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
                                        return $row['title'];
@@ -4313,8 +4452,7 @@ if (version == "n3") {
                        return array();
                }
 
-               reset($this->rootLine);
-               while(list(,$rC)=each($this->rootLine)) {
+               foreach ($this->rootLine as $rC) {
                        if (!$res['_STORAGE_PID'])      $res['_STORAGE_PID']=intval($rC['storage_pid']);
                        if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
                }
@@ -4328,15 +4466,14 @@ if (version == "n3") {
         */
        function getPagesTSconfig()     {
                if (!is_array($this->pagesTSconfig))    {
-                       reset($this->rootLine);
                        $TSdataArray = array();
                        $TSdataArray[] = $this->TYPO3_CONF_VARS['BE']['defaultPageTSconfig'];   // Setting default configuration:
-                       while(list($k,$v)=each($this->rootLine))        {
+                       foreach ($this->rootLine as $k => $v) {
                                $TSdataArray[]=$v['TSconfig'];
                        }
                                // Parsing the user TS (or getting from cache)
                        $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
-                       $userTS = implode(chr(10).'[GLOBAL]'.chr(10),$TSdataArray);
+                       $userTS = implode(LF.'[GLOBAL]'.LF,$TSdataArray);
                        $hash = md5('pageTS:'.$userTS);
                        $cachedContent = $this->sys_page->getHash($hash);
                        if (isset($cachedContent))      {
@@ -4397,7 +4534,7 @@ if (version == "n3") {
         * @param       string          $key is the key in the array, for num-key let the value be empty
         * @param       string          $content is the content if you want any
         * @return      void
-        * @see setJS(), tslib_pibase::pi_setClassStyle()
+        * @see setJS()
         */
        function setCSS($key,$content)  {
                if ($key)       {
@@ -4410,17 +4547,6 @@ if (version == "n3") {
        }
 
        /**
-        * Seeds the random number engine.
-        *
-        * @return      void
-        */
-       function make_seed() {
-               list($usec, $sec) = explode(' ', microtime());
-               $seedV = (float)$sec + ((float)$usec * 100000);
-               srand($seedV);
-       }
-
-       /**
         * Returns a unique md5 hash.
         * There is no special magic in this, the only point is that you don't have to call md5(uniqid()) which is slow and by this you are sure to get a unique string each time in a little faster way.
         *
@@ -4434,10 +4560,14 @@ if (version == "n3") {
        /**
         * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
         *
+        * @param       string          $reason: An optional reason to be written to the syslog.
+        *                                              If not set, debug_backtrace() will be used to track down the call.
         * @return      void
         */
-       function set_no_cache() {
-               if (function_exists('debug_backtrace')) {
+       function set_no_cache($reason = '') {
+               if (strlen($reason)) {
+                       $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
+               } else {
                        $trace = debug_backtrace();
                                // This is a hack to work around ___FILE___ resolving symbolic links
                        $PATH_site_real = str_replace('t3lib','',realpath(PATH_site.'t3lib'));
@@ -4449,22 +4579,32 @@ if (version == "n3") {
                        }
                        $line = $trace[0]['line'];
                        $trigger = $file.' on line '.$line;
-               } else {
-                       $trigger = '[unknown]';
+
+                       $warning = '$TSFE->set_no_cache() was triggered by ' . $trigger.'.';
                }
 
-               $warning = '$TSFE->set_no_cache() was triggered by '.$trigger.'. ';
                if ($this->TYPO3_CONF_VARS['FE']['disableNoCacheParameter']) {
-                       $warning.= 'However $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
+                       $warning.= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
                        $GLOBALS['TT']->setTSlogMessage($warning,2);
                } else {
-                       $warning.= 'Caching is disabled!';
-                       $this->no_cache = 1;
+                       $warning.= ' Caching is disabled!';
+                       $this->disableCache();
                }
+
                t3lib_div::sysLog($warning, 'cms', 2);
        }
 
        /**
+        * Disables caching of the current page.
+        *
+        * @return void
+        * @internal
+        */
+       protected function disableCache() {
+               $this->no_cache = 1;
+       }
+
+       /**
         * Sets the cache-timeout in seconds
         *
         * @param       integer         cache-timeout in seconds
@@ -4480,17 +4620,35 @@ if (version == "n3") {
         * @return      integer         The cache timeout for the current page.
         */
        function get_cache_timeout() {
-                       // Cache period was set for the page:
-               if ($this->page['cache_timeout']) {
-                       $cacheTimeout = $this->page['cache_timeout'];
-                       // Cache period was set for the whole site:
-               } elseif ($this->cacheTimeOutDefault) {
-                       $cacheTimeout = $this->cacheTimeOutDefault;
-                       // No cache period set at all, so we take one day (60*60*24 seconds = 86400 seconds):
-               } else {
-                       $cacheTimeout = 86400;
+               if ($this->getCacheTimeoutCache == NULL) {
+                       if ($this->page['cache_timeout']) {
+                                       // Cache period was set for the page:
+                               $cacheTimeout = $this->page['cache_timeout'];
+                       } elseif ($this->cacheTimeOutDefault) {
+                                       // Cache period was set for the whole site:
+                               $cacheTimeout = $this->cacheTimeOutDefault;
+                       } else {
+                                       // No cache period set at all, so we take one day (60*60*24 seconds = 86400 seconds):
+                               $cacheTimeout = 86400;
+                       }
+
+                       if ($this->config['config']['cache_clearAtMidnight']) {
+                               $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
+                               $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), date('d', $timeOutTime), date('Y', $timeOutTime));
+                                       // If the midnight time of the expire-day is greater than the current time,
+                                       // we may set the timeOutTime to the new midnighttime.
+                               if ($midnightTime > $GLOBALS['EXEC_TIME']) {
+                                       $cacheTimeout = $midnightTime - $GLOBALS['EXEC_TIME'];
+                               }
+                       } else {
+                                       // if cache_clearAtMidnight is not set calculate the timeout time for records on the page
+                               $calculatedCacheTimeout = $this->calculatePageCacheTimeout();
+                               $cacheTimeout = ($calculatedCacheTimeout < $cacheTimeout) ? $calculatedCacheTimeout : $cacheTimeout;
+                       }
+                       $this->getCacheTimeoutCache = $cacheTimeout;
                }
-               return $cacheTimeout;
+
+               return $this->getCacheTimeoutCache;
        }
 
        /**
@@ -4608,12 +4766,14 @@ if (version == "n3") {
         * @param       array           The locallang array in which to search
         * @return      string          Label value of $index key.
         */
-       function getLLL($index, &$LOCAL_LANG)   {
-               if (strcmp($LOCAL_LANG[$this->lang][$index],''))        {
-                       return $LOCAL_LANG[$this->lang][$index];
-               } else {
-                       return $LOCAL_LANG['default'][$index];
+       function getLLL($index, $LOCAL_LANG) {
+               if (isset($LOCAL_LANG[$this->lang][$index][0]['target'])) {
+                       return $LOCAL_LANG[$this->lang][$index][0]['target'];
+               } elseif (isset($LOCAL_LANG['default'][$index][0]['target'])) {
+                       return $LOCAL_LANG['default'][$index][0]['target'];
                }
+
+               return FALSE;
        }
 
        /**
@@ -4626,10 +4786,14 @@ if (version == "n3") {
 
                        // Setting language key and split index:
                $this->lang = $this->config['config']['language'] ? $this->config['config']['language'] : 'default';
+               $this->getPageRenderer()->setLanguage($this->lang);
 
                $ls = explode('|',TYPO3_languages);
-               while(list($i,$v)=each($ls))    {
-                       if ($v==$this->lang)    {$this->langSplitIndex=$i; break;}
+               foreach ($ls as $i => $v) {
+                       if ($v == $this->lang) {
+                               $this->langSplitIndex = $i;
+                               break;
+                       }
                }
 
                        // Setting charsets:
@@ -4683,11 +4847,127 @@ if (version == "n3") {
                        $GLOBALS['HTTP_POST_VARS'] = $_POST;
                }
        }
+
+       /**
+        * Calculates page cache timeout according to the records with starttime/endtime on the page.
+        *
+        * @return int Page cache timeout or PHP_INT_MAX if cannot be determined
+        */
+       protected function calculatePageCacheTimeout() {
+               $result = PHP_INT_MAX;
+
+                       // Get the configuration
+               $tablesToConsider = $this->getCurrentPageCacheConfiguration();
+
+                       // Get the time, rounded to the minute (do not polute MySQL cache!)
+                       // It is ok that we do not take seconds into account here because this
+                       // value will be substracted later. So we never get the time "before"
+                       // the cache change.
+               $now = $GLOBALS['ACCESS_TIME'];
+
+                       // Find timeout by checking every table
+               foreach ($tablesToConsider as $tableDef) {
+                       $result = min($result, $this->getFirstTimeValueForRecord($tableDef, $now));
+               }
+
+                       // We return + 1 second just to ensure that cache is definitely regenerated
+               return ($result == PHP_INT_MAX ? PHP_INT_MAX : $result - $now + 1);
+       }
+
+       /**
+        * Obtains a list of table/pid pairs to consider for page caching.
+        *
+        * TS configuration looks like this:
+        *
+        * The cache lifetime of all pages takes starttime and endtime of news records of page 14 into account:
+        *   config.cache.all = tt_news:14
+        *
+        * The cache lifetime of page 42 takes starttime and endtime of news records of page 15 and addresses of page 16 into account:
+        *   config.cache.42 = tt_news:15,tt_address:16
+        *
+        * @return array Array of 'tablename:pid' pairs. There is at least a current page id in the array
+        * @see tslib_fe::calculatePageCacheTimeout()
+        */
+       protected function getCurrentPageCacheConfiguration() {
+               $result = array('tt_content:' . $this->id);
+               if (isset($this->config['config']['cache.'][$this->id])) {
+                       $result = array_merge($result, t3lib_div::trimExplode(',', $this->config['config']['cache.'][$this->id]));
+               }
+               if (isset($this->config['config']['cache.']['all'])) {
+                       $result = array_merge($result, t3lib_div::trimExplode(',', $this->config['config']['cache.']['all']));
+               }
+               return array_unique($result);
+       }
+
+       /**
+        * Find the minimum starttime or endtime value in the table and pid that is greater than the current time.
+        *
+        * @param string $tableDef Table definition (format tablename:pid)
+        * @param int $now "Now" time value
+        * @return int Value of the next start/stop time or PHP_INT_MAX if not found
+        * @see tslib_fe::calculatePageCacheTimeout()
+        */
+       protected function getFirstTimeValueForRecord($tableDef, $now) {
+               $result = PHP_INT_MAX;
+
+               list($tableName, $pid) = t3lib_div::trimExplode(':', $tableDef);
+
+               if (empty($tableName) || empty($pid)) {
+                       throw new InvalidArgumentException(
+                               'Unexpected value for parameter $tableDef. Expected <tablename>:<pid>, got \'' . htmlspecialchars($tableDef) . '\'.',
+                               1307190365
+                       );
+               }
+                       // Additional fields
+               $showHidden = ($tableName === 'pages' ? $this->showHiddenPage : $this->showHiddenRecords);
+               $enableFields = $this->sys_page->enableFields($tableName, $showHidden, array('starttime' => TRUE, 'endtime' => TRUE));
+
+                       // saves the name of the starttime and endtime field in $tableName (if defined)
+               $timeFields = array();
+                       // saves the SELECT parts of the SQL query
+               $selectFields = array();
+                       // saves the WHERE parts of the SQL query
+               $whereConditions = array();
+
+               foreach (array('starttime', 'endtime') as $field) {
+                               // there is no need to load TCA because we need only enable columns!
+                       if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field])) {
+                               $timeFields[$field] = $GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field];
+                               $selectFields[$field] = 'MIN(' . $timeFields[$field] . ') AS ' . $field;
+                               $whereConditions[$field] = $timeFields[$field] . '>' . $now;
+                       }
+               }
+
+                       // if starttime or endtime are defined, evaluate them
+               if (count($timeFields)) {
+                               // find the timestamp, when the current page's content changes the next time
+                       $row = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
+                                       // MIN(starttime) AS starttime, MIN(endtime) AS endtime
+                               implode(', ', $selectFields),
+                               $tableName,
+                                       // pid=$pid AND starttime>$now AND $endtime>$now . $enablefields
+                               'pid=' . intval($pid) . ' AND (' . implode(' OR ', $whereConditions) . ')' . $enableFields
+                       );
+                       if ($row) {
+                               foreach ($timeFields as $timeField => $_) {
+                                               // if a MIN value is found, take it into account for the cache lifetime
+                                               // we have to filter out start/endtimes < $now, as the SQL query also returns
+                                               // rows with starttime < $now and endtime > $now (and using a starttime from the past
+                                               // would be wrong)
+                                       if (!is_null($row[$timeField]) && $row[$timeField] > $now) {
+                                               $result = min($result, $row[$timeField]);
+                                       }
+                               }
+                       }
+               }
+
+               return $result;
+       }
 }
 
 
-if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php'])       {
-       include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php']);
+if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php'])) {
+       include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php']);
 }
 
-?>
\ No newline at end of file
+?>