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