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