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