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