[CLEANUP] sysext:core/TypoScript 02/35802/9
authorMarkus Klein <klein.t3@reelworx.at>
Mon, 5 Jan 2015 19:52:33 +0000 (20:52 +0100)
committerChristian Kuhn <lolli@schwarzbu.ch>
Mon, 19 Jan 2015 21:58:17 +0000 (22:58 +0100)
Resolves: #64136
Resolves: #64320
Releases: master
Change-Id: Id578a02b98b4f4c5795e256c0c8d9120edf3609c
Reviewed-on: http://review.typo3.org/35802
Reviewed-by: Wouter Wolters <typo3@wouterwolters.nl>
Tested-by: Wouter Wolters <typo3@wouterwolters.nl>
Tested-by: Stefan Neufeind <typo3.neufeind@speedpartner.de>
Reviewed-by: Oliver Klee <typo3-coding@oliverklee.de>
Reviewed-by: Christian Kuhn <lolli@schwarzbu.ch>
Tested-by: Christian Kuhn <lolli@schwarzbu.ch>
typo3/sysext/core/Classes/TypoScript/ConfigurationForm.php
typo3/sysext/core/Classes/TypoScript/ExtendedTemplateService.php
typo3/sysext/core/Classes/TypoScript/Parser/TypoScriptParser.php
typo3/sysext/core/Classes/TypoScript/TemplateService.php

index db6ff0d..3d1b53b 100644 (file)
@@ -14,12 +14,16 @@ namespace TYPO3\CMS\Core\TypoScript;
  * The TYPO3 project - inspiring people to share!
  */
 
+use TYPO3\CMS\Backend\Utility\IconUtility;
+use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Utility\ArrayUtility;
+
 /**
  * Provides a simplified layer for making Constant Editor style configuration forms
  *
  * @author Kasper Skårhøj <kasperYYYY@typo3.com>
  */
-class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateService {
+class ConfigurationForm extends ExtendedTemplateService {
 
        /**
         * @var array
@@ -39,13 +43,23 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
        /**
         * @var bool
         */
-       public $ext_printAll = 1;
+       public $ext_printAll = TRUE;
 
        /**
         * @var array
         */
        public $ext_incomingValues = array();
 
+       /**
+        * @var array
+        */
+       protected $ext_realValues = array();
+
+       /**
+        * @var string
+        */
+       protected $ext_backPath = '';
+
        /**
         * @param string $configTemplate
         * @param string $pathRel PathRel is the path relative to the typo3/ directory
@@ -76,7 +90,7 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
                $temp = $this->flatSetup;
                $this->flatSetup = array();
                $this->flattenSetup($valueArray, '', '');
-               $this->objReg = ($this->ext_realValues = $this->flatSetup);
+               $this->objReg = $this->ext_realValues = $this->flatSetup;
                $this->flatSetup = $temp;
                foreach ($theConstants as $k => $p) {
                        if (isset($this->objReg[$k])) {
@@ -102,7 +116,7 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
         * @return void
         */
        public function ext_makeHelpInformationForCategory($cat) {
-               return $this->ext_getTSCE_config($cat);
+               $this->ext_getTSCE_config($cat);
        }
 
        /**
@@ -113,24 +127,24 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
         * @param string $script
         * @param string $addFields
         * @param string $extKey
-        * @param bool Adds opening <form> tag to the output, if TRUE
+        * @param bool $addFormTag Adds opening <form> tag to the output, if TRUE
         * @return string The form
         */
        public function ext_getForm($cat, $theConstants, $script = '', $addFields = '', $extKey = '', $addFormTag = TRUE) {
                $this->ext_makeHelpInformationForCategory($cat);
                $printFields = trim($this->ext_printFields($theConstants, $cat));
                $content = '';
-               $content .= \TYPO3\CMS\Core\Utility\GeneralUtility::wrapJS('
+               $content .= GeneralUtility::wrapJS('
                        function uFormUrl(aname) {
-                               document.' . $this->ext_CEformName . '.action = ' . \TYPO3\CMS\Core\Utility\GeneralUtility::quoteJSvalue(\TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript() . '#') . '+aname;
+                               document.' . $this->ext_CEformName . '.action = ' . GeneralUtility::quoteJSvalue(GeneralUtility::linkThisScript() . '#') . '+aname;
                        }
                ');
                if ($addFormTag) {
-                       $content .= '<form action="' . htmlspecialchars(($script ?: \TYPO3\CMS\Core\Utility\GeneralUtility::linkThisScript())) . '" name="' . $this->ext_CEformName . '" method="post" enctype="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'] . '">';
+                       $content .= '<form action="' . htmlspecialchars(($script ?: GeneralUtility::linkThisScript())) . '" name="' . $this->ext_CEformName . '" method="post" enctype="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'] . '">';
                }
                $content .= $addFields;
                $content .= $printFields;
-               $content .= '<input class="btn btn-default" type="submit" name="submit" value="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tsfe.xlf:update', TRUE) . '" id="configuration-submit-' . htmlspecialchars($extKey) . '" />';
+               $content .= '<input class="btn btn-default" type="submit" name="submit" value="' . $this->getLanguageService()->sL('LLL:EXT:lang/locallang_tsfe.xlf:update', TRUE) . '" id="configuration-submit-' . htmlspecialchars($extKey) . '" />';
                $example = $this->ext_displayExample();
                $content .= $example ? '<hr/>' . $example : '';
                return $content;
@@ -142,8 +156,11 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
         * @return string
         */
        public function ext_displayExample() {
+               $out = '';
                if ($this->helpConfig['imagetag'] || $this->helpConfig['description'] || $this->helpConfig['header']) {
-                       $out = '<div align="center">' . $this->helpConfig['imagetag'] . '</div><BR>' . ($this->helpConfig['description'] ? implode(explode('//', $this->helpConfig['description']), '<BR>') . '<BR>' : '') . ($this->helpConfig['bulletlist'] ? '<ul><li>' . implode(explode('//', $this->helpConfig['bulletlist']), '<li>') . '</ul>' : '<BR>');
+                       $out = '<div align="center">' . $this->helpConfig['imagetag'] . '</div><br />'
+                               . ($this->helpConfig['description'] ? implode(explode('//', $this->helpConfig['description']), '<br />') . '<br />' : '')
+                               . ($this->helpConfig['bulletlist'] ? '<ul><li>' . implode(explode('//', $this->helpConfig['bulletlist']), '<li>') . '</ul>' : '<BR>');
                }
                return $out;
        }
@@ -155,10 +172,10 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
         * @return array
         */
        public function ext_mergeIncomingWithExisting($arr) {
-               $parseObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+               $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                $parseObj->parse(implode(LF, $this->ext_incomingValues));
                $arr2 = $parseObj->setup;
-               \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($arr, $arr2);
+               ArrayUtility::mergeRecursiveWithOverrule($arr, $arr2);
                return $arr;
        }
 
@@ -168,7 +185,7 @@ class ConfigurationForm extends \TYPO3\CMS\Core\TypoScript\ExtendedTemplateServi
         * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
         */
        public function ext_getKeyImage($key) {
-               \TYPO3\CMS\Core\Utility\GeneralUtility::logDeprecatedFunction();
+               GeneralUtility::logDeprecatedFunction();
                return '<span class="label label-danger">' . $key . '</span>';
        }
 
index 8fd98ac..6a6cbb7 100644 (file)
@@ -14,9 +14,15 @@ namespace TYPO3\CMS\Core\TypoScript;
  * The TYPO3 project - inspiring people to share!
  */
 
+use TYPO3\CMS\Backend\Template\DocumentTemplate;
 use TYPO3\CMS\Backend\Utility\BackendUtility;
 use TYPO3\CMS\Backend\Utility\IconUtility;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Utility\MathUtility;
+use TYPO3\CMS\Core\Utility\PathUtility;
+use TYPO3\CMS\Dbal\Database\DatabaseConnection;
+use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
+use TYPO3\CMS\Lang\LanguageService;
 
 /**
  * TSParser extension class to TemplateService
@@ -211,6 +217,61 @@ class ExtendedTemplateService extends TemplateService {
         */
        protected $lnToScript = NULL;
 
+       /**
+        * @var array
+        */
+       public $clearList_const_temp;
+
+       /**
+        * @var array
+        */
+       public $clearList_setup_temp;
+
+       /**
+        * @var string
+        */
+       protected $Cmarker = '';
+
+       /**
+        * @var string
+        */
+       public $bType = '';
+
+       /**
+        * @var bool
+        */
+       public $linkObjects = FALSE;
+
+       /**
+        * @var array
+        */
+       public $helpConfig = array();
+
+       /**
+        * @var bool
+        */
+       public $changed = FALSE;
+
+       /**
+        * @var int[]
+        */
+       protected $objReg = array();
+
+       /**
+        * @var array
+        */
+       public $raw = array();
+
+       /**
+        * @var int
+        */
+       public $rawP = 0;
+
+       /**
+        * @var string
+        */
+       public $lastComment = '';
+
        /**
         * Substitute constant
         *
@@ -258,7 +319,7 @@ class ExtendedTemplateService extends TemplateService {
                        case 'subst':
                                $all = str_replace(
                                        array('##' . $this->Cmarker . '_B##', '##' . $this->Cmarker . '_E##'),
-                                       array('<font color="green"><strong>', '</strong></font>'),
+                                       array('<strong style="color: green;">', '</strong>'),
                                        $all
                                );
                                break;
@@ -275,19 +336,19 @@ class ExtendedTemplateService extends TemplateService {
         */
        public function generateConfig_constants() {
                // These vars are also set lateron...
-               $this->setup['resources'] = $this->resources;
                $this->setup['sitetitle'] = $this->sitetitle;
                // Parse constants
-               $constants = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+               $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                // Register comments!
                $constants->regComments = 1;
                $constants->setup = $this->mergeConstantsFromPageTSconfig(array());
-               /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
-               $matchObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher::class);
+               /** @var ConditionMatcher $matchObj */
+               $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
                // Matches ALL conditions in TypoScript
                $matchObj->setSimulateMatchResult(TRUE);
                $c = 0;
                $cc = count($this->constants);
+               $defaultConstants = array();
                foreach ($this->constants as $str) {
                        $c++;
                        if ($c == $cc) {
@@ -336,8 +397,8 @@ class ExtendedTemplateService extends TemplateService {
         * @param array $arr
         * @param string $depth_in
         * @param string $depthData
-        * @param string $parentType
-        * @param string $parentValue
+        * @param string $parentType (unused)
+        * @param string $parentValue (unused)
         * @param string $alphaSort sorts the array keys / tree by alphabet when set to 1
         * @return array
         */
@@ -354,7 +415,7 @@ class ExtendedTemplateService extends TemplateService {
                        if (substr($key, -2) != '..') {
                                $key = preg_replace('/\\.$/', '', $key);
                                if (substr($key, -1) != '.') {
-                                       if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
+                                       if (MathUtility::canBeInterpretedAsInteger($key)) {
                                                $keyArr_num[$key] = $arr[$key];
                                        } else {
                                                $keyArr_alpha[$key] = $arr[$key];
@@ -375,7 +436,6 @@ class ExtendedTemplateService extends TemplateService {
                        if ($this->bType !== 'const' || $depth[0] !== '_') {
                                $goto = substr(md5($depth), 0, 6);
                                $deeper = is_array($arr[$key . '.']) && ($this->tsbrowser_depthKeys[$depth] || $this->ext_expandAllNotes) ? 1 : 0;
-                               $PM = 'join';
                                $LN = $a == $c ? 'blank' : 'line';
                                $BTM = $a == $c ? 'bottom' : '';
                                $PM = is_array($arr[$key . '.']) && !$this->ext_noPMicons ? ($deeper ? 'minus' : 'plus') : 'join';
@@ -397,7 +457,7 @@ class ExtendedTemplateService extends TemplateService {
                                $label = $key;
                                // Read only...
                                if (GeneralUtility::inList('types,resources,sitetitle', $depth) && $this->bType == 'setup') {
-                                       $label = '<font color="#666666">' . $label . '</font>';
+                                       $label = '<span style="color: #666666;">' . $label . '</span>';
                                } else {
                                        if ($this->linkObjects) {
                                                $urlParameters = array(
@@ -414,7 +474,7 @@ class ExtendedTemplateService extends TemplateService {
                                                        $ln = '';
                                                }
                                                if ($this->tsbrowser_searchKeys[$depth] & 4) {
-                                                       $label = '<strong><font color="red">' . $label . '</font></strong>';
+                                                       $label = '<strong style="color: red;">' . $label . '</strong>';
                                                }
                                                // The key has matched the search string
                                                $label = '<a href="' . htmlspecialchars($aHref) . '" title="' . htmlspecialchars($ln) . '">' . $label . '</a>';
@@ -452,7 +512,8 @@ class ExtendedTemplateService extends TemplateService {
                                }
                                $HTML .= '<br />';
                                if ($deeper) {
-                                       $HTML .= $this->ext_getObjTree($arr[$key . '.'], $depth, $depthData . IconUtility::getSpriteIcon('treeline-' . $LN), '', $arr[$key], $alphaSort);
+                                       $HTML .= $this->ext_getObjTree($arr[$key . '.'], $depth, $depthData
+                                               . IconUtility::getSpriteIcon('treeline-' . $LN), '', $arr[$key], $alphaSort);
                                }
                        }
                }
@@ -523,7 +584,6 @@ class ExtendedTemplateService extends TemplateService {
                                $keyArr[$key] = 1;
                        }
                }
-               $c = count($keyArr);
                if ($depth_in) {
                        $depth_in = $depth_in . '.';
                }
@@ -570,16 +630,17 @@ class ExtendedTemplateService extends TemplateService {
 
        /**
         * @param int $pid
-        * @return string
+        * @return int
         */
        public function ext_getRootlineNumber($pid) {
-               if ($pid && is_array($GLOBALS['rootLine'])) {
-                       foreach ($GLOBALS['rootLine'] as $key => $val) {
-                               if ($val['uid'] == $pid) {
-                                       return $key;
+               if ($pid) {
+                       foreach ($this->getRootLine() as $key => $val) {
+                               if ((int)$val['uid'] === (int)$pid) {
+                                       return (int)$key;
                                }
                        }
                }
+               return -1;
        }
 
        /**
@@ -605,14 +666,15 @@ class ExtendedTemplateService extends TemplateService {
                        $a++;
                        $deeper = is_array($arr[$key . '.']);
                        $row = $arr[$key];
-                       $PM = 'join';
                        $LN = $a == $c ? 'blank' : 'line';
                        $BTM = $a == $c ? 'top' : '';
                        $PM = 'join';
                        $HTML .= $depthData;
                        $alttext = '[' . $row['templateID'] . ']';
                        $alttext .= $row['pid'] ? ' - ' . BackendUtility::getRecordPath($row['pid'], $GLOBALS['SOBE']->perms_clause, 20) : '';
-                       $icon = substr($row['templateID'], 0, 3) == 'sys' ? \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIconForRecord('sys_template', $row, array('title' => $alttext)) : \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('mimetypes-x-content-template-static', array('title' => $alttext));
+                       $icon = substr($row['templateID'], 0, 3) === 'sys'
+                               ? IconUtility::getSpriteIconForRecord('sys_template', $row, array('title' => $alttext))
+                               : IconUtility::getSpriteIcon('mimetypes-x-content-template-static', array('title' => $alttext));
                        if (in_array($row['templateID'], $this->clearList_const) || in_array($row['templateID'], $this->clearList_setup)) {
                                $urlParameters = array(
                                        'id' => $GLOBALS['SOBE']->id,
@@ -629,15 +691,17 @@ class ExtendedTemplateService extends TemplateService {
                                $A_B = '';
                                $A_E = '';
                        }
-                       $HTML .= ($first ? '' : IconUtility::getSpriteIcon('treeline-' . $PM . $BTM)) . $icon . $A_B . htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $GLOBALS['BE_USER']->uc['titleLen'])) . $A_E . '&nbsp;&nbsp;';
+                       $HTML .= ($first ? '' : IconUtility::getSpriteIcon('treeline-' . $PM . $BTM)) . $icon . $A_B
+                               . htmlspecialchars(GeneralUtility::fixed_lgd_cs($row['title'], $GLOBALS['BE_USER']->uc['titleLen']))
+                               . $A_E . '&nbsp;&nbsp;';
                        $RL = $this->ext_getRootlineNumber($row['pid']);
                        $keyArray[] = '<tr class="' . ($i++ % 2 == 0 ? 'bgColor4' : 'bgColor6') . '">
                                                        <td nowrap="nowrap">' . $HTML . '</td>
-                                                       <td align="center">' . ($row['root'] ? \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;</td>
-                                                       <td align="center">' . ($row['clConf'] ? \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;' . '</td>
-                                                       <td align="center">' . ($row['clConst'] ? \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;' . '</td>
+                                                       <td align="center">' . ($row['root'] ? IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;</td>
+                                                       <td align="center">' . ($row['clConf'] ? IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;' . '</td>
+                                                       <td align="center">' . ($row['clConst'] ? IconUtility::getSpriteIcon('status-status-checked') : '') . '&nbsp;&nbsp;' . '</td>
                                                        <td align="center">' . ($row['pid'] ?: '') . '</td>
-                                                       <td align="center">' . (strcmp($RL, '') ? $RL : '') . '</td>
+                                                       <td align="center">' . ($RL >= 0 ? $RL : '') . '</td>
                                                        <td>' . ($row['next'] ? '&nbsp;' . $row['next'] . '&nbsp;&nbsp;' : '') . '</td>
                                                </tr>';
                        if ($deeper) {
@@ -692,7 +756,7 @@ class ExtendedTemplateService extends TemplateService {
                        $all .= '[GLOBAL]' . LF . $str;
                }
                if ($syntaxHL) {
-                       $tsparser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+                       $tsparser = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                        $tsparser->lineNumberOffset = $this->ext_lineNumberOffset + 1;
                        $tsparser->parentObject = $this;
                        return $tsparser->doSyntaxHighlight($all, $lineNumbers ? array($this->ext_lineNumberOffset + 1) : '', $syntaxHLBlockmode);
@@ -714,7 +778,8 @@ class ExtendedTemplateService extends TemplateService {
                if ($chars >= 4) {
                        if (strlen($string) > $chars) {
                                if (strlen($string) > 24 && substr($string, 0, 12) == '##' . $this->Cmarker . '_B##') {
-                                       return '##' . $this->Cmarker . '_B##' . GeneralUtility::fixed_lgd_cs(substr($string, 12, -12), ($chars - 3)) . '##' . $this->Cmarker . '_E##';
+                                       return '##' . $this->Cmarker . '_B##' . GeneralUtility::fixed_lgd_cs(substr($string, 12, -12), ($chars - 3))
+                                               . '##' . $this->Cmarker . '_E##';
                                } else {
                                        return GeneralUtility::fixed_lgd_cs($string, $chars - 3);
                                }
@@ -729,7 +794,8 @@ class ExtendedTemplateService extends TemplateService {
         * @return string
         */
        public function ext_lnBreakPointWrap($lineNumber, $str) {
-               return '<a href="#" id="line-' . $lineNumber . '" onClick="return brPoint(' . $lineNumber . ',' . ($this->ext_lineNumberOffset_mode == 'setup' ? 1 : 0) . ');">' . $str . '</a>';
+               return '<a href="#" id="line-' . $lineNumber . '" onClick="return brPoint(' . $lineNumber . ','
+                       . ($this->ext_lineNumberOffset_mode == 'setup' ? 1 : 0) . ');">' . $str . '</a>';
        }
 
        /**
@@ -739,7 +805,7 @@ class ExtendedTemplateService extends TemplateService {
         * @param bool $crop
         * @return string
         */
-       public function ext_formatTS($input, $ln, $comments = 1, $crop = 0) {
+       public function ext_formatTS($input, $ln, $comments = TRUE, $crop = FALSE) {
                $cArr = explode(LF, $input);
                $n = ceil(log10(count($cArr) + $this->ext_lineNumberOffset));
                $lineNum = '';
@@ -755,7 +821,7 @@ class ExtendedTemplateService extends TemplateService {
                        $cArr[$k] = $lineNum . str_replace(' ', '&nbsp;', $v);
                        $firstChar = substr(trim($v), 0, 1);
                        if ($firstChar == '[') {
-                               $cArr[$k] = '<font color="green"><strong>' . $cArr[$k] . '</strong></font>';
+                               $cArr[$k] = '<strong style="color: green">' . $cArr[$k] . '</strong>';
                        } elseif ($firstChar == '/' || $firstChar == '#') {
                                if ($comments) {
                                        $cArr[$k] = '<span class="typo3-dimmed">' . $cArr[$k] . '</span>';
@@ -771,42 +837,45 @@ class ExtendedTemplateService extends TemplateService {
        /**
         * @param int $id
         * @param int $template_uid
-        * @return array
+        * @return array|NULL Returns the template record or NULL if none was found
         */
        public function ext_getFirstTemplate($id, $template_uid = 0) {
                // Query is taken from the runThroughTemplates($theRootLine) function in the parent class.
                if ((int)$id) {
-                       if ($template_uid) {
-                               $addC = ' AND uid=' . $template_uid;
-                       }
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$id . $addC . ' ' . $this->whereClause, '', 'sorting', '1');
-                       $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
+                       $addC = $template_uid ? ' AND uid=' . (int)$template_uid : '';
+                       $where = 'pid=' . (int)$id . $addC . ' ' . $this->whereClause;
+                       $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_template', $where, '', 'sorting', '1');
+                       $row = $this->getDatabaseConnection()->sql_fetch_assoc($res);
                        BackendUtility::workspaceOL('sys_template', $row);
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+                       $this->getDatabaseConnection()->sql_free_result($res);
                        // Returns the template row if found.
                        return $row;
                }
+               return NULL;
        }
 
        /**
         * @param int $id
-        * @return array
+        * @return array[] Array of template records
         */
        public function ext_getAllTemplates($id) {
+               if (!$id) {
+                       return array();
+               }
+
                // Query is taken from the runThroughTemplates($theRootLine) function in the parent class.
-               if ((int)$id) {
-                       $outRes = array();
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$id . ' ' . $this->whereClause, '', 'sorting');
-                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
-                               BackendUtility::workspaceOL('sys_template', $row);
-                               if (is_array($row)) {
-                                       $outRes[] = $row;
-                               }
+               $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$id . ' ' . $this->whereClause, '', 'sorting');
+
+               $outRes = array();
+               while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
+                       BackendUtility::workspaceOL('sys_template', $row);
+                       if (is_array($row)) {
+                               $outRes[] = $row;
                        }
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
-                       // Returns the template rows in an array.
-                       return $outRes;
                }
+               $this->getDatabaseConnection()->sql_free_result($res);
+
+               return $outRes;
        }
 
        /**
@@ -819,60 +888,64 @@ class ExtendedTemplateService extends TemplateService {
        public function ext_compareFlatSetups($default) {
                $editableComments = array();
                foreach ($this->flatSetup as $const => $value) {
-                       if (substr($const, -2) != '..' && isset($this->flatSetup[$const . '..'])) {
-                               $comment = trim($this->flatSetup[$const . '..']);
-                               $c_arr = explode(LF, $comment);
-                               foreach ($c_arr as $k => $v) {
-                                       $line = trim(preg_replace('/^[#\\/]*/', '', $v));
-                                       if ($line) {
-                                               $parts = explode(';', $line);
-                                               foreach ($parts as $par) {
-                                                       if (strstr($par, '=')) {
-                                                               $keyValPair = explode('=', $par, 2);
-                                                               switch (trim(strtolower($keyValPair[0]))) {
-                                                                       case 'type':
-                                                                               // Type:
-                                                                               $editableComments[$const]['type'] = trim($keyValPair[1]);
-                                                                               break;
-                                                                       case 'cat':
-                                                                               // List of categories.
-                                                                               $catSplit = explode('/', strtolower($keyValPair[1]));
-                                                                               $catSplit[0] = trim($catSplit[0]);
-                                                                               if (isset($this->categoryLabels[$catSplit[0]])) {
-                                                                                       $catSplit[0] = $this->categoryLabels[$catSplit[0]];
-                                                                               }
-                                                                               $editableComments[$const]['cat'] = $catSplit[0];
-                                                                               // This is the subcategory. Must be a key in $this->subCategories[]. catSplit[2] represents the search-order within the subcat.
-                                                                               $catSplit[1] = trim($catSplit[1]);
-                                                                               if ($catSplit[1] && isset($this->subCategories[$catSplit[1]])) {
-                                                                                       $editableComments[$const]['subcat_name'] = $catSplit[1];
-                                                                                       $editableComments[$const]['subcat'] = $this->subCategories[$catSplit[1]][1] . '/' . $catSplit[1] . '/' . trim($catSplit[2]) . 'z';
-                                                                               } else {
-                                                                                       $editableComments[$const]['subcat'] = 'x' . '/' . trim($catSplit[2]) . 'z';
-                                                                               }
-                                                                               break;
-                                                                       case 'label':
-                                                                               // Label
-                                                                               $editableComments[$const]['label'] = trim($keyValPair[1]);
-                                                                               break;
-                                                                       case 'customcategory':
-                                                                               // Custom category label
-                                                                               $customCategory = explode('=', $keyValPair[1], 2);
-                                                                               if (trim($customCategory[0])) {
-                                                                                       $categoryKey = strtolower($customCategory[0]);
-                                                                                       $this->categoryLabels[$categoryKey] = $GLOBALS['LANG']->sL($customCategory[1]);
-                                                                               }
-                                                                               break;
-                                                                       case 'customsubcategory':
-                                                                               // Custom subCategory label
-                                                                               $customSubcategory = explode('=', $keyValPair[1], 2);
-                                                                               if (trim($customSubcategory[0])) {
-                                                                                       $subCategoryKey = strtolower($customSubcategory[0]);
-                                                                                       $this->subCategories[$subCategoryKey][0] = $GLOBALS['LANG']->sL($customSubcategory[1]);
-                                                                               }
-                                                                               break;
+                       if (substr($const, -2) === '..' || !isset($this->flatSetup[$const . '..'])) {
+                               continue;
+                       }
+                       $comment = trim($this->flatSetup[$const . '..']);
+                       $c_arr = explode(LF, $comment);
+                       foreach ($c_arr as $k => $v) {
+                               $line = trim(preg_replace('/^[#\\/]*/', '', $v));
+                               if (!$line) {
+                                       continue;
+                               }
+                               $parts = explode(';', $line);
+                               foreach ($parts as $par) {
+                                       if (strstr($par, '=')) {
+                                               $keyValPair = explode('=', $par, 2);
+                                               switch (trim(strtolower($keyValPair[0]))) {
+                                                       case 'type':
+                                                               // Type:
+                                                               $editableComments[$const]['type'] = trim($keyValPair[1]);
+                                                               break;
+                                                       case 'cat':
+                                                               // List of categories.
+                                                               $catSplit = explode('/', strtolower($keyValPair[1]));
+                                                               $catSplit[0] = trim($catSplit[0]);
+                                                               if (isset($this->categoryLabels[$catSplit[0]])) {
+                                                                       $catSplit[0] = $this->categoryLabels[$catSplit[0]];
                                                                }
-                                                       }
+                                                               $editableComments[$const]['cat'] = $catSplit[0];
+                                                               // This is the subcategory. Must be a key in $this->subCategories[].
+                                                               // catSplit[2] represents the search-order within the subcat.
+                                                               $catSplit[1] = trim($catSplit[1]);
+                                                               if ($catSplit[1] && isset($this->subCategories[$catSplit[1]])) {
+                                                                       $editableComments[$const]['subcat_name'] = $catSplit[1];
+                                                                       $editableComments[$const]['subcat'] = $this->subCategories[$catSplit[1]][1]
+                                                                               . '/' . $catSplit[1] . '/' . trim($catSplit[2]) . 'z';
+                                                               } else {
+                                                                       $editableComments[$const]['subcat'] = 'x' . '/' . trim($catSplit[2]) . 'z';
+                                                               }
+                                                               break;
+                                                       case 'label':
+                                                               // Label
+                                                               $editableComments[$const]['label'] = trim($keyValPair[1]);
+                                                               break;
+                                                       case 'customcategory':
+                                                               // Custom category label
+                                                               $customCategory = explode('=', $keyValPair[1], 2);
+                                                               if (trim($customCategory[0])) {
+                                                                       $categoryKey = strtolower($customCategory[0]);
+                                                                       $this->categoryLabels[$categoryKey] = $this->getLanguageService()->sL($customCategory[1]);
+                                                               }
+                                                               break;
+                                                       case 'customsubcategory':
+                                                               // Custom subCategory label
+                                                               $customSubcategory = explode('=', $keyValPair[1], 2);
+                                                               if (trim($customSubcategory[0])) {
+                                                                       $subCategoryKey = strtolower($customSubcategory[0]);
+                                                                       $this->subCategories[$subCategoryKey][0] = $this->getLanguageService()->sL($customSubcategory[1]);
+                                                               }
+                                                               break;
                                                }
                                        }
                                }
@@ -981,7 +1054,7 @@ class ExtendedTemplateService extends TemplateService {
                                                $out[$key] = $val;
                                                break;
                                        default:
-                                               if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
+                                               if (MathUtility::canBeInterpretedAsInteger($key)) {
                                                        $constRefs = explode(',', $val);
                                                        foreach ($constRefs as $const) {
                                                                $const = trim($const);
@@ -1007,23 +1080,27 @@ class ExtendedTemplateService extends TemplateService {
        }
 
        /**
-
         * @param string $imgConf
         * @return string
         */
        public function ext_getTSCE_config_image($imgConf) {
+               $iFile = NULL;
+               $tFile = NULL;
                if (substr($imgConf, 0, 4) == 'gfx/') {
                        $iFile = $this->ext_localGfxPrefix . $imgConf;
                        $tFile = $this->ext_localWebGfxPrefix . $imgConf;
                } elseif (substr($imgConf, 0, 4) == 'EXT:') {
                        $iFile = GeneralUtility::getFileAbsFileName($imgConf);
                        if ($iFile) {
-                               $f = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($iFile);
+                               $f = PathUtility::stripPathSitePrefix($iFile);
                                $tFile = $GLOBALS['BACK_PATH'] . '../' . $f;
                        }
                }
-               $imageInfo = @getImagesize($iFile);
-               return '<img src="' . $tFile . '" ' . $imageInfo[3] . '>';
+               if ($iFile !== NULL) {
+                       $imageInfo = @getImagesize($iFile);
+                       return '<img src="' . $tFile . '" ' . $imageInfo[3] . '>';
+               }
+               return '';
        }
 
        /**
@@ -1051,6 +1128,7 @@ class ExtendedTemplateService extends TemplateService {
         */
        public function ext_printFields($theConstants, $category) {
                reset($theConstants);
+               $output = '';
                $subcat = '';
                if (is_array($this->categories[$category])) {
                        $help = $this->helpConfig;
@@ -1065,7 +1143,7 @@ class ExtendedTemplateService extends TemplateService {
                                                $subcat_name = $params['subcat_name'] ? $this->subCategories[$params['subcat_name']][0] : 'Others';
                                                $output .= '<h3 class="typo3-tstemplate-ceditor-subcat">' . $subcat_name . '</h3>';
                                        }
-                                       $label = $GLOBALS['LANG']->sL($params['label']);
+                                       $label = $this->getLanguageService()->sL($params['label']);
                                        $label_parts = explode(':', $label, 2);
                                        if (count($label_parts) == 2) {
                                                $head = trim($label_parts[0]);
@@ -1081,7 +1159,6 @@ class ExtendedTemplateService extends TemplateService {
                                                $head = GeneralUtility::fixed_lgd_cs($head, 35);
                                        }
                                        $typeDat = $this->ext_getTypeData($params['type']);
-                                       $checked = '';
                                        $p_field = '';
                                        $raname = substr(md5($params['name']), 0, 10);
                                        $aname = '\'' . $raname . '\'';
@@ -1090,7 +1167,8 @@ class ExtendedTemplateService extends TemplateService {
                                                case 'int':
 
                                                case 'int+':
-                                                       $p_field = '<input id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(5) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field = '<input id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"'
+                                                               . $this->getDocumentTemplate()->formWidth(5) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        if ($typeDat['paramstr']) {
                                                                $p_field .= ' Range: ' . $typeDat['paramstr'];
                                                        } elseif ($typeDat['type'] == 'int+') {
@@ -1110,24 +1188,24 @@ class ExtendedTemplateService extends TemplateService {
                                                                $p_field .= '<option value="' . htmlspecialchars($val) . '"' . $sel . '>' . $val . '</option>';
                                                        }
                                                        $p_field = '<select id="select-' . $idName . '" rel="' . $idName . '" name="C' . $fN . '" class="typo3-tstemplate-ceditor-color-select" onChange="uFormUrl(' . $aname . ');">' . $p_field . '</select>';
-                                                       $p_field .= '<input type="text" id="input-' . $idName . '" rel="' . $idName . '" name="' . $fN . '" class="typo3-tstemplate-ceditor-color-input" value="' . $fV . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(7) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field .= '<input type="text" id="input-' . $idName . '" rel="' . $idName . '" name="' . $fN . '" class="typo3-tstemplate-ceditor-color-input" value="' . $fV . '"' . $this->getDocumentTemplate()->formWidth(7) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        break;
                                                case 'wrap':
                                                        $wArr = explode('|', $fV);
-                                                       $p_field = '<input type="text" id="' . $idName . '" name="' . $fN . '" value="' . $wArr[0] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(29) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field = '<input type="text" id="' . $idName . '" name="' . $fN . '" value="' . $wArr[0] . '"' . $this->getDocumentTemplate()->formWidth(29) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        $p_field .= ' | ';
-                                                       $p_field .= '<input type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(15) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field .= '<input type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $this->getDocumentTemplate()->formWidth(15) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        break;
                                                case 'offset':
                                                        $wArr = explode(',', $fV);
                                                        $labels = GeneralUtility::trimExplode(',', $typeDat['paramstr']);
-                                                       $p_field = ($labels[0] ? $labels[0] : 'x') . ':<input type="text" name="' . $fN . '" value="' . $wArr[0] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field = ($labels[0] ? $labels[0] : 'x') . ':<input type="text" name="' . $fN . '" value="' . $wArr[0] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        $p_field .= ' , ';
-                                                       $p_field .= ($labels[1] ? $labels[1] : 'y') . ':<input type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field .= ($labels[1] ? $labels[1] : 'y') . ':<input type="text" name="W' . $fN . '" value="' . $wArr[1] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                        $labelsCount = count($labels);
                                                        for ($aa = 2; $aa < $labelsCount; $aa++) {
                                                                if ($labels[$aa]) {
-                                                                       $p_field .= ' , ' . $labels[$aa] . ':<input type="text" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                                       $p_field .= ' , ' . $labels[$aa] . ':<input type="text" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '"' . $this->getDocumentTemplate()->formWidth(4) . ' onChange="uFormUrl(' . $aname . ')" />';
                                                                } else {
                                                                        $p_field .= '<input type="hidden" name="W' . $aa . $fN . '" value="' . $wArr[$aa] . '" />';
                                                                }
@@ -1145,7 +1223,7 @@ class ExtendedTemplateService extends TemplateService {
                                                                        if ($val == $params['value']) {
                                                                                $sel = ' selected';
                                                                        }
-                                                                       $p_field .= '<option value="' . htmlspecialchars($val) . '"' . $sel . '>' . $GLOBALS['LANG']->sL($label) . '</option>';
+                                                                       $p_field .= '<option value="' . htmlspecialchars($val) . '"' . $sel . '>' . $this->getLanguageService()->sL($label) . '</option>';
                                                                }
                                                                $p_field = '<select id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
                                                        }
@@ -1167,21 +1245,18 @@ class ExtendedTemplateService extends TemplateService {
                                                        $p_field .= '<input id="' . $idName . '" type="checkbox" name="' . $fN . '" value=""' . $sel . ' onClick="uFormUrl(' . $aname . ')" />';
                                                        break;
                                                case 'file':
-                                                       $p_field = '<option value=""></option>';
-                                                       $theImage = '';
                                                        // extensionlist
                                                        $extList = $typeDat['paramstr'];
-                                                       $p_field = '<option value="">(' . $extList . ')</option>';
                                                        if ($extList == 'IMAGE_EXT') {
                                                                $extList = $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'];
                                                        }
+                                                       $p_field = '<option value="">(' . $extList . ')</option>';
                                                        if (trim($params['value'])) {
                                                                $val = $params['value'];
                                                                $p_field .= '<option value=""></option>';
                                                                $p_field .= '<option value="' . htmlspecialchars($val) . '" selected>' . $val . '</option>';
                                                        }
                                                        $p_field = '<select id="' . $idName . '" name="' . $fN . '" onChange="uFormUrl(' . $aname . ')">' . $p_field . '</select>';
-                                                       $p_field .= $theImage;
                                                        break;
                                                case 'user':
                                                        $userFunction = $typeDat['paramstr'];
@@ -1192,7 +1267,8 @@ class ExtendedTemplateService extends TemplateService {
 
                                                default:
                                                        $fwidth = $typeDat['type'] == 'small' ? 10 : 46;
-                                                       $p_field = '<input id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"' . $GLOBALS['TBE_TEMPLATE']->formWidth($fwidth) . ' onChange="uFormUrl(' . $aname . ')" />';
+                                                       $p_field = '<input id="' . $idName . '" type="text" name="' . $fN . '" value="' . $fV . '"'
+                                                               . $this->getDocumentTemplate()->formWidth($fwidth) . ' onChange="uFormUrl(' . $aname . ')" />';
                                        }
                                        // Define default names and IDs
                                        $userTyposcriptID = 'userTS-' . $idName;
@@ -1205,24 +1281,27 @@ class ExtendedTemplateService extends TemplateService {
                                        } else {
                                                $color = '';
                                        }
+                                       $userTyposcriptStyle = '';
+                                       $deleteIconHTML = '';
+                                       $constantCheckbox = '';
+                                       $constantDefaultRow = '';
                                        if (!$this->ext_dontCheckIssetValues) {
                                                // Set the default styling options
                                                if (isset($this->objReg[$params['name']])) {
                                                        $checkboxValue = 'checked';
-                                                       $userTyposcriptStyle = '';
                                                        $defaultTyposcriptStyle = 'style="display:none;"';
                                                } else {
                                                        $checkboxValue = '';
                                                        $userTyposcriptStyle = 'style="display:none;"';
                                                        $defaultTyposcriptStyle = '';
                                                }
-                                               $deleteIconHTML = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-edit-undo', array(
+                                               $deleteIconHTML = IconUtility::getSpriteIcon('actions-edit-undo', array(
                                                        'class' => 'typo3-tstemplate-ceditor-control undoIcon',
                                                        'alt' => 'Revert to default Constant',
                                                        'title' => 'Revert to default Constant',
                                                        'rel' => $idName
                                                ));
-                                               $editIconHTML = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-document-open', array(
+                                               $editIconHTML = IconUtility::getSpriteIcon('actions-document-open', array(
                                                        'class' => 'typo3-tstemplate-ceditor-control editIcon',
                                                        'alt' => 'Edit this Constant',
                                                        'title' => 'Edit this Constant',
@@ -1233,9 +1312,12 @@ class ExtendedTemplateService extends TemplateService {
                                                if (!$params['default_value']) {
                                                        $params['default_value'] = '[Empty]';
                                                }
-                                               $constantDefaultRow = '<div class="typo3-tstemplate-ceditor-row" id="' . $defaultTyposcriptID . '" ' . $defaultTyposcriptStyle . '>' . $editIconHTML . htmlspecialchars($params['default_value']) . $color . '</div>';
+                                               $constantDefaultRow = '<div class="typo3-tstemplate-ceditor-row" id="' . $defaultTyposcriptID . '" '
+                                                       . $defaultTyposcriptStyle . '>' . $editIconHTML . htmlspecialchars($params['default_value'])
+                                                       . $color . '</div>';
                                        }
-                                       $constantEditRow = '<div class="typo3-tstemplate-ceditor-row" id="' . $userTyposcriptID . '" ' . $userTyposcriptStyle . '>' . $deleteIconHTML . $p_field . $color . '</div>';
+                                       $constantEditRow = '<div class="typo3-tstemplate-ceditor-row" id="' . $userTyposcriptID . '" '
+                                               . $userTyposcriptStyle . '>' . $deleteIconHTML . $p_field . $color . '</div>';
                                        $constantLabel = '<dt class="typo3-tstemplate-ceditor-label">' . htmlspecialchars($head) . '</dt>';
                                        $constantName = '<dt class="typo3-dimmed">[' . $params['name'] . ']</dt>';
                                        $constantDescription = $body ? '<dd>' . htmlspecialchars($body) . '</dd>' : '';
@@ -1261,7 +1343,7 @@ class ExtendedTemplateService extends TemplateService {
         */
        public function ext_regObjectPositions($constants) {
                // This runs through the lines of the constants-field of the active template and registers the constants-names
-               // and linepositions in an array, $this->objReg
+               // and line positions in an array, $this->objReg
                $this->raw = explode(LF, $constants);
                $this->rawP = 0;
                // Resetting the objReg if the divider is found!!
@@ -1331,7 +1413,7 @@ class ExtendedTemplateService extends TemplateService {
                } else {
                        $this->raw[] = $key . ' =' . $theValue;
                }
-               $this->changed = 1;
+               $this->changed = TRUE;
        }
 
        /**
@@ -1344,7 +1426,7 @@ class ExtendedTemplateService extends TemplateService {
                        $lineNum = $this->objReg[$key];
                        unset($this->raw[$lineNum]);
                }
-               $this->changed = 1;
+               $this->changed = TRUE;
        }
 
        /**
@@ -1404,7 +1486,7 @@ class ExtendedTemplateService extends TemplateService {
                                                switch ($typeDat['type']) {
                                                        case 'int':
                                                                if ($typeDat['paramstr']) {
-                                                                       $var = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($var, $typeDat['params'][0], $typeDat['params'][1]);
+                                                                       $var = MathUtility::forceIntegerInRange($var, $typeDat['params'][0], $typeDat['params'][1]);
                                                                } else {
                                                                        $var = (int)$var;
                                                                }
@@ -1479,7 +1561,8 @@ class ExtendedTemplateService extends TemplateService {
                                }
                        }
                }
-               // Remaining keys in $check indicates fields that are just clicked "on" to be edited. Therefore we get the default value and puts that in the template as a start...
+               // Remaining keys in $check indicates fields that are just clicked "on" to be edited.
+               // Therefore we get the default value and puts that in the template as a start...
                if (!$this->ext_dontCheckIssetValues && is_array($check)) {
                        foreach ($check as $key => $var) {
                                if (isset($theConstants[$key])) {
@@ -1502,6 +1585,35 @@ class ExtendedTemplateService extends TemplateService {
                                return $p;
                        }
                }
+               return array();
+       }
+
+       /**
+        * @return array
+        */
+       protected function getRootLine() {
+               return isset($GLOBALS['rootLine']) ? $GLOBALS['rootLine'] : array();
+       }
+
+       /**
+        * @return DatabaseConnection
+        */
+       protected function getDatabaseConnection() {
+               return $GLOBALS['TYPO3_DB'];
+       }
+
+       /**
+        * @return LanguageService
+        */
+       protected function getLanguageService() {
+               return $GLOBALS['LANG'];
+       }
+
+       /**
+        * @return DocumentTemplate
+        */
+       protected function getDocumentTemplate() {
+               return $GLOBALS['TBE_TEMPLATE'];
        }
 
 }
index 24a8349..44c63c9 100644 (file)
@@ -14,9 +14,11 @@ namespace TYPO3\CMS\Core\TypoScript\Parser;
  * The TYPO3 project - inspiring people to share!
  */
 
+use TYPO3\CMS\Core\TimeTracker\TimeTracker;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
 use TYPO3\CMS\Core\Utility\PathUtility;
 use TYPO3\CMS\Core\Utility\StringUtility;
+use TYPO3\CMS\Core\TypoScript\ExtendedTemplateService;
 
 /**
  * The TypoScript parser
@@ -30,7 +32,7 @@ class TypoScriptParser {
         *
         * @var bool
         */
-       public $strict = 1;
+       public $strict = TRUE;
 
        /**
         * TypoScript hierarchy being build during parsing.
@@ -65,14 +67,14 @@ class TypoScriptParser {
         *
         * @var bool
         */
-       public $commentSet = 0;
+       public $commentSet = FALSE;
 
        /**
         * Internally set, when multiline value is accumulated
         *
         * @var bool
         */
-       public $multiLineEnabled = 0;
+       public $multiLineEnabled = FALSE;
 
        /**
         * Internally set, when multiline value is accumulated
@@ -101,7 +103,7 @@ class TypoScriptParser {
         *
         * @var bool
         */
-       public $lastConditionTrue = 1;
+       public $lastConditionTrue = TRUE;
 
        /**
         * Tracking all conditions found
@@ -122,7 +124,7 @@ class TypoScriptParser {
         *
         * @var bool
         */
-       public $syntaxHighLight = 0;
+       public $syntaxHighLight = FALSE;
 
        /**
         * Syntax highlight data is accumulated in this array. Used by syntaxHighlight_print() to construct the output.
@@ -143,14 +145,14 @@ class TypoScriptParser {
         *
         * @var bool
         */
-       public $regComments = 0;
+       public $regComments = FALSE;
 
        /**
         * DO NOT register the linenumbers. This is default for the ordinary sitetemplate!
         *
         * @var bool
         */
-       public $regLinenumbers = 0;
+       public $regLinenumbers = FALSE;
 
        /**
         * Error accumulation array.
@@ -291,6 +293,7 @@ class TypoScriptParser {
                                return $line;
                        }
                }
+               return '';
        }
 
        /**
@@ -507,6 +510,7 @@ class TypoScriptParser {
                                }
                        }
                }
+               return NULL;
        }
 
        /**
@@ -754,8 +758,9 @@ class TypoScriptParser {
         * @return void
         */
        public function error($err, $num = 2) {
-               if (is_object($GLOBALS['TT'])) {
-                       $GLOBALS['TT']->setTSlogMessage($err, $num);
+               $tt = $this->getTimeTracker();
+               if ($tt !== NULL) {
+                       $tt->setTSlogMessage($err, $num);
                }
                $this->errors[] = array($err, $num, $this->rawP - 1, $this->lineNumberOffset);
        }
@@ -1173,7 +1178,7 @@ class TypoScriptParser {
        public function doSyntaxHighlight($string, $lineNum = '', $highlightBlockMode = FALSE) {
                $this->syntaxHighLight = 1;
                $this->highLightData = array();
-               $this->error = array();
+               $this->errors = array();
                // This is done in order to prevent empty <span>..</span> sections around CR content. Should not do anything but help lessen the amount of HTML code.
                $string = str_replace(CR, '', $string);
                $this->parse($string);
@@ -1248,7 +1253,7 @@ class TypoScriptParser {
                        }
                        if (is_array($lineNumDat)) {
                                $lineNum = $rawP + $lineNumDat[0];
-                               if ($this->parentObject instanceof \TYPO3\CMS\Core\TypoScript\ExtendedTemplateService) {
+                               if ($this->parentObject instanceof ExtendedTemplateService) {
                                        $lineNum = $this->parentObject->ext_lnBreakPointWrap($lineNum, $lineNum);
                                }
                                $lineC = $this->highLightStyles['linenum'][0] . str_pad($lineNum, 4, ' ', STR_PAD_LEFT) . ':' . $this->highLightStyles['linenum'][1] . ' ' . $lineC;
@@ -1258,4 +1263,11 @@ class TypoScriptParser {
                return '<pre class="ts-hl">' . implode(LF, $lines) . '</pre>';
        }
 
+       /**
+        * @return TimeTracker
+        */
+       protected function getTimeTracker() {
+               return isset($GLOBALS['TT']) ? $GLOBALS['TT'] : NULL;
+       }
+
 }
index f2b0c03..485bb0d 100644 (file)
@@ -14,8 +14,19 @@ namespace TYPO3\CMS\Core\TypoScript;
  * The TYPO3 project - inspiring people to share!
  */
 
+use TYPO3\CMS\Backend\Utility\BackendUtility;
+use TYPO3\CMS\Core\Cache\CacheManager;
+use TYPO3\CMS\Core\Database\DatabaseConnection;
+use TYPO3\CMS\Core\TimeTracker\TimeTracker;
+use TYPO3\CMS\Core\Utility\ArrayUtility;
 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
 use TYPO3\CMS\Core\Utility\GeneralUtility;
+use TYPO3\CMS\Core\Utility\MathUtility;
+use TYPO3\CMS\Core\Utility\PathUtility;
+use TYPO3\CMS\Core\Utility\StringUtility;
+use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
+use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
+use TYPO3\CMS\Frontend\Page\PageRepository;
 
 /**
  * Template object that is responsible for generating the TypoScript template based on template records.
@@ -355,10 +366,10 @@ class TemplateService {
                // $this->whereClause is used only to select templates from sys_template.
                // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
                $this->whereClause = 'AND deleted=0 ';
-               if (!$GLOBALS['TSFE']->showHiddenRecords) {
+               if (!$this->getTypoScriptFrontendController()->showHiddenRecords) {
                        $this->whereClause .= 'AND hidden=0 ';
                }
-               if ($GLOBALS['TSFE']->showHiddenRecords || $GLOBALS['SIM_ACCESS_TIME'] != $GLOBALS['ACCESS_TIME']) {
+               if ($this->getTypoScriptFrontendController()->showHiddenRecords || $GLOBALS['SIM_ACCESS_TIME'] != $GLOBALS['ACCESS_TIME']) {
                        // Set the simulation flag, if simulation is detected!
                        $this->simulationHiddenOrTime = 1;
                }
@@ -400,7 +411,7 @@ class TemplateService {
         * @return array Returns the unmatched array $currentPageData if found cached in "cache_pagesection". Otherwise FALSE is returned which means that the array must be generated and stored in the cache
         */
        public function getCurrentPageData() {
-               return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_pagesection')->get((int)$GLOBALS['TSFE']->id . '_' . GeneralUtility::md5int($GLOBALS['TSFE']->MP));
+               return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection')->get((int)$this->getTypoScriptFrontendController()->id . '_' . GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP));
        }
 
        /**
@@ -411,9 +422,10 @@ class TemplateService {
         */
        public function matching($cc) {
                if (is_array($cc['all'])) {
-                       /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
-                       $matchObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher::class);
+                       /** @var $matchObj ConditionMatcher */
+                       $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
                        $matchObj->setRootline((array)$cc['rootLine']);
+                       $sectionsMatch = array();
                        foreach ($cc['all'] as $key => $pre) {
                                if ($matchObj->match($pre)) {
                                        $sectionsMatch[$key] = $pre;
@@ -443,8 +455,8 @@ class TemplateService {
                        // needs to be updated...
                        $isCached = FALSE;
                        $this->runThroughTemplates($theRootLine);
-                       if ($GLOBALS['TSFE']->all) {
-                               $cc = $GLOBALS['TSFE']->all;
+                       if ($this->getTypoScriptFrontendController()->all) {
+                               $cc = $this->getTypoScriptFrontendController()->all;
                                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
                                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
                                        unset($cc);
@@ -459,7 +471,7 @@ class TemplateService {
                        }
                        // This is about getting the hash string which is used to fetch the cached TypoScript template.
                        // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
-                       if (is_array($cc)) {
+                       if (isset($cc) && is_array($cc)) {
                                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
                                if (!$cc['match']) {
                                        // @todo check if this can ever be the case - otherwise remove
@@ -470,7 +482,7 @@ class TemplateService {
                        } else {
                                // If currentPageData was not there, we first find $rowSum (freshly generated). After that we try to see, if it is stored with a list of all conditions. If so we match the result.
                                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
-                               $result = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($rowSumHash);
+                               $result = PageRepository::getHash($rowSumHash);
                                if (is_array($result)) {
                                        $cc = array();
                                        $cc['all'] = $result;
@@ -482,17 +494,17 @@ class TemplateService {
                        }
                        if ($hash) {
                                // Get TypoScript setup array
-                               $setupData = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($hash);
+                               $setupData = PageRepository::getHash($hash);
                        }
                        if (is_array($setupData) && !$this->forceTemplateParsing) {
                                // If TypoScript setup structure was cached we unserialize it here:
                                $this->setup = $setupData;
                                if ($this->tt_track) {
-                                       $GLOBALS['TT']->setTSLogMessage('Using cached TS template data');
+                                       $this->getTimeTracker()->setTSLogMessage('Using cached TS template data');
                                }
                        } else {
                                if ($this->tt_track) {
-                                       $GLOBALS['TT']->setTSLogMessage('Not using any cached TS data');
+                                       $this->getTimeTracker()->setTSLogMessage('Not using any cached TS data');
                                }
 
                                // Make configuration
@@ -507,27 +519,27 @@ class TemplateService {
                                ksort($cc);
                                $hash = md5(serialize($cc));
                                // This stores the data.
-                               \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($hash, $this->setup, 'TS_TEMPLATE');
+                               PageRepository::storeHash($hash, $this->setup, 'TS_TEMPLATE');
                                if ($this->tt_track) {
-                                       $GLOBALS['TT']->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
+                                       $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
                                }
                                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
-                               \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
+                               PageRepository::storeHash($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
                        }
                        // Add rootLine
                        $cc['rootLine'] = $this->rootLine;
                        ksort($cc);
                        // Make global and save
-                       $GLOBALS['TSFE']->all = $cc;
+                       $this->getTypoScriptFrontendController()->all = $cc;
                        // Matching must be executed for every request, so this must never be part of the pagesection cache!
                        unset($cc['match']);
-                       if (!$isCached && !$this->simulationHiddenOrTime && !$GLOBALS['TSFE']->no_cache) {
+                       if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
                                // Only save the data if we're not simulating by hidden/starttime/endtime
-                               $mpvarHash = GeneralUtility::md5int($GLOBALS['TSFE']->MP);
+                               $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
                                /** @var $pageSectionCache \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface */
-                               $pageSectionCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_pagesection');
-                               $pageSectionCache->set((int)$GLOBALS['TSFE']->id . '_' . $mpvarHash, $cc, array(
-                                       'pageId_' . (int)$GLOBALS['TSFE']->id,
+                               $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection');
+                               $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, array(
+                                       'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
                                        'mpvarHash_' . $mpvarHash
                                ));
                        }
@@ -546,7 +558,7 @@ class TemplateService {
        /**
         * Traverses the rootLine from the root and out. For each page it checks if there is a template record. If there is a template record, $this->processTemplate() is called.
         * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
-        * Also creates $this->rootLine which is a root line stopping at the root template (contrary to $GLOBALS['TSFE']->rootLine which goes all the way to the root of the tree
+        * Also creates $this->rootLine which is a root line stopping at the root template (contrary to $this->getTypoScriptFrontendController()->rootLine which goes all the way to the root of the tree
         *
         * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
         * @param int $start_template_uid Set specific template record UID to select; this is only for debugging/development/analysis use in backend modules like "Web > Template". For parsing TypoScript templates in the frontend it should be 0 (zero)
@@ -559,38 +571,38 @@ class TemplateService {
                $this->rowSum = array();
                $this->hierarchyInfoToRoot = array();
                $this->absoluteRootLine = $theRootLine;
-               $this->isDefaultTyposcriptAdded = FALSE;
+               $this->isDefaultTypoScriptAdded = FALSE;
 
                reset($this->absoluteRootLine);
                $c = count($this->absoluteRootLine);
                for ($a = 0; $a < $c; $a++) {
                        // If some template loaded before has set a template-id for the next level, then load this template first!
                        if ($this->nextLevel) {
-                               $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'uid=' . (int)$this->nextLevel . ' ' . $this->whereClause);
+                               $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_template', 'uid=' . (int)$this->nextLevel . ' ' . $this->whereClause);
                                $this->nextLevel = 0;
-                               if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                               if ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
                                        $this->versionOL($row);
                                        if (is_array($row)) {
                                                $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
                                                $this->outermostRootlineIndexWithTemplate = $a;
                                        }
                                }
-                               $GLOBALS['TYPO3_DB']->sql_free_result($res);
+                               $this->getDatabaseConnection()->sql_free_result($res);
                        }
                        $addC = '';
                        // If first loop AND there is set an alternative template uid, use that
                        if ($a == $c - 1 && $start_template_uid) {
                                $addC = ' AND uid=' . (int)$start_template_uid;
                        }
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$this->absoluteRootLine[$a]['uid'] . $addC . ' ' . $this->whereClause, '', 'root DESC, sorting', 1);
-                       if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                       $res = $this->getDatabaseConnection()->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$this->absoluteRootLine[$a]['uid'] . $addC . ' ' . $this->whereClause, '', 'root DESC, sorting', 1);
+                       if ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
                                $this->versionOL($row);
                                if (is_array($row)) {
                                        $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
                                        $this->outermostRootlineIndexWithTemplate = $a;
                                }
                        }
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+                       $this->getDatabaseConnection()->sql_free_result($res);
                        $this->rootLine[] = $this->absoluteRootLine[$a];
                }
 
@@ -611,7 +623,7 @@ class TemplateService {
         *
         * @param array $row A full TypoScript template record (sys_template/static_template/forged "dummy" record made from static template file)
         * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
-        * @param array $pid The PID of the input template record
+        * @param int $pid The PID of the input template record
         * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
         * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
         * @param string $includePath Specifies the path from which the template was included (used with static_includes)
@@ -622,6 +634,8 @@ class TemplateService {
                // Adding basic template record information to rowSum array
                $this->rowSum[] = array($row['uid'], $row['title'], $row['tstamp']);
                // Processing "Clear"-flags
+               $clConst = 0;
+               $clConf = 0;
                if ($row['clear']) {
                        $clConst = $row['clear'] & 1;
                        $clConf = $row['clear'] & 2;
@@ -652,7 +666,7 @@ class TemplateService {
                                        unset($basedOnIds[$key]);
                                }
                        }
-                       $subTemplates = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_template', 'uid IN (' . implode(',', $basedOnIds) . ') ' . $this->whereClause, '', '', '', 'uid');
+                       $subTemplates = $this->getDatabaseConnection()->exec_SELECTgetRows('*', 'sys_template', 'uid IN (' . implode(',', $basedOnIds) . ') ' . $this->whereClause, '', '', '', 'uid');
                        // Traversing list again to ensure the sorting of the templates
                        foreach ($basedOnIds as $id) {
                                if (is_array($subTemplates[$id])) {
@@ -738,7 +752,7 @@ class TemplateService {
         *
         * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
         * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
-        * @param array $pid The PID of the input template record
+        * @param int $pid The PID of the input template record
         * @param array $row A full TypoScript template record
         * @return void
         * @see processTemplate()
@@ -768,9 +782,9 @@ class TemplateService {
                        foreach ($include_static_fileArr as $ISF_file) {
                                if (substr($ISF_file, 0, 4) == 'EXT:') {
                                        list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
-                                       if ((string)$ISF_extKey !== '' && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
+                                       if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
                                                $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
-                                               $ISF_filePath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
+                                               $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
                                                if (@is_dir($ISF_filePath)) {
                                                        $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
                                                        $subrow = array(
@@ -812,7 +826,7 @@ class TemplateService {
         *
         * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
         * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
-        * @param array $pid The PID of the input template record
+        * @param int $pid The PID of the input template record
         * @param array $row A full TypoScript template record
         * @return void
         * @access private
@@ -873,12 +887,12 @@ class TemplateService {
                // To do the fronted call a full frontend is required, just checking for
                // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
                // eId scripts that run in frontend scope, but do not have a full blown frontend.
-               if (is_object($GLOBALS['TSFE']) === TRUE && property_exists($GLOBALS['TSFE'], 'sys_page') === TRUE && method_exists($GLOBALS['TSFE']->sys_page, 'versionOL') === TRUE) {
+               if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
                        // Frontend
-                       $GLOBALS['TSFE']->sys_page->versionOL('sys_template', $row);
+                       $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
                } else {
                        // Backend
-                       \TYPO3\CMS\Backend\Utility\BackendUtility::workspaceOL('sys_template', $row);
+                       BackendUtility::workspaceOL('sys_template', $row);
                }
        }
 
@@ -906,12 +920,12 @@ class TemplateService {
                // Parse TypoScript Constants
                // ****************************
                // Initialize parser and match-condition classes:
-               /** @var $constants \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
-               $constants = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+               /** @var $constants Parser\TypoScriptParser */
+               $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                $constants->breakPointLN = (int)$this->ext_constants_BRP;
                $constants->setup = $this->mergeConstantsFromPageTSconfig(array());
-               /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
-               $matchObj = GeneralUtility::makeInstance(\TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher::class);
+               /** @var $matchObj ConditionMatcher */
+               $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
                $matchObj->setSimulateMatchConditions($this->matchAlternative);
                $matchObj->setSimulateMatchResult((bool)$this->matchAll);
                // Traverse constants text fields and parse them
@@ -927,8 +941,8 @@ class TemplateService {
                // Parse TypoScript Setup (here called "config")
                // ***********************************************
                // Initialize parser and match-condition classes:
-               /** @var $config \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
-               $config = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+               /** @var $config Parser\TypoScriptParser */
+               $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                $config->breakPointLN = (int)$this->ext_config_BRP;
                $config->regLinenumbers = $this->ext_regLinenumbers;
                $config->regComments = $this->ext_regComments;
@@ -945,11 +959,11 @@ class TemplateService {
                }
                // Substitute constants in the Setup code:
                if ($this->tt_track) {
-                       $GLOBALS['TT']->push('Substitute Constants (' . count($this->flatSetup) . ')');
+                       $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
                }
                $all = $this->substituteConstants($all);
                if ($this->tt_track) {
-                       $GLOBALS['TT']->pull();
+                       $this->getTimeTracker()->pull();
                }
 
                // Searching for possible unsubstituted constants left (only for information)
@@ -959,11 +973,11 @@ class TemplateService {
                                $findConst = explode('{$', $all);
                                array_shift($findConst);
                                foreach ($findConst as $constVal) {
-                                       $constLen = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(strcspn($constVal, '}'), 0, 50);
+                                       $constLen = MathUtility::forceIntegerInRange(strcspn($constVal, '}'), 0, 50);
                                        $theConstList[] = '{$' . substr($constVal, 0, ($constLen + 1));
                                }
                                if ($this->tt_track) {
-                                       $GLOBALS['TT']->setTSlogMessage(implode(', ', $theConstList) . ': Constants may remain un-substituted!!', 2);
+                                       $this->getTimeTracker()->setTSlogMessage(implode(', ', $theConstList) . ': Constants may remain un-substituted!!', 2);
                                }
                        }
 
@@ -971,7 +985,7 @@ class TemplateService {
 
                // Logging the textual size of the TypoScript Setup field text with all constants substituted:
                if ($this->tt_track) {
-                       $GLOBALS['TT']->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
+                       $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
                }
                // Finally parse the Setup field TypoScript code (where constants are now substituted)
                $config->parse($all, $matchObj);
@@ -1030,14 +1044,14 @@ class TemplateService {
                $paths = $this->templateIncludePaths;
                $files = array();
                foreach ($this->constants as &$value) {
-                       $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
+                       $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
                        $files = array_merge($files, $includeData['files']);
                        $value = $includeData['typoscript'];
                }
                unset($value);
                $paths = $this->templateIncludePaths;
                foreach ($this->config as &$value) {
-                       $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
+                       $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
                        $files = array_merge($files, $includeData['files']);
                        $value = $includeData['typoscript'];
                }
@@ -1068,13 +1082,13 @@ class TemplateService {
                        $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
                }
                // Parsing the user TS (or getting from cache)
-               $TSdataArray = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
+               $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
                $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
-               /** @var $parseObj \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
-               $parseObj = GeneralUtility::makeInstance(\TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::class);
+               /** @var $parseObj Parser\TypoScriptParser */
+               $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
                $parseObj->parse($userTS);
                if (is_array($parseObj->setup['TSFE.']['constants.'])) {
-                       \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
+                       ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
                }
                return $constArray;
        }
@@ -1090,7 +1104,7 @@ class TemplateService {
        public function flattenSetup($setupArray, $prefix) {
                if (is_array($setupArray)) {
                        foreach ($setupArray as $key => $val) {
-                               if ($prefix || substr($key, 0, 16) != 'TSConstantEditor') {
+                               if ($prefix || !StringUtility::beginsWith($key, 'TSConstantEditor')) {
                                        // We don't want 'TSConstantEditor' in the flattend setup on the first level (190201)
                                        if (is_array($val)) {
                                                $this->flattenSetup($val, $prefix . $key);
@@ -1111,7 +1125,7 @@ class TemplateService {
         */
        public function substituteConstants($all) {
                if ($this->tt_track) {
-                       $GLOBALS['TT']->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
+                       $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
                }
                $noChange = FALSE;
                // Recursive substitution of constants (up to 10 nested levels)
@@ -1165,8 +1179,8 @@ class TemplateService {
                        foreach ($conf as $cKey => $val) {
                                if (is_array($val)) {
                                        $tempConf = $this->splitConfArray($val, $splitCount);
-                                       foreach ($tempConf as $aKey => $val) {
-                                               $conf2[$aKey][$cKey] = $val;
+                                       foreach ($tempConf as $aKey => $val2) {
+                                               $conf2[$aKey][$cKey] = $val2;
                                        }
                                } else {
                                        // Splitting of all values on this level of the TypoScript object tree:
@@ -1176,7 +1190,6 @@ class TemplateService {
                                                }
                                        } else {
                                                $main = explode('|*|', $val);
-                                               $mainCount = count($main);
                                                $lastC = 0;
                                                $middleC = 0;
                                                $firstC = 0;
@@ -1184,10 +1197,13 @@ class TemplateService {
                                                        $first = explode('||', $main[0]);
                                                        $firstC = count($first);
                                                }
+                                               $middle = array();
                                                if ($main[1]) {
                                                        $middle = explode('||', $main[1]);
                                                        $middleC = count($middle);
                                                }
+                                               $last = array();
+                                               $value = '';
                                                if ($main[2]) {
                                                        $last = explode('||', $main[2]);
                                                        $lastC = count($last);
@@ -1215,17 +1231,17 @@ class TemplateService {
         * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
         *
         * @param string $fileFromSetup TypoScript "resource" data type value.
-        * @return string Resulting filename, is either a full absolute URL or a relative path
+        * @return string|NULL Resulting filename, is either a full absolute URL or a relative path. Returns NULL if invalid filename or a directory is given
         */
        public function getFileName($fileFromSetup) {
                $file = trim($fileFromSetup);
                if (!$file) {
-                       return;
+                       return NULL;
                } elseif (strpos($file, '../') !== FALSE) {
                        if ($this->tt_track) {
-                               $GLOBALS['TT']->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
+                               $this->getTimeTracker()->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
                        }
-                       return;
+                       return NULL;
                }
                // Cache
                $hash = md5($file);
@@ -1243,12 +1259,12 @@ class TemplateService {
                $file = GeneralUtility::getFileAbsFileName($file);
                if (!$file) {
                        if ($this->tt_track) {
-                               $GLOBALS['TT']->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
+                               $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
                        }
-                       return;
+                       return NULL;
                }
 
-               $file = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($file);
+               $file = PathUtility::stripPathSitePrefix($file);
 
                // Check if the found file is in the allowed paths
                foreach ($this->allowedPaths as $val) {
@@ -1259,8 +1275,9 @@ class TemplateService {
                }
 
                if ($this->tt_track) {
-                       $GLOBALS['TT']->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
+                       $this->getTimeTracker()->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
                }
+               return NULL;
        }
 
        /**
@@ -1354,7 +1371,7 @@ class TemplateService {
                $keyArr = array();
                $setupArrKeys = array_keys($setupArr);
                foreach ($setupArrKeys as $key) {
-                       if ($acceptOnlyProperties || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
+                       if ($acceptOnlyProperties || MathUtility::canBeInterpretedAsInteger($key)) {
                                $keyArr[] = (int)$key;
                        }
                }
@@ -1394,10 +1411,10 @@ class TemplateService {
         * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, no_cache, title and sectionIndex_uid.
         * @param string $oTarget Default target string to use IF not $page['target'] is set.
         * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
-        * @param string $script Alternative script name if you don't want to use $GLOBALS['TSFE']->config['mainScript'] (normally set to "index.php")
+        * @param string $script Alternative script name if you don't want to use $this->getTypoScriptFrontendController()->config['mainScript'] (normally set to "index.php")
         * @param array $overrideArray Array with overriding values for the $page array.
         * @param string $addParams Additional URL parameters to set in the URL. Syntax is "&foo=bar&foo2=bar2" etc. Also used internally to add parameters if needed.
-        * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $GLOBALS['TSFE']->config['config']['forceTypeValue'] if found.
+        * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $this->getTypoScriptFrontendController()->config['config']['forceTypeValue'] if found.
         * @param string $targetDomain The target Doamin, if any was detected in typolink
         * @return array Contains keys like "totalURL", "url", "sectionIndex", "linkVars", "no_cache", "type", "target" of which "totalURL" is normally the value you would use while the other keys contains various parts that was used to construct "totalURL
         * @see \TYPO3\CMS\Frontend\Page\FramesetRenderer::frameParams(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::SEARCHRESULT(), \TYPO3\CMS\Frontend\Page\PageGenerator::pagegenInit(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
@@ -1414,9 +1431,9 @@ class TemplateService {
                // Adding Mount Points, "&MP=", parameter for the current page if any is set:
                if (!strstr($addParams, '&MP=')) {
                        // Looking for hardcoded defaults:
-                       if (trim($GLOBALS['TSFE']->MP_defaults[$page['uid']])) {
-                               $addParams .= '&MP=' . rawurlencode(trim($GLOBALS['TSFE']->MP_defaults[$page['uid']]));
-                       } elseif ($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']) {
+                       if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
+                               $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
+                       } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
                                // Else look in automatically created map:
                                $m = $this->getFromMPmap($page['uid']);
                                if ($m) {
@@ -1426,7 +1443,7 @@ class TemplateService {
                }
                // Setting ID/alias:
                if (!$script) {
-                       $script = $GLOBALS['TSFE']->config['mainScript'];
+                       $script = $this->getTypoScriptFrontendController()->config['mainScript'];
                }
                if ($page['alias']) {
                        $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
@@ -1437,8 +1454,8 @@ class TemplateService {
                $LD['target'] = trim($page['target']) ?: $oTarget;
                // typeNum
                $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
-               if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$GLOBALS['TSFE']->config['config']['forceTypeValue']) {
-                       $typeOverride = (int)$GLOBALS['TSFE']->config['config']['forceTypeValue'];
+               if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
+                       $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
                }
                if ((string)$typeOverride !== '') {
                        $typeNum = $typeOverride;
@@ -1455,16 +1472,16 @@ class TemplateService {
                $LD['no_cache'] = trim($page['no_cache']) || $no_cache ? '&no_cache=1' : '';
                // linkVars
                if ($addParams) {
-                       $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($GLOBALS['TSFE']->linkVars . $addParams), '', FALSE, TRUE);
+                       $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', FALSE, TRUE);
                } else {
-                       $LD['linkVars'] = $GLOBALS['TSFE']->linkVars;
+                       $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
                }
                // Add absRefPrefix if exists.
-               $LD['url'] = $GLOBALS['TSFE']->absRefPrefix . $LD['url'];
+               $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
                // If the special key 'sectionIndex_uid' (added 'manually' in tslib/menu.php to the page-record) is set, then the link jumps directly to a section on the page.
                $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
                // Compile the normal total url
-               $LD['totalURL'] = $this->removeQueryString(($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $GLOBALS['TSFE']->getMethodUrlIdToken)) . $LD['sectionIndex'];
+               $LD['totalURL'] = $this->removeQueryString(($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken)) . $LD['sectionIndex'];
                // Call post processing function for link rendering:
                if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'])) {
                        $_params = array(
@@ -1493,12 +1510,12 @@ class TemplateService {
                // Create map if not found already:
                if (!is_array($this->MPmap)) {
                        $this->MPmap = array();
-                       $rootPoints = GeneralUtility::trimExplode(',', strtolower($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']), TRUE);
+                       $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), TRUE);
                        // Traverse rootpoints:
                        foreach ($rootPoints as $p) {
+                               $initMParray = array();
                                if ($p == 'root') {
                                        $p = $this->rootLine[0]['uid'];
-                                       $initMParray = array();
                                        if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
                                                $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
                                        }
@@ -1512,6 +1529,7 @@ class TemplateService {
                                return implode(',', $this->MPmap[$pageId]);
                        }
                }
+               return '';
        }
 
        /**
@@ -1531,7 +1549,7 @@ class TemplateService {
                // First level, check id
                if (!$level) {
                        // Find mount point if any:
-                       $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($id);
+                       $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
                        // Overlay mode:
                        if (is_array($mount_info) && $mount_info['overlay']) {
                                $MP_array[] = $mount_info['MPvar'];
@@ -1548,12 +1566,12 @@ class TemplateService {
                if ($id && $level < 20) {
                        $nextLevelAcc = array();
                        // Select and traverse current level pages:
-                       $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'pid=' . (int)$id . ' AND deleted=0 AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_RECYCLER . ' AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_BE_USER_SECTION);
-                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
+                       $res = $this->getDatabaseConnection()->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'pid=' . (int)$id . ' AND deleted=0 AND doktype<>' . PageRepository::DOKTYPE_RECYCLER . ' AND doktype<>' . PageRepository::DOKTYPE_BE_USER_SECTION);
+                       while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
                                // Find mount point if any:
                                $next_id = $row['uid'];
                                $next_MP_array = $MP_array;
-                               $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($next_id, $row);
+                               $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
                                // Overlay mode:
                                if (is_array($mount_info) && $mount_info['overlay']) {
                                        $next_MP_array[] = $mount_info['MPvar'];
@@ -1572,7 +1590,7 @@ class TemplateService {
                                        $nextLevelAcc[] = array($next_id, $next_MP_array);
                                }
                        }
-                       $GLOBALS['TYPO3_DB']->sql_free_result($res);
+                       $this->getDatabaseConnection()->sql_free_result($res);
                        // Call recursively, if any:
                        foreach ($nextLevelAcc as $pSet) {
                                $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
@@ -1619,4 +1637,25 @@ class TemplateService {
                }
        }
 
+       /**
+        * @return DatabaseConnection
+        */
+       protected function getDatabaseConnection() {
+               return $GLOBALS['TYPO3_DB'];
+       }
+
+       /**
+        * @return TypoScriptFrontendController
+        */
+       protected function getTypoScriptFrontendController() {
+               return $GLOBALS['TSFE'];
+       }
+
+       /**
+        * @return TimeTracker
+        */
+       protected function getTimeTracker() {
+               return $GLOBALS['TT'];
+       }
+
 }