[CLEANUP] The correct case must be used for standard PHP types in phpdoc
[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)
951 && (
952 !empty($files['ext_typoscript_constants.txt'])
953 || !empty($files['ext_typoscript_constants.typoscript'])
954 || !empty($files['ext_typoscript_setup.txt'])
955 || !empty($files['ext_typoscript_setup.typoscript'])
956 )
957 ) {
958 $mExtKey = str_replace('_', '', $extKey);
959 $constants = '';
960 $config = '';
961
962 if (!empty($files['ext_typoscript_constants.typoscript'])) {
963 $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
964 } elseif (!empty($files['ext_typoscript_constants.txt'])) {
965 $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
966 }
967
968 if (!empty($files['ext_typoscript_setup.typoscript'])) {
969 $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
970 } elseif (!empty($files['ext_typoscript_setup.txt'])) {
971 $config = @file_get_contents($files['ext_typoscript_setup.txt']);
972 }
973
974 $this->processTemplate(
975 $this->prependStaticExtra([
976 'constants' => $constants,
977 'config' => $config,
978 'title' => $extKey,
979 'uid' => $mExtKey
980 ]),
981 $idList . ',ext_' . $mExtKey,
982 $pid,
983 'ext_' . $mExtKey,
984 $templateID,
985 ExtensionManagementUtility::extPath($extKey)
986 );
987 }
988 }
989 }
990
991 /**
992 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
993 * 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
994 *
995 * @param array $subrow Static template record/file
996 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
997 * @access private
998 * @see addExtensionStatics(), includeStaticTypoScriptSources()
999 */
1000 public function prependStaticExtra($subrow)
1001 {
1002 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
1003 $identifier = $subrow['uid'];
1004 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier];
1005 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier];
1006 // 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
1007 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
1008 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
1009 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
1010 }
1011 return $subrow;
1012 }
1013
1014 /**
1015 * Creating versioning overlay of a sys_template record.
1016 * This will use either frontend or backend overlay functionality depending on environment.
1017 *
1018 * @param array $row Row to overlay (passed by reference)
1019 */
1020 public function versionOL(&$row)
1021 {
1022 // Distinguish frontend and backend call:
1023 // To do the fronted call a full frontend is required, just checking for
1024 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
1025 // eId scripts that run in frontend scope, but do not have a full blown frontend.
1026 if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
1027 // Frontend
1028 $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
1029 } else {
1030 // Backend
1031 BackendUtility::workspaceOL('sys_template', $row);
1032 }
1033 }
1034
1035 /*******************************************************************
1036 *
1037 * Parsing TypoScript code text from Template Records into PHP array
1038 *
1039 *******************************************************************/
1040 /**
1041 * Generates the configuration array by replacing constants and parsing the whole thing.
1042 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
1043 *
1044 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
1045 */
1046 public function generateConfig()
1047 {
1048 // Add default TS for all code types
1049 $this->addDefaultTypoScript();
1050
1051 // Parse the TypoScript code text for include-instructions!
1052 $this->processIncludes();
1053 // These vars are also set lateron...
1054 $this->setup['sitetitle'] = $this->sitetitle;
1055 // ****************************
1056 // Parse TypoScript Constants
1057 // ****************************
1058 // Initialize parser and match-condition classes:
1059 /** @var $constants Parser\TypoScriptParser */
1060 $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1061 $constants->breakPointLN = (int)$this->ext_constants_BRP;
1062 $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1063 /** @var $matchObj ConditionMatcher */
1064 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1065 $matchObj->setSimulateMatchConditions($this->matchAlternative);
1066 $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1067 // Traverse constants text fields and parse them
1068 foreach ($this->constants as $str) {
1069 $constants->parse($str, $matchObj);
1070 }
1071 // Read out parse errors if any
1072 $this->parserErrors['constants'] = $constants->errors;
1073 // 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)
1074 $this->flatSetup = [];
1075 $this->flattenSetup($constants->setup, '');
1076 // ***********************************************
1077 // Parse TypoScript Setup (here called "config")
1078 // ***********************************************
1079 // Initialize parser and match-condition classes:
1080 /** @var $config Parser\TypoScriptParser */
1081 $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1082 $config->breakPointLN = (int)$this->ext_config_BRP;
1083 $config->regLinenumbers = $this->ext_regLinenumbers;
1084 $config->regComments = $this->ext_regComments;
1085 $config->setup = $this->setup;
1086 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1087 $config->sections = $constants->sections;
1088 $config->sectionsMatch = $constants->sectionsMatch;
1089 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1090 $all = '';
1091 foreach ($this->config as $str) {
1092 $all .= '
1093 [GLOBAL]
1094 ' . $str;
1095 }
1096 // Substitute constants in the Setup code:
1097 if ($this->tt_track) {
1098 $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1099 }
1100 $all = $this->substituteConstants($all);
1101 if ($this->tt_track) {
1102 $this->getTimeTracker()->pull();
1103 }
1104
1105 // Searching for possible unsubstituted constants left (only for information)
1106 if ($this->verbose) {
1107 if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1108 if ($this->tt_track) {
1109 $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1110 }
1111 }
1112 }
1113
1114 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1115 if ($this->tt_track) {
1116 $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1117 }
1118 // Finally parse the Setup field TypoScript code (where constants are now substituted)
1119 $config->parse($all, $matchObj);
1120 // Read out parse errors if any
1121 $this->parserErrors['config'] = $config->errors;
1122 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1123 $this->setup = $config->setup;
1124 // Do the same for the constants
1125 $this->setup_constants = $constants->setup;
1126 // ****************************************************************
1127 // Final processing of the $this->setup TypoScript Template array
1128 // Basically: This is unsetting/setting of certain reserved keys.
1129 // ****************************************************************
1130 // 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!
1131 unset($this->setup['sitetitle']);
1132 unset($this->setup['sitetitle.']);
1133 $this->setup['sitetitle'] = $this->sitetitle;
1134 // Unsetting some vars...
1135 unset($this->setup['types.']);
1136 unset($this->setup['types']);
1137 if (is_array($this->setup)) {
1138 foreach ($this->setup as $key => $value) {
1139 if ($value === 'PAGE') {
1140 // Set the typeNum of the current page object:
1141 if (isset($this->setup[$key . '.']['typeNum'])) {
1142 $typeNum = $this->setup[$key . '.']['typeNum'];
1143 $this->setup['types.'][$typeNum] = $key;
1144 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1145 $this->setup['types.'][0] = $key;
1146 }
1147 }
1148 }
1149 }
1150 unset($this->setup['temp.']);
1151 unset($constants);
1152 // Storing the conditions found/matched information:
1153 $this->sections = $config->sections;
1154 $this->sectionsMatch = $config->sectionsMatch;
1155 }
1156
1157 /**
1158 * Searching TypoScript code text (for constants and config (Setup))
1159 * for include instructions and does the inclusion of external TypoScript files
1160 * if needed.
1161 *
1162 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1163 */
1164 public function processIncludes()
1165 {
1166 if ($this->processIncludesHasBeenRun) {
1167 return;
1168 }
1169
1170 $paths = $this->templateIncludePaths;
1171 $files = [];
1172 foreach ($this->constants 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 $paths = $this->templateIncludePaths;
1179 foreach ($this->config as &$value) {
1180 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1181 $files = array_merge($files, $includeData['files']);
1182 $value = $includeData['typoscript'];
1183 }
1184 unset($value);
1185
1186 if (!empty($files)) {
1187 $files = array_unique($files);
1188 foreach ($files as $file) {
1189 $this->rowSum[] = [$file, filemtime($file)];
1190 }
1191 }
1192
1193 $this->processIncludesHasBeenRun = true;
1194 }
1195
1196 /**
1197 * 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!
1198 *
1199 * @param array $constArray Constants array, default input.
1200 * @return array Constants array, modified
1201 * @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...)
1202 */
1203 public function mergeConstantsFromPageTSconfig($constArray)
1204 {
1205 $TSdataArray = [];
1206 // Setting default configuration:
1207 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1208 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1209 if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1210 $includeTsConfigFileList = GeneralUtility::trimExplode(
1211 ',',
1212 $this->absoluteRootLine[$a]['tsconfig_includes'],
1213 true
1214 );
1215
1216 $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1217 }
1218 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1219 }
1220 // Parsing the user TS (or getting from cache)
1221 $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1222 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1223 /** @var $parseObj Parser\TypoScriptParser */
1224 $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1225 $parseObj->parse($userTS);
1226 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1227 ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1228 }
1229
1230 return $constArray;
1231 }
1232
1233 /**
1234 * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1235 *
1236 * @param array $filesToInclude The files to read constants from
1237 * @param array $TSdataArray The TSconfig array the constants should be appended to
1238 * @return array The TSconfig with the included constants appended
1239 */
1240 protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1241 {
1242 foreach ($filesToInclude as $key => $file) {
1243 if (strpos($file, 'EXT:') !== 0) {
1244 continue;
1245 }
1246
1247 list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1248
1249 if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1250 continue;
1251 }
1252 if ((string)$filePath == '') {
1253 continue;
1254 }
1255
1256 $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1257 if (file_exists($tsConfigFile)) {
1258 $TSdataArray[] = file_get_contents($tsConfigFile);
1259 }
1260 }
1261
1262 return $TSdataArray;
1263 }
1264
1265 /**
1266 * This flattens a hierarchical TypoScript array to $this->flatSetup
1267 *
1268 * @param array $setupArray TypoScript array
1269 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1270 * @see generateConfig()
1271 */
1272 public function flattenSetup($setupArray, $prefix)
1273 {
1274 if (is_array($setupArray)) {
1275 foreach ($setupArray as $key => $val) {
1276 if (is_array($val)) {
1277 $this->flattenSetup($val, $prefix . $key);
1278 } else {
1279 $this->flatSetup[$prefix . $key] = $val;
1280 }
1281 }
1282 }
1283 }
1284
1285 /**
1286 * Substitutes the constants from $this->flatSetup in the text string $all
1287 *
1288 * @param string $all TypoScript code text string
1289 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1290 * @see generateConfig(), flattenSetup()
1291 */
1292 public function substituteConstants($all)
1293 {
1294 if ($this->tt_track) {
1295 $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1296 }
1297 $noChange = false;
1298 // Recursive substitution of constants (up to 10 nested levels)
1299 for ($i = 0; $i < 10 && !$noChange; $i++) {
1300 $old_all = $all;
1301 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1302 if ($old_all == $all) {
1303 $noChange = true;
1304 }
1305 }
1306 return $all;
1307 }
1308
1309 /**
1310 * Call back method for preg_replace_callback in substituteConstants
1311 *
1312 * @param array $matches Regular expression matches
1313 * @return string Replacement
1314 * @see substituteConstants()
1315 */
1316 public function substituteConstantsCallBack($matches)
1317 {
1318 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1319 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1320 }
1321
1322 /*******************************************************************
1323 *
1324 * Various API functions, used from elsewhere in the frontend classes
1325 *
1326 *******************************************************************/
1327
1328 /**
1329 * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1330 *
1331 * @param string $fileFromSetup TypoScript "resource" data type value.
1332 * @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
1333 */
1334 public function getFileName($fileFromSetup)
1335 {
1336 $file = trim($fileFromSetup);
1337 if (!$file) {
1338 return null;
1339 }
1340 if (strpos($file, '../') !== false) {
1341 if ($this->tt_track) {
1342 $this->getTimeTracker()->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1343 }
1344 return null;
1345 }
1346 // Cache
1347 $hash = md5($file);
1348 if (isset($this->fileCache[$hash])) {
1349 return $this->fileCache[$hash];
1350 }
1351
1352 // if this is an URL, it can be returned directly
1353 $urlScheme = parse_url($file, PHP_URL_SCHEME);
1354 if ($urlScheme === 'https' || $urlScheme === 'http' || is_file(PATH_site . $file)) {
1355 return $file;
1356 }
1357
1358 // this call also resolves EXT:myext/ files
1359 $file = GeneralUtility::getFileAbsFileName($file);
1360 if (!$file) {
1361 if ($this->tt_track) {
1362 $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1363 }
1364 return null;
1365 }
1366
1367 $file = PathUtility::stripPathSitePrefix($file);
1368
1369 // Check if the found file is in the allowed paths
1370 foreach ($this->allowedPaths as $val) {
1371 if (GeneralUtility::isFirstPartOfStr($file, $val)) {
1372 $this->fileCache[$hash] = $file;
1373 return $file;
1374 }
1375 }
1376
1377 if ($this->tt_track) {
1378 $this->getTimeTracker()->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1379 }
1380 return null;
1381 }
1382
1383 /**
1384 * Compiles the content for the page <title> tag.
1385 *
1386 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1387 * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1388 * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1389 * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
1390 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1391 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContentWithHeader()
1392 */
1393 public function printTitle($pageTitle, $noTitle = false, $showTitleFirst = false, $pageTitleSeparator = '')
1394 {
1395 $siteTitle = trim($this->setup['sitetitle']);
1396 $pageTitle = $noTitle ? '' : $pageTitle;
1397 if ($showTitleFirst) {
1398 $temp = $siteTitle;
1399 $siteTitle = $pageTitle;
1400 $pageTitle = $temp;
1401 }
1402 // only show a separator if there are both site title and page title
1403 if ($pageTitle === '' || $siteTitle === '') {
1404 $pageTitleSeparator = '';
1405 } elseif (empty($pageTitleSeparator)) {
1406 // use the default separator if non given
1407 $pageTitleSeparator = ': ';
1408 }
1409 return $siteTitle . $pageTitleSeparator . $pageTitle;
1410 }
1411
1412 /**
1413 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1414 *
1415 * @param string $list A list of UIDs for which the rootline-level should get returned
1416 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1417 */
1418 public function getRootlineLevel($list)
1419 {
1420 $idx = 0;
1421 foreach ($this->rootLine as $page) {
1422 if (GeneralUtility::inList($list, $page['uid'])) {
1423 return $idx;
1424 }
1425 $idx++;
1426 }
1427 return false;
1428 }
1429
1430 /*******************************************************************
1431 *
1432 * Functions for creating links
1433 *
1434 *******************************************************************/
1435 /**
1436 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1437 * See the references below.
1438 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1439 * 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.
1440 *
1441 * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, title and sectionIndex_uid.
1442 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1443 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1444 * @param string $_ not in use anymore
1445 * @param array $overrideArray Array with overriding values for the $page array.
1446 * @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.
1447 * @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.
1448 * @param string $targetDomain The target Doamin, if any was detected in typolink
1449 * @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
1450 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1451 */
1452 public function linkData($page, $oTarget, $no_cache, $_ = null, $overrideArray = null, $addParams = '', $typeOverride = '', $targetDomain = '')
1453 {
1454 $LD = [];
1455 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1456 if (is_array($overrideArray)) {
1457 foreach ($overrideArray as $theKey => $theNewVal) {
1458 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1459 $page[$theKey] = $theNewVal;
1460 }
1461 }
1462 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1463 if (!strstr($addParams, '&MP=')) {
1464 // Looking for hardcoded defaults:
1465 if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
1466 $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
1467 } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
1468 // Else look in automatically created map:
1469 $m = $this->getFromMPmap($page['uid']);
1470 if ($m) {
1471 $addParams .= '&MP=' . rawurlencode($m);
1472 }
1473 }
1474 }
1475 // Setting ID/alias:
1476 $script = 'index.php';
1477 if ($page['alias']) {
1478 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1479 } else {
1480 $LD['url'] = $script . '?id=' . $page['uid'];
1481 }
1482 // Setting target
1483 $LD['target'] = trim($page['target']) ?: $oTarget;
1484 // typeNum
1485 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1486 if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
1487 $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
1488 }
1489 if ((string)$typeOverride !== '') {
1490 $typeNum = $typeOverride;
1491 }
1492 // Override...
1493 if ($typeNum) {
1494 $LD['type'] = '&type=' . (int)$typeNum;
1495 } else {
1496 $LD['type'] = '';
1497 }
1498 // Preserving the type number.
1499 $LD['orig_type'] = $LD['type'];
1500 // noCache
1501 $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
1502 // linkVars
1503 if ($addParams) {
1504 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', false, true);
1505 } else {
1506 $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
1507 }
1508 // Add absRefPrefix if exists.
1509 $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
1510 // 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.
1511 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1512 // Compile the normal total url
1513 $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
1514 // Call post processing function for link rendering:
1515 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'])) {
1516 $_params = [
1517 'LD' => &$LD,
1518 'args' => ['page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
1519 'typeNum' => $typeNum
1520 ];
1521 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] as $_funcRef) {
1522 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1523 }
1524 }
1525 // Return the LD-array
1526 return $LD;
1527 }
1528
1529 /**
1530 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1531 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1532 *
1533 * @param int $pageId Page id to return MPvar value for.
1534 * @return string
1535 * @see initMPmap_create()
1536 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1537 */
1538 public function getFromMPmap($pageId = 0)
1539 {
1540 // Create map if not found already:
1541 if (!is_array($this->MPmap)) {
1542 $this->MPmap = [];
1543 $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), true);
1544 // Traverse rootpoints:
1545 foreach ($rootPoints as $p) {
1546 $initMParray = [];
1547 if ($p === 'root') {
1548 $p = $this->rootLine[0]['uid'];
1549 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1550 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1551 }
1552 }
1553 $this->initMPmap_create($p, $initMParray);
1554 }
1555 }
1556 // Finding MP var for Page ID:
1557 if ($pageId) {
1558 if (is_array($this->MPmap[$pageId]) && !empty($this->MPmap[$pageId])) {
1559 return implode(',', $this->MPmap[$pageId]);
1560 }
1561 }
1562 return '';
1563 }
1564
1565 /**
1566 * Creating MPmap for a certain ID root point.
1567 *
1568 * @param int $id Root id from which to start map creation.
1569 * @param array $MP_array MP_array passed from root page.
1570 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1571 * @see getFromMPvar()
1572 */
1573 public function initMPmap_create($id, $MP_array = [], $level = 0)
1574 {
1575 $id = (int)$id;
1576 if ($id <= 0) {
1577 return;
1578 }
1579 // First level, check id
1580 if (!$level) {
1581 // Find mount point if any:
1582 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
1583 // Overlay mode:
1584 if (is_array($mount_info) && $mount_info['overlay']) {
1585 $MP_array[] = $mount_info['MPvar'];
1586 $id = $mount_info['mount_pid'];
1587 }
1588 // Set mapping information for this level:
1589 $this->MPmap[$id] = $MP_array;
1590 // Normal mode:
1591 if (is_array($mount_info) && !$mount_info['overlay']) {
1592 $MP_array[] = $mount_info['MPvar'];
1593 $id = $mount_info['mount_pid'];
1594 }
1595 }
1596 if ($id && $level < 20) {
1597 $nextLevelAcc = [];
1598 // Select and traverse current level pages:
1599 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1600 $queryBuilder->getRestrictions()
1601 ->removeAll()
1602 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1603 $queryResult = $queryBuilder
1604 ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
1605 ->from('pages')
1606 ->where(
1607 $queryBuilder->expr()->eq(
1608 'pid',
1609 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1610 ),
1611 $queryBuilder->expr()->neq(
1612 'doktype',
1613 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1614 ),
1615 $queryBuilder->expr()->neq(
1616 'doktype',
1617 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
1618 )
1619 )->execute();
1620 while ($row = $queryResult->fetch()) {
1621 // Find mount point if any:
1622 $next_id = $row['uid'];
1623 $next_MP_array = $MP_array;
1624 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
1625 // Overlay mode:
1626 if (is_array($mount_info) && $mount_info['overlay']) {
1627 $next_MP_array[] = $mount_info['MPvar'];
1628 $next_id = $mount_info['mount_pid'];
1629 }
1630 if (!isset($this->MPmap[$next_id])) {
1631 // Set mapping information for this level:
1632 $this->MPmap[$next_id] = $next_MP_array;
1633 // Normal mode:
1634 if (is_array($mount_info) && !$mount_info['overlay']) {
1635 $next_MP_array[] = $mount_info['MPvar'];
1636 $next_id = $mount_info['mount_pid'];
1637 }
1638 // Register recursive call
1639 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1640 $nextLevelAcc[] = [$next_id, $next_MP_array];
1641 }
1642 }
1643 // Call recursively, if any:
1644 foreach ($nextLevelAcc as $pSet) {
1645 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1646 }
1647 }
1648 }
1649
1650 /**
1651 * Adds the TypoScript from the global array.
1652 * The class property isDefaultTypoScriptAdded ensures
1653 * that the adding only happens once.
1654 *
1655 * @see isDefaultTypoScriptAdded
1656 */
1657 protected function addDefaultTypoScript()
1658 {
1659 // Add default TS for all code types, if not done already
1660 if (!$this->isDefaultTypoScriptAdded) {
1661 // adding default setup and constants
1662 // defaultTypoScript_setup is *very* unlikely to be empty
1663 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1664 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1665 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1666 array_unshift($this->templateIncludePaths, '');
1667 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1668 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo)-1]['templateID'];
1669 $defaultTemplateInfo = [
1670 'root' => '',
1671 'next' => '',
1672 'clConst' => '',
1673 'clConf' => '',
1674 'templateID' => '_defaultTypoScript_',
1675 'templateParent' => $rootTemplateId,
1676 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1677 'uid' => '_defaultTypoScript_',
1678 'pid' => '',
1679 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1680 ];
1681 // push info to information arrays used in BE by TemplateTools (Analyzer)
1682 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1683 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1684 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1685 $this->isDefaultTypoScriptAdded = true;
1686 }
1687 }
1688
1689 /**
1690 * @return TypoScriptFrontendController
1691 */
1692 protected function getTypoScriptFrontendController()
1693 {
1694 return $GLOBALS['TSFE'];
1695 }
1696
1697 /**
1698 * @return TimeTracker
1699 */
1700 protected function getTimeTracker()
1701 {
1702 return GeneralUtility::makeInstance(TimeTracker::class);
1703 }
1704
1705 /**
1706 * Returns data stored for the hash string in the cache "cache_hash"
1707 * used to store the parsed TypoScript template structures.
1708 *
1709 * @param string $identifier The hash-string which was used to store the data value
1710 * @return mixed The data from the cache
1711 */
1712 protected function getCacheEntry($identifier)
1713 {
1714 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1715 }
1716
1717 /**
1718 * Stores $data in the 'cache_hash' cache with the hash key $identifier
1719 *
1720 * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1721 * @param mixed $data The data to store
1722 * @param string $tag Is just a textual identification in order to inform about the content
1723 */
1724 protected function setCacheEntry($identifier, $data, $tag)
1725 {
1726 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1727 }
1728 }