[TASK] Make Tests/Unit/TypoScript/ notice free
[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'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
724 // Processing "Clear"-flags
725 $clConst = 0;
726 $clConf = 0;
727 if (!empty($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 (!isset($row['!$row[\'includeStaticAfterBasedOn\']']) ||
751 isset($row['includeStaticAfterBasedOn']) && !$row['includeStaticAfterBasedOn']
752 ) {
753 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
754 }
755 // Include "Based On" sys_templates:
756 // 'basedOn' is a list of templates to include
757 if (trim($row['basedOn'] ?? '')) {
758 // Normal Operation, which is to include the "based-on" sys_templates,
759 // if they are not already included, and maintaining the sorting of the templates
760 $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
761 // skip template if it's already included
762 foreach ($basedOnIds as $key => $basedOnId) {
763 if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
764 unset($basedOnIds[$key]);
765 }
766 }
767 if (!empty($basedOnIds)) {
768 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
769 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
770 $queryResult = $queryBuilder
771 ->select('*')
772 ->from('sys_template')
773 ->where(
774 $queryBuilder->expr()->in(
775 'uid',
776 $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
777 )
778 )
779 ->execute();
780 // make it an associative array with the UID as key
781 $subTemplates = [];
782 while ($rowItem = $queryResult->fetch()) {
783 $subTemplates[(int)$rowItem['uid']] = $rowItem;
784 }
785 // Traversing list again to ensure the sorting of the templates
786 foreach ($basedOnIds as $id) {
787 if (is_array($subTemplates[$id])) {
788 $this->versionOL($subTemplates[$id]);
789 $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
790 }
791 }
792 }
793 }
794 // Include files (from extensions) (#2/2)
795 if (!empty($row['includeStaticAfterBasedOn'])) {
796 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
797 }
798 // Creating hierarchy information; Used by backend analysis tools
799 $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
800 'root' => trim($row['root'] ?? ''),
801 'next' => $row['nextLevel'] ?? null,
802 'clConst' => $clConst,
803 'clConf' => $clConf,
804 'templateID' => $templateID,
805 'templateParent' => $templateParent,
806 'title' => $row['title'],
807 'uid' => $row['uid'],
808 'pid' => $row['pid'] ?? null,
809 'configLines' => substr_count($row['config'], LF) + 1
810 ]);
811 // Adding the content of the fields constants (Constants) and config (Setup)
812 $this->constants[] = $row['constants'];
813 $this->config[] = $row['config'];
814 $this->templateIncludePaths[] = $includePath;
815 // For backend analysis (Template Analyser) provide the order of added constants/config template IDs
816 $this->clearList_const[] = $templateID;
817 $this->clearList_setup[] = $templateID;
818 if (trim($row['sitetitle'] ?? null)) {
819 $this->sitetitle = $row['sitetitle'];
820 }
821 // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
822 if (trim($row['root'] ?? null)) {
823 $this->rootId = $pid;
824 $this->rootLine = [];
825 }
826 // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
827 if ($row['nextLevel'] ?? null) {
828 $this->nextLevel = $row['nextLevel'];
829 } else {
830 $this->nextLevel = 0;
831 }
832 }
833
834 /**
835 * This function can be used to update the data of the current rootLine
836 * e.g. when a different language is used.
837 *
838 * This function must not be used if there are different pages in the
839 * rootline as before!
840 *
841 * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
842 * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
843 */
844 public function updateRootlineData($fullRootLine)
845 {
846 if (!is_array($this->rootLine) || empty($this->rootLine)) {
847 return;
848 }
849
850 $fullRootLineByUid = [];
851 foreach ($fullRootLine as $rootLineData) {
852 $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
853 }
854
855 foreach ($this->rootLine as $level => $dataArray) {
856 $currentUid = $dataArray['uid'];
857
858 if (!array_key_exists($currentUid, $fullRootLineByUid)) {
859 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);
860 }
861
862 $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
863 }
864 }
865
866 /**
867 * Includes static template files (from extensions) for the input template record row.
868 *
869 * @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.
870 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
871 * @param int $pid The PID of the input template record
872 * @param array $row A full TypoScript template record
873 * @see processTemplate()
874 */
875 public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
876 {
877 // Call function for link rendering:
878 $_params = [
879 'idList' => &$idList,
880 'templateId' => &$templateID,
881 'pid' => &$pid,
882 'row' => &$row
883 ];
884 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
885 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
886 }
887 // If "Include before all static templates if root-flag is set" is set:
888 $staticFileMode = $row['static_file_mode'] ?? null;
889 if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
890 $this->addExtensionStatics($idList, $templateID, $pid, $row);
891 }
892 // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
893 if (trim($row['include_static_file'] ?? '')) {
894 $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
895 // Traversing list
896 foreach ($include_static_fileArr as $ISF_file) {
897 if (strpos($ISF_file, 'EXT:') === 0) {
898 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
899 if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
900 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
901 $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
902 if (@is_dir($ISF_filePath)) {
903 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
904 $subrow = [
905 'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
906 'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
907 'include_static' => @file_exists($ISF_filePath . 'include_static.txt') ? implode(',', array_unique(GeneralUtility::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
908 'include_static_file' => @file_exists($ISF_filePath . 'include_static_file.txt') ? implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
909 'title' => $ISF_file,
910 'uid' => $mExtKey
911 ];
912 $subrow = $this->prependStaticExtra($subrow);
913 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
914 }
915 }
916 }
917 }
918 }
919 // If "Default (include before if root flag is set)" is set OR
920 // "Always include before this template record" AND root-flag are set
921 if ($staticFileMode == 1 || $staticFileMode == 0 && substr($templateID, 0, 4) === 'sys_' && $row['root']) {
922 $this->addExtensionStatics($idList, $templateID, $pid, $row);
923 }
924 // Include Static Template Records after all other TypoScript has been included.
925 $_params = [
926 'idList' => &$idList,
927 'templateId' => &$templateID,
928 'pid' => &$pid,
929 'row' => &$row
930 ];
931 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
932 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
933 }
934 }
935
936 /**
937 * Retrieves the content of the first existing file by extension order.
938 * Returns the empty string if no file is found.
939 *
940 * @param string $filePath The location of the file.
941 * @param string $baseName The base file name. "constants" or "setup".
942 * @return string
943 */
944 protected function getTypoScriptSourceFileContent($filePath, $baseName)
945 {
946 $extensions = ['.typoscript', '.ts', '.txt'];
947 foreach ($extensions as $extension) {
948 $fileName = $filePath . $baseName . $extension;
949 if (@file_exists($fileName)) {
950 return file_get_contents($fileName);
951 }
952 }
953 return '';
954 }
955
956 /**
957 * Adds the default TypoScript files for extensions if any.
958 *
959 * @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.
960 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
961 * @param int $pid The PID of the input template record
962 * @param array $row A full TypoScript template record
963 * @access private
964 * @see includeStaticTypoScriptSources()
965 */
966 public function addExtensionStatics($idList, $templateID, $pid, $row)
967 {
968 $this->extensionStaticsProcessed = true;
969
970 // @todo Change to use new API
971 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
972 if ((is_array($files) || $files instanceof \ArrayAccess)
973 && (
974 !empty($files['ext_typoscript_constants.txt'])
975 || !empty($files['ext_typoscript_constants.typoscript'])
976 || !empty($files['ext_typoscript_setup.txt'])
977 || !empty($files['ext_typoscript_setup.typoscript'])
978 )
979 ) {
980 $mExtKey = str_replace('_', '', $extKey);
981 $constants = '';
982 $config = '';
983
984 if (!empty($files['ext_typoscript_constants.typoscript'])) {
985 $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
986 } elseif (!empty($files['ext_typoscript_constants.txt'])) {
987 $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
988 }
989
990 if (!empty($files['ext_typoscript_setup.typoscript'])) {
991 $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
992 } elseif (!empty($files['ext_typoscript_setup.txt'])) {
993 $config = @file_get_contents($files['ext_typoscript_setup.txt']);
994 }
995
996 $this->processTemplate(
997 $this->prependStaticExtra([
998 'constants' => $constants,
999 'config' => $config,
1000 'title' => $extKey,
1001 'uid' => $mExtKey
1002 ]),
1003 $idList . ',ext_' . $mExtKey,
1004 $pid,
1005 'ext_' . $mExtKey,
1006 $templateID,
1007 ExtensionManagementUtility::extPath($extKey)
1008 );
1009 }
1010 }
1011 }
1012
1013 /**
1014 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
1015 * 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
1016 *
1017 * @param array $subrow Static template record/file
1018 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
1019 * @access private
1020 * @see addExtensionStatics(), includeStaticTypoScriptSources()
1021 */
1022 public function prependStaticExtra($subrow)
1023 {
1024 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
1025 $identifier = $subrow['uid'];
1026 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null;
1027 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null;
1028 // 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
1029 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
1030 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
1031 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
1032 }
1033 return $subrow;
1034 }
1035
1036 /**
1037 * Creating versioning overlay of a sys_template record.
1038 * This will use either frontend or backend overlay functionality depending on environment.
1039 *
1040 * @param array $row Row to overlay (passed by reference)
1041 */
1042 public function versionOL(&$row)
1043 {
1044 // Distinguish frontend and backend call:
1045 // To do the fronted call a full frontend is required, just checking for
1046 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
1047 // eId scripts that run in frontend scope, but do not have a full blown frontend.
1048 if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
1049 // Frontend
1050 $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
1051 } else {
1052 // Backend
1053 BackendUtility::workspaceOL('sys_template', $row);
1054 }
1055 }
1056
1057 /*******************************************************************
1058 *
1059 * Parsing TypoScript code text from Template Records into PHP array
1060 *
1061 *******************************************************************/
1062 /**
1063 * Generates the configuration array by replacing constants and parsing the whole thing.
1064 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
1065 *
1066 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
1067 */
1068 public function generateConfig()
1069 {
1070 // Add default TS for all code types
1071 $this->addDefaultTypoScript();
1072
1073 // Parse the TypoScript code text for include-instructions!
1074 $this->processIncludes();
1075 // These vars are also set lateron...
1076 $this->setup['sitetitle'] = $this->sitetitle;
1077 // ****************************
1078 // Parse TypoScript Constants
1079 // ****************************
1080 // Initialize parser and match-condition classes:
1081 /** @var $constants Parser\TypoScriptParser */
1082 $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1083 $constants->breakPointLN = (int)$this->ext_constants_BRP;
1084 $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1085 /** @var $matchObj ConditionMatcher */
1086 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1087 $matchObj->setSimulateMatchConditions($this->matchAlternative);
1088 $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1089 // Traverse constants text fields and parse them
1090 foreach ($this->constants as $str) {
1091 $constants->parse($str, $matchObj);
1092 }
1093 // Read out parse errors if any
1094 $this->parserErrors['constants'] = $constants->errors;
1095 // 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)
1096 $this->flatSetup = [];
1097 $this->flattenSetup($constants->setup, '');
1098 // ***********************************************
1099 // Parse TypoScript Setup (here called "config")
1100 // ***********************************************
1101 // Initialize parser and match-condition classes:
1102 /** @var $config Parser\TypoScriptParser */
1103 $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1104 $config->breakPointLN = (int)$this->ext_config_BRP;
1105 $config->regLinenumbers = $this->ext_regLinenumbers;
1106 $config->regComments = $this->ext_regComments;
1107 $config->setup = $this->setup;
1108 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1109 $config->sections = $constants->sections;
1110 $config->sectionsMatch = $constants->sectionsMatch;
1111 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1112 $all = '';
1113 foreach ($this->config as $str) {
1114 $all .= '
1115 [GLOBAL]
1116 ' . $str;
1117 }
1118 // Substitute constants in the Setup code:
1119 if ($this->tt_track) {
1120 $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1121 }
1122 $all = $this->substituteConstants($all);
1123 if ($this->tt_track) {
1124 $this->getTimeTracker()->pull();
1125 }
1126
1127 // Searching for possible unsubstituted constants left (only for information)
1128 if ($this->verbose) {
1129 if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1130 if ($this->tt_track) {
1131 $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1132 }
1133 }
1134 }
1135
1136 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1137 if ($this->tt_track) {
1138 $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1139 }
1140 // Finally parse the Setup field TypoScript code (where constants are now substituted)
1141 $config->parse($all, $matchObj);
1142 // Read out parse errors if any
1143 $this->parserErrors['config'] = $config->errors;
1144 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1145 $this->setup = $config->setup;
1146 // Do the same for the constants
1147 $this->setup_constants = $constants->setup;
1148 // ****************************************************************
1149 // Final processing of the $this->setup TypoScript Template array
1150 // Basically: This is unsetting/setting of certain reserved keys.
1151 // ****************************************************************
1152 // 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!
1153 unset($this->setup['sitetitle']);
1154 unset($this->setup['sitetitle.']);
1155 $this->setup['sitetitle'] = $this->sitetitle;
1156 // Unsetting some vars...
1157 unset($this->setup['types.']);
1158 unset($this->setup['types']);
1159 if (is_array($this->setup)) {
1160 foreach ($this->setup as $key => $value) {
1161 if ($value === 'PAGE') {
1162 // Set the typeNum of the current page object:
1163 if (isset($this->setup[$key . '.']['typeNum'])) {
1164 $typeNum = $this->setup[$key . '.']['typeNum'];
1165 $this->setup['types.'][$typeNum] = $key;
1166 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1167 $this->setup['types.'][0] = $key;
1168 }
1169 }
1170 }
1171 }
1172 unset($this->setup['temp.']);
1173 unset($constants);
1174 // Storing the conditions found/matched information:
1175 $this->sections = $config->sections;
1176 $this->sectionsMatch = $config->sectionsMatch;
1177 }
1178
1179 /**
1180 * Searching TypoScript code text (for constants and config (Setup))
1181 * for include instructions and does the inclusion of external TypoScript files
1182 * if needed.
1183 *
1184 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1185 */
1186 public function processIncludes()
1187 {
1188 if ($this->processIncludesHasBeenRun) {
1189 return;
1190 }
1191
1192 $paths = $this->templateIncludePaths;
1193 $files = [];
1194 foreach ($this->constants as &$value) {
1195 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1196 $files = array_merge($files, $includeData['files']);
1197 $value = $includeData['typoscript'];
1198 }
1199 unset($value);
1200 $paths = $this->templateIncludePaths;
1201 foreach ($this->config as &$value) {
1202 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1203 $files = array_merge($files, $includeData['files']);
1204 $value = $includeData['typoscript'];
1205 }
1206 unset($value);
1207
1208 if (!empty($files)) {
1209 $files = array_unique($files);
1210 foreach ($files as $file) {
1211 $this->rowSum[] = [$file, filemtime($file)];
1212 }
1213 }
1214
1215 $this->processIncludesHasBeenRun = true;
1216 }
1217
1218 /**
1219 * 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!
1220 *
1221 * @param array $constArray Constants array, default input.
1222 * @return array Constants array, modified
1223 * @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...)
1224 */
1225 public function mergeConstantsFromPageTSconfig($constArray)
1226 {
1227 $TSdataArray = [];
1228 // Setting default configuration:
1229 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1230 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1231 if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1232 $includeTsConfigFileList = GeneralUtility::trimExplode(
1233 ',',
1234 $this->absoluteRootLine[$a]['tsconfig_includes'],
1235 true
1236 );
1237
1238 $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1239 }
1240 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1241 }
1242 // Parsing the user TS (or getting from cache)
1243 $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1244 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1245 /** @var $parseObj Parser\TypoScriptParser */
1246 $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1247 $parseObj->parse($userTS);
1248 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1249 ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1250 }
1251
1252 return $constArray;
1253 }
1254
1255 /**
1256 * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1257 *
1258 * @param array $filesToInclude The files to read constants from
1259 * @param array $TSdataArray The TSconfig array the constants should be appended to
1260 * @return array The TSconfig with the included constants appended
1261 */
1262 protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1263 {
1264 foreach ($filesToInclude as $key => $file) {
1265 if (strpos($file, 'EXT:') !== 0) {
1266 continue;
1267 }
1268
1269 list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1270
1271 if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1272 continue;
1273 }
1274 if ((string)$filePath == '') {
1275 continue;
1276 }
1277
1278 $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1279 if (file_exists($tsConfigFile)) {
1280 $TSdataArray[] = file_get_contents($tsConfigFile);
1281 }
1282 }
1283
1284 return $TSdataArray;
1285 }
1286
1287 /**
1288 * This flattens a hierarchical TypoScript array to $this->flatSetup
1289 *
1290 * @param array $setupArray TypoScript array
1291 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1292 * @see generateConfig()
1293 */
1294 public function flattenSetup($setupArray, $prefix)
1295 {
1296 if (is_array($setupArray)) {
1297 foreach ($setupArray as $key => $val) {
1298 if (is_array($val)) {
1299 $this->flattenSetup($val, $prefix . $key);
1300 } else {
1301 $this->flatSetup[$prefix . $key] = $val;
1302 }
1303 }
1304 }
1305 }
1306
1307 /**
1308 * Substitutes the constants from $this->flatSetup in the text string $all
1309 *
1310 * @param string $all TypoScript code text string
1311 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1312 * @see generateConfig(), flattenSetup()
1313 */
1314 public function substituteConstants($all)
1315 {
1316 if ($this->tt_track) {
1317 $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1318 }
1319 $noChange = false;
1320 // Recursive substitution of constants (up to 10 nested levels)
1321 for ($i = 0; $i < 10 && !$noChange; $i++) {
1322 $old_all = $all;
1323 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1324 if ($old_all == $all) {
1325 $noChange = true;
1326 }
1327 }
1328 return $all;
1329 }
1330
1331 /**
1332 * Call back method for preg_replace_callback in substituteConstants
1333 *
1334 * @param array $matches Regular expression matches
1335 * @return string Replacement
1336 * @see substituteConstants()
1337 */
1338 public function substituteConstantsCallBack($matches)
1339 {
1340 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1341 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1342 }
1343
1344 /*******************************************************************
1345 *
1346 * Various API functions, used from elsewhere in the frontend classes
1347 *
1348 *******************************************************************/
1349
1350 /**
1351 * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1352 *
1353 * @param string $fileFromSetup TypoScript "resource" data type value.
1354 * @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
1355 */
1356 public function getFileName($fileFromSetup)
1357 {
1358 $file = trim($fileFromSetup);
1359 if (!$file) {
1360 return null;
1361 }
1362 if (strpos($file, '../') !== false) {
1363 if ($this->tt_track) {
1364 $this->getTimeTracker()->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1365 }
1366 return null;
1367 }
1368 // Cache
1369 $hash = md5($file);
1370 if (isset($this->fileCache[$hash])) {
1371 return $this->fileCache[$hash];
1372 }
1373
1374 // if this is an URL, it can be returned directly
1375 $urlScheme = parse_url($file, PHP_URL_SCHEME);
1376 if ($urlScheme === 'https' || $urlScheme === 'http' || is_file(PATH_site . $file)) {
1377 return $file;
1378 }
1379
1380 // this call also resolves EXT:myext/ files
1381 $file = GeneralUtility::getFileAbsFileName($file);
1382 if (!$file) {
1383 if ($this->tt_track) {
1384 $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1385 }
1386 return null;
1387 }
1388
1389 $file = PathUtility::stripPathSitePrefix($file);
1390
1391 // Check if the found file is in the allowed paths
1392 foreach ($this->allowedPaths as $val) {
1393 if (GeneralUtility::isFirstPartOfStr($file, $val)) {
1394 $this->fileCache[$hash] = $file;
1395 return $file;
1396 }
1397 }
1398
1399 if ($this->tt_track) {
1400 $this->getTimeTracker()->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1401 }
1402 return null;
1403 }
1404
1405 /**
1406 * Compiles the content for the page <title> tag.
1407 *
1408 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1409 * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1410 * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1411 * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
1412 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1413 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContentWithHeader()
1414 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use $TSFE->generatePageTitle() instead.
1415 */
1416 public function printTitle($pageTitle, $noTitle = false, $showTitleFirst = false, $pageTitleSeparator = '')
1417 {
1418 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);
1419 $siteTitle = trim($this->setup['sitetitle']);
1420 $pageTitle = $noTitle ? '' : $pageTitle;
1421 if ($showTitleFirst) {
1422 $temp = $siteTitle;
1423 $siteTitle = $pageTitle;
1424 $pageTitle = $temp;
1425 }
1426 // only show a separator if there are both site title and page title
1427 if ($pageTitle === '' || $siteTitle === '') {
1428 $pageTitleSeparator = '';
1429 } elseif (empty($pageTitleSeparator)) {
1430 // use the default separator if non given
1431 $pageTitleSeparator = ': ';
1432 }
1433 return $siteTitle . $pageTitleSeparator . $pageTitle;
1434 }
1435
1436 /**
1437 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1438 *
1439 * @param string $list A list of UIDs for which the rootline-level should get returned
1440 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1441 */
1442 public function getRootlineLevel($list)
1443 {
1444 $idx = 0;
1445 foreach ($this->rootLine as $page) {
1446 if (GeneralUtility::inList($list, $page['uid'])) {
1447 return $idx;
1448 }
1449 $idx++;
1450 }
1451 return false;
1452 }
1453
1454 /**
1455 * Returns the page ID of the rootlevel
1456 *
1457 * @return int
1458 */
1459 public function getRootId(): int
1460 {
1461 return (int)$this->rootId;
1462 }
1463
1464 /*******************************************************************
1465 *
1466 * Functions for creating links
1467 *
1468 *******************************************************************/
1469 /**
1470 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1471 * See the references below.
1472 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1473 * 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.
1474 *
1475 * @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.
1476 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1477 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1478 * @param string $_ not in use anymore
1479 * @param array $overrideArray Array with overriding values for the $page array.
1480 * @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.
1481 * @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.
1482 * @param string $targetDomain The target Doamin, if any was detected in typolink
1483 * @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
1484 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1485 * @deprecated - will be removed in TYPO3 v10.0 - have a look at PageLinkBuilder
1486 */
1487 public function linkData($page, $oTarget, $no_cache, $_ = null, $overrideArray = null, $addParams = '', $typeOverride = '', $targetDomain = '')
1488 {
1489 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);
1490 $LD = [];
1491 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1492 if (is_array($overrideArray)) {
1493 foreach ($overrideArray as $theKey => $theNewVal) {
1494 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1495 $page[$theKey] = $theNewVal;
1496 }
1497 }
1498 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1499 if (!strstr($addParams, '&MP=')) {
1500 // Looking for hardcoded defaults:
1501 if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
1502 $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
1503 } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
1504 // Else look in automatically created map:
1505 $m = $this->getFromMPmap($page['uid']);
1506 if ($m) {
1507 $addParams .= '&MP=' . rawurlencode($m);
1508 }
1509 }
1510 }
1511 // Setting ID/alias:
1512 $script = 'index.php';
1513 if ($page['alias']) {
1514 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1515 } else {
1516 $LD['url'] = $script . '?id=' . $page['uid'];
1517 }
1518 // Setting target
1519 $LD['target'] = trim($page['target']) ?: $oTarget;
1520 // typeNum
1521 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1522 if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
1523 $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
1524 }
1525 if ((string)$typeOverride !== '') {
1526 $typeNum = $typeOverride;
1527 }
1528 // Override...
1529 if ($typeNum) {
1530 $LD['type'] = '&type=' . (int)$typeNum;
1531 } else {
1532 $LD['type'] = '';
1533 }
1534 // Preserving the type number.
1535 $LD['orig_type'] = $LD['type'];
1536 // noCache
1537 $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
1538 // linkVars
1539 if ($addParams) {
1540 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', false, true);
1541 } else {
1542 $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
1543 }
1544 // Add absRefPrefix if exists.
1545 $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
1546 // 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.
1547 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1548 // Compile the normal total url
1549 $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
1550 // Call post processing function for link rendering:
1551 $_params = [
1552 'LD' => &$LD,
1553 'args' => ['page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
1554 'typeNum' => $typeNum
1555 ];
1556 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
1557 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1558 }
1559 // Return the LD-array
1560 return $LD;
1561 }
1562
1563 /**
1564 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1565 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1566 *
1567 * @param int $pageId Page id to return MPvar value for.
1568 * @return string
1569 * @see initMPmap_create()
1570 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1571 * @deprecated - will be removed in TYPO3 v10.
1572 */
1573 public function getFromMPmap($pageId = 0)
1574 {
1575 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);
1576 // Create map if not found already:
1577 if (!is_array($this->MPmap)) {
1578 $this->MPmap = [];
1579 $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), true);
1580 // Traverse rootpoints:
1581 foreach ($rootPoints as $p) {
1582 $initMParray = [];
1583 if ($p === 'root') {
1584 $p = $this->rootLine[0]['uid'];
1585 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1586 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1587 }
1588 }
1589 $this->initMPmap_create($p, $initMParray);
1590 }
1591 }
1592 // Finding MP var for Page ID:
1593 if ($pageId) {
1594 if (is_array($this->MPmap[$pageId]) && !empty($this->MPmap[$pageId])) {
1595 return implode(',', $this->MPmap[$pageId]);
1596 }
1597 }
1598 return '';
1599 }
1600
1601 /**
1602 * Creating MPmap for a certain ID root point.
1603 *
1604 * @param int $id Root id from which to start map creation.
1605 * @param array $MP_array MP_array passed from root page.
1606 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1607 * @see getFromMPvar()
1608 * @deprecated will be removed in TYPO3 v10.0
1609 */
1610 public function initMPmap_create($id, $MP_array = [], $level = 0)
1611 {
1612 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);
1613 $id = (int)$id;
1614 if ($id <= 0) {
1615 return;
1616 }
1617 // First level, check id
1618 if (!$level) {
1619 // Find mount point if any:
1620 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
1621 // Overlay mode:
1622 if (is_array($mount_info) && $mount_info['overlay']) {
1623 $MP_array[] = $mount_info['MPvar'];
1624 $id = $mount_info['mount_pid'];
1625 }
1626 // Set mapping information for this level:
1627 $this->MPmap[$id] = $MP_array;
1628 // Normal mode:
1629 if (is_array($mount_info) && !$mount_info['overlay']) {
1630 $MP_array[] = $mount_info['MPvar'];
1631 $id = $mount_info['mount_pid'];
1632 }
1633 }
1634 if ($id && $level < 20) {
1635 $nextLevelAcc = [];
1636 // Select and traverse current level pages:
1637 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1638 $queryBuilder->getRestrictions()
1639 ->removeAll()
1640 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1641 $queryResult = $queryBuilder
1642 ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
1643 ->from('pages')
1644 ->where(
1645 $queryBuilder->expr()->eq(
1646 'pid',
1647 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1648 ),
1649 $queryBuilder->expr()->neq(
1650 'doktype',
1651 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1652 ),
1653 $queryBuilder->expr()->neq(
1654 'doktype',
1655 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
1656 )
1657 )->execute();
1658 while ($row = $queryResult->fetch()) {
1659 // Find mount point if any:
1660 $next_id = $row['uid'];
1661 $next_MP_array = $MP_array;
1662 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
1663 // Overlay mode:
1664 if (is_array($mount_info) && $mount_info['overlay']) {
1665 $next_MP_array[] = $mount_info['MPvar'];
1666 $next_id = $mount_info['mount_pid'];
1667 }
1668 if (!isset($this->MPmap[$next_id])) {
1669 // Set mapping information for this level:
1670 $this->MPmap[$next_id] = $next_MP_array;
1671 // Normal mode:
1672 if (is_array($mount_info) && !$mount_info['overlay']) {
1673 $next_MP_array[] = $mount_info['MPvar'];
1674 $next_id = $mount_info['mount_pid'];
1675 }
1676 // Register recursive call
1677 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1678 $nextLevelAcc[] = [$next_id, $next_MP_array];
1679 }
1680 }
1681 // Call recursively, if any:
1682 foreach ($nextLevelAcc as $pSet) {
1683 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1684 }
1685 }
1686 }
1687
1688 /**
1689 * Adds the TypoScript from the global array.
1690 * The class property isDefaultTypoScriptAdded ensures
1691 * that the adding only happens once.
1692 *
1693 * @see isDefaultTypoScriptAdded
1694 */
1695 protected function addDefaultTypoScript()
1696 {
1697 // Add default TS for all code types, if not done already
1698 if (!$this->isDefaultTypoScriptAdded) {
1699 // adding default setup and constants
1700 // defaultTypoScript_setup is *very* unlikely to be empty
1701 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1702 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1703 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1704 array_unshift($this->templateIncludePaths, '');
1705 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1706 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1707 $defaultTemplateInfo = [
1708 'root' => '',
1709 'next' => '',
1710 'clConst' => '',
1711 'clConf' => '',
1712 'templateID' => '_defaultTypoScript_',
1713 'templateParent' => $rootTemplateId,
1714 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1715 'uid' => '_defaultTypoScript_',
1716 'pid' => '',
1717 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1718 ];
1719 // push info to information arrays used in BE by TemplateTools (Analyzer)
1720 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1721 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1722 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1723 $this->isDefaultTypoScriptAdded = true;
1724 }
1725 }
1726
1727 /**
1728 * @return TypoScriptFrontendController
1729 */
1730 protected function getTypoScriptFrontendController()
1731 {
1732 return $GLOBALS['TSFE'];
1733 }
1734
1735 /**
1736 * @return TimeTracker
1737 */
1738 protected function getTimeTracker()
1739 {
1740 return GeneralUtility::makeInstance(TimeTracker::class);
1741 }
1742
1743 /**
1744 * Returns data stored for the hash string in the cache "cache_hash"
1745 * used to store the parsed TypoScript template structures.
1746 *
1747 * @param string $identifier The hash-string which was used to store the data value
1748 * @return mixed The data from the cache
1749 */
1750 protected function getCacheEntry($identifier)
1751 {
1752 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1753 }
1754
1755 /**
1756 * Stores $data in the 'cache_hash' cache with the hash key $identifier
1757 *
1758 * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1759 * @param mixed $data The data to store
1760 * @param string $tag Is just a textual identification in order to inform about the content
1761 */
1762 protected function setCacheEntry($identifier, $data, $tag)
1763 {
1764 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1765 }
1766 }