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