1<?php
2
3/*
4 * This file is part of the TYPO3 CMS project.
5 *
6 * It is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU General Public License, either version 2
8 * of the License, or any later version.
9 *
10 * For the full copyright and license information, please read the
11 * LICENSE.txt file that was distributed with this source code.
12 *
13 * The TYPO3 project - inspiring people to share!
14 */
15
16namespace TYPO3\CMS\Core\TypoScript;
17
18use Psr\Log\LogLevel;
19use TYPO3\CMS\Core\Cache\CacheManager;
20use TYPO3\CMS\Core\Context\Context;
21use TYPO3\CMS\Core\Database\Connection;
22use TYPO3\CMS\Core\Database\ConnectionPool;
23use TYPO3\CMS\Core\Database\Query\Restriction\AbstractRestrictionContainer;
24use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
25use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
26use TYPO3\CMS\Core\Domain\Repository\PageRepository;
27use TYPO3\CMS\Core\Exception\SiteNotFoundException;
28use TYPO3\CMS\Core\Package\PackageManager;
29use TYPO3\CMS\Core\Site\Entity\Site;
30use TYPO3\CMS\Core\Site\SiteFinder;
31use TYPO3\CMS\Core\TimeTracker\TimeTracker;
32use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
33use TYPO3\CMS\Core\Utility\ArrayUtility;
34use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
35use TYPO3\CMS\Core\Utility\GeneralUtility;
36use TYPO3\CMS\Core\Utility\PathUtility;
37use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
38use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
39
40/**
41 * Template object that is responsible for generating the TypoScript template based on template records.
42 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
43 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
44 */
45class TemplateService
46{
47    /**
48     * option to enable logging, time-tracking (FE-only)
49     * usually, this is only done when
50     *  - in FE a BE_USER is logged-in
51     *  - in BE when the BE_USER needs information about the template (TypoScript module)
52     * @var bool
53     */
54    protected $verbose = false;
55
56    /**
57     * If set, the global tt-timeobject is used to log the performance.
58     *
59     * @var bool
60     */
61    public $tt_track = true;
62
63    /**
64     * This array is passed on to matchObj by generateConfig().
65     * If it holds elements, they are used for matching instead. See comment at the match-class.
66     * Used for backend modules only. Never frontend!
67     *
68     * @var array
69     * @internal
70     */
71    public $matchAlternative = [];
72
73    /**
74     * If set, the match-class matches everything! Used for backend modules only. Never frontend!
75     *
76     * @var bool
77     */
78    protected $matchAll = false;
79
80    /**
81     * @deprecated Unused since v11, will be removed in v12
82     */
83    public $ext_constants_BRP = 0;
84
85    /**
86     * @deprecated Unused since v11, will be removed in v12
87     */
88    public $ext_config_BRP = 0;
89
90    /**
91     * @var bool
92     */
93    public $ext_regLinenumbers = false;
94
95    /**
96     * @var bool
97     */
98    public $ext_regComments = false;
99
100    /**
101     * Set if preview of some kind is enabled.
102     *
103     * @var bool
104     */
105    protected $simulationHiddenOrTime = false;
106
107    /**
108     * Set, if the TypoScript template structure is loaded and OK, see ->start()
109     *
110     * @var bool
111     */
112    public $loaded = false;
113
114    /**
115     * @var array Contains TypoScript setup part after parsing
116     */
117    public $setup = [];
118
119    /**
120     * @var array
121     */
122    public $flatSetup = [];
123
124    /**
125     * For fetching TypoScript code from template hierarchy before parsing it.
126     * Each array contains code field values from template records/files:
127     * Setup field
128     *
129     * @var array
130     */
131    public $config = [];
132
133    /**
134     * Constant field
135     *
136     * @var array
137     */
138    public $constants = [];
139
140    /**
141     * Holds the include paths of the templates (empty if from database)
142     *
143     * @var array
144     */
145    protected $templateIncludePaths = [];
146
147    /**
148     * For Template Analyzer in backend
149     *
150     * @var array
151     */
152    public $hierarchyInfo = [];
153
154    /**
155     * For Template Analyzer in backend (setup content only)
156     *
157     * @var array
158     */
159    protected $hierarchyInfoToRoot = [];
160
161    /**
162     * The Page UID of the root page
163     *
164     * @var int
165     */
166    protected $rootId;
167
168    /**
169     * The rootline from current page to the root page
170     *
171     * @var array
172     */
173    public $rootLine;
174
175    /**
176     * Rootline all the way to the root. Set but runThroughTemplates
177     *
178     * @var array
179     */
180    protected $absoluteRootLine;
181
182    /**
183     * Array of arrays with title/uid of templates in hierarchy
184     *
185     * @var array
186     */
187    protected $rowSum;
188
189    /**
190     * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
191     *
192     * @var array|null
193     */
194    public $sections;
195
196    /**
197     * Tracking all matching conditions found
198     *
199     * @var array
200     */
201    protected $sectionsMatch;
202
203    /**
204     * Used by Backend only (Typoscript Template Analyzer)
205     * @var string[]
206     */
207    public $clearList_const = [];
208
209    /**
210     * Used by Backend only (Typoscript Template Analyzer)
211     *
212     * @var array
213     */
214    public $clearList_setup = [];
215
216    /**
217     * @var array
218     */
219    public $parserErrors = [];
220
221    /**
222     * @var array
223     */
224    public $setup_constants = [];
225
226    /**
227     * Indicator that extension statics are processed.
228     *
229     * These files are considered if either a root template
230     * has been processed or the $processExtensionStatics
231     * property has been set to TRUE.
232     *
233     * @var bool
234     */
235    protected $extensionStaticsProcessed = false;
236
237    /**
238     * Trigger value, to ensure that extension statics are processed.
239     *
240     * @var bool
241     */
242    protected $processExtensionStatics = false;
243
244    /**
245     * Set to TRUE after the default TypoScript was added during parsing.
246     * This prevents double inclusion of the same TypoScript code.
247     *
248     * @see addDefaultTypoScript()
249     * @var bool
250     */
251    protected $isDefaultTypoScriptAdded = false;
252
253    /**
254     * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
255     *
256     * This prevents double processing of INCLUDES.
257     *
258     * @see processIncludes()
259     * @var bool
260     */
261    protected $processIncludesHasBeenRun = false;
262
263    /**
264     * Contains the restrictions about deleted, and some frontend related topics
265     * @var AbstractRestrictionContainer
266     */
267    protected $queryBuilderRestrictions;
268
269    /**
270     * @var Context
271     */
272    protected $context;
273
274    /**
275     * @var PackageManager
276     */
277    protected $packageManager;
278
279    /**
280     * @var TypoScriptFrontendController|null
281     */
282    protected $frontendController;
283
284    /**
285     * @param Context|null $context
286     * @param PackageManager|null $packageManager
287     * @param TypoScriptFrontendController|null $frontendController
288     */
289    public function __construct(Context $context = null, PackageManager $packageManager = null, TypoScriptFrontendController $frontendController = null)
290    {
291        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
292        $this->packageManager = $packageManager ?? GeneralUtility::makeInstance(PackageManager::class);
293        $this->frontendController = $frontendController;
294        $this->initializeDatabaseQueryRestrictions();
295        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
296            // Set the simulation flag, if simulation is detected!
297            $this->simulationHiddenOrTime = true;
298        }
299        $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
300    }
301
302    /**
303     * @return bool
304     */
305    public function getProcessExtensionStatics()
306    {
307        return $this->processExtensionStatics;
308    }
309
310    /**
311     * @param bool $processExtensionStatics
312     */
313    public function setProcessExtensionStatics($processExtensionStatics)
314    {
315        $this->processExtensionStatics = (bool)$processExtensionStatics;
316    }
317
318    /**
319     * sets the verbose parameter
320     * @param bool $verbose
321     */
322    public function setVerbose($verbose)
323    {
324        $this->verbose = (bool)$verbose;
325    }
326
327    /**
328     * Set up the query builder restrictions, optionally include hidden records
329     */
330    protected function initializeDatabaseQueryRestrictions()
331    {
332        $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
333
334        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)) {
335            $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
336        }
337    }
338
339    /**
340     * Fetches the "currentPageData" array from cache
341     *
342     * NOTE about currentPageData:
343     * It holds information about the TypoScript conditions along with the list
344     * of template uid's which is used on the page. In the getFromCache() function
345     * in TSFE, currentPageData is used to evaluate if there is a template and
346     * if the matching conditions are alright. Unfortunately this does not take
347     * into account if the templates in the rowSum of currentPageData has
348     * changed composition, eg. due to hidden fields or start/end time. So if a
349     * template is hidden or times out, it'll not be discovered unless the page
350     * is regenerated - at least the this->start function must be called,
351     * because this will make a new portion of data in currentPageData string.
352     *
353     * @param int $pageId
354     * @param string $mountPointValue
355     * @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
356     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
357     * @internal
358     */
359    public function getCurrentPageData(int $pageId, string $mountPointValue)
360    {
361        return GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection')->get($pageId . '_' . GeneralUtility::md5int($mountPointValue));
362    }
363
364    /**
365     * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
366     *
367     * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
368     * @return array The input array but with a new key added, "match" which contains the items from the "all" key which when passed to tslib_matchCondition returned TRUE.
369     */
370    public function matching($cc)
371    {
372        if (is_array($cc['all'])) {
373            /** @var ConditionMatcher $matchObj */
374            $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
375            $matchObj->setRootline((array)($cc['rootLine'] ?? []));
376            $sectionsMatch = [];
377            foreach ($cc['all'] as $key => $pre) {
378                if ($matchObj->match($pre)) {
379                    $sectionsMatch[$key] = $pre;
380                }
381            }
382            $cc['match'] = $sectionsMatch;
383        }
384        return $cc;
385    }
386
387    /**
388     * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
389     * The method traverses the rootline structure from out to in, fetches the hierarchy of template records and based on this either finds the cached TypoScript template structure or parses the template and caches it for next time.
390     * Sets $this->setup to the parsed TypoScript template array
391     *
392     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
393     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
394     */
395    public function start($theRootLine)
396    {
397        $cc = [];
398        if (is_array($theRootLine)) {
399            $constantsData = [];
400            $setupData = [];
401            $cacheIdentifier = '';
402            // Flag that indicates that the existing data in cache_pagesection
403            // could be used (this is the case if $TSFE->all is set, and the
404            // rowSum still matches). Based on this we decide if cache_pagesection
405            // needs to be updated...
406            $isCached = false;
407            $this->runThroughTemplates($theRootLine);
408            if ($this->getTypoScriptFrontendController()->all) {
409                $cc = $this->getTypoScriptFrontendController()->all;
410                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
411                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
412                    $cc = [];
413                } else {
414                    // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
415                    if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
416                        $isCached = true;
417                    }
418                    // When the data is serialized below (ROWSUM hash), it must not contain the rootline by concept. So this must be removed (and added again later)...
419                    unset($cc['rootLine']);
420                }
421            }
422            // This is about getting the hash string which is used to fetch the cached TypoScript template.
423            // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
424            if (!empty($cc)) {
425                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
426                if (!$cc['match']) {
427                    // @todo check if this can ever be the case - otherwise remove
428                    $cc = $this->matching($cc);
429                    ksort($cc);
430                }
431                $cacheIdentifier = md5(serialize($cc));
432            } else {
433                // 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.
434                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
435                $result = $this->getCacheEntry($rowSumHash);
436                if (is_array($result)) {
437                    $cc['all'] = $result;
438                    $cc['rowSum'] = $this->rowSum;
439                    $cc = $this->matching($cc);
440                    ksort($cc);
441                    $cacheIdentifier = md5(serialize($cc));
442                }
443            }
444            if ($cacheIdentifier) {
445                // Get TypoScript setup array
446                $cachedData = $this->getCacheEntry($cacheIdentifier);
447                if (is_array($cachedData)) {
448                    $constantsData = $cachedData['constants'];
449                    $setupData = $cachedData['setup'];
450                }
451            }
452            if (!empty($setupData) && !$this->context->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
453                // TypoScript constants + setup are found in the cache
454                $this->setup_constants = $constantsData;
455                $this->setup = $setupData;
456                if ($this->tt_track) {
457                    $this->getTimeTracker()->setTSlogMessage('Using cached TS template data', LogLevel::INFO);
458                }
459            } else {
460                if ($this->tt_track) {
461                    $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data', LogLevel::INFO);
462                }
463
464                // Make configuration
465                $this->generateConfig();
466                // This stores the template hash thing
467                $cc = [];
468                // All sections in the template at this point is found
469                $cc['all'] = $this->sections;
470                // The line of templates is collected
471                $cc['rowSum'] = $this->rowSum;
472                $cc = $this->matching($cc);
473                ksort($cc);
474                $cacheIdentifier = md5(serialize($cc));
475                // This stores the data.
476                $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
477                if ($this->tt_track) {
478                    $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes', LogLevel::INFO);
479                }
480                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
481                $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
482            }
483            // Add rootLine
484            $cc['rootLine'] = $this->rootLine;
485            ksort($cc);
486            // Make global and save
487            $this->getTypoScriptFrontendController()->all = $cc;
488            // Matching must be executed for every request, so this must never be part of the pagesection cache!
489            unset($cc['match']);
490            if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
491                // Only save the data if we're not simulating by hidden/starttime/endtime
492                $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
493                /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
494                $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection');
495                $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
496                    'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
497                    'mpvarHash_' . $mpvarHash,
498                ]);
499            }
500            // If everything OK.
501            if ($this->rootId && $this->rootLine && $this->setup) {
502                $this->loaded = true;
503            }
504        }
505    }
506
507    /*******************************************************************
508     *
509     * Fetching TypoScript code text for the Template Hierarchy
510     *
511     *******************************************************************/
512    /**
513     * 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.
514     * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
515     * 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
516     *
517     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
518     * @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)
519     * @see start()
520     */
521    public function runThroughTemplates($theRootLine, $start_template_uid = 0)
522    {
523        $this->constants = [];
524        $this->config = [];
525        $this->rowSum = [];
526        $this->hierarchyInfoToRoot = [];
527        $this->absoluteRootLine = $theRootLine;
528        $this->isDefaultTypoScriptAdded = false;
529
530        reset($this->absoluteRootLine);
531        $c = count($this->absoluteRootLine);
532        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
533        for ($a = 0; $a < $c; $a++) {
534            $where = [
535                $queryBuilder->expr()->eq(
536                    'pid',
537                    $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
538                ),
539            ];
540            // If first loop AND there is set an alternative template uid, use that
541            if ($a === $c - 1 && $start_template_uid) {
542                $where[] = $queryBuilder->expr()->eq(
543                    'uid',
544                    $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
545                );
546            }
547            $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
548            $queryResult = $queryBuilder
549                ->select('*')
550                ->from('sys_template')
551                ->where(...$where)
552                ->orderBy('root', 'DESC')
553                ->addOrderBy('sorting')
554                ->setMaxResults(1)
555                ->executeQuery();
556            if ($row = $queryResult->fetchAssociative()) {
557                $this->versionOL($row);
558                if (is_array($row)) {
559                    $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
560                }
561            }
562            $this->rootLine[] = $this->absoluteRootLine[$a];
563        }
564
565        // Hook into the default TypoScript to add custom typoscript logic
566        $hookParameters = [
567            'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
568            'isDefaultTypoScriptAdded'  => &$this->isDefaultTypoScriptAdded,
569            'absoluteRootLine' => &$this->absoluteRootLine,
570            'rootLine'         => &$this->rootLine,
571            'startTemplateUid' => $start_template_uid,
572            'rowSum'           => &$this->rowSum,
573        ];
574        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
575            GeneralUtility::callUserFunction($listener, $hookParameters, $this);
576        }
577
578        // Process extension static files if not done yet, but explicitly requested
579        if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
580            $this->addExtensionStatics('sys_0', 'sys_0', 0);
581        }
582
583        // Add the global default TypoScript from the TYPO3_CONF_VARS
584        $this->addDefaultTypoScript();
585
586        $this->processIncludes();
587    }
588
589    /**
590     * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
591     * Builds up $this->rowSum
592     *
593     * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
594     * @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, 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.
595     * @param int $pid The PID of the input template record
596     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
597     * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
598     * @param string $includePath Specifies the path from which the template was included (used with static_includes)
599     * @see runThroughTemplates()
600     */
601    public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
602    {
603        // Adding basic template record information to rowSum array
604        $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
605        // Processing "Clear"-flags
606        $clConst = 0;
607        $clConf = 0;
608        if (!empty($row['clear'])) {
609            $clConst = $row['clear'] & 1;
610            $clConf = $row['clear'] & 2;
611            if ($clConst) {
612                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
613                foreach ($this->constants as &$constantConfiguration) {
614                    $constantConfiguration = '';
615                }
616                unset($constantConfiguration);
617                $this->clearList_const = [];
618            }
619            if ($clConf) {
620                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
621                foreach ($this->config as &$configConfiguration) {
622                    $configConfiguration = '';
623                }
624                unset($configConfiguration);
625                $this->hierarchyInfoToRoot = [];
626                $this->clearList_setup = [];
627            }
628        }
629        // Include files (from extensions) (#1/2)
630        // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
631        if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
632            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
633        }
634        // Include "Based On" sys_templates:
635        // 'basedOn' is a list of templates to include
636        if (trim($row['basedOn'] ?? '')) {
637            // Normal Operation, which is to include the "based-on" sys_templates,
638            // if they are not already included, and maintaining the sorting of the templates
639            $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
640            // skip template if it's already included
641            foreach ($basedOnIds as $key => $basedOnId) {
642                if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
643                    unset($basedOnIds[$key]);
644                }
645            }
646            if (!empty($basedOnIds)) {
647                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
648                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
649                $queryResult = $queryBuilder
650                    ->select('*')
651                    ->from('sys_template')
652                    ->where(
653                        $queryBuilder->expr()->in(
654                            'uid',
655                            $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
656                        )
657                    )
658                    ->executeQuery();
659                // make it an associative array with the UID as key
660                $subTemplates = [];
661                while ($rowItem = $queryResult->fetchAssociative()) {
662                    $subTemplates[(int)$rowItem['uid']] = $rowItem;
663                }
664                // Traversing list again to ensure the sorting of the templates
665                foreach ($basedOnIds as $id) {
666                    if (is_array($subTemplates[$id])) {
667                        $this->versionOL($subTemplates[$id]);
668                        $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
669                    }
670                }
671            }
672        }
673        // Include files (from extensions) (#2/2)
674        if (!empty($row['includeStaticAfterBasedOn'])) {
675            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
676        }
677        // Creating hierarchy information; Used by backend analysis tools
678        $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
679            'root' => trim($row['root'] ?? ''),
680            'clConst' => $clConst,
681            'clConf' => $clConf,
682            'templateID' => $templateID,
683            'templateParent' => $templateParent,
684            'title' => $row['title'],
685            'uid' => $row['uid'],
686            'pid' => $row['pid'] ?? null,
687            'configLines' => substr_count((string)$row['config'], LF) + 1,
688        ]);
689        // Adding the content of the fields constants (Constants) and config (Setup)
690        $this->constants[] = $row['constants'];
691        $this->config[] = $row['config'];
692        $this->templateIncludePaths[] = $includePath;
693        // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
694        $this->clearList_const[] = $templateID;
695        $this->clearList_setup[] = $templateID;
696        // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
697        if (trim($row['root'] ?? '')) {
698            $this->rootId = $pid;
699            $this->rootLine = [];
700        }
701    }
702
703    /**
704     * This function can be used to update the data of the current rootLine
705     * e.g. when a different language is used.
706     *
707     * This function must not be used if there are different pages in the
708     * rootline as before!
709     *
710     * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
711     * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
712     */
713    public function updateRootlineData($fullRootLine)
714    {
715        if (!is_array($this->rootLine) || empty($this->rootLine)) {
716            return;
717        }
718
719        $fullRootLineByUid = [];
720        foreach ($fullRootLine as $rootLineData) {
721            $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
722        }
723
724        foreach ($this->rootLine as $level => $dataArray) {
725            $currentUid = $dataArray['uid'];
726
727            if (!array_key_exists($currentUid, $fullRootLineByUid)) {
728                throw new \RuntimeException(sprintf('The full rootLine does not contain data for the page with the uid %d that is contained in the template rootline.', $currentUid), 1370419654);
729            }
730
731            $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
732        }
733    }
734
735    /**
736     * Includes static template files (from extensions) for the input template record row.
737     *
738     * @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 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.
739     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
740     * @param int $pid The PID of the input template record
741     * @param array $row A full TypoScript template record
742     * @see processTemplate()
743     * @internal
744     */
745    public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
746    {
747        // Call function for link rendering:
748        $_params = [
749            'idList' => &$idList,
750            'templateId' => &$templateID,
751            'pid' => &$pid,
752            'row' => &$row,
753        ];
754        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
755            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
756        }
757        // If "Include before all static templates if root-flag is set" is set:
758        $staticFileMode = $row['static_file_mode'] ?? null;
759        if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
760            $this->addExtensionStatics($idList, $templateID, $pid);
761        }
762        // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
763        if (trim($row['include_static_file'] ?? '')) {
764            $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
765            // Traversing list
766            foreach ($include_static_fileArr as $ISF_file) {
767                if (PathUtility::isExtensionPath($ISF_file)) {
768                    [$ISF_extKey, $ISF_localPath] = explode('/', substr($ISF_file, 4), 2);
769                    if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
770                        $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
771                        $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
772                        if (@is_dir($ISF_filePath)) {
773                            $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
774
775                            $includeStaticTxtPath = $ISF_filePath . 'include_static.txt';
776                            $includeStaticTxtContents = '';
777                            if (@file_exists($includeStaticTxtPath)) {
778                                $includeStaticTxtContents = (string)file_get_contents($includeStaticTxtPath);
779                                $includeStaticTxtContents = implode(',', array_unique(GeneralUtility::intExplode(',', $includeStaticTxtContents)));
780                            }
781
782                            $includeStaticFileTxtPath = $ISF_filePath . 'include_static_file.txt';
783                            $includeStaticFileTxtContents = '';
784                            if (@file_exists($includeStaticFileTxtPath)) {
785                                $includeStaticFileTxtContents = (string)file_get_contents($includeStaticFileTxtPath);
786                                $includeStaticFileTxtContents = implode(',', array_unique(GeneralUtility::trimExplode(',', $includeStaticFileTxtContents)));
787                            }
788
789                            $subrow = [
790                                'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
791                                'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
792                                'include_static' => $includeStaticTxtContents,
793                                'include_static_file' => $includeStaticFileTxtContents,
794                                'title' => $ISF_file,
795                                'uid' => $mExtKey,
796                            ];
797                            $subrow = $this->prependStaticExtra($subrow);
798                            $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
799                        }
800                    }
801                }
802            }
803        }
804        // If "Default (include before if root flag is set)" is set OR
805        // "Always include before this template record" AND root-flag are set
806        if ($staticFileMode == 1 || $staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
807            $this->addExtensionStatics($idList, $templateID, $pid);
808        }
809        // Include Static Template Records after all other TypoScript has been included.
810        $_params = [
811            'idList' => &$idList,
812            'templateId' => &$templateID,
813            'pid' => &$pid,
814            'row' => &$row,
815        ];
816        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
817            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
818        }
819    }
820
821    /**
822     * Retrieves the content of the first existing file by extension order.
823     * Returns the empty string if no file is found.
824     *
825     * @param string $filePath The location of the file.
826     * @param string $baseName The base file name. "constants" or "setup".
827     * @return string
828     */
829    protected function getTypoScriptSourceFileContent($filePath, $baseName)
830    {
831        $extensions = ['.typoscript', '.ts', '.txt'];
832        foreach ($extensions as $extension) {
833            $fileName = $filePath . $baseName . $extension;
834            if (@file_exists($fileName)) {
835                return file_get_contents($fileName);
836            }
837        }
838        return '';
839    }
840
841    /**
842     * Adds the default TypoScript files for extensions if any.
843     *
844     * @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 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.
845     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
846     * @param int $pid The PID of the input template record
847     * @internal
848     * @see includeStaticTypoScriptSources()
849     */
850    public function addExtensionStatics($idList, $templateID, $pid)
851    {
852        $this->extensionStaticsProcessed = true;
853
854        foreach ($this->packageManager->getActivePackages() as $package) {
855            $extKey = $package->getPackageKey();
856            $packagePath = $package->getPackagePath();
857            $filesToCheck = [
858                'ext_typoscript_constants.txt',
859                'ext_typoscript_constants.typoscript',
860                'ext_typoscript_setup.txt',
861                'ext_typoscript_setup.typoscript',
862            ];
863            $files = [];
864            $hasExtensionStatics = false;
865            foreach ($filesToCheck as $file) {
866                $path = $packagePath . $file;
867                if (@file_exists($path)) {
868                    $files[$file] = $path;
869                    $hasExtensionStatics = true;
870                } else {
871                    $files[$file] = null;
872                }
873            }
874
875            if ($hasExtensionStatics) {
876                $mExtKey = str_replace('_', '', $extKey);
877                $constants = '';
878                $config = '';
879
880                if (!empty($files['ext_typoscript_constants.typoscript'])) {
881                    $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
882                } elseif (!empty($files['ext_typoscript_constants.txt'])) {
883                    $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
884                }
885
886                if (!empty($files['ext_typoscript_setup.typoscript'])) {
887                    $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
888                } elseif (!empty($files['ext_typoscript_setup.txt'])) {
889                    $config = @file_get_contents($files['ext_typoscript_setup.txt']);
890                }
891
892                $this->processTemplate(
893                    $this->prependStaticExtra([
894                        'constants' => $constants,
895                        'config' => $config,
896                        'title' => $extKey,
897                        'uid' => $mExtKey,
898                    ]),
899                    $idList . ',ext_' . $mExtKey,
900                    $pid,
901                    'ext_' . $mExtKey,
902                    $templateID,
903                    $packagePath
904                );
905            }
906        }
907    }
908
909    /**
910     * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
911     * For files the "uid" value is the extension key but with any underscores removed. Possibly with a path if its a static file selected in the template record
912     *
913     * @param array $subrow Static template record/file
914     * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
915     * @see addExtensionStatics()
916     * @see includeStaticTypoScriptSources()
917     */
918    protected function prependStaticExtra($subrow)
919    {
920        // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
921        $identifier = $subrow['uid'];
922        $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? '';
923        $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? '';
924        // if this is a template of type "default content rendering", also see if other extensions have added their TypoScript that should be included after the content definitions
925        if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
926            $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'] ?? '';
927            $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'] ?? '';
928        }
929        return $subrow;
930    }
931
932    /**
933     * Creating versioning overlay of a sys_template record.
934     *
935     * @param array $row Row to overlay (passed by reference)
936     */
937    protected function versionOL(&$row)
938    {
939        if ($this->context->getPropertyFromAspect('workspace', 'isOffline')) {
940            $pageRepository = GeneralUtility::makeInstance(PageRepository::class, $this->context);
941            $pageRepository->versionOL('sys_template', $row);
942        }
943    }
944
945    /*******************************************************************
946     *
947     * Parsing TypoScript code text from Template Records into PHP array
948     *
949     *******************************************************************/
950    /**
951     * Generates the configuration array by replacing constants and parsing the whole thing.
952     * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
953     *
954     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
955     * @see start()
956     */
957    public function generateConfig()
958    {
959        // Add default TS for all code types
960        $this->addDefaultTypoScript();
961
962        // Parse the TypoScript code text for include-instructions!
963        $this->processIncludes();
964        // ****************************
965        // Parse TypoScript Constants
966        // ****************************
967        // Initialize parser and match-condition classes:
968        /** @var Parser\TypoScriptParser $constants */
969        $constants = GeneralUtility::makeInstance(TypoScriptParser::class);
970        /** @var ConditionMatcher $matchObj */
971        $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
972        $matchObj->setSimulateMatchConditions($this->matchAlternative);
973        $matchObj->setSimulateMatchResult((bool)$this->matchAll);
974        // Traverse constants text fields and parse them
975        foreach ($this->constants as $str) {
976            $constants->parse($str, $matchObj);
977        }
978        // Read out parse errors if any
979        $this->parserErrors['constants'] = $constants->errors;
980        // Then flatten the structure from a multi-dim array to a single dim array with all constants listed as key/value pairs (ready for substitution)
981        $this->flatSetup = ArrayUtility::flatten($constants->setup, '', true);
982        // ***********************************************
983        // Parse TypoScript Setup (here called "config")
984        // ***********************************************
985        // Initialize parser and match-condition classes:
986        /** @var Parser\TypoScriptParser $config */
987        $config = GeneralUtility::makeInstance(TypoScriptParser::class);
988        $config->regLinenumbers = $this->ext_regLinenumbers;
989        $config->regComments = $this->ext_regComments;
990        $config->setup = $this->setup;
991        // Transfer information about conditions found in "Constants" and which of them returned TRUE.
992        $config->sections = $constants->sections;
993        $config->sectionsMatch = $constants->sectionsMatch;
994        // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
995        $all = '';
996        foreach ($this->config as $str) {
997            $all .= '
998[GLOBAL]
999' . $str;
1000        }
1001        // Substitute constants in the Setup code:
1002        if ($this->tt_track) {
1003            $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1004        }
1005        $all = $this->substituteConstants($all);
1006        if ($this->tt_track) {
1007            $this->getTimeTracker()->pull();
1008        }
1009
1010        // Searching for possible unsubstituted constants left (only for information)
1011        if ($this->verbose) {
1012            if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1013                if ($this->tt_track) {
1014                    $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', LogLevel::WARNING);
1015                }
1016            }
1017        }
1018
1019        // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1020        if ($this->tt_track) {
1021            $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes', LogLevel::INFO);
1022        }
1023        // Finally parse the Setup field TypoScript code (where constants are now substituted)
1024        $config->parse($all, $matchObj);
1025        // Read out parse errors if any
1026        $this->parserErrors['config'] = $config->errors;
1027        // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1028        $this->setup = $config->setup;
1029        // Do the same for the constants
1030        $this->setup_constants = $constants->setup;
1031        // ****************************************************************
1032        // Final processing of the $this->setup TypoScript Template array
1033        // Basically: This is unsetting/setting of certain reserved keys.
1034        // ****************************************************************
1035        // These vars are already set after 'processTemplate', but because $config->setup overrides them (in the line above!), we set them again. They are not changed compared to the value they had in the top of the page!
1036        unset($this->setup['types.']);
1037        unset($this->setup['types']);
1038        if (is_array($this->setup)) {
1039            foreach ($this->setup as $key => $value) {
1040                if ($value === 'PAGE') {
1041                    // Set the typeNum of the current page object:
1042                    if (isset($this->setup[$key . '.']['typeNum'])) {
1043                        $typeNum = $this->setup[$key . '.']['typeNum'];
1044                        $this->setup['types.'][$typeNum] = $key;
1045                    } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1046                        $this->setup['types.'][0] = $key;
1047                    }
1048                }
1049            }
1050        }
1051        unset($this->setup['temp.']);
1052        unset($constants);
1053        // Storing the conditions found/matched information:
1054        $this->sections = $config->sections;
1055        $this->sectionsMatch = $config->sectionsMatch;
1056    }
1057
1058    /**
1059     * Searching TypoScript code text (for constants and config (Setup))
1060     * for include instructions and does the inclusion of external TypoScript files
1061     * if needed.
1062     *
1063     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1064     * @see generateConfig()
1065     */
1066    protected function processIncludes()
1067    {
1068        if ($this->processIncludesHasBeenRun) {
1069            return;
1070        }
1071
1072        $paths = $this->templateIncludePaths;
1073        $files = [];
1074        foreach ($this->constants as &$value) {
1075            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1076            $files = array_merge($files, $includeData['files']);
1077            $value = $includeData['typoscript'];
1078        }
1079        unset($value);
1080        $paths = $this->templateIncludePaths;
1081        foreach ($this->config as &$value) {
1082            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1083            $files = array_merge($files, $includeData['files']);
1084            $value = $includeData['typoscript'];
1085        }
1086        unset($value);
1087
1088        if (!empty($files)) {
1089            $files = array_unique($files);
1090            foreach ($files as $file) {
1091                $this->rowSum[] = [$file, filemtime($file)];
1092            }
1093        }
1094
1095        $this->processIncludesHasBeenRun = true;
1096    }
1097
1098    /**
1099     * Substitutes the constants from $this->flatSetup in the text string $all
1100     *
1101     * @param string $all TypoScript code text string
1102     * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1103     * @see generateConfig()
1104     */
1105    protected function substituteConstants($all)
1106    {
1107        if ($this->tt_track) {
1108            $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup), LogLevel::INFO);
1109        }
1110        $noChange = false;
1111        // Recursive substitution of constants (up to 10 nested levels)
1112        for ($i = 0; $i < 10 && !$noChange; $i++) {
1113            $old_all = $all;
1114            $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all) ?? '';
1115            if ($old_all == $all) {
1116                $noChange = true;
1117            }
1118        }
1119        return $all;
1120    }
1121
1122    /**
1123     * Call back method for preg_replace_callback in substituteConstants
1124     *
1125     * @param array $matches Regular expression matches
1126     * @return string Replacement
1127     * @see substituteConstants()
1128     * @internal
1129     */
1130    public function substituteConstantsCallBack($matches)
1131    {
1132        // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1133        return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1134    }
1135
1136    /*******************************************************************
1137     *
1138     * Various API functions, used from elsewhere in the frontend classes
1139     *
1140     *******************************************************************/
1141
1142    /**
1143     * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1144     *
1145     * @param string $list A list of UIDs for which the rootline-level should get returned
1146     * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1147     */
1148    public function getRootlineLevel($list)
1149    {
1150        $idx = 0;
1151        foreach ($this->rootLine as $page) {
1152            if (GeneralUtility::inList($list, $page['uid'])) {
1153                return $idx;
1154            }
1155            $idx++;
1156        }
1157        return false;
1158    }
1159
1160    /**
1161     * Returns the page ID of the rootlevel
1162     *
1163     * @return int
1164     */
1165    public function getRootId(): int
1166    {
1167        return (int)$this->rootId;
1168    }
1169
1170    /*******************************************************************
1171     *
1172     * Functions for creating links
1173     *
1174     *******************************************************************/
1175    /**
1176     * Adds the TypoScript from the global array.
1177     * The class property isDefaultTypoScriptAdded ensures
1178     * that the adding only happens once.
1179     *
1180     * @see isDefaultTypoScriptAdded
1181     */
1182    protected function addDefaultTypoScript()
1183    {
1184        // Add default TS for all code types, if not done already
1185        if (!$this->isDefaultTypoScriptAdded) {
1186            $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1187
1188            // adding constants from site settings
1189            $siteConstants = '';
1190            if ($this->getTypoScriptFrontendController() instanceof TypoScriptFrontendController) {
1191                $site = $this->getTypoScriptFrontendController()->getSite();
1192            } else {
1193                $currentPage = end($this->absoluteRootLine);
1194                try {
1195                    $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId((int)($currentPage['uid'] ?? 0));
1196                } catch (SiteNotFoundException $exception) {
1197                    $site = null;
1198                }
1199            }
1200            if ($site instanceof Site) {
1201                $siteSettings = $site->getConfiguration()['settings'] ?? [];
1202                if (!empty($siteSettings)) {
1203                    $siteSettings = ArrayUtility::flattenPlain($siteSettings);
1204                    foreach ($siteSettings as $k => $v) {
1205                        $siteConstants .= $k . ' = ' . $v . LF;
1206                    }
1207                }
1208            }
1209
1210            if ($siteConstants !== '') {
1211                // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1212                array_unshift($this->constants, $siteConstants);
1213                array_unshift($this->config, '');
1214                array_unshift($this->templateIncludePaths, '');
1215                // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1216                $defaultTemplateInfo = [
1217                    'root' => '',
1218                    'clConst' => '',
1219                    'clConf' => '',
1220                    'templateID' => '_siteConstants_',
1221                    'templateParent' => $rootTemplateId,
1222                    'title' => 'Site settings',
1223                    'uid' => '_siteConstants_',
1224                    'pid' => '',
1225                    'configLines' => 0,
1226                ];
1227                // push info to information arrays used in BE by TemplateTools (Analyzer)
1228                array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1229                array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1230                array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1231            }
1232
1233            // adding default setup and constants
1234            // defaultTypoScript_setup is *very* unlikely to be empty
1235            // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1236            array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1237            array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1238            array_unshift($this->templateIncludePaths, '');
1239            // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1240            $defaultTemplateInfo = [
1241                'root' => '',
1242                'clConst' => '',
1243                'clConf' => '',
1244                'templateID' => '_defaultTypoScript_',
1245                'templateParent' => $rootTemplateId,
1246                'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1247                'uid' => '_defaultTypoScript_',
1248                'pid' => '',
1249                'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1,
1250            ];
1251            // push info to information arrays used in BE by TemplateTools (Analyzer)
1252            array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1253            array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1254            array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1255
1256            $this->isDefaultTypoScriptAdded = true;
1257        }
1258    }
1259
1260    /**
1261     * @return TypoScriptFrontendController
1262     */
1263    protected function getTypoScriptFrontendController()
1264    {
1265        return $this->frontendController ?? $GLOBALS['TSFE'] ?? null;
1266    }
1267
1268    /**
1269     * @return TimeTracker
1270     */
1271    protected function getTimeTracker()
1272    {
1273        return GeneralUtility::makeInstance(TimeTracker::class);
1274    }
1275
1276    /**
1277     * Returns data stored for the hash string in the cache "cache_hash"
1278     * used to store the parsed TypoScript template structures.
1279     *
1280     * @param string $identifier The hash-string which was used to store the data value
1281     * @return mixed The data from the cache
1282     */
1283    protected function getCacheEntry($identifier)
1284    {
1285        return GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->get($identifier);
1286    }
1287
1288    /**
1289     * Stores $data in the 'hash' cache with the hash key $identifier
1290     *
1291     * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1292     * @param mixed $data The data to store
1293     * @param string $tag Is just a textual identification in order to inform about the content
1294     */
1295    protected function setCacheEntry($identifier, $data, $tag)
1296    {
1297        GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->set($identifier, $data, ['ident_' . $tag], 0);
1298    }
1299}
1300