1<?php
2namespace TYPO3\CMS\Core\TypoScript;
3
4/*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17use TYPO3\CMS\Backend\Utility\BackendUtility;
18use TYPO3\CMS\Core\Cache\CacheManager;
19use TYPO3\CMS\Core\Compatibility\PublicMethodDeprecationTrait;
20use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
21use TYPO3\CMS\Core\Context\Context;
22use TYPO3\CMS\Core\Database\Connection;
23use TYPO3\CMS\Core\Database\ConnectionPool;
24use TYPO3\CMS\Core\Database\Query\Restriction\AbstractRestrictionContainer;
25use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
26use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
27use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
28use TYPO3\CMS\Core\Package\PackageManager;
29use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
30use TYPO3\CMS\Core\Resource\Exception\InvalidFileException;
31use TYPO3\CMS\Core\Resource\Exception\InvalidFileNameException;
32use TYPO3\CMS\Core\Resource\Exception\InvalidPathException;
33use TYPO3\CMS\Core\TimeTracker\TimeTracker;
34use TYPO3\CMS\Core\Utility\ArrayUtility;
35use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
36use TYPO3\CMS\Core\Utility\GeneralUtility;
37use TYPO3\CMS\Core\Utility\HttpUtility;
38use TYPO3\CMS\Core\Utility\MathUtility;
39use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
40use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
41use TYPO3\CMS\Frontend\Page\PageRepository;
42use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
43
44/**
45 * Template object that is responsible for generating the TypoScript template based on template records.
46 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
47 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
48 */
49class TemplateService
50{
51    use PublicPropertyDeprecationTrait;
52    use PublicMethodDeprecationTrait;
53
54    /**
55     * Properties which have been moved to protected status from public
56     * @var array
57     */
58    protected $deprecatedPublicProperties = [
59        'matchAll' => 'Using $matchAll of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
60        'whereClause' => 'Using $whereClause of class TemplateService is discouraged, as this has been superseded by Doctrine DBAL API.',
61        'debug' => 'Using $debug of class TemplateService is discouraged, as this option has no effect anymore.',
62        'allowedPaths' => 'Using $allowedPaths of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
63        'simulationHiddenOrTime' => 'Using $simulationHiddenOrTime of class TemplateService is discouraged, as this has been superseeded by Doctrine DBAL API.',
64        'nextLevel' => 'Using $nextLevel of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
65        'rootId' => 'Using $rootId of class TemplateService from the outside is discouraged, use TemplateService->getRootId() instead.',
66        'absoluteRootLine' => 'Using $absoluteRootLine of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
67        'outermostRootlineIndexWithTemplate' => 'Using $outermostRootlineIndexWithTemplate of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
68        'rowSum' => 'Using $rowSum of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
69        'sitetitle' => 'Using $sitetitle of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
70        'sectionsMatch' => 'Using $sectionsMatch of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
71        'frames' => 'Using $frames of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
72        'MPmap' => 'Using $MPmap of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
73        'fileCache' => 'Using $fileCache of class TemplateService from the outside is discouraged, the property will be removed in TYPO3 v10.0.',
74    ];
75
76    /**
77     * Methods which have been moved to protected status from public
78     * @var array
79     */
80    protected $deprecatedPublicMethods = [
81        'prependStaticExtra' => 'Using prependStaticExtra() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
82        'versionOL' => 'Using versionOL() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
83        'processIncludes' => 'Using processIncludes() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
84        'mergeConstantsFromPageTSconfig' => 'Using mergeConstantsFromPageTSconfig() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
85        'flattenSetup' => 'Using flattenSetup() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
86        'substituteConstants' => 'Using substituteConstants() of class TemplateService from the outside is discouraged, as this method is only meant to be used internally.',
87    ];
88
89    /**
90     * option to enable logging, time-tracking (FE-only)
91     * usually, this is only done when
92     *  - in FE a BE_USER is logged-in
93     *  - in BE when the BE_USER needs information about the template (TypoScript module)
94     * @var bool
95     */
96    protected $verbose = false;
97
98    /**
99     * If set, the global tt-timeobject is used to log the performance.
100     *
101     * @var bool
102     */
103    public $tt_track = true;
104
105    /**
106     * If set, the template is always rendered. Used from Admin Panel.
107     *
108     * @var bool
109     */
110    public $forceTemplateParsing = false;
111
112    /**
113     * This array is passed on to matchObj by generateConfig().
114     * If it holds elements, they are used for matching instead. See comment at the match-class.
115     * Used for backend modules only. Never frontend!
116     *
117     * @var array
118     * @internal
119     */
120    public $matchAlternative = [];
121
122    /**
123     * If set, the match-class matches everything! Used for backend modules only. Never frontend!
124     *
125     * @var bool
126     */
127    protected $matchAll = false;
128
129    /**
130     * Externally set breakpoints (used by Backend Modules)
131     *
132     * @var int
133     */
134    public $ext_constants_BRP = 0;
135
136    /**
137     * @var int
138     */
139    public $ext_config_BRP = 0;
140
141    /**
142     * @var bool
143     */
144    public $ext_regLinenumbers = false;
145
146    /**
147     * @var bool
148     */
149    public $ext_regComments = false;
150
151    /**
152     * This MUST be initialized by the init() function
153     *
154     * @var string
155     */
156    protected $whereClause = '';
157
158    /**
159     * @var bool
160     */
161    protected $debug = false;
162
163    /**
164     * This is the only paths (relative!!) that are allowed for resources in TypoScript.
165     * Should all be appended with '/'. You can extend these by the global array TYPO3_CONF_VARS. See init() function.
166     *
167     * @var array
168     */
169    protected $allowedPaths = [];
170
171    /**
172     * See init(); Set if preview of some kind is enabled.
173     *
174     * @var int
175     */
176    protected $simulationHiddenOrTime = 0;
177
178    /**
179     * Set, if the TypoScript template structure is loaded and OK, see ->start()
180     *
181     * @var bool
182     */
183    public $loaded = false;
184
185    /**
186     * @var array Contains TypoScript setup part after parsing
187     */
188    public $setup = [];
189
190    /**
191     * @var array
192     */
193    public $flatSetup = [];
194
195    /**
196     * For fetching TypoScript code from template hierarchy before parsing it.
197     * Each array contains code field values from template records/files:
198     * Setup field
199     *
200     * @var array
201     */
202    public $config = [];
203
204    /**
205     * Constant field
206     *
207     * @var array
208     */
209    public $constants = [];
210
211    /**
212     * Holds the include paths of the templates (empty if from database)
213     *
214     * @var array
215     */
216    protected $templateIncludePaths = [];
217
218    /**
219     * For Template Analyzer in backend
220     *
221     * @var array
222     */
223    public $hierarchyInfo = [];
224
225    /**
226     * For Template Analyzer in backend (setup content only)
227     *
228     * @var array
229     */
230    protected $hierarchyInfoToRoot = [];
231
232    /**
233     * Next-level flag (see runThroughTemplates())
234     *
235     * @var int
236     */
237    protected $nextLevel = 0;
238
239    /**
240     * The Page UID of the root page
241     *
242     * @var int
243     */
244    protected $rootId;
245
246    /**
247     * The rootline from current page to the root page
248     *
249     * @var array
250     */
251    public $rootLine;
252
253    /**
254     * Rootline all the way to the root. Set but runThroughTemplates
255     *
256     * @var array
257     */
258    protected $absoluteRootLine;
259
260    /**
261     * A pointer to the last entry in the rootline where a template was found.
262     *
263     * @var int
264     */
265    protected $outermostRootlineIndexWithTemplate = 0;
266
267    /**
268     * Array of arrays with title/uid of templates in hierarchy
269     *
270     * @var array
271     */
272    protected $rowSum;
273
274    /**
275     * The current site title field.
276     *
277     * @var string
278     */
279    protected $sitetitle = '';
280
281    /**
282     * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
283     *
284     * @var array|null
285     */
286    public $sections;
287
288    /**
289     * Tracking all matching conditions found
290     *
291     * @var array
292     */
293    protected $sectionsMatch;
294
295    /**
296     * Used by Backend only (Typoscript Template Analyzer)
297     */
298    public $clearList_const = [];
299
300    /**
301     * Used by Backend only (Typoscript Template Analyzer)
302     *
303     * @var array
304     */
305    public $clearList_setup = [];
306
307    /**
308     * @var array
309     */
310    public $parserErrors = [];
311
312    /**
313     * @var array
314     */
315    public $setup_constants = [];
316
317    /**
318     * Used by getFileName for caching of references to file resources
319     *
320     * @var array
321     * @deprecated Will be removed in TYPO3 v10.0
322     */
323    protected $fileCache = [];
324
325    /**
326     * Keys are frame names and values are type-values, which must be used to refer correctly to the content of the frames.
327     *
328     * @var array
329     */
330    protected $frames = [];
331
332    /**
333     * Contains mapping of Page id numbers to MP variables.
334     * This is not used anymore, and will be removed in TYPO3 v10.0.
335     *
336     * @var string
337     */
338    protected $MPmap = '';
339
340    /**
341     * Indicator that extension statics are processed.
342     *
343     * These files are considered if either a root template
344     * has been processed or the $processExtensionStatics
345     * property has been set to TRUE.
346     *
347     * @var bool
348     */
349    protected $extensionStaticsProcessed = false;
350
351    /**
352     * Trigger value, to ensure that extension statics are processed.
353     *
354     * @var bool
355     */
356    protected $processExtensionStatics = false;
357
358    /**
359     * Set to TRUE after the default TypoScript was added during parsing.
360     * This prevents double inclusion of the same TypoScript code.
361     *
362     * @see addDefaultTypoScript()
363     * @var bool
364     */
365    protected $isDefaultTypoScriptAdded = false;
366
367    /**
368     * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
369     *
370     * This prevents double processing of INCLUDES.
371     *
372     * @see processIncludes()
373     * @var bool
374     */
375    protected $processIncludesHasBeenRun = false;
376
377    /**
378     * Contains the restrictions about deleted, and some frontend related topics
379     * @var AbstractRestrictionContainer
380     */
381    protected $queryBuilderRestrictions;
382
383    /**
384     * @var Context
385     */
386    protected $context;
387
388    /**
389     * @var PackageManager
390     */
391    protected $packageManager;
392
393    /**
394     * @param Context|null $context
395     * @param PackageManager|null $packageManager
396     */
397    public function __construct(Context $context = null, PackageManager $packageManager = null)
398    {
399        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
400        $this->packageManager = $packageManager ?? GeneralUtility::makeInstance(PackageManager::class);
401        $this->initializeDatabaseQueryRestrictions();
402        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
403            // Set the simulation flag, if simulation is detected!
404            $this->simulationHiddenOrTime = 1;
405        }
406
407        // Sets the paths from where TypoScript resources are allowed to be used:
408        $this->allowedPaths = [
409            $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
410            // fileadmin/ path
411            'uploads/',
412            'typo3temp/',
413            TYPO3_mainDir . 'ext/',
414            TYPO3_mainDir . 'sysext/',
415            'typo3conf/ext/'
416        ];
417        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
418            $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], true);
419            foreach ($pathArr as $p) {
420                // Once checked for path, but as this may run from typo3/mod/web/ts/ dir, that'll not work!! So the paths ar uncritically included here.
421                $this->allowedPaths[] = $p;
422            }
423        }
424
425        $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
426    }
427
428    /**
429     * @return bool
430     */
431    public function getProcessExtensionStatics()
432    {
433        return $this->processExtensionStatics;
434    }
435
436    /**
437     * @param bool $processExtensionStatics
438     */
439    public function setProcessExtensionStatics($processExtensionStatics)
440    {
441        $this->processExtensionStatics = (bool)$processExtensionStatics;
442    }
443
444    /**
445     * sets the verbose parameter
446     * @param bool $verbose
447     */
448    public function setVerbose($verbose)
449    {
450        $this->verbose = (bool)$verbose;
451    }
452
453    /**
454     * Initialize
455     *
456     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0
457     */
458    public function init()
459    {
460        trigger_error('TemplateService->init() will be removed in TYPO3 v10.0, __construct() does the job.', E_USER_DEPRECATED);
461        $this->initializeDatabaseQueryRestrictions();
462        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
463            // Set the simulation flag, if simulation is detected!
464            $this->simulationHiddenOrTime = 1;
465        }
466
467        // Sets the paths from where TypoScript resources are allowed to be used:
468        $this->allowedPaths = [
469            $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
470            // fileadmin/ path
471            'uploads/',
472            'typo3temp/',
473            TYPO3_mainDir . 'ext/',
474            TYPO3_mainDir . 'sysext/',
475            'typo3conf/ext/'
476        ];
477        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
478            $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], true);
479            foreach ($pathArr as $p) {
480                // Once checked for path, but as this may run from typo3/mod/web/ts/ dir, that'll not work!! So the paths ar uncritically included here.
481                $this->allowedPaths[] = $p;
482            }
483        }
484    }
485
486    /**
487     * $this->whereclause is kept for backwards compatibility
488     */
489    protected function initializeDatabaseQueryRestrictions()
490    {
491        $includeHiddenRecords = $this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false);
492        // $this->whereClause is used only to select templates from sys_template.
493        // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
494        $this->whereClause = 'AND deleted=0 ';
495        if (!$includeHiddenRecords) {
496            $this->whereClause .= 'AND hidden=0 ';
497        }
498        $this->whereClause .= 'AND (starttime<=' . $GLOBALS['SIM_ACCESS_TIME'] . ') AND (endtime=0 OR endtime>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
499
500        // set up the query builder restrictions
501        $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
502
503        if ($includeHiddenRecords) {
504            $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
505        }
506    }
507
508    /**
509     * Fetches the "currentPageData" array from cache
510     *
511     * NOTE about currentPageData:
512     * It holds information about the TypoScript conditions along with the list
513     * of template uid's which is used on the page. In the getFromCache() function
514     * in TSFE, currentPageData is used to evaluate if there is a template and
515     * if the matching conditions are alright. Unfortunately this does not take
516     * into account if the templates in the rowSum of currentPageData has
517     * changed composition, eg. due to hidden fields or start/end time. So if a
518     * template is hidden or times out, it'll not be discovered unless the page
519     * is regenerated - at least the this->start function must be called,
520     * because this will make a new portion of data in currentPageData string.
521     *
522     * @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
523     * @internal
524     */
525    public function getCurrentPageData()
526    {
527        return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection')->get((int)$this->getTypoScriptFrontendController()->id . '_' . GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP));
528    }
529
530    /**
531     * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
532     *
533     * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
534     * @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.
535     */
536    public function matching($cc)
537    {
538        if (is_array($cc['all'])) {
539            /** @var ConditionMatcher $matchObj */
540            $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
541            $matchObj->setRootline((array)$cc['rootLine']);
542            $sectionsMatch = [];
543            foreach ($cc['all'] as $key => $pre) {
544                if ($matchObj->match($pre)) {
545                    $sectionsMatch[$key] = $pre;
546                }
547            }
548            $cc['match'] = $sectionsMatch;
549        }
550        return $cc;
551    }
552
553    /**
554     * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
555     * 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.
556     * Sets $this->setup to the parsed TypoScript template array
557     *
558     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
559     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
560     */
561    public function start($theRootLine)
562    {
563        if (is_array($theRootLine)) {
564            $constantsData = [];
565            $setupData = [];
566            $cacheIdentifier = '';
567            // Flag that indicates that the existing data in cache_pagesection
568            // could be used (this is the case if $TSFE->all is set, and the
569            // rowSum still matches). Based on this we decide if cache_pagesection
570            // needs to be updated...
571            $isCached = false;
572            $this->runThroughTemplates($theRootLine);
573            if ($this->getTypoScriptFrontendController()->all) {
574                $cc = $this->getTypoScriptFrontendController()->all;
575                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
576                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
577                    unset($cc);
578                } else {
579                    // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
580                    if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
581                        $isCached = true;
582                    }
583                    // 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)...
584                    unset($cc['rootLine']);
585                }
586            }
587            // This is about getting the hash string which is used to fetch the cached TypoScript template.
588            // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
589            if (isset($cc) && is_array($cc)) {
590                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
591                if (!$cc['match']) {
592                    // @todo check if this can ever be the case - otherwise remove
593                    $cc = $this->matching($cc);
594                    ksort($cc);
595                }
596                $cacheIdentifier = md5(serialize($cc));
597            } else {
598                // 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.
599                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
600                $result = $this->getCacheEntry($rowSumHash);
601                if (is_array($result)) {
602                    $cc = [];
603                    $cc['all'] = $result;
604                    $cc['rowSum'] = $this->rowSum;
605                    $cc = $this->matching($cc);
606                    ksort($cc);
607                    $cacheIdentifier = md5(serialize($cc));
608                }
609            }
610            if ($cacheIdentifier) {
611                // Get TypoScript setup array
612                $cachedData = $this->getCacheEntry($cacheIdentifier);
613                if (is_array($cachedData)) {
614                    $constantsData = $cachedData['constants'];
615                    $setupData = $cachedData['setup'];
616                }
617            }
618            if (!empty($setupData) && !$this->forceTemplateParsing) {
619                // TypoScript constants + setup are found in the cache
620                $this->setup_constants = $constantsData;
621                $this->setup = $setupData;
622                if ($this->tt_track) {
623                    $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
624                }
625            } else {
626                if ($this->tt_track) {
627                    $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
628                }
629
630                // Make configuration
631                $this->generateConfig();
632                // This stores the template hash thing
633                $cc = [];
634                // All sections in the template at this point is found
635                $cc['all'] = $this->sections;
636                // The line of templates is collected
637                $cc['rowSum'] = $this->rowSum;
638                $cc = $this->matching($cc);
639                ksort($cc);
640                $cacheIdentifier = md5(serialize($cc));
641                // This stores the data.
642                $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
643                if ($this->tt_track) {
644                    $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
645                }
646                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
647                $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
648            }
649            // Add rootLine
650            $cc['rootLine'] = $this->rootLine;
651            ksort($cc);
652            // Make global and save
653            $this->getTypoScriptFrontendController()->all = $cc;
654            // Matching must be executed for every request, so this must never be part of the pagesection cache!
655            unset($cc['match']);
656            if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
657                // Only save the data if we're not simulating by hidden/starttime/endtime
658                $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
659                /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
660                $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection');
661                $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
662                    'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
663                    'mpvarHash_' . $mpvarHash
664                ]);
665            }
666            // If everything OK.
667            if ($this->rootId && $this->rootLine && $this->setup) {
668                $this->loaded = true;
669            }
670        }
671    }
672
673    /*******************************************************************
674     *
675     * Fetching TypoScript code text for the Template Hierarchy
676     *
677     *******************************************************************/
678    /**
679     * 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.
680     * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
681     * 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
682     *
683     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
684     * @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)
685     * @see start()
686     */
687    public function runThroughTemplates($theRootLine, $start_template_uid = 0)
688    {
689        $this->constants = [];
690        $this->config = [];
691        $this->rowSum = [];
692        $this->hierarchyInfoToRoot = [];
693        $this->absoluteRootLine = $theRootLine;
694        $this->isDefaultTypoScriptAdded = false;
695
696        reset($this->absoluteRootLine);
697        $c = count($this->absoluteRootLine);
698        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
699        for ($a = 0; $a < $c; $a++) {
700            // If some template loaded before has set a template-id for the next level, then load this template first!
701            if ($this->nextLevel) {
702                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
703                $queryResult = $queryBuilder
704                    ->select('*')
705                    ->from('sys_template')
706                    ->where(
707                        $queryBuilder->expr()->eq(
708                            'uid',
709                            $queryBuilder->createNamedParameter($this->nextLevel, \PDO::PARAM_INT)
710                        )
711                    )
712                    ->execute();
713                $this->nextLevel = 0;
714                if ($row = $queryResult->fetch()) {
715                    $this->versionOL($row);
716                    if (is_array($row)) {
717                        $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
718                        $this->outermostRootlineIndexWithTemplate = $a;
719                    }
720                }
721            }
722
723            $where = [
724                $queryBuilder->expr()->eq(
725                    'pid',
726                    $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
727                )
728            ];
729            // If first loop AND there is set an alternative template uid, use that
730            if ($a === $c - 1 && $start_template_uid) {
731                $where[] = $queryBuilder->expr()->eq(
732                    'uid',
733                    $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
734                );
735            }
736            $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
737            $queryResult = $queryBuilder
738                ->select('*')
739                ->from('sys_template')
740                ->where(...$where)
741                ->orderBy('root', 'DESC')
742                ->addOrderBy('sorting')
743                ->setMaxResults(1)
744                ->execute();
745            if ($row = $queryResult->fetch()) {
746                $this->versionOL($row);
747                if (is_array($row)) {
748                    $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
749                    $this->outermostRootlineIndexWithTemplate = $a;
750                }
751            }
752            $this->rootLine[] = $this->absoluteRootLine[$a];
753        }
754
755        // Hook into the default TypoScript to add custom typoscript logic
756        $hookParameters = [
757            'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
758            'isDefaultTypoScriptAdded'  => &$this->isDefaultTypoScriptAdded,
759            'absoluteRootLine' => &$this->absoluteRootLine,
760            'rootLine'         => &$this->rootLine,
761            'startTemplateUid' => $start_template_uid,
762        ];
763        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
764            GeneralUtility::callUserFunction($listener, $hookParameters, $this);
765        }
766
767        // Process extension static files if not done yet, but explicitly requested
768        if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
769            $this->addExtensionStatics('sys_0', 'sys_0', 0);
770        }
771
772        // Add the global default TypoScript from the TYPO3_CONF_VARS
773        $this->addDefaultTypoScript();
774
775        $this->processIncludes();
776    }
777
778    /**
779     * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
780     * Builds up $this->rowSum
781     *
782     * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
783     * @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.
784     * @param int $pid The PID of the input template record
785     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
786     * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
787     * @param string $includePath Specifies the path from which the template was included (used with static_includes)
788     * @see runThroughTemplates()
789     */
790    public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
791    {
792        // Adding basic template record information to rowSum array
793        $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
794        // Processing "Clear"-flags
795        $clConst = 0;
796        $clConf = 0;
797        if (!empty($row['clear'])) {
798            $clConst = $row['clear'] & 1;
799            $clConf = $row['clear'] & 2;
800            if ($clConst) {
801                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
802                foreach ($this->constants as &$constantConfiguration) {
803                    $constantConfiguration = '';
804                }
805                unset($constantConfiguration);
806                $this->clearList_const = [];
807            }
808            if ($clConf) {
809                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
810                foreach ($this->config as &$configConfiguration) {
811                    $configConfiguration = '';
812                }
813                unset($configConfiguration);
814                $this->hierarchyInfoToRoot = [];
815                $this->clearList_setup = [];
816            }
817        }
818        // Include files (from extensions) (#1/2)
819        // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
820        if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
821            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
822        }
823        // Include "Based On" sys_templates:
824        // 'basedOn' is a list of templates to include
825        if (trim($row['basedOn'] ?? '')) {
826            // Normal Operation, which is to include the "based-on" sys_templates,
827            // if they are not already included, and maintaining the sorting of the templates
828            $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
829            // skip template if it's already included
830            foreach ($basedOnIds as $key => $basedOnId) {
831                if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
832                    unset($basedOnIds[$key]);
833                }
834            }
835            if (!empty($basedOnIds)) {
836                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
837                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
838                $queryResult = $queryBuilder
839                    ->select('*')
840                    ->from('sys_template')
841                    ->where(
842                        $queryBuilder->expr()->in(
843                            'uid',
844                            $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
845                        )
846                    )
847                    ->execute();
848                // make it an associative array with the UID as key
849                $subTemplates = [];
850                while ($rowItem = $queryResult->fetch()) {
851                    $subTemplates[(int)$rowItem['uid']] = $rowItem;
852                }
853                // Traversing list again to ensure the sorting of the templates
854                foreach ($basedOnIds as $id) {
855                    if (is_array($subTemplates[$id])) {
856                        $this->versionOL($subTemplates[$id]);
857                        $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
858                    }
859                }
860            }
861        }
862        // Include files (from extensions) (#2/2)
863        if (!empty($row['includeStaticAfterBasedOn'])) {
864            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
865        }
866        // Creating hierarchy information; Used by backend analysis tools
867        $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
868            'root' => trim($row['root'] ?? ''),
869            'next' => $row['nextLevel'] ?? null,
870            'clConst' => $clConst,
871            'clConf' => $clConf,
872            'templateID' => $templateID,
873            'templateParent' => $templateParent,
874            'title' => $row['title'],
875            'uid' => $row['uid'],
876            'pid' => $row['pid'] ?? null,
877            'configLines' => substr_count($row['config'], LF) + 1
878        ]);
879        // Adding the content of the fields constants (Constants) and config (Setup)
880        $this->constants[] = $row['constants'];
881        $this->config[] = $row['config'];
882        $this->templateIncludePaths[] = $includePath;
883        // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
884        $this->clearList_const[] = $templateID;
885        $this->clearList_setup[] = $templateID;
886        if (trim($row['sitetitle'] ?? null)) {
887            $this->sitetitle = $row['sitetitle'];
888        }
889        // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
890        if (trim($row['root'] ?? null)) {
891            $this->rootId = $pid;
892            $this->rootLine = [];
893        }
894        // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
895        if ($row['nextLevel'] ?? null) {
896            $this->nextLevel = $row['nextLevel'];
897        } else {
898            $this->nextLevel = 0;
899        }
900    }
901
902    /**
903     * This function can be used to update the data of the current rootLine
904     * e.g. when a different language is used.
905     *
906     * This function must not be used if there are different pages in the
907     * rootline as before!
908     *
909     * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
910     * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
911     */
912    public function updateRootlineData($fullRootLine)
913    {
914        if (!is_array($this->rootLine) || empty($this->rootLine)) {
915            return;
916        }
917
918        $fullRootLineByUid = [];
919        foreach ($fullRootLine as $rootLineData) {
920            $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
921        }
922
923        foreach ($this->rootLine as $level => $dataArray) {
924            $currentUid = $dataArray['uid'];
925
926            if (!array_key_exists($currentUid, $fullRootLineByUid)) {
927                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);
928            }
929
930            $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
931        }
932    }
933
934    /**
935     * Includes static template files (from extensions) for the input template record row.
936     *
937     * @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.
938     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
939     * @param int $pid The PID of the input template record
940     * @param array $row A full TypoScript template record
941     * @see processTemplate()
942     * @internal
943     */
944    public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
945    {
946        // Call function for link rendering:
947        $_params = [
948            'idList' => &$idList,
949            'templateId' => &$templateID,
950            'pid' => &$pid,
951            'row' => &$row
952        ];
953        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
954            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
955        }
956        // If "Include before all static templates if root-flag is set" is set:
957        $staticFileMode = $row['static_file_mode'] ?? null;
958        if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
959            $this->addExtensionStatics($idList, $templateID, $pid);
960        }
961        // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
962        if (trim($row['include_static_file'] ?? '')) {
963            $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
964            // Traversing list
965            foreach ($include_static_fileArr as $ISF_file) {
966                if (strpos($ISF_file, 'EXT:') === 0) {
967                    list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
968                    if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
969                        $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
970                        $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
971                        if (@is_dir($ISF_filePath)) {
972                            $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
973                            $subrow = [
974                                'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
975                                'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
976                                'include_static' => @file_exists($ISF_filePath . 'include_static.txt') ? implode(',', array_unique(GeneralUtility::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
977                                'include_static_file' => @file_exists($ISF_filePath . 'include_static_file.txt') ? implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
978                                'title' => $ISF_file,
979                                'uid' => $mExtKey
980                            ];
981                            $subrow = $this->prependStaticExtra($subrow);
982                            $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
983                        }
984                    }
985                }
986            }
987        }
988        // If "Default (include before if root flag is set)" is set OR
989        // "Always include before this template record" AND root-flag are set
990        if ($staticFileMode == 1 || $staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
991            $this->addExtensionStatics($idList, $templateID, $pid);
992        }
993        // Include Static Template Records after all other TypoScript has been included.
994        $_params = [
995            'idList' => &$idList,
996            'templateId' => &$templateID,
997            'pid' => &$pid,
998            'row' => &$row
999        ];
1000        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
1001            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1002        }
1003    }
1004
1005    /**
1006     * Retrieves the content of the first existing file by extension order.
1007     * Returns the empty string if no file is found.
1008     *
1009     * @param string $filePath The location of the file.
1010     * @param string $baseName The base file name. "constants" or "setup".
1011     * @return string
1012     */
1013    protected function getTypoScriptSourceFileContent($filePath, $baseName)
1014    {
1015        $extensions = ['.typoscript', '.ts', '.txt'];
1016        foreach ($extensions as $extension) {
1017            $fileName = $filePath . $baseName . $extension;
1018            if (@file_exists($fileName)) {
1019                return file_get_contents($fileName);
1020            }
1021        }
1022        return '';
1023    }
1024
1025    /**
1026     * Adds the default TypoScript files for extensions if any.
1027     *
1028     * @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.
1029     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
1030     * @param int $pid The PID of the input template record
1031     * @internal
1032     * @see includeStaticTypoScriptSources()
1033     */
1034    public function addExtensionStatics($idList, $templateID, $pid)
1035    {
1036        $this->extensionStaticsProcessed = true;
1037
1038        foreach ($this->packageManager->getActivePackages() as $package) {
1039            $extKey = $package->getPackageKey();
1040            $packagePath = $package->getPackagePath();
1041            $filesToCheck = [
1042                'ext_typoscript_constants.txt',
1043                'ext_typoscript_constants.typoscript',
1044                'ext_typoscript_setup.txt',
1045                'ext_typoscript_setup.typoscript',
1046            ];
1047            $files = [];
1048            $hasExtensionStatics = false;
1049            foreach ($filesToCheck as $file) {
1050                $path = $packagePath . $file;
1051                if (@file_exists($path)) {
1052                    $files[$file] = $path;
1053                    $hasExtensionStatics = true;
1054                } else {
1055                    $files[$file] = null;
1056                }
1057            }
1058
1059            if ($hasExtensionStatics) {
1060                $mExtKey = str_replace('_', '', $extKey);
1061                $constants = '';
1062                $config = '';
1063
1064                if (!empty($files['ext_typoscript_constants.typoscript'])) {
1065                    $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
1066                } elseif (!empty($files['ext_typoscript_constants.txt'])) {
1067                    $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
1068                }
1069
1070                if (!empty($files['ext_typoscript_setup.typoscript'])) {
1071                    $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
1072                } elseif (!empty($files['ext_typoscript_setup.txt'])) {
1073                    $config = @file_get_contents($files['ext_typoscript_setup.txt']);
1074                }
1075
1076                $this->processTemplate(
1077                    $this->prependStaticExtra([
1078                        'constants' => $constants,
1079                        'config' => $config,
1080                        'title' => $extKey,
1081                        'uid' => $mExtKey
1082                    ]),
1083                    $idList . ',ext_' . $mExtKey,
1084                    $pid,
1085                    'ext_' . $mExtKey,
1086                    $templateID,
1087                    $packagePath
1088                );
1089            }
1090        }
1091    }
1092
1093    /**
1094     * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
1095     * 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
1096     *
1097     * @param array $subrow Static template record/file
1098     * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
1099     * @see addExtensionStatics(), includeStaticTypoScriptSources()
1100     */
1101    protected function prependStaticExtra($subrow)
1102    {
1103        // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
1104        $identifier = $subrow['uid'];
1105        $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null;
1106        $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null;
1107        // 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
1108        if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
1109            $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
1110            $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
1111        }
1112        return $subrow;
1113    }
1114
1115    /**
1116     * Creating versioning overlay of a sys_template record.
1117     * This will use either frontend or backend overlay functionality depending on environment.
1118     *
1119     * @param array $row Row to overlay (passed by reference)
1120     */
1121    protected function versionOL(&$row)
1122    {
1123        // Distinguish frontend and backend call:
1124        // To do the fronted call a full frontend is required, just checking for
1125        // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
1126        // eId scripts that run in frontend scope, but do not have a full blown frontend.
1127        if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
1128            // Frontend
1129            $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
1130        } else {
1131            // Backend
1132            BackendUtility::workspaceOL('sys_template', $row);
1133        }
1134    }
1135
1136    /*******************************************************************
1137     *
1138     * Parsing TypoScript code text from Template Records into PHP array
1139     *
1140     *******************************************************************/
1141    /**
1142     * Generates the configuration array by replacing constants and parsing the whole thing.
1143     * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
1144     *
1145     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
1146     */
1147    public function generateConfig()
1148    {
1149        // Add default TS for all code types
1150        $this->addDefaultTypoScript();
1151
1152        // Parse the TypoScript code text for include-instructions!
1153        $this->processIncludes();
1154        // These vars are also set lateron...
1155        $this->setup['sitetitle'] = $this->sitetitle;
1156        // ****************************
1157        // Parse TypoScript Constants
1158        // ****************************
1159        // Initialize parser and match-condition classes:
1160        /** @var Parser\TypoScriptParser $constants */
1161        $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1162        $constants->breakPointLN = (int)$this->ext_constants_BRP;
1163        $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1164        /** @var ConditionMatcher $matchObj */
1165        $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1166        $matchObj->setSimulateMatchConditions($this->matchAlternative);
1167        $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1168        // Traverse constants text fields and parse them
1169        foreach ($this->constants as $str) {
1170            $constants->parse($str, $matchObj);
1171        }
1172        // Read out parse errors if any
1173        $this->parserErrors['constants'] = $constants->errors;
1174        // 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)
1175        $this->flatSetup = [];
1176        $this->flattenSetup($constants->setup, '');
1177        // ***********************************************
1178        // Parse TypoScript Setup (here called "config")
1179        // ***********************************************
1180        // Initialize parser and match-condition classes:
1181        /** @var Parser\TypoScriptParser $config */
1182        $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1183        $config->breakPointLN = (int)$this->ext_config_BRP;
1184        $config->regLinenumbers = $this->ext_regLinenumbers;
1185        $config->regComments = $this->ext_regComments;
1186        $config->setup = $this->setup;
1187        // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1188        $config->sections = $constants->sections;
1189        $config->sectionsMatch = $constants->sectionsMatch;
1190        // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1191        $all = '';
1192        foreach ($this->config as $str) {
1193            $all .= '
1194[GLOBAL]
1195' . $str;
1196        }
1197        // Substitute constants in the Setup code:
1198        if ($this->tt_track) {
1199            $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1200        }
1201        $all = $this->substituteConstants($all);
1202        if ($this->tt_track) {
1203            $this->getTimeTracker()->pull();
1204        }
1205
1206        // Searching for possible unsubstituted constants left (only for information)
1207        if ($this->verbose) {
1208            if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1209                if ($this->tt_track) {
1210                    $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1211                }
1212            }
1213        }
1214
1215        // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1216        if ($this->tt_track) {
1217            $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1218        }
1219        // Finally parse the Setup field TypoScript code (where constants are now substituted)
1220        $config->parse($all, $matchObj);
1221        // Read out parse errors if any
1222        $this->parserErrors['config'] = $config->errors;
1223        // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1224        $this->setup = $config->setup;
1225        // Do the same for the constants
1226        $this->setup_constants = $constants->setup;
1227        // ****************************************************************
1228        // Final processing of the $this->setup TypoScript Template array
1229        // Basically: This is unsetting/setting of certain reserved keys.
1230        // ****************************************************************
1231        // 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!
1232        unset($this->setup['sitetitle']);
1233        unset($this->setup['sitetitle.']);
1234        $this->setup['sitetitle'] = $this->sitetitle;
1235        // Unsetting some vars...
1236        unset($this->setup['types.']);
1237        unset($this->setup['types']);
1238        if (is_array($this->setup)) {
1239            foreach ($this->setup as $key => $value) {
1240                if ($value === 'PAGE') {
1241                    // Set the typeNum of the current page object:
1242                    if (isset($this->setup[$key . '.']['typeNum'])) {
1243                        $typeNum = $this->setup[$key . '.']['typeNum'];
1244                        $this->setup['types.'][$typeNum] = $key;
1245                    } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1246                        $this->setup['types.'][0] = $key;
1247                    }
1248                }
1249            }
1250        }
1251        unset($this->setup['temp.']);
1252        unset($constants);
1253        // Storing the conditions found/matched information:
1254        $this->sections = $config->sections;
1255        $this->sectionsMatch = $config->sectionsMatch;
1256    }
1257
1258    /**
1259     * Searching TypoScript code text (for constants and config (Setup))
1260     * for include instructions and does the inclusion of external TypoScript files
1261     * if needed.
1262     *
1263     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1264     */
1265    protected function processIncludes()
1266    {
1267        if ($this->processIncludesHasBeenRun) {
1268            return;
1269        }
1270
1271        $paths = $this->templateIncludePaths;
1272        $files = [];
1273        foreach ($this->constants as &$value) {
1274            $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1275            $files = array_merge($files, $includeData['files']);
1276            $value = $includeData['typoscript'];
1277        }
1278        unset($value);
1279        $paths = $this->templateIncludePaths;
1280        foreach ($this->config as &$value) {
1281            $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1282            $files = array_merge($files, $includeData['files']);
1283            $value = $includeData['typoscript'];
1284        }
1285        unset($value);
1286
1287        if (!empty($files)) {
1288            $files = array_unique($files);
1289            foreach ($files as $file) {
1290                $this->rowSum[] = [$file, filemtime($file)];
1291            }
1292        }
1293
1294        $this->processIncludesHasBeenRun = true;
1295    }
1296
1297    /**
1298     * Loads Page TSconfig until the outermost template record and parses the configuration - if TSFE.constants object path is found it is merged with the default data in here!
1299     *
1300     * @param array $constArray Constants array, default input.
1301     * @return array Constants array, modified
1302     * @todo Apply caching to the parsed Page TSconfig. This is done in the other similar functions for both frontend and backend. However, since this functions works for BOTH frontend and backend we will have to either write our own local caching function or (more likely) detect if we are in FE or BE and use caching functions accordingly. Not having caching affects mostly the backend modules inside the "Template" module since the overhead in the frontend is only seen when TypoScript templates are parsed anyways (after which point they are cached anyways...)
1303     */
1304    protected function mergeConstantsFromPageTSconfig($constArray)
1305    {
1306        $TSdataArray = [];
1307        // Setting default configuration:
1308        $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1309        for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1310            if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1311                $includeTsConfigFileList = GeneralUtility::trimExplode(
1312                    ',',
1313                    $this->absoluteRootLine[$a]['tsconfig_includes'],
1314                    true
1315                );
1316
1317                $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1318            }
1319            $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1320        }
1321        // Parsing the user TS (or getting from cache)
1322        $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1323        $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1324        /** @var Parser\TypoScriptParser $parseObj */
1325        $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1326        $parseObj->parse($userTS);
1327        if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1328            ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1329        }
1330
1331        return $constArray;
1332    }
1333
1334    /**
1335     * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1336     *
1337     * @param array $filesToInclude The files to read constants from
1338     * @param array $TSdataArray The TSconfig array the constants should be appended to
1339     * @return array The TSconfig with the included constants appended
1340     */
1341    protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1342    {
1343        foreach ($filesToInclude as $key => $file) {
1344            if (strpos($file, 'EXT:') !== 0) {
1345                continue;
1346            }
1347
1348            list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1349
1350            if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1351                continue;
1352            }
1353            if ((string)$filePath == '') {
1354                continue;
1355            }
1356
1357            $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1358            if (file_exists($tsConfigFile)) {
1359                $TSdataArray[] = file_get_contents($tsConfigFile);
1360            }
1361        }
1362
1363        return $TSdataArray;
1364    }
1365
1366    /**
1367     * This flattens a hierarchical TypoScript array to $this->flatSetup
1368     *
1369     * @param array $setupArray TypoScript array
1370     * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1371     * @see generateConfig()
1372     */
1373    protected function flattenSetup($setupArray, $prefix)
1374    {
1375        if (is_array($setupArray)) {
1376            foreach ($setupArray as $key => $val) {
1377                if (is_array($val)) {
1378                    $this->flattenSetup($val, $prefix . $key);
1379                } else {
1380                    $this->flatSetup[$prefix . $key] = $val;
1381                }
1382            }
1383        }
1384    }
1385
1386    /**
1387     * Substitutes the constants from $this->flatSetup in the text string $all
1388     *
1389     * @param string $all TypoScript code text string
1390     * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1391     * @see generateConfig(), flattenSetup()
1392     */
1393    protected function substituteConstants($all)
1394    {
1395        if ($this->tt_track) {
1396            $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1397        }
1398        $noChange = false;
1399        // Recursive substitution of constants (up to 10 nested levels)
1400        for ($i = 0; $i < 10 && !$noChange; $i++) {
1401            $old_all = $all;
1402            $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1403            if ($old_all == $all) {
1404                $noChange = true;
1405            }
1406        }
1407        return $all;
1408    }
1409
1410    /**
1411     * Call back method for preg_replace_callback in substituteConstants
1412     *
1413     * @param array $matches Regular expression matches
1414     * @return string Replacement
1415     * @see substituteConstants()
1416     * @internal
1417     */
1418    public function substituteConstantsCallBack($matches)
1419    {
1420        // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1421        return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1422    }
1423
1424    /*******************************************************************
1425     *
1426     * Various API functions, used from elsewhere in the frontend classes
1427     *
1428     *******************************************************************/
1429
1430    /**
1431     * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1432     *
1433     * @param string $fileFromSetup TypoScript "resource" data type value.
1434     * @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
1435     * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0.
1436     */
1437    public function getFileName($fileFromSetup)
1438    {
1439        trigger_error('TemplateService->getFileName() will be removed in TYPO3 v10.0. Use FilePathSanitizer->sanitize() of EXT:frontend instead.', E_USER_DEPRECATED);
1440        try {
1441            $file = GeneralUtility::makeInstance(FilePathSanitizer::class)->sanitize((string)$fileFromSetup);
1442            $hash = md5($file);
1443            if (!isset($this->fileCache[$hash])) {
1444                $this->fileCache[$hash] = $file;
1445            }
1446            return $file;
1447        } catch (InvalidFileNameException $e) {
1448            // Empty file name
1449        } catch (InvalidPathException $e) {
1450            if ($this->tt_track) {
1451                $this->getTimeTracker()->setTSlogMessage('File path "' . $fileFromSetup . '" contained illegal string "../"!', 3);
1452            }
1453        } catch (FileDoesNotExistException $e) {
1454            if ($this->tt_track) {
1455                $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1456            }
1457        } catch (InvalidFileException $e) {
1458            if ($this->tt_track) {
1459                $this->getTimeTracker()->setTSlogMessage('"' . $fileFromSetup . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1460            }
1461        }
1462        return null;
1463    }
1464
1465    /**
1466     * Compiles the content for the page <title> tag.
1467     *
1468     * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1469     * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1470     * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1471     * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
1472     * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1473     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContentWithHeader()
1474     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0, use $TSFE->generatePageTitle() instead.
1475     */
1476    public function printTitle($pageTitle, $noTitle = false, $showTitleFirst = false, $pageTitleSeparator = '')
1477    {
1478        trigger_error('TemplateService->printTitle() will be removed in TYPO3 v10.0. Title tag generation has been moved into $TSFE itself, re-implement this method if you need to, otherwise use TSFE->generatePageTitle() for full usage.', E_USER_DEPRECATED);
1479        $siteTitle = trim($this->setup['sitetitle']);
1480        $pageTitle = $noTitle ? '' : $pageTitle;
1481        if ($showTitleFirst) {
1482            $temp = $siteTitle;
1483            $siteTitle = $pageTitle;
1484            $pageTitle = $temp;
1485        }
1486        // only show a separator if there are both site title and page title
1487        if ($pageTitle === '' || $siteTitle === '') {
1488            $pageTitleSeparator = '';
1489        } elseif (empty($pageTitleSeparator)) {
1490            // use the default separator if non given
1491            $pageTitleSeparator = ': ';
1492        }
1493        return $siteTitle . $pageTitleSeparator . $pageTitle;
1494    }
1495
1496    /**
1497     * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1498     *
1499     * @param string $list A list of UIDs for which the rootline-level should get returned
1500     * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1501     */
1502    public function getRootlineLevel($list)
1503    {
1504        $idx = 0;
1505        foreach ($this->rootLine as $page) {
1506            if (GeneralUtility::inList($list, $page['uid'])) {
1507                return $idx;
1508            }
1509            $idx++;
1510        }
1511        return false;
1512    }
1513
1514    /**
1515     * Returns the page ID of the rootlevel
1516     *
1517     * @return int
1518     */
1519    public function getRootId(): int
1520    {
1521        return (int)$this->rootId;
1522    }
1523
1524    /*******************************************************************
1525     *
1526     * Functions for creating links
1527     *
1528     *******************************************************************/
1529    /**
1530     * The mother of all functions creating links/URLs etc in a TypoScript environment.
1531     * See the references below.
1532     * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1533     * It is important to pass all links created through this function since this is the guarantee that globally configured settings for link creating are observed and that your applications will conform to the various/many configuration options in TypoScript Templates regarding this.
1534     *
1535     * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, title and sectionIndex_uid.
1536     * @param string $oTarget Default target string to use IF not $page['target'] is set.
1537     * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1538     * @param string $_ not in use anymore
1539     * @param array $overrideArray Array with overriding values for the $page array.
1540     * @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.
1541     * @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.
1542     * @param string $targetDomain The target Doamin, if any was detected in typolink
1543     * @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
1544     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1545     * @deprecated - will be removed in TYPO3 v10.0 - have a look at PageLinkBuilder
1546     */
1547    public function linkData($page, $oTarget, $no_cache, $_ = null, $overrideArray = null, $addParams = '', $typeOverride = '', $targetDomain = '')
1548    {
1549        trigger_error('Creating URLs to pages is now encapsulated into PageLinkBuilder, and should be used in the future. TemplateService->linkData() will be removed in TYPO3 v10.0.', E_USER_DEPRECATED);
1550        $LD = [];
1551        // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1552        if (is_array($overrideArray)) {
1553            foreach ($overrideArray as $theKey => $theNewVal) {
1554                $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1555                $page[$theKey] = $theNewVal;
1556            }
1557        }
1558        // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1559        if (!strstr($addParams, '&MP=')) {
1560            // Looking for hardcoded defaults:
1561            if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
1562                $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
1563            } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
1564                // Else look in automatically created map:
1565                $m = $this->getFromMPmap($page['uid']);
1566                if ($m) {
1567                    $addParams .= '&MP=' . rawurlencode($m);
1568                }
1569            }
1570        }
1571        // Setting ID/alias:
1572        $script = 'index.php';
1573        if ($page['alias']) {
1574            $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1575        } else {
1576            $LD['url'] = $script . '?id=' . $page['uid'];
1577        }
1578        // Setting target
1579        $LD['target'] = trim($page['target']) ?: $oTarget;
1580        // typeNum
1581        $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1582        if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
1583            $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
1584        }
1585        if ((string)$typeOverride !== '') {
1586            $typeNum = $typeOverride;
1587        }
1588        // Override...
1589        if ($typeNum) {
1590            $LD['type'] = '&type=' . (int)$typeNum;
1591        } else {
1592            $LD['type'] = '';
1593        }
1594        // Preserving the type number.
1595        $LD['orig_type'] = $LD['type'];
1596        // noCache
1597        $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
1598        // linkVars
1599        if ($addParams) {
1600            $LD['linkVars'] = HttpUtility::buildQueryString(GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '&');
1601        } else {
1602            $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
1603        }
1604        // Add absRefPrefix if exists.
1605        $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
1606        // 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.
1607        $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1608        // Compile the normal total url
1609        $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
1610        // Call post processing function for link rendering:
1611        $_params = [
1612            'LD' => &$LD,
1613            'args' => ['page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
1614            'typeNum' => $typeNum
1615        ];
1616        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
1617            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1618        }
1619        // Return the LD-array
1620        return $LD;
1621    }
1622
1623    /**
1624     * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1625     * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1626     *
1627     * @param int $pageId Page id to return MPvar value for.
1628     * @return string
1629     * @see initMPmap_create()
1630     * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1631     * @deprecated - will be removed in TYPO3 v10.0.
1632     */
1633    public function getFromMPmap($pageId = 0)
1634    {
1635        trigger_error('Getting a mount point parameter for a page is now built into PageLinkBuilder, and should be used in the future. TemplateService->getFromMPmap() will be removed in TYPO3 v10.0.', E_USER_DEPRECATED);
1636        // Create map if not found already:
1637        if (!is_array($this->MPmap)) {
1638            $this->MPmap = [];
1639            $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), true);
1640            // Traverse rootpoints:
1641            foreach ($rootPoints as $p) {
1642                $initMParray = [];
1643                if ($p === 'root') {
1644                    $p = $this->rootLine[0]['uid'];
1645                    if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1646                        $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1647                    }
1648                }
1649                $this->initMPmap_create($p, $initMParray);
1650            }
1651        }
1652        // Finding MP var for Page ID:
1653        if ($pageId) {
1654            if (is_array($this->MPmap[$pageId]) && !empty($this->MPmap[$pageId])) {
1655                return implode(',', $this->MPmap[$pageId]);
1656            }
1657        }
1658        return '';
1659    }
1660
1661    /**
1662     * Creating MPmap for a certain ID root point.
1663     *
1664     * @param int $id Root id from which to start map creation.
1665     * @param array $MP_array MP_array passed from root page.
1666     * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1667     * @see getFromMPvar()
1668     * @deprecated will be removed in TYPO3 v10.0
1669     */
1670    public function initMPmap_create($id, $MP_array = [], $level = 0)
1671    {
1672        trigger_error('Building a mount point parameter map is now built into PageLinkBuilder, and should be used in the future. TemplateService->initMPmap_creat() will be removed in TYPO3 v10.0.', E_USER_DEPRECATED);
1673        $id = (int)$id;
1674        if ($id <= 0) {
1675            return;
1676        }
1677        // First level, check id
1678        if (!$level) {
1679            // Find mount point if any:
1680            $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
1681            // Overlay mode:
1682            if (is_array($mount_info) && $mount_info['overlay']) {
1683                $MP_array[] = $mount_info['MPvar'];
1684                $id = $mount_info['mount_pid'];
1685            }
1686            // Set mapping information for this level:
1687            $this->MPmap[$id] = $MP_array;
1688            // Normal mode:
1689            if (is_array($mount_info) && !$mount_info['overlay']) {
1690                $MP_array[] = $mount_info['MPvar'];
1691                $id = $mount_info['mount_pid'];
1692            }
1693        }
1694        if ($id && $level < 20) {
1695            $nextLevelAcc = [];
1696            // Select and traverse current level pages:
1697            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1698            $queryBuilder->getRestrictions()
1699                ->removeAll()
1700                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1701            $queryResult = $queryBuilder
1702                ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
1703                ->from('pages')
1704                ->where(
1705                    $queryBuilder->expr()->eq(
1706                        'pid',
1707                        $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1708                    ),
1709                    $queryBuilder->expr()->neq(
1710                        'doktype',
1711                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1712                    ),
1713                    $queryBuilder->expr()->neq(
1714                        'doktype',
1715                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
1716                    )
1717                )->execute();
1718            while ($row = $queryResult->fetch()) {
1719                // Find mount point if any:
1720                $next_id = $row['uid'];
1721                $next_MP_array = $MP_array;
1722                $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
1723                // Overlay mode:
1724                if (is_array($mount_info) && $mount_info['overlay']) {
1725                    $next_MP_array[] = $mount_info['MPvar'];
1726                    $next_id = $mount_info['mount_pid'];
1727                }
1728                if (!isset($this->MPmap[$next_id])) {
1729                    // Set mapping information for this level:
1730                    $this->MPmap[$next_id] = $next_MP_array;
1731                    // Normal mode:
1732                    if (is_array($mount_info) && !$mount_info['overlay']) {
1733                        $next_MP_array[] = $mount_info['MPvar'];
1734                        $next_id = $mount_info['mount_pid'];
1735                    }
1736                    // Register recursive call
1737                    // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1738                    $nextLevelAcc[] = [$next_id, $next_MP_array];
1739                }
1740            }
1741            // Call recursively, if any:
1742            foreach ($nextLevelAcc as $pSet) {
1743                $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1744            }
1745        }
1746    }
1747
1748    /**
1749     * Adds the TypoScript from the global array.
1750     * The class property isDefaultTypoScriptAdded ensures
1751     * that the adding only happens once.
1752     *
1753     * @see isDefaultTypoScriptAdded
1754     */
1755    protected function addDefaultTypoScript()
1756    {
1757        // Add default TS for all code types, if not done already
1758        if (!$this->isDefaultTypoScriptAdded) {
1759            // adding default setup and constants
1760            // defaultTypoScript_setup is *very* unlikely to be empty
1761            // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1762            array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1763            array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1764            array_unshift($this->templateIncludePaths, '');
1765            // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1766            $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1767            $defaultTemplateInfo = [
1768                'root' => '',
1769                'next' => '',
1770                'clConst' => '',
1771                'clConf' => '',
1772                'templateID' => '_defaultTypoScript_',
1773                'templateParent' => $rootTemplateId,
1774                'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1775                'uid' => '_defaultTypoScript_',
1776                'pid' => '',
1777                'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1778            ];
1779            // push info to information arrays used in BE by TemplateTools (Analyzer)
1780            array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1781            array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1782            array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1783            $this->isDefaultTypoScriptAdded = true;
1784        }
1785    }
1786
1787    /**
1788     * @return TypoScriptFrontendController
1789     */
1790    protected function getTypoScriptFrontendController()
1791    {
1792        return $GLOBALS['TSFE'];
1793    }
1794
1795    /**
1796     * @return TimeTracker
1797     */
1798    protected function getTimeTracker()
1799    {
1800        return GeneralUtility::makeInstance(TimeTracker::class);
1801    }
1802
1803    /**
1804     * Returns data stored for the hash string in the cache "cache_hash"
1805     * used to store the parsed TypoScript template structures.
1806     *
1807     * @param string $identifier The hash-string which was used to store the data value
1808     * @return mixed The data from the cache
1809     */
1810    protected function getCacheEntry($identifier)
1811    {
1812        return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1813    }
1814
1815    /**
1816     * Stores $data in the 'cache_hash' cache with the hash key $identifier
1817     *
1818     * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1819     * @param mixed $data The data to store
1820     * @param string $tag Is just a textual identification in order to inform about the content
1821     */
1822    protected function setCacheEntry($identifier, $data, $tag)
1823    {
1824        GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1825    }
1826}
1827