[BUGFIX] Regression: filelistFolderTree constructor is recursive
[Packages/TYPO3.CMS.git] / typo3 / template.php
index 8d381cd..c3e0f25 100644 (file)
@@ -2,7 +2,7 @@
 /***************************************************************
 *  Copyright notice
 *
 /***************************************************************
 *  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
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 /**
  * Contains class with layout/output function for TYPO3 Backend Scripts
  *
 /**
  * Contains class with layout/output function for TYPO3 Backend Scripts
  *
- * $Id$
- * Revised for TYPO3 3.6 2/2003 by Kasper Skaarhoj
+ * Revised for TYPO3 3.6 2/2003 by Kasper Skårhøj
  * XHTML-trans compliant
  *
  * XHTML-trans compliant
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
- */
-/**
- * [CLASS/FUNCTION INDEX of SCRIPT]
- *
- *  145: function fw($str)
- *
- *
- *  169: class template
- *  224:     function template()
- *
- *              SECTION: EVALUATION FUNCTIONS
- *  298:     function wrapClickMenuOnIcon($str,$table,$uid='',$listFr=1,$addParams='',$enDisItems='', $returnOnClick=FALSE)
- *  315:     function viewPageIcon($id,$backPath,$addParams='hspace="3"')
- *  341:     function issueCommand($params,$rUrl='')
- *  356:     function isCMlayers()
- *  366:     function thisBlur()
- *  376:     function helpStyle()
- *  393:     function getHeader($table,$row,$path,$noViewPageIcon=0,$tWrap=array('',''))
- *  419:     function getFileheader($title,$path,$iconfile)
- *  434:     function makeShortcutIcon($gvList,$setList,$modName,$motherModName="")
- *  467:     function makeShortcutUrl($gvList,$setList)
- *  488:     function formWidth($size=48,$textarea=0,$styleOverride='')
- *  513:     function formWidthText($size=48,$styleOverride='',$wrap='')
- *  530:     function redirectUrls($thisLocation='')
- *  554:     function formatTime($tstamp,$type)
- *  571:     function parseTime()
- *
- *              SECTION: PAGE BUILDING FUNCTIONS.
- *  604:     function startPage($title)
- *  686:     function endPage()
- *  720:     function header($text)
- *  741:     function section($label,$text,$nostrtoupper=FALSE,$sH=FALSE,$type=0,$allowHTMLinHeader=FALSE)
- *  765:     function divider($dist)
- *  781:     function spacer($dist)
- *  800:     function sectionHeader($label,$sH=FALSE,$addAttrib='')
- *  817:     function sectionBegin()
- *  838:     function sectionEnd()
- *  858:     function middle()
- *  867:     function endPageJS()
- *  884:     function docBodyTagBegin()
- *  894:     function docStyle()
- *  936:     function insertStylesAndJS($content)
- *  956:     function initCharset()
- *  968:     function generator()
- *
- *              SECTION: OTHER ELEMENTS
- * 1001:     function icons($type, $styleAttribValue='')
- * 1030:     function t3Button($onClick,$label)
- * 1041:     function dfw($string)
- * 1051:     function rfw($string)
- * 1061:     function wrapInCData($string)
- * 1078:     function wrapScriptTags($string, $linebreak=TRUE)
- * 1117:     function table($arr, $layout='')
- * 1159:     function menuTable($arr1,$arr2=array(), $arr3=array())
- * 1192:     function funcMenu($content,$menu)
- * 1210:     function clearCacheMenu($id,$addSaveOptions=0)
- * 1246:     function getContextMenuCode()
- * 1251:     function showClickmenu(table, uid, listFr, enDisItems, backPath, addParams)
- * 1280:     function showClickmenu_noajax(url)
- * 1287:     function showClickmenu_ajax(t3ajax)
- * 1472:     function getDragDropCode($table)
- * 1483:     function cancelDragEvent(event)
- * 1496:     function mouseMoveEvent (event)
- * 1509:     function dragElement(id,elementID)
- * 1528:     function dropElement(id)
- * 1577:     function getTabMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')
- * 1607:     function getTabMenuRaw($menuItems)
- * 1676:     function getDynTabMenu($menuItems,$identString,$toggle=0,$foldout=FALSE,$newRowCharLimit=50,$noWrap=1,$fullWidth=FALSE,$defaultTabIndex=1)
- * 1801:     function getDynTabMenuJScode()
- * 1892:     function getVersionSelector($id,$noAction=FALSE)
- *
- *
- * 2060: class bigDoc extends template
- *
- *
- * 2069: class noDoc extends template
- *
- *
- * 2078: class smallDoc extends template
- *
- *
- * 2087: class mediumDoc extends template
- *
- * TOTAL FUNCTIONS: 57
- * (This index is automatically created/updated by the extension "extdeveval")
- *
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  */
 
 
  */
 
 
@@ -126,18 +39,6 @@ if (!defined('TYPO3_MODE')) die("Can't include this file directly.");
 
 
 /**
 
 
 /**
- * Deprecated fontwrap function. Is just transparent now.
- *
- * @param      string          Input string
- * @return     string          Output string (in the old days this was wrapped in <font> tags)
- * @deprecated since TYPO3 3.6
- */
-function fw($str)      {
-       return $str;
-}
-
-
-/**
  * TYPO3 Backend Template Class
  *
  * This class contains functions for starting and ending the HTML of backend modules
  * TYPO3 Backend Template Class
  *
  * This class contains functions for starting and ending the HTML of backend modules
@@ -152,7 +53,7 @@ function fw($str)    {
  *
  * Please refer to Inside TYPO3 for a discussion of how to use this API.
  *
  *
  * Please refer to Inside TYPO3 for a discussion of how to use this API.
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  * @package TYPO3
  * @subpackage core
  */
  * @package TYPO3
  * @subpackage core
  */
@@ -168,6 +69,7 @@ class template {
        var $postCode='';                               // Additional 'page-end' code could be accommulated in this var. It will be outputted at the end of page before </body> and some other internal page-end code.
        var $docType = '';                              // Doc-type used in the header. Default is xhtml_trans. You can also set it to 'html_3', 'xhtml_strict' or 'xhtml_frames'.
        var $moduleTemplate = '';               // HTML template with markers for module
        var $postCode='';                               // Additional 'page-end' code could be accommulated in this var. It will be outputted at the end of page before </body> and some other internal page-end code.
        var $docType = '';                              // Doc-type used in the header. Default is xhtml_trans. You can also set it to 'html_3', 'xhtml_strict' or 'xhtml_frames'.
        var $moduleTemplate = '';               // HTML template with markers for module
+       protected $moduleTemplateFilename = ''; // the base file (not overlaid by TBE_STYLES) for the current module, useful for hooks when finding out which modules is rendered currently
 
                // Other vars you can change, but less frequently used:
        var $scriptID='';                               // Script ID.
 
                // Other vars you can change, but less frequently used:
        var $scriptID='';                               // Script ID.
@@ -178,10 +80,9 @@ class template {
        var $form_rowsToStylewidth = 9.58;      // Multiplication factor for formWidth() input size (default is 48* this value).
        var $form_largeComp = 1.33;             // Compensation for large documents (used in class.t3lib_tceforms.php)
        var $endJS=1;                                   // If set, then a JavaScript section will be outputted in the bottom of page which will try and update the top.busy session expiry object.
        var $form_rowsToStylewidth = 9.58;      // Multiplication factor for formWidth() input size (default is 48* this value).
        var $form_largeComp = 1.33;             // Compensation for large documents (used in class.t3lib_tceforms.php)
        var $endJS=1;                                   // If set, then a JavaScript section will be outputted in the bottom of page which will try and update the top.busy session expiry object.
-       protected $additionalStyleSheets=array();       // Links to additional style sheets
 
                // TYPO3 Colorscheme.
 
                // TYPO3 Colorscheme.
-               // If you want to change this, please do so through a skin using the global var $TBE_STYLES
+               // If you want to change this, please do so through a skin using the global var $GLOBALS['TBE_STYLES']
        var $bgColor = '#F7F3EF';               // Light background color
        var $bgColor2 = '#9BA1A8';              // Steel-blue
        var $bgColor3 = '#F6F2E6';              // dok.color
        var $bgColor = '#F7F3EF';               // Light background color
        var $bgColor2 = '#9BA1A8';              // Steel-blue
        var $bgColor3 = '#F6F2E6';              // dok.color
@@ -189,14 +90,42 @@ class template {
        var $bgColor5 = '#ABBBB4';              // light tablerow background, greenish
        var $bgColor6 = '#E7DBA8';              // light tablerow background, yellowish, for section headers. Light.
        var $hoverColor = '#254D7B';
        var $bgColor5 = '#ABBBB4';              // light tablerow background, greenish
        var $bgColor6 = '#E7DBA8';              // light tablerow background, yellowish, for section headers. Light.
        var $hoverColor = '#254D7B';
-       var $styleSheetFile = 'stylesheet.css'; // Filename of stylesheet (relative to PATH_typo3)
+       var $styleSheetFile = '';       // Filename of stylesheet (relative to PATH_typo3)
        var $styleSheetFile2 = '';              // Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script (relative to PATH_typo3)
        var $styleSheetFile_post = '';  // Filename of a post-stylesheet - included right after all inline styles.
        var $backGroundImage = '';              // Background image of page (relative to PATH_typo3)
        var $inDocStyles_TBEstyle = ''; // Inline css styling set from TBE_STYLES array
 
        var $styleSheetFile2 = '';              // Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script (relative to PATH_typo3)
        var $styleSheetFile_post = '';  // Filename of a post-stylesheet - included right after all inline styles.
        var $backGroundImage = '';              // Background image of page (relative to PATH_typo3)
        var $inDocStyles_TBEstyle = ''; // Inline css styling set from TBE_STYLES array
 
+       /**
+        * Whether to use the X-UA-Compatible meta tag
+        * @var boolean
+        */
+       protected $useCompatibilityTag = TRUE;
+
+               // Skinning
+               // stylesheets from core
+       protected $stylesheetsCore = array(
+               'structure' => 'stylesheets/structure/',
+               'visual' => 'stylesheets/visual/',
+               'generatedSprites' => '../typo3temp/sprites/',
+       );
+
+               // include these CSS directories from skins by default
+       protected $stylesheetsSkins = array(
+               'structure' => 'stylesheets/structure/',
+               'visual' => 'stylesheets/visual/',
+       );
+
+       /**
+        * JavaScript files loaded for every page in the Backend
+        * @var array
+        */
+       protected $jsFiles = array(
+               'modernizr' => 'contrib/modernizr/modernizr.min.js',
+       );
+
                // DEV:
                // DEV:
-       var $parseTimeFlag = 0;                 // Will output the parsetime of the scripts in milliseconds (for admin-users). Set this to false when releasing TYPO3. Only for dev.
+       var $parseTimeFlag = 0;                 // Will output the parsetime of the scripts in milliseconds (for admin-users). Set this to FALSE when releasing TYPO3. Only for dev.
 
                // INTERNAL
        var $charset = 'iso-8859-1';    // Default charset. see function initCharset()
 
                // INTERNAL
        var $charset = 'iso-8859-1';    // Default charset. see function initCharset()
@@ -204,33 +133,35 @@ class template {
        var $sectionFlag=0;                             // Internal: Indicates if a <div>-output section is open
        var $divClass = '';                             // (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
 
        var $sectionFlag=0;                             // Internal: Indicates if a <div>-output section is open
        var $divClass = '';                             // (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
 
-               // internal flags for JS-libraries
-       protected $addPrototype = false;
-       protected $addScriptaculousModules = array(
-               'builder'  => false,
-               'effects'  => false,
-               'dragdrop' => false,
-               'controls' => false,
-               'slider'   => false
-       );
-       protected $addExtJS = false;
-       protected $extJSadapter = 'ext/ext-base.js';
-       protected $enableExtJsDebug = false;
+       var $pageHeaderBlock = '';
+       var $endOfPageJsBlock = '';
+
+       var $hasDocheader = TRUE;
 
 
-       // available adapters for extJs
-       const EXTJS_ADAPTER_JQUERY = 'jquery'; 
-       const EXTJS_ADAPTER_PROTOTYPE = 'prototype'; 
-       const EXTJS_ADAPTER_YUI = 'yui';
+       /**
+        * @var t3lib_PageRenderer
+        */
+       protected $pageRenderer;
+       protected $pageHeaderFooterTemplateFile = '';   // alternative template file
+
+       protected $extDirectStateProvider = FALSE;
 
 
+       /**
+        * Whether flashmessages should be rendered or not
+        *
+        * @var $showFlashMessages
+        */
+       public $showFlashMessages = TRUE;
 
        /**
         * Constructor
 
        /**
         * Constructor
-        * Imports relevant parts from global $TBE_STYLES (colorscheme)
+        * Imports relevant parts from global $GLOBALS['TBE_STYLES'] (colorscheme)
         *
         * @return      void
         */
         *
         * @return      void
         */
-       function template()     {
-               global $TBE_STYLES;
+       function __construct()  {
+                       // Initializes the page rendering object:
+               $this->getPageRenderer();
 
                        // Setting default scriptID:
                if (($temp_M = (string) t3lib_div::_GET('M')) && $GLOBALS['TBE_MODULES']['_PATHS'][$temp_M]) {
 
                        // Setting default scriptID:
                if (($temp_M = (string) t3lib_div::_GET('M')) && $GLOBALS['TBE_MODULES']['_PATHS'][$temp_M]) {
@@ -245,38 +176,87 @@ class template {
                $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/','-',$this->scriptID);
 
                        // Individual configuration per script? If so, make a recursive merge of the arrays:
                $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/','-',$this->scriptID);
 
                        // Individual configuration per script? If so, make a recursive merge of the arrays:
-               if (is_array($TBE_STYLES['scriptIDindex'][$this->scriptID]))    {
-                       $ovr = $TBE_STYLES['scriptIDindex'][$this->scriptID];           // Make copy
-                       $TBE_STYLES = t3lib_div::array_merge_recursive_overrule($TBE_STYLES,$ovr);              // merge styles.
-                       unset($TBE_STYLES['scriptIDindex'][$this->scriptID]);   // Have to unset - otherwise the second instantiation will do it again!
+               if (is_array($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID])) {
+                       $ovr = $GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID];                // Make copy
+                       $GLOBALS['TBE_STYLES'] = t3lib_div::array_merge_recursive_overrule($GLOBALS['TBE_STYLES'],$ovr);                // merge styles.
+                       unset($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID]);        // Have to unset - otherwise the second instantiation will do it again!
                }
 
                        // Color scheme:
                }
 
                        // Color scheme:
-               if ($TBE_STYLES['mainColors']['bgColor'])       $this->bgColor=$TBE_STYLES['mainColors']['bgColor'];
-               if ($TBE_STYLES['mainColors']['bgColor1'])      $this->bgColor1=$TBE_STYLES['mainColors']['bgColor1'];
-               if ($TBE_STYLES['mainColors']['bgColor2'])      $this->bgColor2=$TBE_STYLES['mainColors']['bgColor2'];
-               if ($TBE_STYLES['mainColors']['bgColor3'])      $this->bgColor3=$TBE_STYLES['mainColors']['bgColor3'];
-               if ($TBE_STYLES['mainColors']['bgColor4'])      $this->bgColor4=$TBE_STYLES['mainColors']['bgColor4'];
-               if ($TBE_STYLES['mainColors']['bgColor5'])      $this->bgColor5=$TBE_STYLES['mainColors']['bgColor5'];
-               if ($TBE_STYLES['mainColors']['bgColor6'])      $this->bgColor6=$TBE_STYLES['mainColors']['bgColor6'];
-               if ($TBE_STYLES['mainColors']['hoverColor'])    $this->hoverColor=$TBE_STYLES['mainColors']['hoverColor'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor'])    $this->bgColor=$GLOBALS['TBE_STYLES']['mainColors']['bgColor'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor1'])   $this->bgColor1=$GLOBALS['TBE_STYLES']['mainColors']['bgColor1'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor2'])   $this->bgColor2=$GLOBALS['TBE_STYLES']['mainColors']['bgColor2'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor3'])   $this->bgColor3=$GLOBALS['TBE_STYLES']['mainColors']['bgColor3'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor4'])   $this->bgColor4=$GLOBALS['TBE_STYLES']['mainColors']['bgColor4'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor5'])   $this->bgColor5=$GLOBALS['TBE_STYLES']['mainColors']['bgColor5'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['bgColor6'])   $this->bgColor6=$GLOBALS['TBE_STYLES']['mainColors']['bgColor6'];
+               if ($GLOBALS['TBE_STYLES']['mainColors']['hoverColor']) $this->hoverColor=$GLOBALS['TBE_STYLES']['mainColors']['hoverColor'];
 
                        // Main Stylesheets:
 
                        // Main Stylesheets:
-               if ($TBE_STYLES['stylesheet'])  $this->styleSheetFile = $TBE_STYLES['stylesheet'];
-               if ($TBE_STYLES['stylesheet2']) $this->styleSheetFile2 = $TBE_STYLES['stylesheet2'];
-               if ($TBE_STYLES['styleSheetFile_post']) $this->styleSheetFile_post = $TBE_STYLES['styleSheetFile_post'];
-               if ($TBE_STYLES['inDocStyles_TBEstyle'])        $this->inDocStyles_TBEstyle = $TBE_STYLES['inDocStyles_TBEstyle'];
+               if ($GLOBALS['TBE_STYLES']['stylesheet'])       $this->styleSheetFile = $GLOBALS['TBE_STYLES']['stylesheet'];
+               if ($GLOBALS['TBE_STYLES']['stylesheet2'])      $this->styleSheetFile2 = $GLOBALS['TBE_STYLES']['stylesheet2'];
+               if ($GLOBALS['TBE_STYLES']['styleSheetFile_post'])      $this->styleSheetFile_post = $GLOBALS['TBE_STYLES']['styleSheetFile_post'];
+               if ($GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'])     $this->inDocStyles_TBEstyle = $GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'];
+
+                       // include all stylesheets
+               foreach ($this->getSkinStylesheetDirectories() as $stylesheetDirectory) {
+                       $this->addStylesheetDirectory($stylesheetDirectory);
+               }
 
                        // Background image
 
                        // Background image
-               if ($TBE_STYLES['background'])  $this->backGroundImage = $TBE_STYLES['background'];
+               if ($GLOBALS['TBE_STYLES']['background'])       $this->backGroundImage = $GLOBALS['TBE_STYLES']['background'];
        }
 
        }
 
+       /**
+        * Compatibility constructor.
+        *
+        * @deprecated since TYPO3 4.6 and will be removed in TYPO3 4.8. Use __construct() instead.
+        */
+       public function template() {
+               t3lib_div::logDeprecatedFunction();
+                       // Note: we cannot call $this->__construct() here because it would call the derived class constructor and cause recursion
+                       // This code uses official PHP behavior (http://www.php.net/manual/en/language.oop5.basic.php) when $this in the
+                       // statically called non-static method inherits $this from the caller's scope.
+               template::__construct();
+       }
 
 
+       /**
+        * Gets instance of PageRenderer
+        *
+        * @return      t3lib_PageRenderer
+        */
+       public function getPageRenderer() {
+               if (!isset($this->pageRenderer)) {
+                       $this->pageRenderer = t3lib_div::makeInstance('t3lib_PageRenderer');
+                       $this->pageRenderer->setTemplateFile(
+                               TYPO3_mainDir . 'templates/template_page_backend.html'
+                       );
+                       $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang);
+                       $this->pageRenderer->enableConcatenateFiles();
+                       $this->pageRenderer->enableCompressCss();
+                       $this->pageRenderer->enableCompressJavascript();
+
+                               // add all JavaScript files defined in $this->jsFiles to the PageRenderer
+                       foreach ($this->jsFiles as $file) {
+                               $this->pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . $file);
+                       }
+               }
+               if (intval($GLOBALS['TYPO3_CONF_VARS']['BE']['debug']) === 1) {
+                       $this->pageRenderer->enableDebugMode();
+               }
+               return $this->pageRenderer;
+       }
 
 
 
 
 
 
-
-
+   /**
+        * Sets inclusion of StateProvider
+        *
+        * @return void
+        */
+       public function setExtDirectStateProvider() {
+               $this->extDirectStateProvider = TRUE;
+       }
 
 
 
 
 
 
@@ -299,7 +279,7 @@ class template {
         * The link will load the top frame with the parameter "&item" which is the table,uid and listFr arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$listFr)
         *
         * @param       string          String to be wrapped in link, typ. image tag.
         * The link will load the top frame with the parameter "&item" which is the table,uid and listFr arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$listFr)
         *
         * @param       string          String to be wrapped in link, typ. image tag.
-        * @param       string          Table name/File path. If the icon is for a database record, enter the tablename from $TCA. If a file then enter the absolute filepath
+        * @param       string          Table name/File path. If the icon is for a database record, enter the tablename from $GLOBALS['TCA']. If a file then enter the absolute filepath
         * @param       integer         If icon is for database record this is the UID for the record from $table
         * @param       boolean         Tells the top frame script that the link is coming from a "list" frame which means a frame from within the backend content frame.
         * @param       string          Additional GET parameters for the link to alt_clickmenu.php
         * @param       integer         If icon is for database record this is the UID for the record from $table
         * @param       boolean         Tells the top frame script that the link is coming from a "list" frame which means a frame from within the backend content frame.
         * @param       string          Additional GET parameters for the link to alt_clickmenu.php
@@ -325,15 +305,16 @@ class template {
         * @return      string          HTML string with linked icon(s)
         */
        function viewPageIcon($id,$backPath,$addParams='hspace="3"')    {
         * @return      string          HTML string with linked icon(s)
         */
        function viewPageIcon($id,$backPath,$addParams='hspace="3"')    {
-               global $BE_USER;
-               $str = '';
+
                        // If access to Web>List for user, then link to that module.
                        // If access to Web>List for user, then link to that module.
-               if ($BE_USER->check('modules','web_list'))      {
-                       $href=$backPath.'db_list.php?id='.$id.'&returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'));
-                       $str.= '<a href="'.htmlspecialchars($href).'">'.
-                                       '<img'.t3lib_iconWorks::skinImg($backPath,'gfx/list.gif','width="11" height="11"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showList',1).'"'.($addParams?' '.trim($addParams):'').' alt="" />'.
-                                       '</a>';
-               }
+               $str = t3lib_BEfunc::getListViewLink(
+                       array(
+                               'id' => $id,
+                               'returnUrl' => t3lib_div::getIndpEnv('REQUEST_URI'),
+                       ),
+                       $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showList')
+               );
+
                        // Make link to view page
                $str.= '<a href="#" onclick="'.htmlspecialchars(t3lib_BEfunc::viewOnClick($id,$backPath,t3lib_BEfunc::BEgetRootLine($id))).'">'.
                                '<img'.t3lib_iconWorks::skinImg($backPath,'gfx/zoom.gif','width="12" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showPage',1).'"'.($addParams?' '.trim($addParams):"").' hspace="3" alt="" />'.
                        // Make link to view page
                $str.= '<a href="#" onclick="'.htmlspecialchars(t3lib_BEfunc::viewOnClick($id,$backPath,t3lib_BEfunc::BEgetRootLine($id))).'">'.
                                '<img'.t3lib_iconWorks::skinImg($backPath,'gfx/zoom.gif','width="12" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showPage',1).'"'.($addParams?' '.trim($addParams):"").' hspace="3" alt="" />'.
@@ -352,15 +333,18 @@ class template {
         */
        function issueCommand($params,$rUrl='') {
                $rUrl = $rUrl ? $rUrl : t3lib_div::getIndpEnv('REQUEST_URI');
         */
        function issueCommand($params,$rUrl='') {
                $rUrl = $rUrl ? $rUrl : t3lib_div::getIndpEnv('REQUEST_URI');
-               return $this->backPath.'tce_db.php?'.
-                               $params.
-                               '&redirect='.($rUrl==-1?"'+T3_THIS_LOCATION+'":rawurlencode($rUrl)).
-                               '&vC='.rawurlencode($GLOBALS['BE_USER']->veriCode()).
+               $commandUrl = $this->backPath.'tce_db.php?' .
+                               $params .
+                               '&redirect=' . ($rUrl==-1 ? "'+T3_THIS_LOCATION+'" : rawurlencode($rUrl)) .
+                               '&vC='.rawurlencode($GLOBALS['BE_USER']->veriCode()) .
+                               t3lib_BEfunc::getUrlToken('tceAction') .
                                '&prErr=1&uPT=1';
                                '&prErr=1&uPT=1';
+
+               return $commandUrl;
        }
 
        /**
        }
 
        /**
-        * Returns true if click-menu layers can be displayed for the current user/browser
+        * Returns TRUE if click-menu layers can be displayed for the current user/browser
         * Use this to test if click-menus (context sensitive menus) can and should be displayed in the backend.
         *
         * @return      boolean
         * Use this to test if click-menus (context sensitive menus) can and should be displayed in the backend.
         *
         * @return      boolean
@@ -374,8 +358,10 @@ class template {
         * Use this in links to remove the underlining after being clicked
         *
         * @return      string
         * Use this in links to remove the underlining after being clicked
         *
         * @return      string
+        * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7
         */
        function thisBlur()     {
         */
        function thisBlur()     {
+               t3lib_div::logDeprecatedFunction();
                return ($GLOBALS['CLIENT']['FORMSTYLE']?'this.blur();':'');
        }
 
                return ($GLOBALS['CLIENT']['FORMSTYLE']?'this.blur();':'');
        }
 
@@ -384,8 +370,10 @@ class template {
         * Use for <a>-links to help texts
         *
         * @return      string
         * Use for <a>-links to help texts
         *
         * @return      string
+        * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7
         */
        function helpStyle()    {
         */
        function helpStyle()    {
+               t3lib_div::logDeprecatedFunction();
                return $GLOBALS['CLIENT']['FORMSTYLE'] ? ' style="cursor:help;"':'';
        }
 
                return $GLOBALS['CLIENT']['FORMSTYLE'] ? ' style="cursor:help;"':'';
        }
 
@@ -398,19 +386,18 @@ class template {
         * @param       string          Table name
         * @param       array           Record row
         * @param       string          Alt text
         * @param       string          Table name
         * @param       array           Record row
         * @param       string          Alt text
-        * @param       boolean         Set $noViewPageIcon true if you don't want a magnifier-icon for viewing the page in the frontend
+        * @param       boolean         Set $noViewPageIcon TRUE if you don't want a magnifier-icon for viewing the page in the frontend
         * @param       array           $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
         * @return      string          HTML content
         */
        function getHeader($table,$row,$path,$noViewPageIcon=0,$tWrap=array('',''))     {
         * @param       array           $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
         * @return      string          HTML content
         */
        function getHeader($table,$row,$path,$noViewPageIcon=0,$tWrap=array('',''))     {
-               global $TCA;
                if (is_array($row) && $row['uid'])      {
                if (is_array($row) && $row['uid'])      {
-                       $iconImgTag=t3lib_iconWorks::getIconImage($table,$row,$this->backPath,'title="'.htmlspecialchars($path).'"');
-                       $title= strip_tags($row[$TCA[$table]['ctrl']['label']]);
+                       $iconImgTag=t3lib_iconWorks::getSpriteIconForRecord($table, $row , array('title' => htmlspecialchars($path)));
+                       $title = strip_tags(t3lib_BEfunc::getRecordTitle($table, $row));
                        $viewPage = $noViewPageIcon ? '' : $this->viewPageIcon($row['uid'],$this->backPath,'');
                        if ($table=='pages')    $path.=' - '.t3lib_BEfunc::titleAttribForPages($row,'',0);
                } else {
                        $viewPage = $noViewPageIcon ? '' : $this->viewPageIcon($row['uid'],$this->backPath,'');
                        if ($table=='pages')    $path.=' - '.t3lib_BEfunc::titleAttribForPages($row,'',0);
                } else {
-                       $iconImgTag='<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/i/_icon_website.gif',$wHattribs='width="18" height="16"').' title="'.htmlspecialchars($path).'" alt="" />';
+                       $iconImgTag = t3lib_iconWorks::getSpriteIcon('apps-pagetree-page-domain', array('title' => htmlspecialchars($path)));
                        $title=$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
                }
 
                        $title=$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
                }
 
@@ -430,7 +417,7 @@ class template {
         */
        function getFileheader($title,$path,$iconfile)  {
                $fileInfo = t3lib_div::split_fileref($title);
         */
        function getFileheader($title,$path,$iconfile)  {
                $fileInfo = t3lib_div::split_fileref($title);
-               $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($fileInfo['path'],-35)).'<b>'.htmlspecialchars($fileInfo['file']).'</b>';
+               $title = htmlspecialchars(t3lib_div::fixed_lgd_cs($fileInfo['path'],-35)).'<strong>'.htmlspecialchars($fileInfo['file']).'</strong>';
                return '<span class="typo3-moduleHeader"><img'.t3lib_iconWorks::skinImg($this->backPath,$iconfile,'width="18" height="16"').' title="'.htmlspecialchars($path).'" alt="" />'.$title.'</span>';
        }
 
                return '<span class="typo3-moduleHeader"><img'.t3lib_iconWorks::skinImg($this->backPath,$iconfile,'width="18" height="16"').' title="'.htmlspecialchars($path).'" alt="" />'.$title.'</span>';
        }
 
@@ -460,13 +447,14 @@ class template {
                } else $mMN='';
 
                $onClick = 'top.ShortcutManager.createShortcut('
                } else $mMN='';
 
                $onClick = 'top.ShortcutManager.createShortcut('
-                       .$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.makeShortcut')).', '
+                       .$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.makeBookmark')).', '
                        .'\''.$backPath.'\', '
                        .'\''.rawurlencode($modName).'\', '
                        .'\''.rawurlencode($pathInfo['path']."?".$storeUrl).$mMN.'\''
                .');return false;';
 
                        .'\''.$backPath.'\', '
                        .'\''.rawurlencode($modName).'\', '
                        .'\''.rawurlencode($pathInfo['path']."?".$storeUrl).$mMN.'\''
                .');return false;';
 
-               $sIcon = '<a href="#" onclick="'.htmlspecialchars($onClick).'"><img'.t3lib_iconWorks::skinImg($backPath,'gfx/shortcut.gif','width="14" height="14"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.makeShortcut',1).'" alt="" /></a>';
+               $sIcon = '<a href="#" onclick="' . htmlspecialchars($onClick).'" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.makeBookmark', TRUE) . '">'
+                       . t3lib_iconworks::getSpriteIcon('actions-system-shortcut-new') . '</a>';
                return $sIcon;
        }
 
                return $sIcon;
        }
 
@@ -553,7 +541,7 @@ class template {
                ));
 
                $out ="
                ));
 
                $out ="
-       var T3_RETURN_URL = '".str_replace('%20','',rawurlencode(t3lib_div::_GP('returnUrl')))."';
+       var T3_RETURN_URL = '".str_replace('%20','',rawurlencode(t3lib_div::sanitizeLocalUrl(t3lib_div::_GP('returnUrl'))))."';
        var T3_THIS_LOCATION = '".str_replace('%20','',rawurlencode($thisLocation))."';
                ";
                return $out;
        var T3_THIS_LOCATION = '".str_replace('%20','',rawurlencode($thisLocation))."';
                ";
                return $out;
@@ -591,6 +579,16 @@ class template {
                }
        }
 
                }
        }
 
+       /**
+        * Defines whether to use the X-UA-Compatible meta tag.
+        *
+        * @param boolean $useCompatibilityTag Whether to use the tag
+        * @return void
+        */
+       public function useCompatibilityTag($useCompatibilityTag = TRUE) {
+               $this->useCompatibilityTag = (bool) $useCompatibilityTag;
+       }
+
 
 
 
 
 
 
@@ -614,10 +612,11 @@ class template {
         * This includes the proper header with charset, title, meta tag and beginning body-tag.
         *
         * @param       string          HTML Page title for the header
         * This includes the proper header with charset, title, meta tag and beginning body-tag.
         *
         * @param       string          HTML Page title for the header
+        * @param       boolean         flag for including CSH
         * @return      string          Returns the whole header section of a HTML-document based on settings in internal variables (like styles, javascript code, charset, generator and docType)
         * @see endPage()
         */
         * @return      string          Returns the whole header section of a HTML-document based on settings in internal variables (like styles, javascript code, charset, generator and docType)
         * @see endPage()
         */
-       function startPage($title)      {
+       function startPage($title, $includeCsh = TRUE) {
                        // hook pre start page
                if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'])) {
                        $preStartPageHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'];
                        // hook pre start page
                if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'])) {
                        $preStartPageHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'];
@@ -631,14 +630,20 @@ class template {
                        }
                }
 
                        }
                }
 
-                       // Get META tag containing the currently selected charset for backend output. The function sets $this->charSet.
-               $charSet = $this->initCharset();
-               $generator = $this->generator();
+               $this->pageRenderer->backPath = $this->backPath;
 
 
+                       // alternative template for Header and Footer
+               if ($this->pageHeaderFooterTemplateFile) {
+                       $file =  t3lib_div::getFileAbsFileName($this->pageHeaderFooterTemplateFile, TRUE);
+                       if ($file) {
+                               $this->pageRenderer->setTemplateFile($file);
+                       }
+               }
                        // For debugging: If this outputs "QuirksMode"/"BackCompat" (IE) the browser runs in quirks-mode. Otherwise the value is "CSS1Compat"
 #              $this->JScodeArray[]='alert(document.compatMode);';
 
                        // Send HTTP header for selected charset. Added by Robert Lemke 23.10.2003
                        // For debugging: If this outputs "QuirksMode"/"BackCompat" (IE) the browser runs in quirks-mode. Otherwise the value is "CSS1Compat"
 #              $this->JScodeArray[]='alert(document.compatMode);';
 
                        // Send HTTP header for selected charset. Added by Robert Lemke 23.10.2003
+               $this->initCharset();
                header ('Content-Type:text/html;charset='.$this->charset);
 
                        // Standard HTML tag
                header ('Content-Type:text/html;charset='.$this->charset);
 
                        // Standard HTML tag
@@ -648,6 +653,8 @@ class template {
                        case 'html_3':
                                $headerStart = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">';
                                $htmlTag = '<html>';
                        case 'html_3':
                                $headerStart = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">';
                                $htmlTag = '<html>';
+                               // disable rendering of XHTML tags
+                               $this->getPageRenderer()->setRenderXhtml(FALSE);
                                break;
                        case 'xhtml_strict':
                                $headerStart = '<!DOCTYPE html
                                break;
                        case 'xhtml_strict':
                                $headerStart = '<!DOCTYPE html
@@ -656,26 +663,39 @@ class template {
                                break;
                        case 'xhtml_frames':
                                $headerStart = '<!DOCTYPE html
                                break;
                        case 'xhtml_frames':
                                $headerStart = '<!DOCTYPE html
-     PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
-     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">';
+       PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
+       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">';
                                break;
                                break;
-                       // The fallthrough is intended as XHTML 1.0 transitional is the default for the BE.
                        case 'xhtml_trans':
                        case 'xhtml_trans':
-                       default:
                                $headerStart = '<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
                                $headerStart = '<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
+                               break;
+                       case 'html5':
+                       default:
+                                       // The fallthrough is intended as HTML5, as this is the default for the BE since TYPO3 4.5
+                               $headerStart = '<!DOCTYPE html>' . LF;
+                               $htmlTag = '<html>';
+                               // disable rendering of XHTML tags
+                               $this->getPageRenderer()->setRenderXhtml(FALSE);
+                               break;
                }
 
                }
 
+               $this->pageRenderer->setHtmlTag($htmlTag);
+
                // This loads the tabulator-in-textarea feature. It automatically modifies
                // every textarea which is found.
                if (!$GLOBALS['BE_USER']->uc['disableTabInTextarea']) {
                        $this->loadJavascriptLib('tab.js');
                }
 
                // This loads the tabulator-in-textarea feature. It automatically modifies
                // every textarea which is found.
                if (!$GLOBALS['BE_USER']->uc['disableTabInTextarea']) {
                        $this->loadJavascriptLib('tab.js');
                }
 
+                       // include the JS for the Context Sensitive Help
+               if ($includeCsh) {
+                       $this->loadCshJavascript();
+               }
+
                        // Get the browser info
                        // Get the browser info
-               $matchObject = t3lib_div::makeInstance('t3lib_matchCondition');
-               $browserInfo = $matchObject->browserInfo(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
+               $browserInfo = t3lib_utility_Client::getBrowserInfo(t3lib_div::getIndpEnv('HTTP_USER_AGENT'));
 
                        // Set the XML prologue
                $xmlPrologue = '<?xml version="1.0" encoding="' . $this->charset . '"?>';
 
                        // Set the XML prologue
                $xmlPrologue = '<?xml version="1.0" encoding="' . $this->charset . '"?>';
@@ -684,40 +704,95 @@ class template {
                $xmlStylesheet = '<?xml-stylesheet href="#internalStyle" type="text/css"?>';
 
                        // Add the XML prologue for XHTML doctypes
                $xmlStylesheet = '<?xml-stylesheet href="#internalStyle" type="text/css"?>';
 
                        // Add the XML prologue for XHTML doctypes
-               if ($this->docType !== 'html_3') {
+               if (strpos($this->docType, 'xhtml') !== FALSE) {
                                // Put the XML prologue before or after the doctype declaration according to browser
                        if ($browserInfo['browser'] === 'msie' && $browserInfo['version'] < 7) {
                                // Put the XML prologue before or after the doctype declaration according to browser
                        if ($browserInfo['browser'] === 'msie' && $browserInfo['version'] < 7) {
-                               $headerStart = $headerStart . chr(10) . $xmlPrologue;
+                               $headerStart = $headerStart . LF . $xmlPrologue;
                        } else {
                        } else {
-                               $headerStart = $xmlPrologue . chr(10) . $headerStart;
+                               $headerStart = $xmlPrologue . LF . $headerStart;
                        }
 
                                // Add the xml stylesheet according to doctype
                        if ($this->docType !== 'xhtml_frames') {
                        }
 
                                // Add the xml stylesheet according to doctype
                        if ($this->docType !== 'xhtml_frames') {
-                               $headerStart = $headerStart . chr(10) . $xmlStylesheet;
+                               $headerStart = $headerStart . LF . $xmlStylesheet;
+                       }
+               }
+
+               $this->pageRenderer->setXmlPrologAndDocType($headerStart);
+               $this->pageRenderer->setHeadTag('<head>' . LF. '<!-- TYPO3 Script ID: '.htmlspecialchars($this->scriptID).' -->');
+               $this->pageRenderer->setCharSet($this->charset);
+               $this->pageRenderer->addMetaTag($this->generator());
+               if ($this->useCompatibilityTag) {
+                       $this->pageRenderer->addMetaTag($this->xUaCompatible());
+               }
+               $this->pageRenderer->setTitle($title);
+
+               // add docstyles
+               $this->docStyle();
+
+          if ($this->extDirectStateProvider) {
+                       $this->pageRenderer->addJsFile($this->backPath . '../t3lib/js/extjs/ExtDirect.StateProvider.js');
+               }
+
+                       // add jsCode for overriding the console with a debug panel connection
+               $this->pageRenderer->addJsInlineCode(
+                       'consoleOverrideWithDebugPanel',
+                       'if (typeof top.Ext === "object") {
+                               top.Ext.onReady(function() {
+                                       if (typeof console === "undefined") {
+                                               if (top && top.TYPO3 && top.TYPO3.Backend && top.TYPO3.Backend.DebugConsole) {
+                                                       console = top.TYPO3.Backend.DebugConsole;
+                                               } else {
+                                                       console = {
+                                                               log: Ext.log,
+                                                               info: Ext.log,
+                                                               warn: Ext.log,
+                                                               error: Ext.log
+                                                       };
+                                               }
+                                       }
+                               });
+                       }
+               ');
+
+               $this->pageRenderer->addHeaderData($this->JScode);
+
+               foreach ($this->JScodeArray as $name => $code) {
+                       $this->pageRenderer->addJsInlineCode($name, $code);
+               }
+
+               if (count($this->JScodeLibArray)) {
+                       foreach($this->JScodeLibArray as $library) {
+                               $this->pageRenderer->addHeaderData($library);
+                       }
+               }
+
+               if ($this->extJScode) {
+                       $this->pageRenderer->addExtOnReadyCode($this->extJScode);
+               }
+
+                       // hook for additional headerData
+               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'])) {
+                       $preHeaderRenderHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'];
+                       if (is_array($preHeaderRenderHook)) {
+                               $hookParameters = array(
+                                       'pageRenderer' => &$this->pageRenderer,
+                               );
+                               foreach ($preHeaderRenderHook as $hookFunction) {
+                                       t3lib_div::callUserFunction($hookFunction, $hookParameters, $this);
+                               }
                        }
                }
 
                        // Construct page header.
                        }
                }
 
                        // Construct page header.
-               $str = $headerStart . chr(10) . $htmlTag . '
-<head>
-       <!-- TYPO3 Script ID: '.htmlspecialchars($this->scriptID).' -->
-       '.$charSet.'
-       '.$generator.'
-       <title>'.htmlspecialchars($title).'</title>
-       '.$this->docStyle().'
-       ' . $this->renderJSlibraries() . '
-       '.$this->JScode.'
-       '.$this->wrapScriptTags(implode("\n", $this->JScodeArray)).
-       ($this->extJScode ? $this->wrapScriptTags('Ext.onReady(function() {' . chr(10) . $this->extJScode . chr(10) . '});') : '') .
-       '
-       <!--###POSTJSMARKER###-->
-</head>
-';
+               $str = $this->pageRenderer->render(t3lib_PageRenderer::PART_HEADER);
+
                $this->JScodeLibArray = array();
                $this->JScode = $this->extJScode = '';
                $this->JScodeArray = array();
 
                $this->JScodeLibArray = array();
                $this->JScode = $this->extJScode = '';
                $this->JScodeArray = array();
 
+               $this->endOfPageJsBlock = $this->pageRenderer->render(t3lib_PageRenderer::PART_FOOTER);
+
                if ($this->docType=='xhtml_frames')     {
                        return $str;
                } else
                if ($this->docType=='xhtml_frames')     {
                        return $str;
                } else
@@ -725,8 +800,8 @@ $str.=$this->docBodyTagBegin().
 ($this->divClass?'
 
 <!-- Wrapping DIV-section for whole page BEGIN -->
 ($this->divClass?'
 
 <!-- Wrapping DIV-section for whole page BEGIN -->
-<div class="'.$this->divClass.'">
-':'').trim($this->form);
+<div class="' . $this->divClass . '">
+' : '' ) . trim($this->form);
                return $str;
        }
 
                return $str;
        }
 
@@ -744,26 +819,44 @@ $str.=$this->docBodyTagBegin().
                                $this->parseTime().
                                ($this->form?'
 </form>':'');
                                $this->parseTime().
                                ($this->form?'
 </form>':'');
+                       // if something is in buffer like debug, put it to end of page
+               if (ob_get_contents()) {
+                       $str .= ob_get_clean();
+                       header('Content-Encoding: None');
+               }
 
 
-               if ($this->docType!='xhtml_frames') {
+               if ($this->docType !== 'xhtml_frames') {
 
                        $str .= ($this->divClass?'
 
 <!-- Wrapping DIV-section for whole page END -->
 
                        $str .= ($this->divClass?'
 
 <!-- Wrapping DIV-section for whole page END -->
-</div>':'').'
-</body>        ';
-
+</div>':'') . $this->endOfPageJsBlock ;
                }
 
                }
 
-               $str .= '</html>';
 
                        // Logging: Can't find better place to put it:
 
                        // Logging: Can't find better place to put it:
-               if (TYPO3_DLOG) t3lib_div::devLog('END of BACKEND session', 'template', 0, array('_FLUSH' => true));
+               if (TYPO3_DLOG) t3lib_div::devLog('END of BACKEND session', 'template', 0, array('_FLUSH' => TRUE));
 
                return $str;
        }
 
        /**
 
                return $str;
        }
 
        /**
+        * Shortcut for render the complete page of a module
+        *
+        * @param  $title  page title
+        * @param  $content  page content
+        * @param bool $includeCsh  flag for including csh code
+        * @return string complete page
+        */
+       public function render($title, $content, $includeCsh = TRUE)  {
+               $pageContent = $this->startPage($title, $includeCsh);
+               $pageContent .= $content;
+               $pageContent .= $this->endPage();
+
+               return $this->insertStylesAndJS($pageContent);
+       }
+
+       /**
         * Returns the header-bar in the top of most backend modules
         * Closes section if open.
         *
         * Returns the header-bar in the top of most backend modules
         * Closes section if open.
         *
@@ -850,19 +943,22 @@ $str.=$this->docBodyTagBegin().
         * @param       string          Additional attributes to h-tag, eg. ' class=""'
         * @return      string          HTML content
         */
         * @param       string          Additional attributes to h-tag, eg. ' class=""'
         * @return      string          HTML content
         */
-       function sectionHeader($label,$sH=FALSE,$addAttrib='')  {
-               $tag = ($sH?'h3':'h4');
+       function sectionHeader($label, $sH=FALSE, $addAttrib='') {
+               $tag = ($sH ? 'h3' : 'h4');
+               if ($addAttrib && substr($addAttrib, 0, 1) !== ' ') {
+                       $addAttrib = ' ' . $addAttrib;
+               }
                $str='
 
        <!-- Section header -->
                $str='
 
        <!-- Section header -->
-       <'.$tag.$addAttrib.'>'.$label.'</'.$tag.'>
+       <' . $tag . $addAttrib . '>' . $label . '</' . $tag . '>
 ';
 ';
-               return $this->sectionBegin().$str;
+               return $this->sectionBegin() . $str;
        }
 
        /**
         * Begins an output section.
        }
 
        /**
         * Begins an output section.
-        * Returns the <div>-begin tag AND sets the ->sectionFlag true (if the ->sectionFlag is not already set!)
+        * Returns the <div>-begin tag AND sets the ->sectionFlag TRUE (if the ->sectionFlag is not already set!)
         * You can call this function even if a section is already begun since the function will only return something if the sectionFlag is not already set!
         *
         * @return      string          HTML content
         * You can call this function even if a section is already begun since the function will only return something if the sectionFlag is not already set!
         *
         * @return      string          HTML content
@@ -901,19 +997,8 @@ $str.=$this->docBodyTagBegin().
        }
 
        /**
        }
 
        /**
-        * Originally it printed a kind of divider.
-        * Deprecated. Just remove function calls to it or call the divider() function instead.
-        *
-        * @return      void
-        * @internal
-        * @deprecated since TYPO3 3.6
-        */
-       function middle()       {
-       }
-
-       /**
         * If a form-tag is defined in ->form then and end-tag for that <form> element is outputted
         * If a form-tag is defined in ->form then and end-tag for that <form> element is outputted
-        * Further a JavaScript section is outputted which will update the top.busy session-expiry object (unless $this->endJS is set to false)
+        * Further a JavaScript section is outputted which will update the top.busy session-expiry object (unless $this->endJS is set to FALSE)
         *
         * @return      string          HTML content (<script> tag section)
         */
         *
         * @return      string          HTML content (<script> tag section)
         */
@@ -956,28 +1041,20 @@ $str.=$this->docBodyTagBegin().
                $this->inDocStylesArray[] = $this->inDocStyles_TBEstyle;
 
                        // Implode it all:
                $this->inDocStylesArray[] = $this->inDocStyles_TBEstyle;
 
                        // Implode it all:
-               $inDocStyles = implode('
-                                       ',$this->inDocStylesArray);
-
-                       // The default color scheme should also in full be represented in the stylesheet.
-               $style=trim('
-                       '.($this->styleSheetFile?'<link rel="stylesheet" type="text/css" href="'.$this->backPath.$this->styleSheetFile.'" />':'').'
-                       '.($this->styleSheetFile2?'<link rel="stylesheet" type="text/css" href="'.$this->backPath.$this->styleSheetFile2.'" />':'').'
-                       <style type="text/css" id="internalStyle">
-                               /*<![CDATA[*/
-                                       '.trim($inDocStyles).'
-                                       /*###POSTCSSMARKER###*/
-                               /*]]>*/
-                       </style>
-                       '.($this->styleSheetFile_post?'<link rel="stylesheet" type="text/css" href="'.$this->backPath.$this->styleSheetFile_post.'" />':'').'
-                       '.implode("\n", $this->additionalStyleSheets)
-               )
-               ;
-               $this->inDocStyles='';
-               $this->inDocStylesArray=array();
+               $inDocStyles = implode(LF, $this->inDocStylesArray);
+
+               if ($this->styleSheetFile) {
+                       $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile);
+               }
+               if ($this->styleSheetFile2) {
+                       $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile2);
+               }
+
+               $this->pageRenderer->addCssInlineBlock('inDocStyles', $inDocStyles . LF . '/*###POSTCSSMARKER###*/');
+               if ($this->styleSheetFile_post) {
+                       $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile_post);
+               }
 
 
-               return '
-                       '.$style;
        }
 
        /**
        }
 
        /**
@@ -990,10 +1067,32 @@ $str.=$this->docBodyTagBegin().
         * @return      void
         */
        function addStyleSheet($key, $href, $title='', $relation='stylesheet') {
         * @return      void
         */
        function addStyleSheet($key, $href, $title='', $relation='stylesheet') {
-               if (!isset($this->additionalStyleSheets[$key])) {
-                       $this->additionalStyleSheets[$key] = '<link rel="' . $relation . '" type="text/css" href="' . $href . '"' . ($title ? (' title="' . $title . '"') : '') . ' />';
+               if (strpos($href, '://') !== FALSE || substr($href, 0, 1) === '/') {
+                       $file = $href;
+               } else {
+                       $file = $this->backPath . $href;
+               }
+               $this->pageRenderer->addCssFile($file, $relation, 'screen', $title);
+       }
+
+       /**
+        * Add all *.css files of the directory $path to the stylesheets
+        *
+        * @param       string          directory to add
+        * @return      void
+        */
+       function addStyleSheetDirectory($path) {
+                       // calculation needed, when TYPO3 source is used via a symlink
+                       // absolute path to the stylesheets
+               $filePath = dirname(t3lib_div::getIndpEnv('SCRIPT_FILENAME')) . '/' . $GLOBALS['BACK_PATH'] . $path;
+                       // clean the path
+               $resolvedPath = t3lib_div::resolveBackPath($filePath);
+                       // read all files in directory and sort them alphabetically
+               $files = t3lib_div::getFilesInDir($resolvedPath, 'css', FALSE, 1);
+               foreach ($files as $file) {
+                       $this->pageRenderer->addCssFile($GLOBALS['BACK_PATH'] . $path . $file, 'stylesheet', 'all');
                }
                }
-        }
+       }
 
        /**
         * Insert post rendering document style into already rendered content
 
        /**
         * Insert post rendering document style into already rendered content
@@ -1005,17 +1104,61 @@ $str.=$this->docBodyTagBegin().
        function insertStylesAndJS($content)    {
                        // insert accumulated CSS
                $this->inDocStylesArray[] = $this->inDocStyles;
        function insertStylesAndJS($content)    {
                        // insert accumulated CSS
                $this->inDocStylesArray[] = $this->inDocStyles;
-               $styles = "\n".implode("\n", $this->inDocStylesArray);
+               $styles = LF.implode(LF, $this->inDocStylesArray);
                $content = str_replace('/*###POSTCSSMARKER###*/',$styles,$content);
 
                        // insert accumulated JS
                $content = str_replace('/*###POSTCSSMARKER###*/',$styles,$content);
 
                        // insert accumulated JS
-               $jscode = $this->JScode."\n".$this->wrapScriptTags(implode("\n", $this->JScodeArray));
+               $jscode = $this->JScode.LF.$this->wrapScriptTags(implode(LF, $this->JScodeArray));
                $content = str_replace('<!--###POSTJSMARKER###-->',$jscode,$content);
 
                return $content;
        }
 
        /**
                $content = str_replace('<!--###POSTJSMARKER###-->',$jscode,$content);
 
                return $content;
        }
 
        /**
+        * Returns an array of all stylesheet directories belonging to core and skins
+        *
+        * @return      array   Stylesheet directories
+        */
+       public function getSkinStylesheetDirectories() {
+               $stylesheetDirectories = array();
+
+                       // add default core stylesheets
+               foreach ($this->stylesheetsCore as $stylesheetDir) {
+                       $stylesheetDirectories[] = $stylesheetDir;
+               }
+
+                       // Stylesheets from skins
+                       // merge default css directories ($this->stylesheetsSkin) with additional ones and include them
+               if (is_array($GLOBALS['TBE_STYLES']['skins'])) {
+                               // loop over all registered skins
+                       foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinExtKey => $skin) {
+                               $skinStylesheetDirs = $this->stylesheetsSkins;
+
+                                       // skins can add custom stylesheetDirectories using
+                                       // $GLOBALS['TBE_STYLES']['skins'][$_EXTKEY]['stylesheetDirectories']
+                               if (is_array($skin['stylesheetDirectories'])) {
+                                       $skinStylesheetDirs = array_merge($skinStylesheetDirs, $skin['stylesheetDirectories']);
+                               }
+
+                                       // add all registered directories
+                               foreach ($skinStylesheetDirs as $stylesheetDir) {
+                                               // for EXT:myskin/stylesheets/ syntax
+                                       if (substr($stylesheetDir, 0, 4) === 'EXT:') {
+                                               list($extKey, $path) = explode('/', substr($stylesheetDir, 4), 2);
+                                               if (strcmp($extKey, '') && t3lib_extMgm::isLoaded($extKey) && strcmp($path, '')) {
+                                                       $stylesheetDirectories[] = t3lib_extMgm::extRelPath($extKey) . $path;
+                                               }
+                                       } else {
+                                               // for relative paths
+                                               $stylesheetDirectories[] = t3lib_extMgm::extRelPath($skinExtKey) . $stylesheetDir;
+                                       }
+                               }
+                       }
+               }
+               return $stylesheetDirectories;
+       }
+
+       /**
         * Initialize the charset.
         * Sets the internal $this->charset variable to the charset defined in $GLOBALS["LANG"] (or the default as set in this class)
         * Returns the meta-tag for the document header
         * Initialize the charset.
         * Sets the internal $this->charset variable to the charset defined in $GLOBALS["LANG"] (or the default as set in this class)
         * Returns the meta-tag for the document header
@@ -1035,10 +1178,19 @@ $str.=$this->docBodyTagBegin().
         * @return      string          <meta> tag with name "generator"
         */
        function generator()    {
         * @return      string          <meta> tag with name "generator"
         */
        function generator()    {
-               $str = 'TYPO3 '.TYPO3_branch.', http://typo3.com, &#169; Kasper Sk&#229;rh&#248;j 1998-2009, extensions are copyright of their respective owners.';
+               $str = 'TYPO3 '.TYPO3_branch.', ' . TYPO3_URL_GENERAL . ', &#169; Kasper Sk&#229;rh&#248;j 1998-2009, extensions are copyright of their respective owners.';
                return '<meta name="generator" content="'.$str .'" />';
        }
 
                return '<meta name="generator" content="'.$str .'" />';
        }
 
+       /**
+        * Returns X-UA-Compatible meta tag
+        *
+        * @param       string          $content Content of the compatible tag (default: IE-8)
+        * @return      string          <meta http-equiv="X-UA-Compatible" content="???" />
+        */
+       public function xUaCompatible($content = 'IE=8') {
+               return '<meta http-equiv="X-UA-Compatible" content="' . $content . '" />';
+       }
 
 
 
 
 
 
@@ -1070,22 +1222,22 @@ $str.=$this->docBodyTagBegin().
        function icons($type, $styleAttribValue='')     {
                switch($type)   {
                        case '3':
        function icons($type, $styleAttribValue='')     {
                switch($type)   {
                        case '3':
-                               $icon = 'gfx/icon_fatalerror.gif';
+                               $icon = 'status-dialog-error';
                        break;
                        case '2':
                        break;
                        case '2':
-                               $icon = 'gfx/icon_warning.gif';
+                               $icon = 'status-dialog-warning';
                        break;
                        case '1':
                        break;
                        case '1':
-                               $icon = 'gfx/icon_note.gif';
+                               $icon = 'status-dialog-notification';
                        break;
                        case '-1':
                        break;
                        case '-1':
-                               $icon = 'gfx/icon_ok.gif';
+                               $icon = 'status-dialog-ok';
                        break;
                        default:
                        break;
                }
                if ($icon)      {
                        break;
                        default:
                        break;
                }
                if ($icon)      {
-                       return '<img'.t3lib_iconWorks::skinImg($this->backPath,$icon,'width="18" height="16"').' class="absmiddle"'.($styleAttribValue ? ' style="'.htmlspecialchars($styleAttribValue).'"' : '').' alt="" />';
+                       return t3lib_iconWorks::getSpriteIcon($icon);
                }
        }
 
                }
        }
 
@@ -1147,14 +1299,14 @@ $str.=$this->docBodyTagBegin().
        function wrapScriptTags($string, $linebreak=TRUE)       {
                if(trim($string)) {
                                // <script wrapped in nl?
        function wrapScriptTags($string, $linebreak=TRUE)       {
                if(trim($string)) {
                                // <script wrapped in nl?
-                       $cr = $linebreak? "\n" : '';
+                       $cr = $linebreak? LF : '';
 
                                // remove nl from the beginning
                        $string = preg_replace ('/^\n+/', '', $string);
                                // re-ident to one tab using the first line as reference
                        $match = array();
                        if(preg_match('/^(\t+)/',$string,$match)) {
 
                                // remove nl from the beginning
                        $string = preg_replace ('/^\n+/', '', $string);
                                // re-ident to one tab using the first line as reference
                        $match = array();
                        if(preg_match('/^(\t+)/',$string,$match)) {
-                               $string = str_replace($match[1],"\t", $string);
+                               $string = str_replace($match[1],TAB, $string);
                        }
                        $string = $cr.'<script type="text/javascript">
 /*<![CDATA[*/
                        }
                        $string = $cr.'<script type="text/javascript">
 /*<![CDATA[*/
@@ -1173,7 +1325,7 @@ $str.=$this->docBodyTagBegin().
                )
        );
        var $table_TR = '<tr>';
                )
        );
        var $table_TR = '<tr>';
-       var $table_TABLE = '<table border="0" cellspacing="0" cellpadding="0" id="typo3-tmpltable">';
+       var $table_TABLE = '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist" id="typo3-tmpltable">';
 
        /**
         * Returns a table based on the input $data
 
        /**
         * Returns a table based on the input $data
@@ -1279,28 +1431,37 @@ $str.=$this->docBodyTagBegin().
         * @return      string          <select> tag with content - a selector box for clearing the cache
         */
        function clearCacheMenu($id,$addSaveOptions=0)  {
         * @return      string          <select> tag with content - a selector box for clearing the cache
         */
        function clearCacheMenu($id,$addSaveOptions=0)  {
-               global $BE_USER;
                $opt=array();
                if ($addSaveOptions)    {
                        $opt[]='<option value="">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.menu',1).'</option>';
                        $opt[]='<option value="TBE_EDITOR.checkAndDoSubmit(1);">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveDoc',1).'</option>';
                        $opt[]='<option value="document.editform.closeDoc.value=-2; TBE_EDITOR.checkAndDoSubmit(1);">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveCloseDoc',1).'</option>';
                $opt=array();
                if ($addSaveOptions)    {
                        $opt[]='<option value="">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.menu',1).'</option>';
                        $opt[]='<option value="TBE_EDITOR.checkAndDoSubmit(1);">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveDoc',1).'</option>';
                        $opt[]='<option value="document.editform.closeDoc.value=-2; TBE_EDITOR.checkAndDoSubmit(1);">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveCloseDoc',1).'</option>';
-                       if ($BE_USER->uc['allSaveFunctions'])   $opt[]='<option value="document.editform.closeDoc.value=-3; TBE_EDITOR.checkAndDoSubmit(1);">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveCloseAllDocs',1).'</option>';
+                       if ($GLOBALS['BE_USER']->uc['allSaveFunctions']) {
+                               $opt[] = '<option value="document.editform.closeDoc.value=-3; TBE_EDITOR.checkAndDoSubmit(1);">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.saveCloseAllDocs', 1) . '</option>';
+                       }
                        $opt[]='<option value="document.editform.closeDoc.value=2; document.editform.submit();">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.closeDoc',1).'</option>';
                        $opt[]='<option value="document.editform.closeDoc.value=3; document.editform.submit();">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.closeAllDocs',1).'</option>';
                        $opt[]='<option value=""></option>';
                }
                $opt[]='<option value="">[ '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_clearCache',1).' ]</option>';
                if ($id) $opt[]='<option value="'.$id.'">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_thisPage',1).'</option>';
                        $opt[]='<option value="document.editform.closeDoc.value=2; document.editform.submit();">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.closeDoc',1).'</option>';
                        $opt[]='<option value="document.editform.closeDoc.value=3; document.editform.submit();">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.closeAllDocs',1).'</option>';
                        $opt[]='<option value=""></option>';
                }
                $opt[]='<option value="">[ '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_clearCache',1).' ]</option>';
                if ($id) $opt[]='<option value="'.$id.'">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_thisPage',1).'</option>';
-               if ($BE_USER->isAdmin() || $BE_USER->getTSConfigVal('options.clearCache.pages')) $opt[]='<option value="pages">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_pages',1).'</option>';
-               if ($BE_USER->isAdmin() || $BE_USER->getTSConfigVal('options.clearCache.all')) $opt[]='<option value="all">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_all',1).'</option>';
+               if ($GLOBALS['BE_USER']->isAdmin() || $GLOBALS['BE_USER']->getTSConfigVal('options.clearCache.pages')) {
+                       $opt[] = '<option value="pages">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_pages', 1) . '</option>';
+               }
+               if ($GLOBALS['BE_USER']->isAdmin() || $GLOBALS['BE_USER']->getTSConfigVal('options.clearCache.all')) {
+                       $opt[] = '<option value="all">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:rm.clearCache_all', 1) . '</option>';
+               }
 
                $onChange = 'if (!this.options[this.selectedIndex].value) {
                                this.selectedIndex=0;
                        } else if (this.options[this.selectedIndex].value.indexOf(\';\')!=-1) {
                                eval(this.options[this.selectedIndex].value);
 
                $onChange = 'if (!this.options[this.selectedIndex].value) {
                                this.selectedIndex=0;
                        } else if (this.options[this.selectedIndex].value.indexOf(\';\')!=-1) {
                                eval(this.options[this.selectedIndex].value);
-                       }else{
-                               window.location.href=\''.$this->backPath.'tce_db.php?vC='.$BE_USER->veriCode().'&redirect='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')).'&cacheCmd=\'+this.options[this.selectedIndex].value;
+                       } else {
+                               window.location.href=\'' . $this->backPath .
+                                               'tce_db.php?vC=' . $GLOBALS['BE_USER']->veriCode() .
+                                               t3lib_BEfunc::getUrlToken('tceAction') .
+                                               '&redirect=' . rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')) .
+                                               '&cacheCmd=\'+this.options[this.selectedIndex].value;
                        }';
                $af_content = '<select name="cacheCmd" onchange="'.htmlspecialchars($onChange).'">'.implode('',$opt).'</select>';
 
                        }';
                $af_content = '<select name="cacheCmd" onchange="'.htmlspecialchars($onChange).'">'.implode('',$opt).'</select>';
 
@@ -1319,26 +1480,10 @@ $str.=$this->docBodyTagBegin().
         * @return      void
         */
        function loadJavascriptLib($lib)        {
         * @return      void
         */
        function loadJavascriptLib($lib)        {
-               if (!isset($this->JScodeLibArray[$lib]))        {
-                       $this->JScodeLibArray[$lib] = '<script type="text/javascript" src="' . $this->backPath . $lib . '"></script>';
-               }
+               $this->pageRenderer->addJsFile($this->backPath . $lib);
        }
 
 
        }
 
 
-       /**
-        *
-        * @param string $lib   it will remove lib from general JScodeLibArray because lib is loaded already.
-        */
-       protected function removeJavascriptLib($lib) {
-               if (count($this->JScodeLibArray)) {
-                       $scripts = array_keys($this->JScodeLibArray);
-                       foreach ($scripts as $script) {
-                               if (strpos($script, '/' . $lib . '/') !== false) {
-                                       unset ($this->JScodeLibArray[$script]);
-                               }
-                       }
-               }
-       }
 
        /**
         * Includes the necessary Javascript function for the clickmenu (context sensitive menus) in the document
 
        /**
         * Includes the necessary Javascript function for the clickmenu (context sensitive menus) in the document
@@ -1347,7 +1492,7 @@ $str.=$this->docBodyTagBegin().
         *                      Please just call this function without expecting a return value for future calls
         */
        function getContextMenuCode()   {
         *                      Please just call this function without expecting a return value for future calls
         */
        function getContextMenuCode()   {
-              $this->loadPrototype();
+              $this->pageRenderer->loadPrototype();
               $this->loadJavascriptLib('js/clickmenu.js');
 
               $this->JScodeArray['clickmenu'] = '
               $this->loadJavascriptLib('js/clickmenu.js');
 
               $this->JScodeArray['clickmenu'] = '
@@ -1366,7 +1511,7 @@ $str.=$this->docBodyTagBegin().
         * @return      array           If values are present: [0] = A <script> section for the HTML page header, [1] = onmousemove/onload handler for HTML tag or alike, [2] = One empty <div> layer for the follow-mouse drag element
         */
        function getDragDropCode($table)        {
         * @return      array           If values are present: [0] = A <script> section for the HTML page header, [1] = onmousemove/onload handler for HTML tag or alike, [2] = One empty <div> layer for the follow-mouse drag element
         */
        function getDragDropCode($table)        {
-               $this->loadPrototype();
+               $this->pageRenderer->loadPrototype();
                $this->loadJavascriptLib('js/common.js');
                $this->loadJavascriptLib('js/tree.js');
 
                $this->loadJavascriptLib('js/common.js');
                $this->loadJavascriptLib('js/tree.js');
 
@@ -1381,6 +1526,16 @@ $str.=$this->docBodyTagBegin().
               return array('','','');
        }
 
               return array('','','');
        }
 
+        /**
+        * This loads everything needed for the Context Sensitive Help (CSH)
+        *
+        * @return void
+        */
+       protected function loadCshJavascript() {
+               $this->pageRenderer->loadExtJS();
+               $this->pageRenderer->addJsFile($this->backPath .'../t3lib/js/extjs/contexthelp.js');
+               $this->pageRenderer->addExtDirectCode();
+       }
 
        /**
         * Creates a tab menu from an array definition
 
        /**
         * Creates a tab menu from an array definition
@@ -1395,7 +1550,7 @@ $str.=$this->docBodyTagBegin().
         * @param       string          $script is the script to send the &id to, if empty it's automatically found
         * @param       string          $addParams is additional parameters to pass to the script.
         * @return      string          HTML code for tab menu
         * @param       string          $script is the script to send the &id to, if empty it's automatically found
         * @param       string          $addParams is additional parameters to pass to the script.
         * @return      string          HTML code for tab menu
-        * @author      Rene Fritz <r.fritz@colorcube.de>
+        * @author      René Fritz <r.fritz@colorcube.de>
         */
        function getTabMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='') {
                $content='';
         */
        function getTabMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='') {
                $content='';
@@ -1444,7 +1599,6 @@ $str.=$this->docBodyTagBegin().
                        $widthAct = $widthNo + $addToAct;
                        $widthRight = 100 - ($widthLeft + ($count*$widthNo) + $addToAct);
 
                        $widthAct = $widthNo + $addToAct;
                        $widthRight = 100 - ($widthLeft + ($count*$widthNo) + $addToAct);
 
-                       $first=true;
                        foreach($menuItems as $id => $def) {
                                $isActive = $def['isActive'];
                                $class = $isActive ? 'tabact' : 'tab';
                        foreach($menuItems as $id => $def) {
                                $isActive = $def['isActive'];
                                $class = $isActive ? 'tabact' : 'tab';
@@ -1455,14 +1609,7 @@ $str.=$this->docBodyTagBegin().
                                $url = htmlspecialchars($def['url']);
                                $params = $def['addParams'];
 
                                $url = htmlspecialchars($def['url']);
                                $params = $def['addParams'];
 
-                               if($first) {
-                                       $options.= '
-                                                       <td width="'.$width.'%" class="'.$class.'" style="border-left: solid #000 1px;"><a href="'.$url.'" style="padding-left:5px;padding-right:2px;" '.$params.'>'.$label.'</a></td>';
-                               } else {
-                                       $options.='
-                                                       <td width="'.$width.'%" class="'.$class.'"><a href="'.$url.'" '.$params.'>'.$label.'</a></td>';
-                               }
-                               $first=false;
+                               $options .= '<td width="' . $width . '%" class="' . $class . '"><a href="' . $url . '" ' . $params . '>' . $label . '</a></td>';
                        }
 
                        if ($options)   {
                        }
 
                        if ($options)   {
@@ -1490,15 +1637,15 @@ $str.=$this->docBodyTagBegin().
         * @param       string          Identification string. This should be unique for every instance of a dynamic menu!
         * @param       integer         If "1", then enabling one tab does not hide the others - they simply toggles each sheet on/off. This makes most sense together with the $foldout option. If "-1" then it acts normally where only one tab can be active at a time BUT you can click a tab and it will close so you have no active tabs.
         * @param       boolean         If set, the tabs are rendered as headers instead over each sheet. Effectively this means there is no tab menu, but rather a foldout/foldin menu. Make sure to set $toggle as well for this option.
         * @param       string          Identification string. This should be unique for every instance of a dynamic menu!
         * @param       integer         If "1", then enabling one tab does not hide the others - they simply toggles each sheet on/off. This makes most sense together with the $foldout option. If "-1" then it acts normally where only one tab can be active at a time BUT you can click a tab and it will close so you have no active tabs.
         * @param       boolean         If set, the tabs are rendered as headers instead over each sheet. Effectively this means there is no tab menu, but rather a foldout/foldin menu. Make sure to set $toggle as well for this option.
-        * @param       integer         Character limit for a new row.
+        * @param       integer         Character limit for a new row, 0 by default, because this parameter is deprecated since TYPO3 4.5
         * @param       boolean         If set, tab table cells are not allowed to wrap their content
         * @param       boolean         If set, the tabs will span the full width of their position
         * @param       integer         Default tab to open (for toggle <=0). Value corresponds to integer-array index + 1 (index zero is "1", index "1" is 2 etc.). A value of zero (or something non-existing) will result in no default tab open.
         * @param       integer         If set to '1' empty tabs will be remove, If set to '2' empty tabs will be disabled
         * @return      string          JavaScript section for the HTML header.
         */
         * @param       boolean         If set, tab table cells are not allowed to wrap their content
         * @param       boolean         If set, the tabs will span the full width of their position
         * @param       integer         Default tab to open (for toggle <=0). Value corresponds to integer-array index + 1 (index zero is "1", index "1" is 2 etc.). A value of zero (or something non-existing) will result in no default tab open.
         * @param       integer         If set to '1' empty tabs will be remove, If set to '2' empty tabs will be disabled
         * @return      string          JavaScript section for the HTML header.
         */
-       function getDynTabMenu($menuItems,$identString,$toggle=0,$foldout=FALSE,$newRowCharLimit=50,$noWrap=1,$fullWidth=FALSE,$defaultTabIndex=1,$dividers2tabs=2)     {
-               // load the static code, if not already done with the function below
+       public function getDynTabMenu($menuItems, $identString, $toggle = 0, $foldout = FALSE, $newRowCharLimit = 0, $noWrap = 1, $fullWidth = FALSE, $defaultTabIndex = 1, $dividers2tabs = 2) {
+                       // load the static code, if not already done with the function below
                $this->loadJavascriptLib('js/tabmenu.js');
 
                $content = '';
                $this->loadJavascriptLib('js/tabmenu.js');
 
                $content = '';
@@ -1517,10 +1664,12 @@ $str.=$this->docBodyTagBegin().
                        $tabRows=0;
                        $titleLenCount = 0;
                        foreach($menuItems as $index => $def) {
                        $tabRows=0;
                        $titleLenCount = 0;
                        foreach($menuItems as $index => $def) {
-                               $index+=1;      // Need to add one so checking for first index in JavaScript is different than if it is not set at all.
+                                       // Need to add one so checking for first index in JavaScript
+                                       // is different than if it is not set at all.
+                               $index += 1;
 
                                        // Switch to next tab row if needed
 
                                        // Switch to next tab row if needed
-                               if (!$foldout && ($titleLenCount>$newRowCharLimit | ($def['newline'] === true && $titleLenCount > 0))) {
+                               if (!$foldout && (($newRowCharLimit > 0 && $titleLenCount > $newRowCharLimit) | ($def['newline'] === TRUE && $titleLenCount > 0))) {
                                        $titleLenCount=0;
                                        $tabRows++;
                                        $options[$tabRows] = array();
                                        $titleLenCount=0;
                                        $tabRows++;
                                        $options[$tabRows] = array();
@@ -1534,13 +1683,13 @@ $str.=$this->docBodyTagBegin().
 
                                $isEmpty = !(strcmp(trim($def['content']),'') || strcmp(trim($def['icon']),''));
 
 
                                $isEmpty = !(strcmp(trim($def['content']),'') || strcmp(trim($def['icon']),''));
 
-                               // "Removes" empty tabs
+                                       // "Removes" empty tabs
                                if ($isEmpty && $dividers2tabs == 1) {
                                        continue;
                                }
 
                                $mouseOverOut = ' onmouseover="DTM_mouseOver(this);" onmouseout="DTM_mouseOut(this);"';
                                if ($isEmpty && $dividers2tabs == 1) {
                                        continue;
                                }
 
                                $mouseOverOut = ' onmouseover="DTM_mouseOver(this);" onmouseout="DTM_mouseOut(this);"';
-                               $requiredIcon = '<img name="' . $id . '-' . $index . '-REQ" src="' . $GLOBALS['BACK_PATH'] . 'gfx/clear.gif" width="10" height="10" hspace="4" alt="" />';
+                               $requiredIcon = '<img name="' . $id . '-' . $index . '-REQ" src="' . $GLOBALS['BACK_PATH'] . 'gfx/clear.gif" class="t3-TCEforms-reqTabImg" alt="" />';
 
                                if (!$foldout)  {
                                                // Create TAB cell:
 
                                if (!$foldout)  {
                                                // Create TAB cell:
@@ -1644,12 +1793,12 @@ $str.=$this->docBodyTagBegin().
         * (as long as it is called before $this->startPage())
         * The return value is not needed anymore
         *
         * (as long as it is called before $this->startPage())
         * The return value is not needed anymore
         *
-        * @return      string          JavaScript section for the HTML header. (return value is deprecated since TYPO3 4.3, will be removed in TYPO3 4.5)
+        * @deprecated since TYPO3 4.5, as the getDynTabMenu() function includes the function automatically since TYPO3 4.3
+        * @return      void
         */
         */
-       function getDynTabMenuJScode()  {
+       function getDynTabMenuJScode() {
+               t3lib_div::logDeprecatedFunction();
                $this->loadJavascriptLib('js/tabmenu.js');
                $this->loadJavascriptLib('js/tabmenu.js');
-               // return value deprecated since TYPO3 4.3
-               return '';
        }
 
        /**
        }
 
        /**
@@ -1660,177 +1809,39 @@ $str.=$this->docBodyTagBegin().
         * @param       boolean         If set, there will be no button for swapping page.
         * @return      void
         */
         * @param       boolean         If set, there will be no button for swapping page.
         * @return      void
         */
-       function getVersionSelector($id,$noAction=FALSE)        {
-
-               if ($id>0)      {
-                       if (t3lib_extMgm::isLoaded('version') && $GLOBALS['BE_USER']->workspace==0)     {
-
-                                       // Get Current page record:
-                               $curPage = t3lib_BEfunc::getRecord('pages',$id);
-                                       // If the selected page is not online, find the right ID
-                               $onlineId = ($curPage['pid']==-1 ? $curPage['t3ver_oid'] : $id);
-                                       // Select all versions of online version:
-                               $versions = t3lib_BEfunc::selectVersionsOfRecord('pages', $onlineId, 'uid,pid,t3ver_label,t3ver_oid,t3ver_wsid,t3ver_id');
-
-                                       // If more than one was found...:
-                               if (count($versions)>1) {
-
-                                               // Create selector box entries:
-                                       $opt = array();
-                                       foreach($versions as $vRow)     {
-                                               $opt[] = '<option value="'.htmlspecialchars(t3lib_div::linkThisScript(array('id'=>$vRow['uid']))).'"'.($id==$vRow['uid']?' selected="selected"':'').'>'.
-                                                               htmlspecialchars($vRow['t3ver_label'].' [v#'.$vRow['t3ver_id'].', WS:'.$vRow['t3ver_wsid'].']'.($vRow['uid']==$onlineId ? ' =>'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.online').'<=':'')).
-                                                               '</option>';
-                                       }
-
-                                               // Add management link:
-                                       $opt[] = '<option value="'.htmlspecialchars(t3lib_div::linkThisScript(array('id'=>$id))).'">---</option>';
-                                       $opt[] = '<option value="'.htmlspecialchars($this->backPath.t3lib_extMgm::extRelPath('version').'cm1/index.php?table=pages&uid='.$onlineId).'">'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.mgm',1).'</option>';
-
-                                               // Create onchange handler:
-                                       $onChange = "window.location.href=this.options[this.selectedIndex].value;";
-
-                                               // Controls:
-                                       if ($id==$onlineId)     {
-                                               $controls = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/blinkarrow_left.gif','width="5" height="9"').' class="absmiddle" alt="" /> <b>'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.online',1).'</b>';
-                                       } elseif (!$noAction) {
-                                               $controls = '<a href="'.$this->issueCommand('&cmd[pages]['.$onlineId.'][version][swapWith]='.$id.'&cmd[pages]['.$onlineId.'][version][action]=swap',t3lib_div::linkThisScript(array('id'=>$onlineId))).'" class="nobr">'.
-                                                               '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/insert1.gif','width="14" height="14"').' style="margin-right: 2px;" class="absmiddle" alt="" title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.swapPage',1).'" />'.
-                                                               '<b>'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.swap',1).'</b></a>';
-                                       }
-
-                                               // Write out HTML code:
-                                       return '
-
-                                               <!--
-                                                       Version selector:
-                                               -->
-                                               <table border="0" cellpadding="0" cellspacing="0" id="typo3-versionSelector">
-                                                       <tr>
-                                                               <td>'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:ver.selVer',1).'</td>
-                                                               <td>
-                                                                       <select onchange="'.htmlspecialchars($onChange).'">
-                                                                               '.implode('',$opt).'
-                                                                       </select></td>
-                                                               <td>'.$controls.'</td>
-                                                       </tr>
-                                               </table>
-                                       ';
-                               }
-                       } elseif ($GLOBALS['BE_USER']->workspace!==0) {
-
-                                       // Write out HTML code:
-                               switch($GLOBALS['BE_USER']->workspace)  {
-                                       case 0:
-                                               $wsTitle = 'LIVE';
-                                       break;
-                                       case -1:
-                                               $wsTitle = 'Draft';
-                                       break;
-                                       default:
-                                               $wsTitle = $GLOBALS['BE_USER']->workspaceRec['title'];
-                                       break;
-                               }
-
-                               if (t3lib_BEfunc::isPidInVersionizedBranch($id)=='branchpoint') {
-                                       return '
-
-                                               <!--
-                                                       Version selector:
-                                               -->
-                                               <table border="0" cellpadding="0" cellspacing="0" id="typo3-versionSelector">
-                                                       <tr>
-                                                               <td>Workspace: "'.htmlspecialchars($wsTitle).'"</td>
-                                                               <td><em>Inside branch, no further versioning possible</em></td>
-                                                       </tr>
-                                               </table>
-                                       ';
-                               } else {
-                                               // Get Current page record:
-                                       $curPage = t3lib_BEfunc::getRecord('pages',$id);
-                                               // If the selected page is not online, find the right ID
-                                       $onlineId = ($curPage['pid']==-1 ? $curPage['t3ver_oid'] : $id);
-                                               // The version of page:
-                                       $verPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, 'pages', $onlineId);
-
-                                       if (!$verPage)  {
-
-                                               if (!count(t3lib_BEfunc::countVersionsOfRecordsOnPage($GLOBALS['BE_USER']->workspace, $onlineId)))      {
-                                                       if ($GLOBALS['BE_USER']->workspaceVersioningTypeAccess(0))      {
-
-                                                               $onClick = $this->issueCommand('&cmd[pages]['.$onlineId.'][version][action]=new&cmd[pages]['.$onlineId.'][version][treeLevels]=0',t3lib_div::linkThisScript(array('id'=>$onlineId)));
-                                                               $onClick = 'window.location.href=\''.$onClick.'\'; return false;';
-                                                                       // Write out HTML code:
-                                                               return '
-
-                                                                       <!--
-                                                                               No version yet, create one?
-                                                                       -->
-                                                                       <table border="0" cellpadding="0" cellspacing="0" id="typo3-versionSelector">
-                                                                               <tr>
-                                                                                       <td>Workspace: "'.htmlspecialchars($wsTitle).'"</td>
-                                                                                       <td>
-                                                                                               <input type="submit" value="New version of page" name="_" onclick="'.htmlspecialchars($onClick).'" /></td>
-                                                                               </tr>
-                                                                       </table>
-                                                               ';
-                                                       }
-                                               } else {
-                                                       return '
-
-                                                               <!--
-                                                                       Version selector:
-                                                               -->
-                                                               <table border="0" cellpadding="0" cellspacing="0" id="typo3-versionSelector">
-                                                                       <tr>
-                                                                               <td>Workspace: "'.htmlspecialchars($wsTitle).'"</td>
-                                                                               <td><em>Versions found on page, no "Page" versioning possible</em></td>
-                                                                       </tr>
-                                                               </table>
-                                                       ';
-                                               }
-                                       } elseif ($verPage['t3ver_swapmode']==0) {
-                                               $onClick = $this->issueCommand('&cmd[pages]['.$onlineId.'][version][action]=swap&cmd[pages]['.$onlineId.'][version][swapWith]='.$verPage['uid'],t3lib_div::linkThisScript(array('id'=>$onlineId)));
-                                               $onClick = 'window.location.href=\''.$onClick.'\'; return false;';
-
-                                                       // Write out HTML code:
-                                               return '
-
-                                                       <!--
-                                                               Version selector:
-                                                       -->
-                                                       <table border="0" cellpadding="0" cellspacing="0" id="typo3-versionSelector">
-                                                               <tr>
-                                                                       <td>Workspace: "'.htmlspecialchars($wsTitle).'"</td>
-                                                                       <td>
-                                                                               <input type="submit" value="Publish page" name="_" onclick="'.htmlspecialchars($onClick).'" /></td>
-                                                               </tr>
-                                                       </table>
-                                               ';
-                                       }
-                               }
-                       }
+       public function getVersionSelector($id, $noAction = FALSE) {
+               if (t3lib_extMgm::isLoaded('version')) {
+                       $versionGuiObj = t3lib_div::makeInstance('tx_version_gui');
+                       return $versionGuiObj->getVersionSelector($id, $noAction);
                }
        }
 
                }
        }
 
-
        /**
         * Function to load a HTML template file with markers.
         * When calling from own extension, use  syntax getHtmlTemplate('EXT:extkey/template.html')
        /**
         * Function to load a HTML template file with markers.
         * When calling from own extension, use  syntax getHtmlTemplate('EXT:extkey/template.html')
-        * 
+        *
         * @param       string          tmpl name, usually in the typo3/template/ directory
         * @return      string          HTML of template
         */
        function getHtmlTemplate($filename)     {
         * @param       string          tmpl name, usually in the typo3/template/ directory
         * @return      string          HTML of template
         */
        function getHtmlTemplate($filename)     {
+                       // setting the name of the original HTML template
+               $this->moduleTemplateFilename = $filename;
+
                if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
                        $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
                }
                if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
                        $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
                }
-               if (substr($filename,0,4) != 'EXT:') {
+               if (t3lib_div::isFirstPartOfStr($filename, 'EXT:')) {
+                       $filename = t3lib_div::getFileAbsFileName($filename, TRUE, TRUE);
+               } elseif (!t3lib_div::isAbsPath($filename)) {
                        $filename = t3lib_div::resolveBackPath($this->backPath . $filename);
                        $filename = t3lib_div::resolveBackPath($this->backPath . $filename);
-               } else {
-                       $filename = t3lib_div::getFileAbsFileName($filename, true, true);
+               } elseif (!t3lib_div::isAllowedAbsPath($filename)) {
+                       $filename = '';
+               }
+               $htmlTemplate = '';
+               if ($filename !== '') {
+                       $htmlTemplate = t3lib_div::getUrl($filename);
                }
                }
-               return t3lib_div::getURL($filename);
+               return $htmlTemplate;
        }
 
        /**
        }
 
        /**
@@ -1838,9 +1849,9 @@ $str.=$this->docBodyTagBegin().
         *
         * @param       string          filename
         */
         *
         * @param       string          filename
         */
-       function setModuleTemplate($filename) {
+       public function setModuleTemplate($filename) {
                        // Load Prototype lib for IE event
                        // Load Prototype lib for IE event
-               $this->loadPrototype();
+               $this->pageRenderer->loadPrototype();
                $this->loadJavascriptLib('js/iecompatibility.js');
                $this->moduleTemplate = $this->getHtmlTemplate($filename);
        }
                $this->loadJavascriptLib('js/iecompatibility.js');
                $this->moduleTemplate = $this->getHtmlTemplate($filename);
        }
@@ -1859,20 +1870,7 @@ $str.=$this->docBodyTagBegin().
                $moduleBody = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###FULLDOC###');
                        // Add CSS
                $this->inDocStylesArray[] = 'html { overflow: hidden; }';
                $moduleBody = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###FULLDOC###');
                        // Add CSS
                $this->inDocStylesArray[] = 'html { overflow: hidden; }';
-                       // Add JS code to the <head> for IE
-               $this->JScode.= $this->wrapScriptTags('
-                               // workaround since IE6 cannot deal with relative height for scrolling elements
-                       function resizeDocBody()        {
-                               $("typo3-docbody").style.height = (document.body.offsetHeight - parseInt($("typo3-docheader").getStyle("height")));
-                       }
-                       if (Prototype.Browser.IE) {
-                               var version = parseFloat(navigator.appVersion.split(\';\')[1].strip().split(\' \')[1]);
-                               if (version == 6) {
-                                       Event.observe(window, "resize", resizeDocBody, false);
-                                       Event.observe(window, "load", resizeDocBody, false);
-                               }
-                       }
-               ');
+
                        // Get the page path for the docheader
                $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
                        // Get the page info for the docheader
                        // Get the page path for the docheader
                $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
                        // Get the page info for the docheader
@@ -1885,6 +1883,39 @@ $str.=$this->docBodyTagBegin().
                foreach ($subpartArray as $marker => $content) {
                        $moduleBody = t3lib_parsehtml::substituteSubpart($moduleBody, $marker, $content);
                }
                foreach ($subpartArray as $marker => $content) {
                        $moduleBody = t3lib_parsehtml::substituteSubpart($moduleBody, $marker, $content);
                }
+
+                       // adding flash messages
+               if ($this->showFlashMessages) {
+                       $flashMessages = t3lib_FlashMessageQueue::renderFlashMessages();
+                       if (!empty($flashMessages)) {
+                               $markerArray['FLASHMESSAGES'] = '<div id="typo3-messages">' . $flashMessages . '</div>';
+
+                                       // if there is no dedicated marker for the messages present
+                                       // then force them to appear before the content
+                               if (strpos($moduleBody, '###FLASHMESSAGES###') === FALSE) {
+                                       $moduleBody = str_replace(
+                                               '###CONTENT###',
+                                               '###FLASHMESSAGES######CONTENT###',
+                                               $moduleBody
+                                       );
+                               }
+                       }
+               }
+
+                       // Hook for adding more markers/content to the page, like the version selector
+               if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'])) {
+                       $params = array(
+                               'moduleTemplateFilename' => &$this->moduleTemplateFilename,
+                               'moduleTemplate' => &$this->moduleTemplate,
+                               'moduleBody' => &$moduleBody,
+                               'markers' => &$markerArray,
+                               'parentObject' => &$this
+                       );
+                       foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'] as $funcRef) {
+                               t3lib_div::callUserFunction($funcRef, $params, $this);
+                       }
+               }
+
                        // replacing all markers with the finished markers and return the HTML content
                return t3lib_parsehtml::substituteMarkerArray($moduleBody, $markerArray, '###|###');
 
                        // replacing all markers with the finished markers and return the HTML content
                return t3lib_parsehtml::substituteMarkerArray($moduleBody, $markerArray, '###|###');
 
@@ -1904,7 +1935,7 @@ $str.=$this->docBodyTagBegin().
                                // Get the template for each float
                        $buttonTemplate = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
                                // Fill the button markers in this float
                                // Get the template for each float
                        $buttonTemplate = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
                                // Fill the button markers in this float
-                       $buttonTemplate = t3lib_parsehtml::substituteMarkerArray($buttonTemplate, $buttons, '###|###', true);
+                       $buttonTemplate = t3lib_parsehtml::substituteMarkerArray($buttonTemplate, $buttons, '###|###', TRUE);
                                // getting the wrap for each group
                        $buttonWrap = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
                                // looping through the groups (max 6) and remove the empty groups
                                // getting the wrap for each group
                        $buttonWrap = t3lib_parsehtml::getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
                                // looping through the groups (max 6) and remove the empty groups
@@ -1919,9 +1950,9 @@ $str.=$this->docBodyTagBegin().
                                }
                        }
                                // replace the marker with the template and remove all line breaks (for IE compat)
                                }
                        }
                                // replace the marker with the template and remove all line breaks (for IE compat)
-                       $markers['BUTTONLIST_' . strtoupper($key)] = str_replace("\n", '', $buttonTemplate);
+                       $markers['BUTTONLIST_' . strtoupper($key)] = str_replace(LF, '', $buttonTemplate);
                }
                }
-               
+
                        // Hook for manipulating docHeaderButtons
                if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'])) {
                        $params = array(
                        // Hook for manipulating docHeaderButtons
                if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'])) {
                        $params = array(
@@ -1946,10 +1977,16 @@ $str.=$this->docBodyTagBegin().
        protected function getPagePath($pageRecord) {
                        // Is this a real page
                if ($pageRecord['uid']) {
        protected function getPagePath($pageRecord) {
                        // Is this a real page
                if ($pageRecord['uid']) {
-                       $title = $pageRecord['_thePathFull'];
+                       $title = substr($pageRecord['_thePathFull'], 0, -1);
+                               // remove current page title
+                       $pos = strrpos($title, '/');
+                       if ($pos !== FALSE) {
+                               $title = substr($title, 0, $pos) . '/';
+                       }
                } else {
                } else {
-                       $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
+                       $title = '';
                }
                }
+
                        // Setting the path of the page
                $pagePath = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.path', 1) . ': <span class="typo3-docheader-pagePath">';
 
                        // Setting the path of the page
                $pagePath = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.path', 1) . ': <span class="typo3-docheader-pagePath">';
 
@@ -1972,180 +2009,95 @@ $str.=$this->docBodyTagBegin().
         * @return      string  Page info
         */
        protected function getPageInfo($pageRecord) {
         * @return      string  Page info
         */
        protected function getPageInfo($pageRecord) {
-               global $BE_USER;
+
                                // Add icon with clickmenu, etc:
                if ($pageRecord['uid']) {       // If there IS a real page
                        $alttext = t3lib_BEfunc::getRecordIconAltText($pageRecord, 'pages');
                                // Add icon with clickmenu, etc:
                if ($pageRecord['uid']) {       // If there IS a real page
                        $alttext = t3lib_BEfunc::getRecordIconAltText($pageRecord, 'pages');
-                       $iconImg = t3lib_iconWorks::getIconImage('pages', $pageRecord, $this->backPath, 'class="absmiddle" title="'. htmlspecialchars($alttext) . '"');
+                       $iconImg = t3lib_iconWorks::getSpriteIconForRecord('pages', $pageRecord, array('title'=>$alttext));
                                // Make Icon:
                        $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
                                // Make Icon:
                        $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
+                       $uid = $pageRecord['uid'];
+                       $title = t3lib_BEfunc::getRecordTitle('pages', $pageRecord);
                } else {        // On root-level of page tree
                                // Make Icon
                } else {        // On root-level of page tree
                                // Make Icon
-                       $iconImg = '<img' . t3lib_iconWorks::skinImg($this->backPath, 'gfx/i/_icon_website.gif') . ' alt="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" />';
-                       if($BE_USER->user['admin']) {
+                       $iconImg = t3lib_iconWorks::getSpriteIcon('apps-pagetree-root', array('title' => htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'])));
+                       if ($GLOBALS['BE_USER']->user['admin']) {
                                $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', 0);
                        } else {
                                $theIcon = $iconImg;
                        }
                                $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', 0);
                        } else {
                                $theIcon = $iconImg;
                        }
+                       $uid = '0';
+                       $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
                }
 
                        // Setting icon with clickmenu + uid
                }
 
                        // Setting icon with clickmenu + uid
-               $pageInfo = $theIcon . '<em>[pid: ' . $pageRecord['uid'] . ']</em>';
+               $pageInfo = $theIcon . '<strong>' . htmlspecialchars($title) . '&nbsp;[' . $uid . ']</strong>';
                return $pageInfo;
        }
 
                return $pageInfo;
        }
 
-
        /**
        /**
-        *  Following functions are help function for JS library include.
-        *  They enable loading the libraries prototype, scriptaculous and extJS from contrib-directory
-        */
-
-
-       /**
-        * Function for render the JS-libraries in header
-        * Load order is prototype / scriptaculous / extJS
-        */
-       protected function renderJSlibraries() {
-               $libs = array();
-
-                       // include prototype
-               if ($this->addPrototype) {
-                       $libs[] = 'contrib/prototype/prototype.js';
-                               // remove prototype from JScodeLibArray
-                       $this->removeJavascriptLib('prototype');
-               }
-
-                       // include scriptaculous
-               if ($this->addScriptaculous) {
-                       $mods = array();
-                       foreach ($this->addScriptaculousModules as $key => $value) {
-                               if ($this->addScriptaculousModules[$key]) {
-                                       $mods[] = $key;
-                               }
-                       }
-                               // resolve dependencies
-                       if (in_array('dragdrop', $mods) || in_array('controls', $mods)) {
-                               $mods = array_merge(array('effects'), $mods);
-                       }
-
-                       if (count($mods)) {
-                               $moduleLoadString = '?load=' . implode(',', $mods);
-                       }
-                       $libs[] = 'contrib/scriptaculous/scriptaculous.js' . $moduleLoadString;
-                               // remove scriptaculous from JScodeLibArray
-                       $this->removeJavascriptLib('scriptaculous');
-               }
-
-                       // include extJS
-               if ($this->addExtJS) {
-                               // use the base adapter all the time
-                       $libs[] = 'contrib/extjs/adapter/' . ($this->enableExtJsDebug ? str_replace('.js', '-debug.js', $this->extJSadapter) : $this->extJSadapter);
-                       $libs[] = 'contrib/extjs/ext-all' . ($this->enableExtJsDebug ? '-debug' : '') . '.js';
-
-                               // add extJS localization
-                       $localeMap = $GLOBAL['LANG']->csConvObj->isoArray;      // load standard ISO mapping and modify for use with ExtJS
-                       $localeMap[''] = 'en';
-                       $localeMap['default'] = 'en';
-                       $localeMap['gr'] = 'el_GR';     // Greek
-                       $localeMap['no'] = 'no_BO';     // Norwegian Bokmaal
-                       $localeMap['se'] = 'se_SV';     // Swedish
-                       $extJsLang = isset($localeMap[$GLOBALS['BE_USER']->uc['lang']]) ? $localeMap[$GLOBALS['BE_USER']->uc['lang']] : $GLOBALS['BE_USER']->uc['lang'];
-                       // TODO autoconvert file from UTF8 to current BE charset if necessary!!!!
-                       $extJsLocaleFile = 'contrib/extjs/locale/ext-lang-' . $extJsLang . '-min.js';
-                       if (file_exists(PATH_typo3 . $extJsLocaleFile)) {
-                               $libs[] = $extJsLocaleFile;
-                       }
-                               // set clear.gif
-                       $this->extJScode .= 'Ext.BLANK_IMAGE_URL = "' . htmlspecialchars(t3lib_div::locationHeaderUrl('gfx/clear.gif')) . '";';
-                               // remove extjs from JScodeLibArray
-                       $this->removeJavascriptLib('contrib/extjs');
-               }
-
-               foreach ($libs as &$lib) {
-                       $lib = '<script type="text/javascript" src="' . $this->backPath . $lib . '"></script>';
-               }
-
-                       // add other JavascriptLibs and return it
-               $libs = array_merge($libs, $this->JScodeLibArray);
-               return count($libs) ? chr(10) . chr(10) . implode(chr(10), $libs) . chr(10) . chr(10) : '';
-       }
-
-       /**
-        *  call function if you need the prototype library
+        * Makes a collapseable section. See reports module for an example
+        *
+        * @param  string  $title
+        * @param  string  $html
+        * @param  string  $id
+        * @param  string $saveStatePointer
+        * @return string
         */
         */
-       public function loadPrototype() {
-               $this->addPrototype = true;
-       }
+       public function collapseableSection($title, $html, $id, $saveStatePointer = '') {
+               $hasSave = $saveStatePointer ? TRUE : FALSE;
+               $collapsedStyle =  $collapsedClass = '';
 
 
-       /**
-        *  call function if you need the Scriptaculous library
-        * @param string $modules   add modules you need. use "all" if you need complete modules
-        */
-       public function loadScriptaculous($modules='') {
-                       // Scriptaculous require prototype, so load prototype too.
-               $this->addPrototype = true;
-               $this->addScriptaculous = true;
-               if ($modules) {
-                       if ($modules == 'all') {
-                               foreach ($this->addScriptaculousModules as $key => $value) {
-                                       $this->addScriptaculousModules[$key] = true;
-                               }
+               if ($hasSave) {
+                       /** @var $settings extDirect_DataProvider_BackendUserSettings */
+                       $settings = t3lib_div::makeInstance('extDirect_DataProvider_BackendUserSettings');
+                       $value = $settings->get($saveStatePointer . '.' . $id);
+                       if ($value) {
+                               $collapsedStyle = ' style="display: none"';
+                               $collapsedClass = ' collapsed';
                        } else {
                        } else {
-                               $mods = t3lib_div::trimExplode(',', $modules);
-                               foreach ($mods as $mod) {
-                                       if (isset($this->addScriptaculousModules[strtolower($mod)])) {
-                                               $this->addScriptaculousModules[strtolower($mod)] = true;
-                                       }
-                               }
+                               $collapsedStyle = '';
+                               $collapsedClass = ' expanded';
                        }
                }
                        }
                }
-       }
 
 
-       /**
-        *  call this function if you need the extJS library
-        * @param boolean $css flag, if set the ext-css will be loaded
-        * @param boolean $theme flag, if set the ext-theme "grey" will be loaded
-        * @param string $adapter choose alternative adapter, possible values: yui, prototype, jquery
-        */
-       public function loadExtJS($css = true, $theme = true, $adapter = '') {
-               if ($adapter) {
-                               // empty $adapter will always load the ext adapter
-                       switch (t3lib_div::strtolower(trim($adapter))) {
-                               case template::EXTJS_ADAPTER_YUI:
-                                       $this->extJSadapter = 'yui/ext-yui-adapter.js';
-                               break;
-                               case template::EXTJS_ADAPTER_PROTOTYPE:
-                                   $this->extJSadapter = 'prototype/ext-prototype-adapter.js';
-                               break;
-                               case template::EXTJS_ADAPTER_JQUERY:
-                                       $this->extJSadapter = 'jquery/ext-jquery-adapter.js';
-                               break;
-                       }
-               }
-               if (!$this->addExtJS) {
-                       $this->addExtJS = true;
-                       if ($css) {
-                               if (isset($GLOBALS['TBE_STYLES']['extJS']['all'])) {
-                                       $this->addStyleSheet('ext-all', $this->backPath . $GLOBALS['TBE_STYLES']['extJS']['all']);
-                               } else {
-                                       $this->addStyleSheet('ext-all', $this->backPath . 'contrib/extjs/resources/css/ext-all-notheme.css');
-                               }
-                       }
-                       if ($theme) {
-                               if (isset($GLOBALS['TBE_STYLES']['extJS']['theme'])) {
-                                       $this->addStyleSheet('ext-theme', $this->backPath . $GLOBALS['TBE_STYLES']['extJS']['theme']);
-                               } else {
-                                       $this->addStyleSheet('ext-theme', $this->backPath . 'contrib/extjs/resources/css/xtheme-blue.css');
-                               }
-                       }
-               }
-       }
+               $this->pageRenderer->loadExtJS();
+               $this->pageRenderer->addExtOnReadyCode('
+                       Ext.select("h2.section-header").each(function(element){
+                               element.on("click", function(event, tag) {
+                                       var state = 0,
+                                               el = Ext.fly(tag),
+                                               div = el.next("div"),
+                                               saveKey = el.getAttribute("rel");
+                                       if (el.hasClass("collapsed")) {
+                                               el.removeClass("collapsed").addClass("expanded");
+                                               div.slideIn("t", {
+                                                       easing: "easeIn",
+                                                       duration: .5
+                                               });
+                                       } else {
+                                               el.removeClass("expanded").addClass("collapsed");
+                                               div.slideOut("t", {
+                                                       easing: "easeOut",
+                                                       duration: .5,
+                                                       remove: false,
+                                                       useDisplay: true
+                                               });
+                                               state = 1;
+                                       }
+                                       if (saveKey) {
+                                               try {
+                                                       top.TYPO3.BackendUserSettings.ExtDirect.set(saveKey + "." + tag.id, state, function(response) {});
+                                               } catch(e) {}
+                                       }
+                               });
+                       });
+               ');
+               return '
+                 <h2 id="' . $id . '" class="section-header' . $collapsedClass . '" rel="' . $saveStatePointer . '"> ' . $title . '</h2>
+                 <div' . $collapsedStyle  . '>' . $html . '</div>
+               ';
 
 
-       /**
-        * call this function to load debug version of extJS. Use this for development only
-        */
-       public function enableExtJsDebug() {
-               $this->enableExtJsDebug = true;
        }
 
 
        }
 
 
@@ -2200,7 +2152,18 @@ class mediumDoc extends template {
  * Extension class for "template" - used in the context of frontend editing.
  */
 class frontendDoc extends template {
  * Extension class for "template" - used in the context of frontend editing.
  */
 class frontendDoc extends template {
-       var $backPath = 'typo3/';
+
+       /**
+        * Gets instance of PageRenderer
+        *
+        * @return      t3lib_PageRenderer
+        */
+       public function getPageRenderer() {
+               if (!isset($this->pageRenderer)) {
+                       $this->pageRenderer = $GLOBALS['TSFE']->getPageRenderer();
+               }
+               return $this->pageRenderer;
+       }
 
        /**
         * Used in the frontend context to insert header data via TSFE->additionalHeaderData.
 
        /**
         * Used in the frontend context to insert header data via TSFE->additionalHeaderData.
@@ -2209,20 +2172,26 @@ class frontendDoc extends template {
         * @return      void
         */
        public function insertHeaderData() {
         * @return      void
         */
        public function insertHeaderData() {
-               $GLOBALS['TSFE']->additionalHeaderData['docStyle'] = $this->docStyle();
-               $GLOBALS['TSFE']->additionalHeaderData['JSLibraries'] = $this->renderJSlibraries();
-               $GLOBALS['TSFE']->additionalHeaderData['JScode'] = $this->JScode;
-               $GLOBALS['TSFE']->additionalHeaderData['JScodeArray'] = $this->wrapScriptTags(implode("\n", $this->JScodeArray));
-               
-               if ($this->extJScode) {
-                       $GLOBALS['TSFE']->additionalHeaderData['extJScode'] = $this->wrapScriptTags('Ext.onReady(function() {' . chr(10) . $this->extJScode . chr(10) . '});');
+
+               $this->backPath = $GLOBALS['TSFE']->backPath = TYPO3_mainDir;
+               $this->pageRenderer->setBackPath($this->backPath);
+               $this->docStyle();
+
+                       // add applied JS/CSS to $GLOBALS['TSFE']
+               if ($this->JScode) {
+                       $this->pageRenderer->addHeaderData($this->JScode);
+               }
+               if (count($this->JScodeArray)) {
+                       foreach ($this->JScodeArray as $name => $code) {
+                               $this->pageRenderer->addJsInlineCode($name, $code);
+                       }
                }
        }
 }
 
 
                }
        }
 }
 
 
-if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/template.php'])     {
-       include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/template.php']);
+if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['typo3/template.php'])) {
+       include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['typo3/template.php']);
 }
 
 
 }
 
 
@@ -2232,4 +2201,5 @@ if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['typo3/templ
 // ******************************
 $GLOBALS['TBE_TEMPLATE'] = t3lib_div::makeInstance('template');
 
 // ******************************
 $GLOBALS['TBE_TEMPLATE'] = t3lib_div::makeInstance('template');
 
+
 ?>
 ?>