Passed
Push — master ( 49da42...5ad792 )
by
unknown
13:36
created

TemplateService::getProcessExtensionStatics()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\TypoScript;
17
18
use TYPO3\CMS\Core\Cache\CacheManager;
19
use TYPO3\CMS\Core\Context\Context;
20
use TYPO3\CMS\Core\Database\Connection;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Database\Query\Restriction\AbstractRestrictionContainer;
23
use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
24
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
25
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
26
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
27
use TYPO3\CMS\Core\Package\PackageManager;
28
use TYPO3\CMS\Core\Site\Entity\Site;
29
use TYPO3\CMS\Core\Site\SiteFinder;
30
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
31
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
32
use TYPO3\CMS\Core\Utility\ArrayUtility;
33
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
36
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
37
38
/**
39
 * Template object that is responsible for generating the TypoScript template based on template records.
40
 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
41
 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
42
 */
43
class TemplateService
44
{
45
    /**
46
     * option to enable logging, time-tracking (FE-only)
47
     * usually, this is only done when
48
     *  - in FE a BE_USER is logged-in
49
     *  - in BE when the BE_USER needs information about the template (TypoScript module)
50
     * @var bool
51
     */
52
    protected $verbose = false;
53
54
    /**
55
     * If set, the global tt-timeobject is used to log the performance.
56
     *
57
     * @var bool
58
     */
59
    public $tt_track = true;
60
61
    /**
62
     * This array is passed on to matchObj by generateConfig().
63
     * If it holds elements, they are used for matching instead. See comment at the match-class.
64
     * Used for backend modules only. Never frontend!
65
     *
66
     * @var array
67
     * @internal
68
     */
69
    public $matchAlternative = [];
70
71
    /**
72
     * If set, the match-class matches everything! Used for backend modules only. Never frontend!
73
     *
74
     * @var bool
75
     */
76
    protected $matchAll = false;
77
78
    /**
79
     * Externally set breakpoints (used by Backend Modules)
80
     *
81
     * @var int
82
     */
83
    public $ext_constants_BRP = 0;
84
85
    /**
86
     * @var int
87
     */
88
    public $ext_config_BRP = 0;
89
90
    /**
91
     * @var bool
92
     */
93
    public $ext_regLinenumbers = false;
94
95
    /**
96
     * @var bool
97
     */
98
    public $ext_regComments = false;
99
100
    /**
101
     * Set if preview of some kind is enabled.
102
     *
103
     * @var bool
104
     */
105
    protected $simulationHiddenOrTime = false;
106
107
    /**
108
     * Set, if the TypoScript template structure is loaded and OK, see ->start()
109
     *
110
     * @var bool
111
     */
112
    public $loaded = false;
113
114
    /**
115
     * @var array Contains TypoScript setup part after parsing
116
     */
117
    public $setup = [];
118
119
    /**
120
     * @var array
121
     */
122
    public $flatSetup = [];
123
124
    /**
125
     * For fetching TypoScript code from template hierarchy before parsing it.
126
     * Each array contains code field values from template records/files:
127
     * Setup field
128
     *
129
     * @var array
130
     */
131
    public $config = [];
132
133
    /**
134
     * Constant field
135
     *
136
     * @var array
137
     */
138
    public $constants = [];
139
140
    /**
141
     * Holds the include paths of the templates (empty if from database)
142
     *
143
     * @var array
144
     */
145
    protected $templateIncludePaths = [];
146
147
    /**
148
     * For Template Analyzer in backend
149
     *
150
     * @var array
151
     */
152
    public $hierarchyInfo = [];
153
154
    /**
155
     * For Template Analyzer in backend (setup content only)
156
     *
157
     * @var array
158
     */
159
    protected $hierarchyInfoToRoot = [];
160
161
    /**
162
     * The Page UID of the root page
163
     *
164
     * @var int
165
     */
166
    protected $rootId;
167
168
    /**
169
     * The rootline from current page to the root page
170
     *
171
     * @var array
172
     */
173
    public $rootLine;
174
175
    /**
176
     * Rootline all the way to the root. Set but runThroughTemplates
177
     *
178
     * @var array
179
     */
180
    protected $absoluteRootLine;
181
182
    /**
183
     * Array of arrays with title/uid of templates in hierarchy
184
     *
185
     * @var array
186
     */
187
    protected $rowSum;
188
189
    /**
190
     * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
191
     *
192
     * @var array|null
193
     */
194
    public $sections;
195
196
    /**
197
     * Tracking all matching conditions found
198
     *
199
     * @var array
200
     */
201
    protected $sectionsMatch;
202
203
    /**
204
     * Used by Backend only (Typoscript Template Analyzer)
205
     * @var string[]
206
     */
207
    public $clearList_const = [];
208
209
    /**
210
     * Used by Backend only (Typoscript Template Analyzer)
211
     *
212
     * @var array
213
     */
214
    public $clearList_setup = [];
215
216
    /**
217
     * @var array
218
     */
219
    public $parserErrors = [];
220
221
    /**
222
     * @var array
223
     */
224
    public $setup_constants = [];
225
226
    /**
227
     * Indicator that extension statics are processed.
228
     *
229
     * These files are considered if either a root template
230
     * has been processed or the $processExtensionStatics
231
     * property has been set to TRUE.
232
     *
233
     * @var bool
234
     */
235
    protected $extensionStaticsProcessed = false;
236
237
    /**
238
     * Trigger value, to ensure that extension statics are processed.
239
     *
240
     * @var bool
241
     */
242
    protected $processExtensionStatics = false;
243
244
    /**
245
     * Set to TRUE after the default TypoScript was added during parsing.
246
     * This prevents double inclusion of the same TypoScript code.
247
     *
248
     * @see addDefaultTypoScript()
249
     * @var bool
250
     */
251
    protected $isDefaultTypoScriptAdded = false;
252
253
    /**
254
     * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
255
     *
256
     * This prevents double processing of INCLUDES.
257
     *
258
     * @see processIncludes()
259
     * @var bool
260
     */
261
    protected $processIncludesHasBeenRun = false;
262
263
    /**
264
     * Contains the restrictions about deleted, and some frontend related topics
265
     * @var AbstractRestrictionContainer
266
     */
267
    protected $queryBuilderRestrictions;
268
269
    /**
270
     * @var Context
271
     */
272
    protected $context;
273
274
    /**
275
     * @var PackageManager
276
     */
277
    protected $packageManager;
278
279
    /**
280
     * @var TypoScriptFrontendController|null
281
     */
282
    protected $frontendController;
283
284
    /**
285
     * @param Context|null $context
286
     * @param PackageManager|null $packageManager
287
     * @param TypoScriptFrontendController|null $frontendController
288
     */
289
    public function __construct(Context $context = null, PackageManager $packageManager = null, TypoScriptFrontendController $frontendController = null)
290
    {
291
        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
292
        $this->packageManager = $packageManager ?? GeneralUtility::makeInstance(PackageManager::class);
293
        $this->frontendController = $frontendController;
294
        $this->initializeDatabaseQueryRestrictions();
295
        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
296
            // Set the simulation flag, if simulation is detected!
297
            $this->simulationHiddenOrTime = true;
298
        }
299
        $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
300
    }
301
302
    /**
303
     * @return bool
304
     */
305
    public function getProcessExtensionStatics()
306
    {
307
        return $this->processExtensionStatics;
308
    }
309
310
    /**
311
     * @param bool $processExtensionStatics
312
     */
313
    public function setProcessExtensionStatics($processExtensionStatics)
314
    {
315
        $this->processExtensionStatics = (bool)$processExtensionStatics;
316
    }
317
318
    /**
319
     * sets the verbose parameter
320
     * @param bool $verbose
321
     */
322
    public function setVerbose($verbose)
323
    {
324
        $this->verbose = (bool)$verbose;
325
    }
326
327
    /**
328
     * Set up the query builder restrictions, optionally include hidden records
329
     */
330
    protected function initializeDatabaseQueryRestrictions()
331
    {
332
        $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
333
334
        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)) {
335
            $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
336
        }
337
    }
338
339
    /**
340
     * Fetches the "currentPageData" array from cache
341
     *
342
     * NOTE about currentPageData:
343
     * It holds information about the TypoScript conditions along with the list
344
     * of template uid's which is used on the page. In the getFromCache() function
345
     * in TSFE, currentPageData is used to evaluate if there is a template and
346
     * if the matching conditions are alright. Unfortunately this does not take
347
     * into account if the templates in the rowSum of currentPageData has
348
     * changed composition, eg. due to hidden fields or start/end time. So if a
349
     * template is hidden or times out, it'll not be discovered unless the page
350
     * is regenerated - at least the this->start function must be called,
351
     * because this will make a new portion of data in currentPageData string.
352
     *
353
     * @param int $pageId
354
     * @param string $mountPointValue
355
     * @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
356
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
357
     * @internal
358
     */
359
    public function getCurrentPageData(int $pageId, string $mountPointValue)
360
    {
361
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection')->get($pageId . '_' . GeneralUtility::md5int($mountPointValue));
362
    }
363
364
    /**
365
     * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
366
     *
367
     * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
368
     * @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.
369
     */
370
    public function matching($cc)
371
    {
372
        if (is_array($cc['all'])) {
373
            /** @var ConditionMatcher $matchObj */
374
            $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
375
            $matchObj->setRootline((array)$cc['rootLine']);
376
            $sectionsMatch = [];
377
            foreach ($cc['all'] as $key => $pre) {
378
                if ($matchObj->match($pre)) {
379
                    $sectionsMatch[$key] = $pre;
380
                }
381
            }
382
            $cc['match'] = $sectionsMatch;
383
        }
384
        return $cc;
385
    }
386
387
    /**
388
     * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
389
     * 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.
390
     * Sets $this->setup to the parsed TypoScript template array
391
     *
392
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
393
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
394
     */
395
    public function start($theRootLine)
396
    {
397
        $cc = [];
398
        if (is_array($theRootLine)) {
0 ignored issues
show
introduced by
The condition is_array($theRootLine) is always true.
Loading history...
399
            $constantsData = [];
400
            $setupData = [];
401
            $cacheIdentifier = '';
402
            // Flag that indicates that the existing data in cache_pagesection
403
            // could be used (this is the case if $TSFE->all is set, and the
404
            // rowSum still matches). Based on this we decide if cache_pagesection
405
            // needs to be updated...
406
            $isCached = false;
407
            $this->runThroughTemplates($theRootLine);
408
            if ($this->getTypoScriptFrontendController()->all) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getTypoScriptFrontendController()->all of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
409
                $cc = $this->getTypoScriptFrontendController()->all;
410
                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
411
                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
412
                    $cc = [];
413
                } else {
414
                    // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
415
                    if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
416
                        $isCached = true;
417
                    }
418
                    // 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)...
419
                    unset($cc['rootLine']);
420
                }
421
            }
422
            // This is about getting the hash string which is used to fetch the cached TypoScript template.
423
            // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
424
            if (!empty($cc)) {
425
                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
426
                if (!$cc['match']) {
427
                    // @todo check if this can ever be the case - otherwise remove
428
                    $cc = $this->matching($cc);
429
                    ksort($cc);
430
                }
431
                $cacheIdentifier = md5(serialize($cc));
432
            } else {
433
                // 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.
434
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
435
                $result = $this->getCacheEntry($rowSumHash);
436
                if (is_array($result)) {
437
                    $cc['all'] = $result;
438
                    $cc['rowSum'] = $this->rowSum;
439
                    $cc = $this->matching($cc);
440
                    ksort($cc);
441
                    $cacheIdentifier = md5(serialize($cc));
442
                }
443
            }
444
            if ($cacheIdentifier) {
445
                // Get TypoScript setup array
446
                $cachedData = $this->getCacheEntry($cacheIdentifier);
447
                if (is_array($cachedData)) {
448
                    $constantsData = $cachedData['constants'];
449
                    $setupData = $cachedData['setup'];
450
                }
451
            }
452
            if (!empty($setupData) && !$this->context->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
453
                // TypoScript constants + setup are found in the cache
454
                $this->setup_constants = $constantsData;
455
                $this->setup = $setupData;
456
                if ($this->tt_track) {
457
                    $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
458
                }
459
            } else {
460
                if ($this->tt_track) {
461
                    $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
462
                }
463
464
                // Make configuration
465
                $this->generateConfig();
466
                // This stores the template hash thing
467
                $cc = [];
468
                // All sections in the template at this point is found
469
                $cc['all'] = $this->sections;
470
                // The line of templates is collected
471
                $cc['rowSum'] = $this->rowSum;
472
                $cc = $this->matching($cc);
473
                ksort($cc);
474
                $cacheIdentifier = md5(serialize($cc));
475
                // This stores the data.
476
                $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
477
                if ($this->tt_track) {
478
                    $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
479
                }
480
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
481
                $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
482
            }
483
            // Add rootLine
484
            $cc['rootLine'] = $this->rootLine;
485
            ksort($cc);
486
            // Make global and save
487
            $this->getTypoScriptFrontendController()->all = $cc;
488
            // Matching must be executed for every request, so this must never be part of the pagesection cache!
489
            unset($cc['match']);
490
            if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
491
                // Only save the data if we're not simulating by hidden/starttime/endtime
492
                $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
493
                /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
494
                $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection');
495
                $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
496
                    'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
497
                    'mpvarHash_' . $mpvarHash
498
                ]);
499
            }
500
            // If everything OK.
501
            if ($this->rootId && $this->rootLine && $this->setup) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rootLine of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
502
                $this->loaded = true;
503
            }
504
        }
505
    }
506
507
    /*******************************************************************
508
     *
509
     * Fetching TypoScript code text for the Template Hierarchy
510
     *
511
     *******************************************************************/
512
    /**
513
     * 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.
514
     * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
515
     * 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
516
     *
517
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
518
     * @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)
519
     * @see start()
520
     */
521
    public function runThroughTemplates($theRootLine, $start_template_uid = 0)
522
    {
523
        $this->constants = [];
524
        $this->config = [];
525
        $this->rowSum = [];
526
        $this->hierarchyInfoToRoot = [];
527
        $this->absoluteRootLine = $theRootLine;
528
        $this->isDefaultTypoScriptAdded = false;
529
530
        reset($this->absoluteRootLine);
531
        $c = count($this->absoluteRootLine);
532
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
533
        for ($a = 0; $a < $c; $a++) {
534
            $where = [
535
                $queryBuilder->expr()->eq(
536
                    'pid',
537
                    $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
538
                )
539
            ];
540
            // If first loop AND there is set an alternative template uid, use that
541
            if ($a === $c - 1 && $start_template_uid) {
542
                $where[] = $queryBuilder->expr()->eq(
543
                    'uid',
544
                    $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
545
                );
546
            }
547
            $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
548
            $queryResult = $queryBuilder
549
                ->select('*')
550
                ->from('sys_template')
551
                ->where(...$where)
552
                ->orderBy('root', 'DESC')
553
                ->addOrderBy('sorting')
554
                ->setMaxResults(1)
555
                ->execute();
556
            if ($row = $queryResult->fetch()) {
557
                $this->versionOL($row);
558
                if (is_array($row)) {
559
                    $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
560
                }
561
            }
562
            $this->rootLine[] = $this->absoluteRootLine[$a];
563
        }
564
565
        // Hook into the default TypoScript to add custom typoscript logic
566
        $hookParameters = [
567
            'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
568
            'isDefaultTypoScriptAdded'  => &$this->isDefaultTypoScriptAdded,
569
            'absoluteRootLine' => &$this->absoluteRootLine,
570
            'rootLine'         => &$this->rootLine,
571
            'startTemplateUid' => $start_template_uid,
572
        ];
573
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
574
            GeneralUtility::callUserFunction($listener, $hookParameters, $this);
575
        }
576
577
        // Process extension static files if not done yet, but explicitly requested
578
        if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
579
            $this->addExtensionStatics('sys_0', 'sys_0', 0);
0 ignored issues
show
Bug introduced by
The method addExtensionStatics() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

579
            $this->/** @scrutinizer ignore-call */ 
580
                   addExtensionStatics('sys_0', 'sys_0', 0);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
580
        }
581
582
        // Add the global default TypoScript from the TYPO3_CONF_VARS
583
        $this->addDefaultTypoScript();
584
585
        $this->processIncludes();
586
    }
587
588
    /**
589
     * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
590
     * Builds up $this->rowSum
591
     *
592
     * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
593
     * @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.
594
     * @param int $pid The PID of the input template record
595
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
596
     * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
597
     * @param string $includePath Specifies the path from which the template was included (used with static_includes)
598
     * @see runThroughTemplates()
599
     */
600
    public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
601
    {
602
        // Adding basic template record information to rowSum array
603
        $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
604
        // Processing "Clear"-flags
605
        $clConst = 0;
606
        $clConf = 0;
607
        if (!empty($row['clear'])) {
608
            $clConst = $row['clear'] & 1;
609
            $clConf = $row['clear'] & 2;
610
            if ($clConst) {
611
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
612
                foreach ($this->constants as &$constantConfiguration) {
613
                    $constantConfiguration = '';
614
                }
615
                unset($constantConfiguration);
616
                $this->clearList_const = [];
617
            }
618
            if ($clConf) {
619
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
620
                foreach ($this->config as &$configConfiguration) {
621
                    $configConfiguration = '';
622
                }
623
                unset($configConfiguration);
624
                $this->hierarchyInfoToRoot = [];
625
                $this->clearList_setup = [];
626
            }
627
        }
628
        // Include files (from extensions) (#1/2)
629
        // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
630
        if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
631
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
632
        }
633
        // Include "Based On" sys_templates:
634
        // 'basedOn' is a list of templates to include
635
        if (trim($row['basedOn'] ?? '')) {
636
            // Normal Operation, which is to include the "based-on" sys_templates,
637
            // if they are not already included, and maintaining the sorting of the templates
638
            $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
639
            // skip template if it's already included
640
            foreach ($basedOnIds as $key => $basedOnId) {
641
                if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
642
                    unset($basedOnIds[$key]);
643
                }
644
            }
645
            if (!empty($basedOnIds)) {
646
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
647
                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
648
                $queryResult = $queryBuilder
649
                    ->select('*')
650
                    ->from('sys_template')
651
                    ->where(
652
                        $queryBuilder->expr()->in(
653
                            'uid',
654
                            $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
655
                        )
656
                    )
657
                    ->execute();
658
                // make it an associative array with the UID as key
659
                $subTemplates = [];
660
                while ($rowItem = $queryResult->fetch()) {
661
                    $subTemplates[(int)$rowItem['uid']] = $rowItem;
662
                }
663
                // Traversing list again to ensure the sorting of the templates
664
                foreach ($basedOnIds as $id) {
665
                    if (is_array($subTemplates[$id])) {
666
                        $this->versionOL($subTemplates[$id]);
667
                        $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
668
                    }
669
                }
670
            }
671
        }
672
        // Include files (from extensions) (#2/2)
673
        if (!empty($row['includeStaticAfterBasedOn'])) {
674
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
675
        }
676
        // Creating hierarchy information; Used by backend analysis tools
677
        $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
678
            'root' => trim($row['root'] ?? ''),
679
            'clConst' => $clConst,
680
            'clConf' => $clConf,
681
            'templateID' => $templateID,
682
            'templateParent' => $templateParent,
683
            'title' => $row['title'],
684
            'uid' => $row['uid'],
685
            'pid' => $row['pid'] ?? null,
686
            'configLines' => substr_count($row['config'], LF) + 1
687
        ]);
688
        // Adding the content of the fields constants (Constants) and config (Setup)
689
        $this->constants[] = $row['constants'];
690
        $this->config[] = $row['config'];
691
        $this->templateIncludePaths[] = $includePath;
692
        // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
693
        $this->clearList_const[] = $templateID;
694
        $this->clearList_setup[] = $templateID;
695
        // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
696
        if (trim($row['root'] ?? null)) {
697
            $this->rootId = $pid;
698
            $this->rootLine = [];
699
        }
700
    }
701
702
    /**
703
     * This function can be used to update the data of the current rootLine
704
     * e.g. when a different language is used.
705
     *
706
     * This function must not be used if there are different pages in the
707
     * rootline as before!
708
     *
709
     * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
710
     * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
711
     */
712
    public function updateRootlineData($fullRootLine)
713
    {
714
        if (!is_array($this->rootLine) || empty($this->rootLine)) {
0 ignored issues
show
introduced by
The condition is_array($this->rootLine) is always true.
Loading history...
715
            return;
716
        }
717
718
        $fullRootLineByUid = [];
719
        foreach ($fullRootLine as $rootLineData) {
720
            $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
721
        }
722
723
        foreach ($this->rootLine as $level => $dataArray) {
724
            $currentUid = $dataArray['uid'];
725
726
            if (!array_key_exists($currentUid, $fullRootLineByUid)) {
727
                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);
728
            }
729
730
            $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
731
        }
732
    }
733
734
    /**
735
     * Includes static template files (from extensions) for the input template record row.
736
     *
737
     * @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.
738
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
739
     * @param int $pid The PID of the input template record
740
     * @param array $row A full TypoScript template record
741
     * @see processTemplate()
742
     * @internal
743
     */
744
    public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
745
    {
746
        // Call function for link rendering:
747
        $_params = [
748
            'idList' => &$idList,
749
            'templateId' => &$templateID,
750
            'pid' => &$pid,
751
            'row' => &$row
752
        ];
753
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
754
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
755
        }
756
        // If "Include before all static templates if root-flag is set" is set:
757
        $staticFileMode = $row['static_file_mode'] ?? null;
758
        if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
759
            $this->addExtensionStatics($idList, $templateID, $pid);
760
        }
761
        // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
762
        if (trim($row['include_static_file'] ?? '')) {
763
            $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
764
            // Traversing list
765
            foreach ($include_static_fileArr as $ISF_file) {
766
                if (strpos($ISF_file, 'EXT:') === 0) {
767
                    [$ISF_extKey, $ISF_localPath] = explode('/', substr($ISF_file, 4), 2);
768
                    if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
769
                        $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
770
                        $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
771
                        if (@is_dir($ISF_filePath)) {
772
                            $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
773
                            $subrow = [
774
                                'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
775
                                'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
776
                                'include_static' => @file_exists($ISF_filePath . 'include_static.txt') ? implode(',', array_unique(GeneralUtility::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
777
                                'include_static_file' => @file_exists($ISF_filePath . 'include_static_file.txt') ? implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
778
                                'title' => $ISF_file,
779
                                'uid' => $mExtKey
780
                            ];
781
                            $subrow = $this->prependStaticExtra($subrow);
782
                            $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
783
                        }
784
                    }
785
                }
786
            }
787
        }
788
        // If "Default (include before if root flag is set)" is set OR
789
        // "Always include before this template record" AND root-flag are set
790
        if ($staticFileMode == 1 || $staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $staticFileMode of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
791
            $this->addExtensionStatics($idList, $templateID, $pid);
792
        }
793
        // Include Static Template Records after all other TypoScript has been included.
794
        $_params = [
795
            'idList' => &$idList,
796
            'templateId' => &$templateID,
797
            'pid' => &$pid,
798
            'row' => &$row
799
        ];
800
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
801
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
802
        }
803
    }
804
805
    /**
806
     * Retrieves the content of the first existing file by extension order.
807
     * Returns the empty string if no file is found.
808
     *
809
     * @param string $filePath The location of the file.
810
     * @param string $baseName The base file name. "constants" or "setup".
811
     * @return string
812
     */
813
    protected function getTypoScriptSourceFileContent($filePath, $baseName)
814
    {
815
        $extensions = ['.typoscript', '.ts', '.txt'];
816
        foreach ($extensions as $extension) {
817
            $fileName = $filePath . $baseName . $extension;
818
            if (@file_exists($fileName)) {
819
                return file_get_contents($fileName);
820
            }
821
        }
822
        return '';
823
    }
824
825
    /**
826
     * Adds the default TypoScript files for extensions if any.
827
     *
828
     * @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.
829
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
830
     * @param int $pid The PID of the input template record
831
     * @internal
832
     * @see includeStaticTypoScriptSources()
833
     */
834
    public function addExtensionStatics($idList, $templateID, $pid)
835
    {
836
        $this->extensionStaticsProcessed = true;
837
838
        foreach ($this->packageManager->getActivePackages() as $package) {
839
            $extKey = $package->getPackageKey();
840
            $packagePath = $package->getPackagePath();
841
            $filesToCheck = [
842
                'ext_typoscript_constants.txt',
843
                'ext_typoscript_constants.typoscript',
844
                'ext_typoscript_setup.txt',
845
                'ext_typoscript_setup.typoscript',
846
            ];
847
            $files = [];
848
            $hasExtensionStatics = false;
849
            foreach ($filesToCheck as $file) {
850
                $path = $packagePath . $file;
851
                if (@file_exists($path)) {
852
                    $files[$file] = $path;
853
                    $hasExtensionStatics = true;
854
                } else {
855
                    $files[$file] = null;
856
                }
857
            }
858
859
            if ($hasExtensionStatics) {
860
                $mExtKey = str_replace('_', '', $extKey);
861
                $constants = '';
862
                $config = '';
863
864
                if (!empty($files['ext_typoscript_constants.typoscript'])) {
865
                    $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
866
                } elseif (!empty($files['ext_typoscript_constants.txt'])) {
867
                    $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
868
                }
869
870
                if (!empty($files['ext_typoscript_setup.typoscript'])) {
871
                    $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
872
                } elseif (!empty($files['ext_typoscript_setup.txt'])) {
873
                    $config = @file_get_contents($files['ext_typoscript_setup.txt']);
874
                }
875
876
                $this->processTemplate(
877
                    $this->prependStaticExtra([
878
                        'constants' => $constants,
879
                        'config' => $config,
880
                        'title' => $extKey,
881
                        'uid' => $mExtKey
882
                    ]),
883
                    $idList . ',ext_' . $mExtKey,
884
                    $pid,
885
                    'ext_' . $mExtKey,
886
                    $templateID,
887
                    $packagePath
888
                );
889
            }
890
        }
891
    }
892
893
    /**
894
     * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
895
     * 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
896
     *
897
     * @param array $subrow Static template record/file
898
     * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
899
     * @see addExtensionStatics()
900
     * @see includeStaticTypoScriptSources()
901
     */
902
    protected function prependStaticExtra($subrow)
903
    {
904
        // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
905
        $identifier = $subrow['uid'];
906
        $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null;
907
        $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null;
908
        // 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
909
        if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
910
            $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
911
            $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
912
        }
913
        return $subrow;
914
    }
915
916
    /**
917
     * Creating versioning overlay of a sys_template record.
918
     *
919
     * @param array $row Row to overlay (passed by reference)
920
     */
921
    protected function versionOL(&$row)
922
    {
923
        if ($this->context->getPropertyFromAspect('workspace', 'isOffline')) {
924
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class, $this->context);
925
            $pageRepository->versionOL('sys_template', $row);
926
        }
927
    }
928
929
    /*******************************************************************
930
     *
931
     * Parsing TypoScript code text from Template Records into PHP array
932
     *
933
     *******************************************************************/
934
    /**
935
     * Generates the configuration array by replacing constants and parsing the whole thing.
936
     * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
937
     *
938
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
939
     * @see start()
940
     */
941
    public function generateConfig()
942
    {
943
        // Add default TS for all code types
944
        $this->addDefaultTypoScript();
945
946
        // Parse the TypoScript code text for include-instructions!
947
        $this->processIncludes();
948
        // ****************************
949
        // Parse TypoScript Constants
950
        // ****************************
951
        // Initialize parser and match-condition classes:
952
        /** @var Parser\TypoScriptParser $constants */
953
        $constants = GeneralUtility::makeInstance(TypoScriptParser::class);
954
        $constants->breakPointLN = (int)$this->ext_constants_BRP;
955
        /** @var ConditionMatcher $matchObj */
956
        $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
957
        $matchObj->setSimulateMatchConditions($this->matchAlternative);
958
        $matchObj->setSimulateMatchResult((bool)$this->matchAll);
959
        // Traverse constants text fields and parse them
960
        foreach ($this->constants as $str) {
961
            $constants->parse($str, $matchObj);
962
        }
963
        // Read out parse errors if any
964
        $this->parserErrors['constants'] = $constants->errors;
965
        // 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)
966
        $this->flatSetup = ArrayUtility::flatten($constants->setup, '', true);
967
        // ***********************************************
968
        // Parse TypoScript Setup (here called "config")
969
        // ***********************************************
970
        // Initialize parser and match-condition classes:
971
        /** @var Parser\TypoScriptParser $config */
972
        $config = GeneralUtility::makeInstance(TypoScriptParser::class);
973
        $config->breakPointLN = (int)$this->ext_config_BRP;
974
        $config->regLinenumbers = $this->ext_regLinenumbers;
975
        $config->regComments = $this->ext_regComments;
976
        $config->setup = $this->setup;
977
        // Transfer information about conditions found in "Constants" and which of them returned TRUE.
978
        $config->sections = $constants->sections;
979
        $config->sectionsMatch = $constants->sectionsMatch;
980
        // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
981
        $all = '';
982
        foreach ($this->config as $str) {
983
            $all .= '
984
[GLOBAL]
985
' . $str;
986
        }
987
        // Substitute constants in the Setup code:
988
        if ($this->tt_track) {
989
            $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
990
        }
991
        $all = $this->substituteConstants($all);
992
        if ($this->tt_track) {
993
            $this->getTimeTracker()->pull();
994
        }
995
996
        // Searching for possible unsubstituted constants left (only for information)
997
        if ($this->verbose) {
998
            if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
999
                if ($this->tt_track) {
1000
                    $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1001
                }
1002
            }
1003
        }
1004
1005
        // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1006
        if ($this->tt_track) {
1007
            $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1008
        }
1009
        // Finally parse the Setup field TypoScript code (where constants are now substituted)
1010
        $config->parse($all, $matchObj);
1011
        // Read out parse errors if any
1012
        $this->parserErrors['config'] = $config->errors;
1013
        // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1014
        $this->setup = $config->setup;
1015
        // Do the same for the constants
1016
        $this->setup_constants = $constants->setup;
1017
        // ****************************************************************
1018
        // Final processing of the $this->setup TypoScript Template array
1019
        // Basically: This is unsetting/setting of certain reserved keys.
1020
        // ****************************************************************
1021
        // 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!
1022
        unset($this->setup['types.']);
1023
        unset($this->setup['types']);
1024
        if (is_array($this->setup)) {
1025
            foreach ($this->setup as $key => $value) {
1026
                if ($value === 'PAGE') {
1027
                    // Set the typeNum of the current page object:
1028
                    if (isset($this->setup[$key . '.']['typeNum'])) {
1029
                        $typeNum = $this->setup[$key . '.']['typeNum'];
1030
                        $this->setup['types.'][$typeNum] = $key;
1031
                    } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1032
                        $this->setup['types.'][0] = $key;
1033
                    }
1034
                }
1035
            }
1036
        }
1037
        unset($this->setup['temp.']);
1038
        unset($constants);
1039
        // Storing the conditions found/matched information:
1040
        $this->sections = $config->sections;
1041
        $this->sectionsMatch = $config->sectionsMatch;
1042
    }
1043
1044
    /**
1045
     * Searching TypoScript code text (for constants and config (Setup))
1046
     * for include instructions and does the inclusion of external TypoScript files
1047
     * if needed.
1048
     *
1049
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1050
     * @see generateConfig()
1051
     */
1052
    protected function processIncludes()
1053
    {
1054
        if ($this->processIncludesHasBeenRun) {
1055
            return;
1056
        }
1057
1058
        $paths = $this->templateIncludePaths;
1059
        $files = [];
1060
        foreach ($this->constants as &$value) {
1061
            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1062
            $files = array_merge($files, $includeData['files']);
1063
            $value = $includeData['typoscript'];
1064
        }
1065
        unset($value);
1066
        $paths = $this->templateIncludePaths;
1067
        foreach ($this->config as &$value) {
1068
            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1069
            $files = array_merge($files, $includeData['files']);
1070
            $value = $includeData['typoscript'];
1071
        }
1072
        unset($value);
1073
1074
        if (!empty($files)) {
1075
            $files = array_unique($files);
1076
            foreach ($files as $file) {
1077
                $this->rowSum[] = [$file, filemtime($file)];
1078
            }
1079
        }
1080
1081
        $this->processIncludesHasBeenRun = true;
1082
    }
1083
1084
    /**
1085
     * Substitutes the constants from $this->flatSetup in the text string $all
1086
     *
1087
     * @param string $all TypoScript code text string
1088
     * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1089
     * @see generateConfig()
1090
     */
1091
    protected function substituteConstants($all)
1092
    {
1093
        if ($this->tt_track) {
1094
            $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1095
        }
1096
        $noChange = false;
1097
        // Recursive substitution of constants (up to 10 nested levels)
1098
        for ($i = 0; $i < 10 && !$noChange; $i++) {
1099
            $old_all = $all;
1100
            $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1101
            if ($old_all == $all) {
1102
                $noChange = true;
1103
            }
1104
        }
1105
        return $all;
1106
    }
1107
1108
    /**
1109
     * Call back method for preg_replace_callback in substituteConstants
1110
     *
1111
     * @param array $matches Regular expression matches
1112
     * @return string Replacement
1113
     * @see substituteConstants()
1114
     * @internal
1115
     */
1116
    public function substituteConstantsCallBack($matches)
1117
    {
1118
        // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1119
        return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1120
    }
1121
1122
    /*******************************************************************
1123
     *
1124
     * Various API functions, used from elsewhere in the frontend classes
1125
     *
1126
     *******************************************************************/
1127
1128
    /**
1129
     * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1130
     *
1131
     * @param string $list A list of UIDs for which the rootline-level should get returned
1132
     * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1133
     */
1134
    public function getRootlineLevel($list)
1135
    {
1136
        $idx = 0;
1137
        foreach ($this->rootLine as $page) {
1138
            if (GeneralUtility::inList($list, $page['uid'])) {
1139
                return $idx;
1140
            }
1141
            $idx++;
1142
        }
1143
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
1144
    }
1145
1146
    /**
1147
     * Returns the page ID of the rootlevel
1148
     *
1149
     * @return int
1150
     */
1151
    public function getRootId(): int
1152
    {
1153
        return (int)$this->rootId;
1154
    }
1155
1156
    /*******************************************************************
1157
     *
1158
     * Functions for creating links
1159
     *
1160
     *******************************************************************/
1161
    /**
1162
     * Adds the TypoScript from the global array.
1163
     * The class property isDefaultTypoScriptAdded ensures
1164
     * that the adding only happens once.
1165
     *
1166
     * @see isDefaultTypoScriptAdded
1167
     */
1168
    protected function addDefaultTypoScript()
1169
    {
1170
        // Add default TS for all code types, if not done already
1171
        if (!$this->isDefaultTypoScriptAdded) {
1172
            $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1173
1174
            // adding constants from site settings
1175
            $siteConstants = '';
1176
            if ($this->getTypoScriptFrontendController() instanceof TypoScriptFrontendController) {
0 ignored issues
show
introduced by
$this->getTypoScriptFrontendController() is always a sub-type of TYPO3\CMS\Frontend\Contr...criptFrontendController.
Loading history...
1177
                $site = $this->getTypoScriptFrontendController()->getSite();
1178
            } else {
1179
                $currentPage = end($this->absoluteRootLine);
1180
                try {
1181
                    $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId((int)($currentPage['uid'] ?? 0));
1182
                } catch (SiteNotFoundException $exception) {
1183
                    $site = null;
1184
                }
1185
            }
1186
            if ($site instanceof Site) {
0 ignored issues
show
introduced by
$site is always a sub-type of TYPO3\CMS\Core\Site\Entity\Site.
Loading history...
1187
                $siteSettings = $site->getConfiguration()['settings'] ?? [];
1188
                if (!empty($siteSettings)) {
1189
                    $siteSettings = ArrayUtility::flatten($siteSettings);
1190
                    foreach ($siteSettings as $k => $v) {
1191
                        $siteConstants .= $k . ' = ' . $v . LF;
1192
                    }
1193
                }
1194
            }
1195
1196
            if ($siteConstants !== '') {
1197
                // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1198
                array_unshift($this->constants, $siteConstants);
1199
                array_unshift($this->config, '');
1200
                array_unshift($this->templateIncludePaths, '');
1201
                // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1202
                $defaultTemplateInfo = [
1203
                    'root' => '',
1204
                    'clConst' => '',
1205
                    'clConf' => '',
1206
                    'templateID' => '_siteConstants_',
1207
                    'templateParent' => $rootTemplateId,
1208
                    'title' => 'Site settings',
1209
                    'uid' => '_siteConstants_',
1210
                    'pid' => '',
1211
                    'configLines' => 0
1212
                ];
1213
                // push info to information arrays used in BE by TemplateTools (Analyzer)
1214
                array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1215
                array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1216
                array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1217
            }
1218
1219
            // adding default setup and constants
1220
            // defaultTypoScript_setup is *very* unlikely to be empty
1221
            // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1222
            array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1223
            array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1224
            array_unshift($this->templateIncludePaths, '');
1225
            // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1226
            $defaultTemplateInfo = [
1227
                'root' => '',
1228
                'clConst' => '',
1229
                'clConf' => '',
1230
                'templateID' => '_defaultTypoScript_',
1231
                'templateParent' => $rootTemplateId,
1232
                'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1233
                'uid' => '_defaultTypoScript_',
1234
                'pid' => '',
1235
                'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1236
            ];
1237
            // push info to information arrays used in BE by TemplateTools (Analyzer)
1238
            array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1239
            array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1240
            array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1241
1242
            $this->isDefaultTypoScriptAdded = true;
1243
        }
1244
    }
1245
1246
    /**
1247
     * @return TypoScriptFrontendController
1248
     */
1249
    protected function getTypoScriptFrontendController()
1250
    {
1251
        return $this->frontendController ?? $GLOBALS['TSFE'];
1252
    }
1253
1254
    /**
1255
     * @return TimeTracker
1256
     */
1257
    protected function getTimeTracker()
1258
    {
1259
        return GeneralUtility::makeInstance(TimeTracker::class);
1260
    }
1261
1262
    /**
1263
     * Returns data stored for the hash string in the cache "cache_hash"
1264
     * used to store the parsed TypoScript template structures.
1265
     *
1266
     * @param string $identifier The hash-string which was used to store the data value
1267
     * @return mixed The data from the cache
1268
     */
1269
    protected function getCacheEntry($identifier)
1270
    {
1271
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->get($identifier);
1272
    }
1273
1274
    /**
1275
     * Stores $data in the 'hash' cache with the hash key $identifier
1276
     *
1277
     * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1278
     * @param mixed $data The data to store
1279
     * @param string $tag Is just a textual identification in order to inform about the content
1280
     */
1281
    protected function setCacheEntry($identifier, $data, $tag)
1282
    {
1283
        GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->set($identifier, $data, ['ident_' . $tag], 0);
1284
    }
1285
}
1286