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