Completed
Push — master ( 01e78e...ee7667 )
by
unknown
35:38 queued 22:54
created

TypoScriptFrontendController::initUserGroups()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
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\Frontend\Controller;
17
18
use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
use Psr\Log\LoggerAwareInterface;
21
use Psr\Log\LoggerAwareTrait;
22
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
23
use TYPO3\CMS\Core\Cache\CacheManager;
24
use TYPO3\CMS\Core\Charset\CharsetConverter;
25
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
26
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
27
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
28
use TYPO3\CMS\Core\Context\Context;
29
use TYPO3\CMS\Core\Context\DateTimeAspect;
30
use TYPO3\CMS\Core\Context\LanguageAspect;
31
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
32
use TYPO3\CMS\Core\Context\UserAspect;
33
use TYPO3\CMS\Core\Context\VisibilityAspect;
34
use TYPO3\CMS\Core\Context\WorkspaceAspect;
35
use TYPO3\CMS\Core\Core\Environment;
36
use TYPO3\CMS\Core\Database\Connection;
37
use TYPO3\CMS\Core\Database\ConnectionPool;
38
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
39
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
40
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
41
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
42
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
43
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
44
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
45
use TYPO3\CMS\Core\Exception\Page\RootLineException;
46
use TYPO3\CMS\Core\Http\ImmediateResponseException;
47
use TYPO3\CMS\Core\Http\ServerRequestFactory;
48
use TYPO3\CMS\Core\Localization\LanguageService;
49
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
50
use TYPO3\CMS\Core\Locking\LockFactory;
51
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
52
use TYPO3\CMS\Core\Page\AssetCollector;
53
use TYPO3\CMS\Core\Page\PageRenderer;
54
use TYPO3\CMS\Core\PageTitle\PageTitleProviderManager;
55
use TYPO3\CMS\Core\Resource\Exception;
56
use TYPO3\CMS\Core\Resource\StorageRepository;
57
use TYPO3\CMS\Core\Routing\PageArguments;
58
use TYPO3\CMS\Core\Site\Entity\Site;
59
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
60
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
61
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
62
use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
63
use TYPO3\CMS\Core\Type\Bitmask\Permission;
64
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
65
use TYPO3\CMS\Core\TypoScript\TemplateService;
66
use TYPO3\CMS\Core\Utility\ArrayUtility;
67
use TYPO3\CMS\Core\Utility\GeneralUtility;
68
use TYPO3\CMS\Core\Utility\HttpUtility;
69
use TYPO3\CMS\Core\Utility\MathUtility;
70
use TYPO3\CMS\Core\Utility\PathUtility;
71
use TYPO3\CMS\Core\Utility\RootlineUtility;
72
use TYPO3\CMS\Frontend\Aspect\PreviewAspect;
73
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
74
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
75
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
76
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
77
use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons;
78
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
79
80
/**
81
 * Class for the built TypoScript based frontend. Instantiated in
82
 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
83
 *
84
 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
85
 * as the global object TSFE.
86
 *
87
 * This class has a lot of functions and internal variable which are used from
88
 * \TYPO3\CMS\Frontend\Http\RequestHandler
89
 *
90
 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
91
 *
92
 * The use of this class should be inspired by the order of function calls as
93
 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
94
 */
95
class TypoScriptFrontendController implements LoggerAwareInterface
96
{
97
    use LoggerAwareTrait;
98
99
    /**
100
     * The page id (int)
101
     * @var string
102
     */
103
    public $id = '';
104
105
    /**
106
     * The type (read-only)
107
     * @var int|string
108
     */
109
    public $type = '';
110
111
    /**
112
     * @var Site
113
     */
114
    protected $site;
115
116
    /**
117
     * @var SiteLanguage
118
     */
119
    protected $language;
120
121
    /**
122
     * @var PageArguments
123
     * @internal
124
     */
125
    protected $pageArguments;
126
127
    /**
128
     * Page will not be cached. Write only TRUE. Never clear value (some other
129
     * code might have reasons to set it TRUE).
130
     * @var bool
131
     */
132
    public $no_cache = false;
133
134
    /**
135
     * The rootLine (all the way to tree root, not only the current site!)
136
     * @var array
137
     */
138
    public $rootLine = [];
139
140
    /**
141
     * The pagerecord
142
     * @var array
143
     */
144
    public $page = [];
145
146
    /**
147
     * This will normally point to the same value as id, but can be changed to
148
     * point to another page from which content will then be displayed instead.
149
     * @var int
150
     */
151
    public $contentPid = 0;
152
153
    /**
154
     * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
155
     * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
156
     * should be redirected to.
157
     *
158
     * @var array|null
159
     */
160
    protected $originalMountPointPage;
161
162
    /**
163
     * Gets set when we are processing a page of type shortcut in the early stages
164
     * of the request when we do not know about languages yet, used later in the request
165
     * to determine the correct shortcut in case a translation changes the shortcut
166
     * target
167
     * @var array|null
168
     * @see checkTranslatedShortcut()
169
     */
170
    protected $originalShortcutPage;
171
172
    /**
173
     * sys_page-object, pagefunctions
174
     *
175
     * @var PageRepository|string
176
     */
177
    public $sys_page = '';
178
179
    /**
180
     * Is set to 1 if a pageNotFound handler could have been called.
181
     * @var int
182
     * @internal
183
     */
184
    public $pageNotFound = 0;
185
186
    /**
187
     * Array containing a history of why a requested page was not accessible.
188
     * @var array
189
     */
190
    protected $pageAccessFailureHistory = [];
191
192
    /**
193
     * @var string
194
     * @internal
195
     */
196
    public $MP = '';
197
198
    /**
199
     * The frontend user
200
     *
201
     * @var FrontendUserAuthentication
202
     */
203
    public $fe_user;
204
205
    /**
206
     * Shows whether logins are allowed in branch
207
     * @var bool
208
     */
209
    protected $loginAllowedInBranch = true;
210
211
    /**
212
     * Shows specific mode (all or groups)
213
     * @var string
214
     * @internal
215
     */
216
    protected $loginAllowedInBranch_mode = '';
217
218
    /**
219
     * Value that contains the simulated usergroup if any
220
     * @var int
221
     * @internal only to be used in AdminPanel, and within TYPO3 Core
222
     */
223
    public $simUserGroup = 0;
224
225
    /**
226
     * "CONFIG" object from TypoScript. Array generated based on the TypoScript
227
     * configuration of the current page. Saved with the cached pages.
228
     * @var array
229
     */
230
    public $config = [];
231
232
    /**
233
     * The TypoScript template object. Used to parse the TypoScript template
234
     *
235
     * @var TemplateService
236
     */
237
    public $tmpl;
238
239
    /**
240
     * Is set to the time-to-live time of cached pages. Default is 60*60*24, which is 24 hours.
241
     *
242
     * @var int
243
     * @internal
244
     */
245
    protected $cacheTimeOutDefault = 86400;
246
247
    /**
248
     * Set internally if cached content is fetched from the database.
249
     *
250
     * @var bool
251
     * @internal
252
     */
253
    protected $cacheContentFlag = false;
254
255
    /**
256
     * Set to the expire time of cached content
257
     * @var int
258
     * @internal
259
     */
260
    protected $cacheExpires = 0;
261
262
    /**
263
     * Set if cache headers allowing caching are sent.
264
     * @var bool
265
     * @internal
266
     */
267
    protected $isClientCachable = false;
268
269
    /**
270
     * Used by template fetching system. This array is an identification of
271
     * the template. If $this->all is empty it's because the template-data is not
272
     * cached, which it must be.
273
     * @var array
274
     * @internal
275
     */
276
    public $all = [];
277
278
    /**
279
     * Toplevel - objArrayName, eg 'page'
280
     * @var string
281
     * @internal should only be used by TYPO3 Core
282
     */
283
    public $sPre = '';
284
285
    /**
286
     * TypoScript configuration of the page-object pointed to by sPre.
287
     * $this->tmpl->setup[$this->sPre.'.']
288
     * @var array|string
289
     * @internal should only be used by TYPO3 Core
290
     */
291
    public $pSetup = '';
292
293
    /**
294
     * This hash is unique to the template, the $this->id and $this->type vars and
295
     * the list of groups. Used to get and later store the cached data
296
     * @var string
297
     * @internal
298
     */
299
    public $newHash = '';
300
301
    /**
302
     * This flag is set before the page is generated IF $this->no_cache is set. If this
303
     * flag is set after the page content was generated, $this->no_cache is forced to be set.
304
     * This is done in order to make sure that PHP code from Plugins / USER scripts does not falsely
305
     * clear the no_cache flag.
306
     * @var bool
307
     * @internal
308
     */
309
    protected $no_cacheBeforePageGen = false;
310
311
    /**
312
     * May be set to the pagesTSconfig
313
     * @var array|string
314
     * @internal
315
     */
316
    protected $pagesTSconfig = '';
317
318
    /**
319
     * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
320
     * once. Use associative keys.
321
     *
322
     * Keys in use:
323
     *
324
     * used to accumulate additional HTML-code for the header-section,
325
     * <head>...</head>. Insert either associative keys (like
326
     * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
327
     * (like additionalHeaderData[] = '...')
328
     *
329
     * @var array
330
     */
331
    public $additionalHeaderData = [];
332
333
    /**
334
     * Used to accumulate additional HTML-code for the footer-section of the template
335
     * @var array
336
     */
337
    public $additionalFooterData = [];
338
339
    /**
340
     * Default internal target
341
     * @var string
342
     */
343
    public $intTarget = '';
344
345
    /**
346
     * Default external target
347
     * @var string
348
     */
349
    public $extTarget = '';
350
351
    /**
352
     * Default file link target
353
     * @var string
354
     */
355
    public $fileTarget = '';
356
357
    /**
358
     * If set, typolink() function encrypts email addresses.
359
     * @var string|int
360
     */
361
    public $spamProtectEmailAddresses = 0;
362
363
    /**
364
     * Absolute Reference prefix
365
     * @var string
366
     */
367
    public $absRefPrefix = '';
368
369
    /**
370
     * <A>-tag parameters
371
     * @var string
372
     */
373
    public $ATagParams = '';
374
375
    /**
376
     * Search word regex, calculated if there has been search-words send. This is
377
     * used to mark up the found search words on a page when jumped to from a link
378
     * in a search-result.
379
     * @var string
380
     * @internal
381
     */
382
    public $sWordRegEx = '';
383
384
    /**
385
     * Is set to the incoming array sword_list in case of a page-view jumped to from
386
     * a search-result.
387
     * @var string
388
     * @internal
389
     */
390
    public $sWordList = '';
391
392
    /**
393
     * A string prepared for insertion in all links on the page as url-parameters.
394
     * Based on configuration in TypoScript where you defined which GET_VARS you
395
     * would like to pass on.
396
     * @var string
397
     */
398
    public $linkVars = '';
399
400
    /**
401
     * If set, edit icons are rendered aside content records. Must be set only if
402
     * the ->beUserLogin flag is set and set_no_cache() must be called as well.
403
     * @var string
404
     */
405
    public $displayEditIcons = '';
406
407
    /**
408
     * If set, edit icons are rendered aside individual fields of content. Must be
409
     * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
410
     * well.
411
     * @var string
412
     */
413
    public $displayFieldEditIcons = '';
414
415
    /**
416
     * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
417
     * extensions.
418
     * @var array
419
     */
420
    public $applicationData = [];
421
422
    /**
423
     * @var array
424
     */
425
    public $register = [];
426
427
    /**
428
     * Stack used for storing array and retrieving register arrays (see
429
     * LOAD_REGISTER and RESTORE_REGISTER)
430
     * @var array
431
     */
432
    public $registerStack = [];
433
434
    /**
435
     * Checking that the function is not called eternally. This is done by
436
     * interrupting at a depth of 50
437
     * @var int
438
     */
439
    public $cObjectDepthCounter = 50;
440
441
    /**
442
     * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
443
     * rendered twice through it!
444
     * @var array
445
     */
446
    public $recordRegister = [];
447
448
    /**
449
     * This is set to the [table]:[uid] of the latest record rendered. Note that
450
     * class ContentObjectRenderer has an equal value, but that is pointing to the
451
     * record delivered in the $data-array of the ContentObjectRenderer instance, if
452
     * the cObjects CONTENT or RECORD created that instance
453
     * @var string
454
     */
455
    public $currentRecord = '';
456
457
    /**
458
     * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
459
     * to keep track of access-keys.
460
     * @var array
461
     */
462
    public $accessKey = [];
463
464
    /**
465
     * Used to generate page-unique keys. Point is that uniqid() functions is very
466
     * slow, so a unikey key is made based on this, see function uniqueHash()
467
     * @var int
468
     * @internal
469
     */
470
    protected $uniqueCounter = 0;
471
472
    /**
473
     * @var string
474
     * @internal
475
     */
476
    protected $uniqueString = '';
477
478
    /**
479
     * This value will be used as the title for the page in the indexer (if
480
     * indexing happens)
481
     * @var string
482
     * @internal only used by TYPO3 Core, use PageTitle API instead.
483
     */
484
    public $indexedDocTitle = '';
485
486
    /**
487
     * The base URL set for the page header.
488
     * @var string
489
     */
490
    public $baseUrl = '';
491
492
    /**
493
     * Page content render object
494
     *
495
     * @var ContentObjectRenderer
496
     */
497
    public $cObj;
498
499
    /**
500
     * All page content is accumulated in this variable. See RequestHandler
501
     * @var string
502
     */
503
    public $content = '';
504
505
    /**
506
     * Output charset of the websites content. This is the charset found in the
507
     * header, meta tag etc. If different than utf-8 a conversion
508
     * happens before output to browser. Defaults to utf-8.
509
     * @var string
510
     */
511
    public $metaCharset = 'utf-8';
512
513
    /**
514
     * Internal calculations for labels
515
     *
516
     * @var LanguageService
517
     */
518
    protected $languageService;
519
520
    /**
521
     * @var LockingStrategyInterface[][]
522
     */
523
    protected $locks = [];
524
525
    /**
526
     * @var PageRenderer
527
     */
528
    protected $pageRenderer;
529
530
    /**
531
     * The page cache object, use this to save pages to the cache and to
532
     * retrieve them again
533
     *
534
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
535
     */
536
    protected $pageCache;
537
538
    /**
539
     * @var array
540
     */
541
    protected $pageCacheTags = [];
542
543
    /**
544
     * Content type HTTP header being sent in the request.
545
     * @todo Ticket: #63642 Should be refactored to a request/response model later
546
     * @internal Should only be used by TYPO3 core for now
547
     *
548
     * @var string
549
     */
550
    protected $contentType = 'text/html';
551
552
    /**
553
     * Doctype to use
554
     *
555
     * @var string
556
     */
557
    public $xhtmlDoctype = '';
558
559
    /**
560
     * @var int
561
     */
562
    public $xhtmlVersion;
563
564
    /**
565
     * Originally requested id from the initial $_GET variable
566
     *
567
     * @var int
568
     */
569
    protected $requestedId;
570
571
    /**
572
     * The context for keeping the current state, mostly related to current page information,
573
     * backend user / frontend user access, workspaceId
574
     *
575
     * @var Context
576
     */
577
    protected $context;
578
579
    /**
580
     * Since TYPO3 v10.0, TSFE is composed out of
581
     *  - Context
582
     *  - Site
583
     *  - SiteLanguage
584
     *  - PageArguments (containing ID, Type, cHash and MP arguments)
585
     *
586
     * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
587
     *
588
     * @param Context $context the Context object to work with
589
     * @param SiteInterface $site The resolved site to work with
590
     * @param SiteLanguage $siteLanguage The resolved language to work with
591
     * @param PageArguments $pageArguments The PageArguments object containing Page ID, type and GET parameters
592
     * @param FrontendUserAuthentication $frontendUser a FrontendUserAuthentication object
593
     */
594
    public function __construct(Context $context, SiteInterface $site, SiteLanguage $siteLanguage, PageArguments $pageArguments, FrontendUserAuthentication $frontendUser)
595
    {
596
        $this->initializeContext($context);
597
        $this->site = $site;
0 ignored issues
show
Documentation Bug introduced by
$site is of type TYPO3\CMS\Core\Site\Entity\SiteInterface, but the property $site was declared to be of type TYPO3\CMS\Core\Site\Entity\Site. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
598
        $this->language = $siteLanguage;
599
        $this->setPageArguments($pageArguments);
600
        $this->fe_user = $frontendUser;
601
        $this->uniqueString = md5(microtime());
602
        $this->initPageRenderer();
603
        $this->initCaches();
604
        // Initialize LLL behaviour
605
        $this->setOutputLanguage();
606
    }
607
608
    private function initializeContext(Context $context): void
609
    {
610
        $this->context = $context;
611
        if (!$this->context->hasAspect('frontend.preview')) {
612
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
613
        }
614
    }
615
616
    /**
617
     * Initializes the page renderer object
618
     */
619
    protected function initPageRenderer()
620
    {
621
        if ($this->pageRenderer !== null) {
622
            return;
623
        }
624
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
625
        $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
626
        // As initPageRenderer could be called in constructor and for USER_INTs, this information is only set
627
        // once - in order to not override any previous settings of PageRenderer.
628
        if ($this->language instanceof SiteLanguage) {
0 ignored issues
show
introduced by
$this->language is always a sub-type of TYPO3\CMS\Core\Site\Entity\SiteLanguage.
Loading history...
629
            $this->pageRenderer->setLanguage($this->language->getTypo3Language());
630
        }
631
    }
632
633
    /**
634
     * @param string $contentType
635
     * @internal Should only be used by TYPO3 core for now
636
     */
637
    public function setContentType($contentType)
638
    {
639
        $this->contentType = $contentType;
640
    }
641
642
    /********************************************
643
     *
644
     * Initializing, resolving page id
645
     *
646
     ********************************************/
647
    /**
648
     * Initializes the caching system.
649
     */
650
    protected function initCaches()
651
    {
652
        $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pages');
653
    }
654
655
    /**
656
     * Initializes the front-end user groups.
657
     * Sets frontend.user aspect based on front-end user status.
658
     */
659
    public function initUserGroups()
660
    {
661
        $userAspect = $this->fe_user->createUserAspect((bool)$this->loginAllowedInBranch);
662
        $this->context->setAspect('frontend.user', $userAspect);
663
    }
664
665
    /**
666
     * Checking if a user is logged in or a group constellation different from "0,-1"
667
     *
668
     * @return bool TRUE if either a login user is found (array fe_user->user) OR if the gr_list is set to something else than '0,-1' (could be done even without a user being logged in!)
669
     */
670
    public function isUserOrGroupSet()
671
    {
672
        /** @var UserAspect $userAspect */
673
        $userAspect = $this->context->getAspect('frontend.user');
674
        return $userAspect->isUserOrGroupSet();
675
    }
676
677
    /**
678
     * Clears the preview-flags, sets sim_exec_time to current time.
679
     * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
680
     * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
681
     */
682
    public function clear_preview()
683
    {
684
        if ($this->context->getPropertyFromAspect('frontend.preview', 'isPreview')
685
            || $GLOBALS['EXEC_TIME'] !== $GLOBALS['SIM_EXEC_TIME']
686
            || $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages', false)
687
            || $this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)
688
        ) {
689
            $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
690
            $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
691
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
692
            $this->context->setAspect('date', GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $GLOBALS['SIM_EXEC_TIME'])));
693
            $this->context->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
694
        }
695
    }
696
697
    /**
698
     * Checks if a backend user is logged in
699
     *
700
     * @return bool whether a backend user is logged in
701
     */
702
    public function isBackendUserLoggedIn()
703
    {
704
        return (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
705
    }
706
707
    /**
708
     * Determines the id and evaluates any preview settings
709
     * Basically this function is about determining whether a backend user is logged in,
710
     * if he has read access to the page and if he's previewing the page.
711
     * That all determines which id to show and how to initialize the id.
712
     *
713
     * @param ServerRequestInterface|null $request
714
     */
715
    public function determineId(ServerRequestInterface $request = null)
716
    {
717
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
718
        // Call pre processing function for id determination
719
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
720
            $parameters = ['parentObject' => $this];
721
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
722
        }
723
        // If there is a Backend login we are going to check for any preview settings
724
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
0 ignored issues
show
Bug introduced by
The method getBackendUser() 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

724
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->/** @scrutinizer ignore-call */ getBackendUser());

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...
725
        // If the front-end is showing a preview, caching MUST be disabled.
726
        $isPreview = $this->context->getPropertyFromAspect('frontend.preview', 'isPreview');
727
        if ($isPreview) {
728
            $this->disableCache();
729
        }
730
        // Now, get the id, validate access etc:
731
        $this->fetch_the_id($request);
732
        // Check if backend user has read access to this page. If not, recalculate the id.
733
        if ($this->isBackendUserLoggedIn() && $isPreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
734
            $this->unsetBackendUser();
735
            // Resetting
736
            $this->clear_preview();
737
            $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
738
            // Fetching the id again, now with the preview settings reset.
739
            $this->fetch_the_id($request);
740
        }
741
        // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
742
        $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
743
        // Logins are not allowed, but there is a login, so will we run this.
744
        if (!$this->loginAllowedInBranch && $this->isUserOrGroupSet()) {
745
            // Clear out user, and the group will be re-set in >initUserGroups() due to
746
            // $this->loginAllowedInBranch = false
747
            if ($this->loginAllowedInBranch_mode === 'all') {
748
                $this->fe_user->hideActiveLogin();
749
            }
750
            // Fetching the id again, now with the preview settings reset and respecting $this->loginAllowedInBranch = false
751
            $this->fetch_the_id($request);
752
        }
753
        // Final cleaning.
754
        // Make sure it's an integer
755
        $this->id = ($this->contentPid = (int)$this->id);
756
        // Make sure it's an integer
757
        $this->type = (int)$this->type;
758
        // Setting language and fetch translated page
759
        $this->settingLanguage($request);
760
        // Call post processing function for id determination:
761
        $_params = ['pObj' => &$this];
762
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
763
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
764
        }
765
    }
766
767
    protected function unsetBackendUser(): void
768
    {
769
        // Register an empty backend user as aspect
770
        unset($GLOBALS['BE_USER']);
771
        $this->context->setAspect('backend.user', GeneralUtility::makeInstance(UserAspect::class));
772
        $this->context->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class));
773
    }
774
775
    /**
776
     * Evaluates admin panel or workspace settings to see if
777
     * visibility settings like
778
     * - Preview Aspect: isPreview
779
     * - Visibility Aspect: includeHiddenPages
780
     * - Visibility Aspect: includeHiddenContent
781
     * - $simUserGroup
782
     * should be applied to the current object.
783
     *
784
     * @param FrontendBackendUserAuthentication $backendUser
785
     * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
786
     * @internal
787
     */
788
    protected function applyPreviewSettings($backendUser = null)
789
    {
790
        if (!$backendUser) {
791
            return null;
792
        }
793
        $originalFrontendUserGroup = null;
794
        if ($this->fe_user->user) {
795
            $originalFrontendUserGroup = $this->context->getPropertyFromAspect('frontend.user', 'groupIds');
796
        }
797
798
        // The preview flag is set if the current page turns out to be hidden
799
        if ($this->id && $this->determineIdIsHiddenPage()) {
800
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
801
            /** @var VisibilityAspect $aspect */
802
            $aspect = $this->context->getAspect('visibility');
803
            $newAspect = GeneralUtility::makeInstance(VisibilityAspect::class, true, $aspect->includeHiddenContent(), $aspect->includeDeletedRecords());
804
            $this->context->setAspect('visibility', $newAspect);
805
        }
806
        // The preview flag will be set if an offline workspace will be previewed
807
        if ($this->whichWorkspace() > 0) {
808
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
809
        }
810
        return $this->context->getPropertyFromAspect('frontend.preview', 'preview', false) ? $originalFrontendUserGroup : null;
811
    }
812
813
    /**
814
     * Checks if the page is hidden in the active workspace.
815
     * If it is hidden, preview flags will be set.
816
     *
817
     * @return bool
818
     */
819
    protected function determineIdIsHiddenPage()
820
    {
821
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
822
            ->getQueryBuilderForTable('pages');
823
        $queryBuilder
824
            ->getRestrictions()
825
            ->removeAll()
826
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
827
828
        $queryBuilder
829
            ->select('uid', 'hidden', 'starttime', 'endtime')
830
            ->from('pages')
831
            ->where(
832
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
833
            )
834
            ->setMaxResults(1);
835
836
        // $this->id always points to the ID of the default language page, so we check
837
        // the current site language to determine if we need to fetch a translation but consider fallbacks
838
        if ($this->language->getLanguageId() > 0) {
839
            $languagesToCheck = array_merge([$this->language->getLanguageId()], $this->language->getFallbackLanguageIds());
840
            // Check for the language and all its fallbacks
841
            $constraint = $queryBuilder->expr()->andX(
842
                $queryBuilder->expr()->eq('l10n_parent', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
843
                $queryBuilder->expr()->in('sys_language_uid', $queryBuilder->createNamedParameter(array_filter($languagesToCheck), Connection::PARAM_INT_ARRAY))
844
            );
845
            // If the fallback language Ids also contains the default language, this needs to be considered
846
            if (in_array(0, $languagesToCheck, true)) {
847
                $constraint = $queryBuilder->expr()->orX(
848
                    $constraint,
849
                    // Ensure to also fetch the default record
850
                    $queryBuilder->expr()->andX(
851
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
852
                        $queryBuilder->expr()->in('sys_language_uid', 0)
853
                    )
854
                );
855
            }
856
            // Ensure that the translated records are shown first (maxResults is set to 1)
857
            $queryBuilder->orderBy('sys_language_uid', 'DESC');
858
        } else {
859
            $constraint = $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT));
860
        }
861
        $queryBuilder->andWhere($constraint);
862
863
        $page = $queryBuilder->execute()->fetch();
864
865
        if ($this->whichWorkspace() > 0) {
866
            // Fetch overlay of page if in workspace and check if it is hidden
867
            $customContext = clone $this->context;
868
            $customContext->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class, $this->whichWorkspace()));
869
            $customContext->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
870
            $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class, $customContext);
871
            $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
872
            // Also checks if the workspace version is NOT hidden but the live version is in fact still hidden
873
            $result = $targetPage === -1 || $targetPage === -2 || (is_array($targetPage) && $targetPage['hidden'] == 0 && $page['hidden'] == 1);
874
        } else {
875
            $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
876
        }
877
        return $result;
878
    }
879
880
    /**
881
     * Resolves the page id and sets up several related properties.
882
     *
883
     * If $this->id is not set at all or is not a plain integer, the method
884
     * does it's best to set the value to an integer. Resolving is based on
885
     * this options:
886
     *
887
     * - Splitting $this->id if it contains an additional type parameter.
888
     * - Finding the domain record start page
889
     * - First visible page
890
     * - Relocating the id below the domain record if outside
891
     *
892
     * The following properties may be set up or updated:
893
     *
894
     * - id
895
     * - requestedId
896
     * - type
897
     * - sys_page
898
     * - sys_page->where_groupAccess
899
     * - sys_page->where_hid_del
900
     * - Context: FrontendUser Aspect
901
     * - no_cache
902
     * - register['SYS_LASTCHANGED']
903
     * - pageNotFound
904
     *
905
     * Via getPageAndRootlineWithDomain()
906
     *
907
     * - rootLine
908
     * - page
909
     * - MP
910
     * - originalShortcutPage
911
     * - originalMountPointPage
912
     * - pageAccessFailureHistory['direct_access']
913
     * - pageNotFound
914
     *
915
     * @todo:
916
     *
917
     * On the first impression the method does to much. This is increased by
918
     * the fact, that is is called repeated times by the method determineId.
919
     * The reasons are manifold.
920
     *
921
     * 1.) The first part, the creation of sys_page and the type
922
     * resolution don't need to be repeated. They could be separated to be
923
     * called only once.
924
     *
925
     * 2.) The user group setup could be done once on a higher level.
926
     *
927
     * 3.) The workflow of the resolution could be elaborated to be less
928
     * tangled. Maybe the check of the page id to be below the domain via the
929
     * root line doesn't need to be done each time, but for the final result
930
     * only.
931
     *
932
     * 4.) The root line does not need to be directly addressed by this class.
933
     * A root line is always related to one page. The rootline could be handled
934
     * indirectly by page objects. Page objects still don't exist.
935
     *
936
     * @internal
937
     * @param ServerRequestInterface|null $request
938
     */
939
    public function fetch_the_id(ServerRequestInterface $request = null)
940
    {
941
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
942
        $timeTracker = $this->getTimeTracker();
943
        $timeTracker->push('fetch_the_id initialize/');
944
        // Set the valid usergroups for FE
945
        $this->initUserGroups();
946
        // Initialize the PageRepository has to be done after the frontend usergroups are initialized / resolved, as
947
        // frontend group aspect is modified before
948
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
949
        // The id and type is set to the integer-value - just to be sure...
950
        $this->id = (int)$this->id;
951
        $this->type = (int)$this->type;
952
        $timeTracker->pull();
953
        // We find the first page belonging to the current domain
954
        $timeTracker->push('fetch_the_id domain/');
955
        if (!$this->id) {
956
            // If the id was not previously set, set it to the root page id of the site.
957
            $this->id = $this->site->getRootPageId();
958
        }
959
        $timeTracker->pull();
960
        $timeTracker->push('fetch_the_id rootLine/');
961
        // We store the originally requested id
962
        $this->requestedId = $this->id;
963
        try {
964
            $this->getPageAndRootlineWithDomain($this->site->getRootPageId(), $request);
965
        } catch (ShortcutTargetPageNotFoundException $e) {
966
            $this->pageNotFound = 1;
967
        }
968
        $timeTracker->pull();
969
        if ($this->pageNotFound) {
970
            switch ($this->pageNotFound) {
971
                case 1:
972
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
973
                        $request,
974
                        'ID was not an accessible page',
975
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_PAGE_NOT_RESOLVED)
976
                    );
977
                    break;
978
                case 2:
979
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
980
                        $request,
981
                        'Subsection was found and not accessible',
982
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_SUBSECTION_NOT_RESOLVED)
983
                    );
984
                    break;
985
                case 3:
986
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
987
                        $request,
988
                        'ID was outside the domain',
989
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_HOST_PAGE_MISMATCH)
990
                    );
991
                    break;
992
                default:
993
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
994
                        $request,
995
                        'Unspecified error',
996
                        $this->getPageAccessFailureReasons()
997
                    );
998
            }
999
            throw new ImmediateResponseException($response, 1533931329);
1000
        }
1001
1002
        $this->setRegisterValueForSysLastChanged($this->page);
1003
1004
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1005
            $parameters = ['parentObject' => $this];
1006
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1007
        }
1008
    }
1009
1010
    /**
1011
     * Loads the page and root line records based on $this->id
1012
     *
1013
     * A final page and the matching root line are determined and loaded by
1014
     * the algorithm defined by this method.
1015
     *
1016
     * First it loads the initial page from the page repository for $this->id.
1017
     * If that can't be loaded directly, it gets the root line for $this->id.
1018
     * It walks up the root line towards the root page until the page
1019
     * repository can deliver a page record. (The loading restrictions of
1020
     * the root line records are more liberal than that of the page record.)
1021
     *
1022
     * Now the page type is evaluated and handled if necessary. If the page is
1023
     * a short cut, it is replaced by the target page. If the page is a mount
1024
     * point in overlay mode, the page is replaced by the mounted page.
1025
     *
1026
     * After this potential replacements are done, the root line is loaded
1027
     * (again) for this page record. It walks up the root line up to
1028
     * the first viewable record.
1029
     *
1030
     * (While upon the first accessibility check of the root line it was done
1031
     * by loading page by page from the page repository, this time the method
1032
     * checkRootlineForIncludeSection() is used to find the most distant
1033
     * accessible page within the root line.)
1034
     *
1035
     * Having found the final page id, the page record and the root line are
1036
     * loaded for last time by this method.
1037
     *
1038
     * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1039
     * or root lines.
1040
     *
1041
     * May set or update this properties:
1042
     *
1043
     * @see TypoScriptFrontendController::$id
1044
     * @see TypoScriptFrontendController::$MP
1045
     * @see TypoScriptFrontendController::$page
1046
     * @see TypoScriptFrontendController::$pageNotFound
1047
     * @see TypoScriptFrontendController::$pageAccessFailureHistory
1048
     * @see TypoScriptFrontendController::$originalMountPointPage
1049
     * @see TypoScriptFrontendController::$originalShortcutPage
1050
     *
1051
     * @throws ServiceUnavailableException
1052
     * @throws PageNotFoundException
1053
     */
1054
    protected function getPageAndRootline(ServerRequestInterface $request)
1055
    {
1056
        $requestedPageRowWithoutGroupCheck = [];
1057
        $this->resolveTranslatedPageId();
1058
        if (empty($this->page)) {
1059
            // If no page, we try to find the page before in the rootLine.
1060
            // Page is 'not found' in case the id itself was not an accessible page. code 1
1061
            $this->pageNotFound = 1;
1062
            $requestedPageIsHidden = false;
1063
            try {
1064
                $hiddenField = $GLOBALS['TCA']['pages']['ctrl']['enablecolumns']['disabled'] ?? '';
1065
                $includeHiddenPages = $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages') || $this->isBackendUserLoggedIn();
1066
                if (!empty($hiddenField) && !$includeHiddenPages) {
1067
                    // Page is "hidden" => 404 (deliberately done in default language, as this cascades to language overlays)
1068
                    $rawPageRecord = $this->sys_page->getPage_noCheck($this->id);
1069
                    $requestedPageIsHidden = (bool)$rawPageRecord[$hiddenField];
1070
                }
1071
1072
                $requestedPageRowWithoutGroupCheck = $this->sys_page->getPage($this->id, true);
1073
                if (!empty($requestedPageRowWithoutGroupCheck)) {
1074
                    $this->pageAccessFailureHistory['direct_access'][] = $requestedPageRowWithoutGroupCheck;
1075
                }
1076
                $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1077
                if (!empty($this->rootLine)) {
1078
                    $c = count($this->rootLine) - 1;
1079
                    while ($c > 0) {
1080
                        // Add to page access failure history:
1081
                        $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1082
                        // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1083
                        $c--;
1084
                        $this->id = $this->rootLine[$c]['uid'];
1085
                        $this->page = $this->sys_page->getPage($this->id);
1086
                        if (!empty($this->page)) {
1087
                            break;
1088
                        }
1089
                    }
1090
                }
1091
            } catch (RootLineException $e) {
1092
                $this->rootLine = [];
1093
            }
1094
            // If still no page...
1095
            if ($requestedPageIsHidden || (empty($requestedPageRowWithoutGroupCheck) && empty($this->page))) {
1096
                $message = 'The requested page does not exist!';
1097
                $this->logger->error($message);
1098
                try {
1099
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1100
                        $request,
1101
                        $message,
1102
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::PAGE_NOT_FOUND)
1103
                    );
1104
                    throw new ImmediateResponseException($response, 1533931330);
1105
                } catch (PageNotFoundException $e) {
1106
                    throw new PageNotFoundException($message, 1301648780);
1107
                }
1108
            }
1109
        }
1110
        // Spacer and sysfolders is not accessible in frontend
1111
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER || $this->page['doktype'] == PageRepository::DOKTYPE_SYSFOLDER) {
1112
            $message = 'The requested page does not exist!';
1113
            $this->logger->error($message);
1114
            try {
1115
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1116
                    $request,
1117
                    $message,
1118
                    $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_INVALID_PAGETYPE)
1119
                );
1120
                throw new ImmediateResponseException($response, 1533931343);
1121
            } catch (PageNotFoundException $e) {
1122
                throw new PageNotFoundException($message, 1301648781);
1123
            }
1124
        }
1125
        // Is the ID a link to another page??
1126
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1127
            // We need to clear MP if the page is a shortcut. Reason is if the short cut goes to another page, then we LEAVE the rootline which the MP expects.
1128
            $this->MP = '';
1129
            // saving the page so that we can check later - when we know
1130
            // about languages - whether we took the correct shortcut or
1131
            // whether a translation of the page overwrites the shortcut
1132
            // target and we need to follow the new target
1133
            $this->originalShortcutPage = $this->page;
1134
            $this->page = $this->sys_page->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1135
            $this->id = $this->page['uid'];
1136
        }
1137
        // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1138
        // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1139
        // the current ID and the user is redirected by checkPageForMountpointRedirect().
1140
        if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1141
            $this->originalMountPointPage = $this->page;
1142
            $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1143
            if (empty($this->page)) {
1144
                $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1145
                    . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1146
                throw new PageNotFoundException($message, 1402043263);
1147
            }
1148
            // If the current page is a shortcut, the MP parameter will be replaced
1149
            if ($this->MP === '' || !empty($this->originalShortcutPage)) {
1150
                $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1151
            } else {
1152
                $this->MP .= ',' . $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1153
            }
1154
            $this->id = $this->page['uid'];
1155
        }
1156
        // Gets the rootLine
1157
        try {
1158
            $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1159
        } catch (RootLineException $e) {
1160
            $this->rootLine = [];
1161
        }
1162
        // If not rootline we're off...
1163
        if (empty($this->rootLine)) {
1164
            $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1165
            $this->logger->error($message);
1166
            try {
1167
                $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1168
                    $request,
1169
                    $message,
1170
                    $this->getPageAccessFailureReasons(PageAccessFailureReasons::ROOTLINE_BROKEN)
1171
                );
1172
                throw new ImmediateResponseException($response, 1533931350);
1173
            } catch (ServiceUnavailableException $e) {
1174
                throw new ServiceUnavailableException($message, 1301648167);
1175
            }
1176
        }
1177
        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1178
        if ($this->checkRootlineForIncludeSection()) {
1179
            if (empty($this->rootLine)) {
1180
                $message = 'The requested page was not accessible!';
1181
                try {
1182
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1183
                        $request,
1184
                        $message,
1185
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_GENERAL)
1186
                    );
1187
                    throw new ImmediateResponseException($response, 1533931351);
1188
                } catch (ServiceUnavailableException $e) {
1189
                    $this->logger->warning($message);
1190
                    throw new ServiceUnavailableException($message, 1301648234);
1191
                }
1192
            } else {
1193
                $el = reset($this->rootLine);
1194
                $this->id = $el['uid'];
1195
                $this->page = $this->sys_page->getPage($this->id);
1196
                try {
1197
                    $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1198
                } catch (RootLineException $e) {
1199
                    $this->rootLine = [];
1200
                }
1201
            }
1202
        }
1203
    }
1204
1205
    /**
1206
     * If $this->id contains a translated page record, this needs to be resolved to the default language
1207
     * in order for all rootline functionality and access restrictions to be in place further on.
1208
     *
1209
     * Additionally, if a translated page is found, LanguageAspect is set as well.
1210
     */
1211
    protected function resolveTranslatedPageId()
1212
    {
1213
        $this->page = $this->sys_page->getPage($this->id);
0 ignored issues
show
Bug introduced by
$this->id of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Core\Domain\Re...geRepository::getPage(). ( Ignorable by Annotation )

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

1213
        $this->page = $this->sys_page->getPage(/** @scrutinizer ignore-type */ $this->id);
Loading history...
1214
        // Accessed a default language page record, nothing to resolve
1215
        if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1216
            return;
1217
        }
1218
        $languageId = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1219
        $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1220
        $this->context->setAspect('language', GeneralUtility::makeInstance(LanguageAspect::class, $languageId));
1221
        $this->id = $this->page['uid'];
1222
    }
1223
1224
    /**
1225
     * Checks if visibility of the page is blocked upwards in the root line.
1226
     *
1227
     * If any page in the root line is blocking visibility, true is returned.
1228
     *
1229
     * All pages from the blocking page downwards are removed from the root
1230
     * line, so that the remaining pages can be used to relocate the page up
1231
     * to lowest visible page.
1232
     *
1233
     * The blocking feature of a page must be turned on by setting the page
1234
     * record field 'extendToSubpages' to 1 in case of hidden, starttime,
1235
     * endtime or fe_group restrictions.
1236
     *
1237
     * Additionally this method checks for backend user sections in root line
1238
     * and if found evaluates if a backend user is logged in and has access.
1239
     *
1240
     * Recyclers are also checked and trigger page not found if found in root
1241
     * line.
1242
     *
1243
     * @todo Find a better name, i.e. checkVisibilityByRootLine
1244
     * @todo Invert boolean return value. Return true if visible.
1245
     *
1246
     * @return bool
1247
     */
1248
    protected function checkRootlineForIncludeSection(): bool
1249
    {
1250
        $c = count($this->rootLine);
1251
        $removeTheRestFlag = false;
1252
        for ($a = 0; $a < $c; $a++) {
1253
            if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1254
                // Add to page access failure history and mark the page as not found
1255
                // Keep the rootline however to trigger an access denied error instead of a service unavailable error
1256
                $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1257
                $this->pageNotFound = 2;
1258
            }
1259
1260
            if ((int)$this->rootLine[$a]['doktype'] === PageRepository::DOKTYPE_BE_USER_SECTION) {
1261
                // If there is a backend user logged in, check if they have read access to the page:
1262
                if ($this->isBackendUserLoggedIn()) {
1263
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1264
                        ->getQueryBuilderForTable('pages');
1265
1266
                    $queryBuilder
1267
                        ->getRestrictions()
1268
                        ->removeAll();
1269
1270
                    $row = $queryBuilder
1271
                        ->select('uid')
1272
                        ->from('pages')
1273
                        ->where(
1274
                            $queryBuilder->expr()->eq(
1275
                                'uid',
1276
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1277
                            ),
1278
                            $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1279
                        )
1280
                        ->execute()
1281
                        ->fetch();
1282
1283
                    // versionOL()?
1284
                    if (!$row) {
1285
                        // If there was no page selected, the user apparently did not have read access to the current PAGE (not position in rootline) and we set the remove-flag...
1286
                        $removeTheRestFlag = true;
1287
                    }
1288
                } else {
1289
                    // Don't go here, if there is no backend user logged in.
1290
                    $removeTheRestFlag = true;
1291
                }
1292
            } elseif ((int)$this->rootLine[$a]['doktype'] === PageRepository::DOKTYPE_RECYCLER) {
1293
                // page is in a recycler
1294
                $removeTheRestFlag = true;
1295
            }
1296
            if ($removeTheRestFlag) {
1297
                // Page is 'not found' in case a subsection was found and not accessible, code 2
1298
                $this->pageNotFound = 2;
1299
                unset($this->rootLine[$a]);
1300
            }
1301
        }
1302
        return $removeTheRestFlag;
1303
    }
1304
1305
    /**
1306
     * Checks page record for enableFields
1307
     * Returns TRUE if enableFields does not disable the page record.
1308
     * Takes notice of the includeHiddenPages visibility aspect flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1309
     *
1310
     * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1311
     * @param bool $bypassGroupCheck Bypass group-check
1312
     * @return bool TRUE, if record is viewable.
1313
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1314
     * @see checkPagerecordForIncludeSection()
1315
     */
1316
    public function checkEnableFields($row, $bypassGroupCheck = false)
1317
    {
1318
        $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1319
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1320
            // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1321
            $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1322
            if ($return === false) {
1323
                return false;
1324
            }
1325
        }
1326
        if ((!$row['hidden'] || $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages', false))
1327
            && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME']
1328
            && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME'])
1329
            && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1330
            return true;
1331
        }
1332
        return false;
1333
    }
1334
1335
    /**
1336
     * Check group access against a page record
1337
     *
1338
     * @param array $row The page record to evaluate (needs field: fe_group)
1339
     * @return bool TRUE, if group access is granted.
1340
     * @internal
1341
     */
1342
    public function checkPageGroupAccess($row)
1343
    {
1344
        /** @var UserAspect $userAspect */
1345
        $userAspect = $this->context->getAspect('frontend.user');
1346
        $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1347
        return count(array_intersect($userAspect->getGroupIds(), $pageGroupList)) > 0;
1348
    }
1349
1350
    /**
1351
     * Checks if the current page of the root line is visible.
1352
     *
1353
     * If the field extendToSubpages is 0, access is granted,
1354
     * else the fields hidden, starttime, endtime, fe_group are evaluated.
1355
     *
1356
     * @todo Find a better name, i.e. isVisibleRecord()
1357
     *
1358
     * @param array $row The page record
1359
     * @return bool true if visible
1360
     * @internal
1361
     * @see checkEnableFields()
1362
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1363
     * @see checkRootlineForIncludeSection()
1364
     */
1365
    public function checkPagerecordForIncludeSection(array $row): bool
1366
    {
1367
        return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1368
    }
1369
1370
    /**
1371
     * Checks if logins are allowed in the current branch of the page tree. Traverses the full root line and returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1372
     *
1373
     * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1374
     */
1375
    public function checkIfLoginAllowedInBranch()
1376
    {
1377
        // Initialize:
1378
        $c = count($this->rootLine);
1379
        $loginAllowed = true;
1380
        // Traverse root line from root and outwards:
1381
        for ($a = 0; $a < $c; $a++) {
1382
            // If a value is set for login state:
1383
            if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1384
                // Determine state from value:
1385
                if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1386
                    $loginAllowed = false;
1387
                    $this->loginAllowedInBranch_mode = 'all';
1388
                } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1389
                    $loginAllowed = false;
1390
                    $this->loginAllowedInBranch_mode = 'groups';
1391
                } else {
1392
                    $loginAllowed = true;
1393
                }
1394
            }
1395
        }
1396
        return $loginAllowed;
1397
    }
1398
1399
    /**
1400
     * Analysing $this->pageAccessFailureHistory into a summary array telling which features disabled display and on which pages and conditions. That data can be used inside a page-not-found handler
1401
     *
1402
     * @param string $failureReasonCode the error code to be attached (optional), see PageAccessFailureReasons list for details
1403
     * @return array Summary of why page access was not allowed.
1404
     */
1405
    public function getPageAccessFailureReasons(string $failureReasonCode = null)
1406
    {
1407
        $output = [];
1408
        if ($failureReasonCode) {
1409
            $output['code'] = $failureReasonCode;
1410
        }
1411
        $combinedRecords = array_merge(is_array($this->pageAccessFailureHistory['direct_access']) ? $this->pageAccessFailureHistory['direct_access'] : [['fe_group' => 0]], is_array($this->pageAccessFailureHistory['sub_section']) ? $this->pageAccessFailureHistory['sub_section'] : []);
1412
        if (!empty($combinedRecords)) {
1413
            foreach ($combinedRecords as $k => $pagerec) {
1414
                // If $k=0 then it is the very first page the original ID was pointing at and that will get a full check of course
1415
                // If $k>0 it is parent pages being tested. They are only significant for the access to the first page IF they had the extendToSubpages flag set, hence checked only then!
1416
                if (!$k || $pagerec['extendToSubpages']) {
1417
                    if ($pagerec['hidden']) {
1418
                        $output['hidden'][$pagerec['uid']] = true;
1419
                    }
1420
                    if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1421
                        $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1422
                    }
1423
                    if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1424
                        $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1425
                    }
1426
                    if (!$this->checkPageGroupAccess($pagerec)) {
1427
                        $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1428
                    }
1429
                }
1430
            }
1431
        }
1432
        return $output;
1433
    }
1434
1435
    /**
1436
     * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1437
     * If not inside a site, then default to first page in site.
1438
     *
1439
     * @param int $rootPageId Page uid of the page where the found site is located
1440
     * @internal
1441
     */
1442
    public function getPageAndRootlineWithDomain($rootPageId, ServerRequestInterface $request)
1443
    {
1444
        $this->getPageAndRootline($request);
1445
        // Checks if the $domain-startpage is in the rootLine. This is necessary so that references to page-id's via ?id=123 from other sites are not possible.
1446
        if (is_array($this->rootLine) && $this->rootLine !== []) {
1447
            $idFound = false;
1448
            foreach ($this->rootLine as $key => $val) {
1449
                if ($val['uid'] == $rootPageId) {
1450
                    $idFound = true;
1451
                    break;
1452
                }
1453
            }
1454
            if (!$idFound) {
1455
                // Page is 'not found' in case the id was outside the domain, code 3
1456
                $this->pageNotFound = 3;
1457
                $this->id = $rootPageId;
1458
                // re-get the page and rootline if the id was not found.
1459
                $this->getPageAndRootline($request);
1460
            }
1461
        }
1462
    }
1463
1464
    /********************************************
1465
     *
1466
     * Template and caching related functions.
1467
     *
1468
     *******************************************/
1469
1470
    protected function setPageArguments(PageArguments $pageArguments): void
1471
    {
1472
        $this->pageArguments = $pageArguments;
1473
        $this->id = $pageArguments->getPageId();
1474
        $this->type = $pageArguments->getPageType() ?: 0;
1475
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
1476
            $this->MP = (string)($pageArguments->getArguments()['MP'] ?? '');
1477
        }
1478
    }
1479
1480
    /**
1481
     * Fetches the arguments that are relevant for creating the hash base from the given PageArguments object.
1482
     * Excluded parameters are not taken into account when calculating the hash base.
1483
     *
1484
     * @param PageArguments $pageArguments
1485
     * @return array
1486
     */
1487
    protected function getRelevantParametersForCachingFromPageArguments(PageArguments $pageArguments): array
1488
    {
1489
        $queryParams = $pageArguments->getDynamicArguments();
1490
        if (!empty($queryParams) && $pageArguments->getArguments()['cHash'] ?? false) {
1491
            $queryParams['id'] = $pageArguments->getPageId();
1492
            return GeneralUtility::makeInstance(CacheHashCalculator::class)
1493
                ->getRelevantParameters(HttpUtility::buildQueryString($queryParams));
1494
        }
1495
        return [];
1496
    }
1497
1498
    /**
1499
     * See if page is in cache and get it if so
1500
     * Stores the page content in $this->content if something is found.
1501
     *
1502
     * @param ServerRequestInterface|null $request if given this is used to determine values in headerNoCache() instead of the superglobal $_SERVER
1503
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
1504
     */
1505
    public function getFromCache(ServerRequestInterface $request = null)
1506
    {
1507
        // clearing the content-variable, which will hold the pagecontent
1508
        $this->content = '';
1509
        // Unsetting the lowlevel config
1510
        $this->config = [];
1511
        $this->cacheContentFlag = false;
1512
1513
        if ($this->no_cache) {
1514
            return;
1515
        }
1516
1517
        if (!$this->tmpl instanceof TemplateService) {
0 ignored issues
show
introduced by
$this->tmpl is always a sub-type of TYPO3\CMS\Core\TypoScript\TemplateService.
Loading history...
1518
            $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context, null, $this);
1519
        }
1520
1521
        $pageSectionCacheContent = $this->tmpl->getCurrentPageData((int)$this->id, (string)$this->MP);
1522
        if (!is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
1523
            // Nothing in the cache, we acquire an "exclusive lock" for the key now.
1524
            // We use the Registry to store this lock centrally,
1525
            // but we protect the access again with a global exclusive lock to avoid race conditions
1526
1527
            $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
1528
            //
1529
            // from this point on we're the only one working on that page ($key)
1530
            //
1531
1532
            // query the cache again to see if the page data are there meanwhile
1533
            $pageSectionCacheContent = $this->tmpl->getCurrentPageData((int)$this->id, (string)$this->MP);
1534
            if (is_array($pageSectionCacheContent)) {
1535
                // we have the content, nice that some other process did the work for us already
1536
                $this->releaseLock('pagesection');
1537
            }
1538
            // We keep the lock set, because we are the ones generating the page now and filling the cache.
1539
            // This indicates that we have to release the lock later in releaseLocks()
1540
        }
1541
1542
        if (is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
1543
            // BE CAREFUL to change the content of the cc-array. This array is serialized and an md5-hash based on this is used for caching the page.
1544
            // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
1545
            // This array is an identification of the template. If $this->all is empty it's because the template-data is not cached, which it must be.
1546
            $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
1547
            ksort($pageSectionCacheContent);
1548
            $this->all = $pageSectionCacheContent;
1549
        }
1550
1551
        // Look for page in cache only if a shift-reload is not sent to the server.
1552
        $lockHash = $this->getLockHash();
1553
        if (!$this->headerNoCache($request) && $this->all) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->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...
1554
            // we got page section information (TypoScript), so lets see if there is also a cached version
1555
            // of this page in the pages cache.
1556
            $this->newHash = $this->getHash();
1557
            $this->getTimeTracker()->push('Cache Row');
1558
            $row = $this->getFromCache_queryRow();
1559
            if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
1560
                // nothing in the cache, we acquire an exclusive lock now
1561
                $this->acquireLock('pages', $lockHash);
1562
                //
1563
                // from this point on we're the only one working on that page ($lockHash)
1564
                //
1565
1566
                // query the cache again to see if the data are there meanwhile
1567
                $row = $this->getFromCache_queryRow();
1568
                if (is_array($row)) {
1569
                    // we have the content, nice that some other process did the work for us
1570
                    $this->releaseLock('pages');
1571
                }
1572
                // We keep the lock set, because we are the ones generating the page now and filling the cache.
1573
                // This indicates that we have to release the lock later in releaseLocks()
1574
            }
1575
            if (is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
1576
                $this->populatePageDataFromCache($row);
1577
            }
1578
            $this->getTimeTracker()->pull();
1579
        } else {
1580
            // the user forced rebuilding the page cache or there was no pagesection information
1581
            // get a lock for the page content so other processes will not interrupt the regeneration
1582
            $this->acquireLock('pages', $lockHash);
1583
        }
1584
    }
1585
1586
    /**
1587
     * Returning the cached version of page with hash = newHash
1588
     *
1589
     * @return array Cached row, if any. Otherwise void.
1590
     */
1591
    public function getFromCache_queryRow()
1592
    {
1593
        $this->getTimeTracker()->push('Cache Query');
1594
        $row = $this->pageCache->get($this->newHash);
1595
        $this->getTimeTracker()->pull();
1596
        return $row;
1597
    }
1598
1599
    /**
1600
     * This method properly sets the values given from the pages cache into the corresponding
1601
     * TSFE variables. The counterpart is setPageCacheContent() where all relevant information is fetched.
1602
     * This also contains all data that could be cached, even for pages that are partially cached, as they
1603
     * have non-cacheable content still to be rendered.
1604
     *
1605
     * @see getFromCache()
1606
     * @see setPageCacheContent()
1607
     * @param array $cachedData
1608
     */
1609
    protected function populatePageDataFromCache(array $cachedData): void
1610
    {
1611
        // Call hook when a page is retrieved from cache
1612
        $_params = ['pObj' => &$this, 'cache_pages_row' => &$cachedData];
1613
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
1614
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1615
        }
1616
        // Fetches the lowlevel config stored with the cached data
1617
        $this->config = $cachedData['cache_data'];
1618
        // Getting the content
1619
        $this->content = $cachedData['content'];
1620
        // Setting flag, so we know, that some cached content has been loaded
1621
        $this->cacheContentFlag = true;
1622
        $this->cacheExpires = $cachedData['expires'];
1623
        // Restore the current tags as they can be retrieved by getPageCacheTags()
1624
        $this->pageCacheTags = $cachedData['cacheTags'] ?? [];
1625
1626
        // Restore page title information, this is needed to generate the page title for
1627
        // partially cached pages.
1628
        $this->page['title'] = $cachedData['pageTitleInfo']['title'];
1629
        $this->indexedDocTitle = $cachedData['pageTitleInfo']['indexedDocTitle'];
1630
1631
        if (isset($this->config['config']['debug'])) {
1632
            $debugCacheTime = (bool)$this->config['config']['debug'];
1633
        } else {
1634
            $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
1635
        }
1636
        if ($debugCacheTime) {
1637
            $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
1638
            $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
1639
            $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $cachedData['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $cachedData['expires']) . ' -->';
1640
        }
1641
    }
1642
1643
    /**
1644
     * Detecting if shift-reload has been clicked
1645
     * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
1646
     * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
1647
     *
1648
     * @param ServerRequestInterface|null $request
1649
     * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
1650
     */
1651
    public function headerNoCache(ServerRequestInterface $request = null)
1652
    {
1653
        if ($request instanceof ServerRequestInterface) {
1654
            $serverParams = $request->getServerParams();
1655
        } else {
1656
            $serverParams = $_SERVER;
1657
        }
1658
        $disableAcquireCacheData = false;
1659
        if ($this->isBackendUserLoggedIn()) {
1660
            if (strtolower($serverParams['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($serverParams['HTTP_PRAGMA']) === 'no-cache') {
1661
                $disableAcquireCacheData = true;
1662
            }
1663
        }
1664
        // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
1665
        $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
1666
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
1667
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1668
        }
1669
        return $disableAcquireCacheData;
1670
    }
1671
1672
    /**
1673
     * Calculates the cache-hash
1674
     * This hash is unique to the template, the variables ->id, ->type, list of fe user groups, ->MP (Mount Points) and cHash array
1675
     * Used to get and later store the cached data.
1676
     *
1677
     * @return string MD5 hash of serialized hash base from createHashBase()
1678
     * @see getFromCache()
1679
     * @see getLockHash()
1680
     */
1681
    protected function getHash()
1682
    {
1683
        return md5($this->createHashBase(false));
1684
    }
1685
1686
    /**
1687
     * Calculates the lock-hash
1688
     * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
1689
     *
1690
     * @return string MD5 hash
1691
     * @see getFromCache()
1692
     * @see getHash()
1693
     */
1694
    protected function getLockHash()
1695
    {
1696
        $lockHash = $this->createHashBase(true);
1697
        return md5($lockHash);
1698
    }
1699
1700
    /**
1701
     * Calculates the cache-hash (or the lock-hash)
1702
     * This hash is unique to the template,
1703
     * the variables ->id, ->type, list of frontend user groups,
1704
     * ->MP (Mount Points) and cHash array
1705
     * Used to get and later store the cached data.
1706
     *
1707
     * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
1708
     * @return string the serialized hash base
1709
     */
1710
    protected function createHashBase($createLockHashBase = false)
1711
    {
1712
        // Fetch the list of user groups
1713
        /** @var UserAspect $userAspect */
1714
        $userAspect = $this->context->getAspect('frontend.user');
1715
        $hashParameters = [
1716
            'id' => (int)$this->id,
1717
            'type' => (int)$this->type,
1718
            'groupIds' => (string)implode(',', $userAspect->getGroupIds()),
1719
            'MP' => (string)$this->MP,
1720
            'site' => $this->site->getIdentifier(),
1721
            // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
1722
            // is not cached properly as we don't have any language-specific conditions anymore
1723
            'siteBase' => (string)$this->language->getBase(),
1724
            // additional variation trigger for static routes
1725
            'staticRouteArguments' => $this->pageArguments->getStaticArguments(),
1726
            // dynamic route arguments (if route was resolved)
1727
            'dynamicArguments' => $this->getRelevantParametersForCachingFromPageArguments($this->pageArguments),
1728
        ];
1729
        // Include the template information if we shouldn't create a lock hash
1730
        if (!$createLockHashBase) {
1731
            $hashParameters['all'] = $this->all;
1732
        }
1733
        // Call hook to influence the hash calculation
1734
        $_params = [
1735
            'hashParameters' => &$hashParameters,
1736
            'createLockHashBase' => $createLockHashBase
1737
        ];
1738
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
1739
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1740
        }
1741
        return serialize($hashParameters);
1742
    }
1743
1744
    /**
1745
     * Checks if config-array exists already but if not, gets it
1746
     *
1747
     * @param ServerRequestInterface|null $request
1748
     * @throws ServiceUnavailableException
1749
     */
1750
    public function getConfigArray(ServerRequestInterface $request = null)
1751
    {
1752
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
1753
        if (!$this->tmpl instanceof TemplateService) {
0 ignored issues
show
introduced by
$this->tmpl is always a sub-type of TYPO3\CMS\Core\TypoScript\TemplateService.
Loading history...
1754
            $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context, null, $this);
1755
        }
1756
1757
        // If config is not set by the cache (which would be a major mistake somewhere) OR if INTincScripts-include-scripts have been registered, then we must parse the template in order to get it
1758
        if (empty($this->config) || $this->isINTincScript() || $this->context->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
1759
            $timeTracker = $this->getTimeTracker();
1760
            $timeTracker->push('Parse template');
1761
            // Start parsing the TS template. Might return cached version.
1762
            $this->tmpl->start($this->rootLine);
1763
            $timeTracker->pull();
1764
            // At this point we have a valid pagesection_cache (generated in $this->tmpl->start()),
1765
            // so let all other processes proceed now. (They are blocked at the pagessection_lock in getFromCache())
1766
            $this->releaseLock('pagesection');
1767
            if ($this->tmpl->loaded) {
1768
                $timeTracker->push('Setting the config-array');
1769
                // toplevel - objArrayName
1770
                $typoScriptPageTypeName = $this->tmpl->setup['types.'][$this->type];
1771
                $this->sPre = $typoScriptPageTypeName;
1772
                $this->pSetup = $this->tmpl->setup[$typoScriptPageTypeName . '.'];
1773
                if (!is_array($this->pSetup)) {
1774
                    $message = 'The page is not configured! [type=' . $this->type . '][' . $typoScriptPageTypeName . '].';
1775
                    $this->logger->alert($message);
1776
                    try {
1777
                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1778
                            $request,
1779
                            $message,
1780
                            ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_CONFIGURED]
1781
                        );
1782
                        throw new ImmediateResponseException($response, 1533931374);
1783
                    } catch (PageNotFoundException $e) {
1784
                        $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
1785
                        throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
1786
                    }
1787
                } else {
1788
                    if (!isset($this->config['config'])) {
1789
                        $this->config['config'] = [];
1790
                    }
1791
                    // Filling the config-array, first with the main "config." part
1792
                    if (is_array($this->tmpl->setup['config.'])) {
1793
                        ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
1794
                        $this->config['config'] = $this->tmpl->setup['config.'];
1795
                    }
1796
                    // override it with the page/type-specific "config."
1797
                    if (is_array($this->pSetup['config.'])) {
1798
                        ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
1799
                    }
1800
                    // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
1801
                    if (!isset($this->config['config']['removeDefaultJS'])) {
1802
                        $this->config['config']['removeDefaultJS'] = 'external';
1803
                    }
1804
                    if (!isset($this->config['config']['inlineStyle2TempFile'])) {
1805
                        $this->config['config']['inlineStyle2TempFile'] = 1;
1806
                    }
1807
1808
                    if (!isset($this->config['config']['compressJs'])) {
1809
                        $this->config['config']['compressJs'] = 0;
1810
                    }
1811
                    // Rendering charset of HTML page.
1812
                    if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
1813
                        $this->metaCharset = $this->config['config']['metaCharset'];
1814
                    }
1815
                    // Setting default cache_timeout
1816
                    if (isset($this->config['config']['cache_period'])) {
1817
                        $this->set_cache_timeout_default((int)$this->config['config']['cache_period']);
1818
                    }
1819
1820
                    // Processing for the config_array:
1821
                    $this->config['rootLine'] = $this->tmpl->rootLine;
1822
                    // Class for render Header and Footer parts
1823
                    if ($this->pSetup['pageHeaderFooterTemplateFile']) {
1824
                        try {
1825
                            $file = GeneralUtility::makeInstance(FilePathSanitizer::class)
1826
                                ->sanitize((string)$this->pSetup['pageHeaderFooterTemplateFile']);
1827
                            $this->pageRenderer->setTemplateFile($file);
1828
                        } catch (Exception $e) {
1829
                            // do nothing
1830
                        }
1831
                    }
1832
                }
1833
                $timeTracker->pull();
1834
            } else {
1835
                $message = 'No TypoScript template found!';
1836
                $this->logger->alert($message);
1837
                try {
1838
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1839
                        $request,
1840
                        $message,
1841
                        ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_FOUND]
1842
                    );
1843
                    throw new ImmediateResponseException($response, 1533931380);
1844
                } catch (ServiceUnavailableException $e) {
1845
                    throw new ServiceUnavailableException($message, 1294587218);
1846
                }
1847
            }
1848
        }
1849
1850
        // No cache
1851
        // Set $this->no_cache TRUE if the config.no_cache value is set!
1852
        if ($this->config['config']['no_cache']) {
1853
            $this->set_no_cache('config.no_cache is set', true);
1854
        }
1855
1856
        // Auto-configure settings when a site is configured
1857
        $this->config['config']['absRefPrefix'] = $this->config['config']['absRefPrefix'] ?? 'auto';
1858
1859
        // Hook for postProcessing the configuration array
1860
        $params = ['config' => &$this->config['config']];
1861
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
1862
            GeneralUtility::callUserFunction($funcRef, $params, $this);
1863
        }
1864
    }
1865
1866
    /********************************************
1867
     *
1868
     * Further initialization and data processing
1869
     *
1870
     *******************************************/
1871
    /**
1872
     * Setting the language key that will be used by the current page.
1873
     * In this function it should be checked, 1) that this language exists, 2) that a page_overlay_record exists, .. and if not the default language, 0 (zero), should be set.
1874
     *
1875
     * @param ServerRequestInterface|null $request
1876
     * @internal
1877
     */
1878
    public function settingLanguage(ServerRequestInterface $request = null)
1879
    {
1880
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
1881
        $_params = [];
1882
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
1883
            $ref = $this; // introduced for phpstan to not lose type information when passing $this into callUserFunction
1884
            GeneralUtility::callUserFunction($_funcRef, $_params, $ref);
1885
        }
1886
1887
        // Get values from site language
1888
        $languageAspect = LanguageAspectFactory::createFromSiteLanguage($this->language);
1889
1890
        $languageId = $languageAspect->getId();
1891
        $languageContentId = $languageAspect->getContentId();
1892
1893
        $pageTranslationVisibility = new PageTranslationVisibility((int)($this->page['l18n_cfg'] ?? 0));
1894
        // If sys_language_uid is set to another language than default:
1895
        if ($languageAspect->getId() > 0) {
1896
            // check whether a shortcut is overwritten by a translated page
1897
            // we can only do this now, as this is the place where we get
1898
            // to know about translations
1899
            $this->checkTranslatedShortcut($languageAspect->getId(), $request);
1900
            // Request the overlay record for the sys_language_uid:
1901
            $olRec = $this->sys_page->getPageOverlay($this->id, $languageAspect->getId());
1902
            if (empty($olRec)) {
1903
                // If requested translation is not available:
1904
                if ($pageTranslationVisibility->shouldHideTranslationIfNoTranslatedRecordExists()) {
1905
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1906
                        $request,
1907
                        'Page is not available in the requested language.',
1908
                        ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE]
1909
                    );
1910
                    throw new ImmediateResponseException($response, 1533931388);
1911
                }
1912
                switch ((string)$languageAspect->getLegacyLanguageMode()) {
1913
                    case 'strict':
1914
                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1915
                            $request,
1916
                            'Page is not available in the requested language (strict).',
1917
                            ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE_STRICT_MODE]
1918
                        );
1919
                        throw new ImmediateResponseException($response, 1533931395);
1920
                    case 'fallback':
1921
                    case 'content_fallback':
1922
                        // Setting content uid (but leaving the sys_language_uid) when a content_fallback
1923
                        // value was found.
1924
                        foreach ($languageAspect->getFallbackChain() ?? [] as $orderValue) {
1925
                            if ($orderValue === '0' || $orderValue === 0 || $orderValue === '') {
1926
                                $languageContentId = 0;
1927
                                break;
1928
                            }
1929
                            if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
1930
                                $languageContentId = (int)$orderValue;
1931
                                break;
1932
                            }
1933
                            if ($orderValue === 'pageNotFound') {
1934
                                // The existing fallbacks have not been found, but instead of continuing
1935
                                // page rendering with default language, a "page not found" message should be shown
1936
                                // instead.
1937
                                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1938
                                    $request,
1939
                                    'Page is not available in the requested language (fallbacks did not apply).',
1940
                                    ['code' => PageAccessFailureReasons::LANGUAGE_AND_FALLBACKS_NOT_AVAILABLE]
1941
                                );
1942
                                throw new ImmediateResponseException($response, 1533931402);
1943
                            }
1944
                        }
1945
                        break;
1946
                    case 'ignore':
1947
                        $languageContentId = $languageAspect->getId();
1948
                        break;
1949
                    default:
1950
                        // Default is that everything defaults to the default language...
1951
                        $languageId = ($languageContentId = 0);
1952
                }
1953
            }
1954
1955
            // Define the language aspect again now
1956
            $languageAspect = GeneralUtility::makeInstance(
1957
                LanguageAspect::class,
1958
                $languageId,
1959
                $languageContentId,
1960
                $languageAspect->getOverlayType(),
1961
                $languageAspect->getFallbackChain()
1962
            );
1963
1964
            // Setting sys_language if an overlay record was found (which it is only if a language is used)
1965
            // We'll do this every time since the language aspect might have changed now
1966
            // Doing this ensures that page properties like the page title are returned in the correct language
1967
            $this->page = $this->sys_page->getPageOverlay($this->page, $languageAspect->getContentId());
1968
1969
            // Update SYS_LASTCHANGED for localized page record
1970
            $this->setRegisterValueForSysLastChanged($this->page);
1971
        }
1972
1973
        // Set the language aspect
1974
        $this->context->setAspect('language', $languageAspect);
1975
1976
        // Setting sys_language_uid inside sys-page by creating a new page repository
1977
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
1978
        // If default language is not available:
1979
        if ((!$languageAspect->getContentId() || !$languageAspect->getId())
1980
            && $pageTranslationVisibility->shouldBeHiddenInDefaultLanguage()
1981
        ) {
1982
            $message = 'Page is not available in default language.';
1983
            $this->logger->error($message);
1984
            $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1985
                $request,
1986
                $message,
1987
                ['code' => PageAccessFailureReasons::LANGUAGE_DEFAULT_NOT_AVAILABLE]
1988
            );
1989
            throw new ImmediateResponseException($response, 1533931423);
1990
        }
1991
1992
        if ($languageAspect->getId() > 0) {
1993
            $this->updateRootLinesWithTranslations();
1994
        }
1995
1996
        $_params = [];
1997
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
1998
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1999
        }
2000
    }
2001
2002
    /**
2003
     * Updating content of the two rootLines IF the language key is set!
2004
     */
2005
    protected function updateRootLinesWithTranslations()
2006
    {
2007
        try {
2008
            $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
2009
        } catch (RootLineException $e) {
2010
            $this->rootLine = [];
2011
        }
2012
    }
2013
2014
    /**
2015
     * Checks whether a translated shortcut page has a different shortcut
2016
     * target than the original language page.
2017
     * If that is the case, things get corrected to follow that alternative
2018
     * shortcut
2019
     * @param int $languageId
2020
     * @param ServerRequestInterface $request
2021
     */
2022
    protected function checkTranslatedShortcut(int $languageId, ServerRequestInterface $request)
2023
    {
2024
        if (!is_null($this->originalShortcutPage)) {
2025
            $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $languageId);
2026
            if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2027
                // the translation of the original shortcut page has a different shortcut target!
2028
                // set the correct page and id
2029
                $shortcut = $this->sys_page->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2030
                $this->id = ($this->contentPid = $shortcut['uid']);
2031
                $this->page = $this->sys_page->getPage($this->id);
2032
                // Fix various effects on things like menus f.e.
2033
                $this->fetch_the_id($request);
2034
                $this->tmpl->rootLine = array_reverse($this->rootLine);
2035
            }
2036
        }
2037
    }
2038
2039
    /**
2040
     * Calculates and sets the internal linkVars based upon the current request parameters
2041
     * and the setting "config.linkVars".
2042
     *
2043
     * @param array $queryParams $_GET (usually called with a PSR-7 $request->getQueryParams())
2044
     */
2045
    public function calculateLinkVars(array $queryParams)
2046
    {
2047
        $this->linkVars = '';
2048
        $adminCommand = $queryParams['ADMCMD_prev'] ?? '';
2049
        if (($adminCommand === 'LIVE' || $adminCommand === 'IGNORE') && $this->isBackendUserLoggedIn()) {
2050
            $this->config['config']['linkVars'] = ltrim(($this->config['config']['linkVars'] ?? '') . ',ADMCMD_prev', ',');
2051
        }
2052
        if (empty($this->config['config']['linkVars'])) {
2053
            return;
2054
        }
2055
2056
        $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2057
2058
        if (empty($linkVars)) {
2059
            return;
2060
        }
2061
        foreach ($linkVars as $linkVar) {
2062
            $test = $value = '';
2063
            if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2064
                $linkVar = trim($match[1]);
2065
                $test = trim($match[2]);
2066
            }
2067
2068
            $keys = explode('|', $linkVar);
2069
            $numberOfLevels = count($keys);
2070
            $rootKey = trim($keys[0]);
2071
            if (!isset($queryParams[$rootKey])) {
2072
                continue;
2073
            }
2074
            $value = $queryParams[$rootKey];
2075
            for ($i = 1; $i < $numberOfLevels; $i++) {
2076
                $currentKey = trim($keys[$i]);
2077
                if (isset($value[$currentKey])) {
2078
                    $value = $value[$currentKey];
2079
                } else {
2080
                    $value = false;
2081
                    break;
2082
                }
2083
            }
2084
            if ($value !== false) {
2085
                $parameterName = $keys[0];
2086
                for ($i = 1; $i < $numberOfLevels; $i++) {
2087
                    $parameterName .= '[' . $keys[$i] . ']';
2088
                }
2089
                if (!is_array($value)) {
2090
                    $temp = rawurlencode($value);
2091
                    if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2092
                        // Error: This value was not allowed for this key
2093
                        continue;
2094
                    }
2095
                    $value = '&' . $parameterName . '=' . $temp;
2096
                } else {
2097
                    if ($test !== '' && $test !== 'array') {
2098
                        // Error: This key must not be an array!
2099
                        continue;
2100
                    }
2101
                    $value = HttpUtility::buildQueryString([$parameterName => $value], '&');
2102
                }
2103
                $this->linkVars .= $value;
2104
            }
2105
        }
2106
    }
2107
2108
    /**
2109
     * Split the link vars string by "," but not if the "," is inside of braces
2110
     *
2111
     * @param string $string
2112
     *
2113
     * @return array
2114
     */
2115
    protected function splitLinkVarsString(string $string): array
2116
    {
2117
        $tempCommaReplacementString = '###KASPER###';
2118
2119
        // replace every "," wrapped in "()" by a "unique" string
2120
        $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2121
            return str_replace(',', $tempCommaReplacementString, $result[0]);
2122
        }, $string) ?? '';
2123
2124
        $string = GeneralUtility::trimExplode(',', $string);
2125
2126
        // replace all "unique" strings back to ","
2127
        return str_replace($tempCommaReplacementString, ',', $string);
2128
    }
2129
2130
    /**
2131
     * Checks if the value defined in "config.linkVars" contains an allowed value.
2132
     * Otherwise, return FALSE which means the value will not be added to any links.
2133
     *
2134
     * @param string $haystack The string in which to find $needle
2135
     * @param string $needle The string to find in $haystack
2136
     * @return bool Returns TRUE if $needle matches or is found in $haystack
2137
     */
2138
    protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2139
    {
2140
        $isAllowed = false;
2141
        // Integer
2142
        if ($needle === 'int' || $needle === 'integer') {
2143
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2144
                $isAllowed = true;
2145
            }
2146
        } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2147
            // Regular expression, only "//" is allowed as delimiter
2148
            if (@preg_match($needle, $haystack)) {
2149
                $isAllowed = true;
2150
            }
2151
        } elseif (strpos($needle, '-') !== false) {
2152
            // Range
2153
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2154
                $range = explode('-', $needle);
2155
                if ($range[0] <= $haystack && $range[1] >= $haystack) {
2156
                    $isAllowed = true;
2157
                }
2158
            }
2159
        } elseif (strpos($needle, '|') !== false) {
2160
            // List
2161
            // Trim the input
2162
            $haystack = str_replace(' ', '', $haystack);
2163
            if (strpos('|' . $needle . '|', '|' . $haystack . '|') !== false) {
2164
                $isAllowed = true;
2165
            }
2166
        } elseif ((string)$needle === (string)$haystack) {
2167
            // String comparison
2168
            $isAllowed = true;
2169
        }
2170
        return $isAllowed;
2171
    }
2172
2173
    /**
2174
     * Returns URI of target page, if the current page is an overlaid mountpoint.
2175
     *
2176
     * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2177
     * and is accessed directly, the user will be redirected to the mountpoint context.
2178
     * @internal
2179
     * @param ServerRequestInterface $request
2180
     * @return string|null
2181
     */
2182
    public function getRedirectUriForMountPoint(ServerRequestInterface $request): ?string
2183
    {
2184
        if (!empty($this->originalMountPointPage) && (int)$this->originalMountPointPage['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
2185
            return $this->getUriToCurrentPageForRedirect($request);
2186
        }
2187
2188
        return null;
2189
    }
2190
2191
    /**
2192
     * Returns URI of target page, if the current page is a Shortcut.
2193
     *
2194
     * If the current page is of type shortcut and accessed directly via its URL,
2195
     * the user will be redirected to shortcut target.
2196
     *
2197
     * @internal
2198
     * @param ServerRequestInterface $request
2199
     * @return string|null
2200
     */
2201
    public function getRedirectUriForShortcut(ServerRequestInterface $request): ?string
2202
    {
2203
        if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2204
            return $this->getUriToCurrentPageForRedirect($request);
2205
        }
2206
2207
        return null;
2208
    }
2209
2210
    /**
2211
     * Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
2212
     *
2213
     * @param ServerRequestInterface $request
2214
     * @return string
2215
     */
2216
    protected function getUriToCurrentPageForRedirect(ServerRequestInterface $request): string
2217
    {
2218
        $this->calculateLinkVars($request->getQueryParams());
2219
        $parameter = $this->page['uid'];
2220
        if ($this->type && MathUtility::canBeInterpretedAsInteger($this->type)) {
2221
            $parameter .= ',' . $this->type;
2222
        }
2223
        return GeneralUtility::makeInstance(ContentObjectRenderer::class, $this)->typoLink_URL([
2224
            'parameter' => $parameter,
2225
            'addQueryString' => true,
2226
            'addQueryString.' => ['exclude' => 'id'],
2227
            'forceAbsoluteUrl' => true
2228
        ]);
2229
    }
2230
2231
    /********************************************
2232
     *
2233
     * Page generation; cache handling
2234
     *
2235
     *******************************************/
2236
    /**
2237
     * Returns TRUE if the page should be generated.
2238
     * That is if no URL handler is active and the cacheContentFlag is not set.
2239
     *
2240
     * @return bool
2241
     */
2242
    public function isGeneratePage()
2243
    {
2244
        return !$this->cacheContentFlag;
2245
    }
2246
2247
    /**
2248
     * Set cache content to $this->content
2249
     */
2250
    protected function realPageCacheContent()
2251
    {
2252
        // seconds until a cached page is too old
2253
        $cacheTimeout = $this->get_cache_timeout();
2254
        $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
2255
        $usePageCache = true;
2256
        // Hook for deciding whether page cache should be written to the cache backend or not
2257
        // NOTE: as hooks are called in a loop, the last hook will have the final word (however each
2258
        // hook receives the current status of the $usePageCache flag)
2259
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['usePageCache'] ?? [] as $className) {
2260
            $usePageCache = GeneralUtility::makeInstance($className)->usePageCache($this, $usePageCache);
2261
        }
2262
        // Write the page to cache, if necessary
2263
        if ($usePageCache) {
2264
            $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
2265
        }
2266
        // Hook for cache post processing (eg. writing static files!)
2267
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] ?? [] as $className) {
2268
            GeneralUtility::makeInstance($className)->insertPageIncache($this, $timeOutTime);
2269
        }
2270
    }
2271
2272
    /**
2273
     * Sets cache content; Inserts the content string into the cache_pages cache.
2274
     *
2275
     * @param string $content The content to store in the HTML field of the cache table
2276
     * @param mixed $data The additional cache_data array, fx. $this->config
2277
     * @param int $expirationTstamp Expiration timestamp
2278
     * @see realPageCacheContent()
2279
     */
2280
    protected function setPageCacheContent($content, $data, $expirationTstamp)
2281
    {
2282
        $cacheData = [
2283
            'identifier' => $this->newHash,
2284
            'page_id' => $this->id,
2285
            'content' => $content,
2286
            'cache_data' => $data,
2287
            'expires' => $expirationTstamp,
2288
            'tstamp' => $GLOBALS['EXEC_TIME'],
2289
            'pageTitleInfo' => [
2290
                'title' => $this->page['title'],
2291
                'indexedDocTitle' => $this->indexedDocTitle
2292
            ]
2293
        ];
2294
        $this->cacheExpires = $expirationTstamp;
2295
        $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
2296
        // Respect the page cache when content of pid is shown
2297
        if ($this->id !== $this->contentPid) {
0 ignored issues
show
introduced by
The condition $this->id !== $this->contentPid is always true.
Loading history...
2298
            $this->pageCacheTags[] = 'pageId_' . $this->contentPid;
2299
        }
2300
        if (!empty($this->page['cache_tags'])) {
2301
            $tags = GeneralUtility::trimExplode(',', $this->page['cache_tags'], true);
2302
            $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
2303
        }
2304
        // Add the cache themselves as well, because they are fetched by getPageCacheTags()
2305
        $cacheData['cacheTags'] = $this->pageCacheTags;
2306
        $this->pageCache->set($this->newHash, $cacheData, $this->pageCacheTags, $expirationTstamp - $GLOBALS['EXEC_TIME']);
2307
    }
2308
2309
    /**
2310
     * Clears cache content (for $this->newHash)
2311
     */
2312
    public function clearPageCacheContent()
2313
    {
2314
        $this->pageCache->remove($this->newHash);
2315
    }
2316
2317
    /**
2318
     * Sets sys last changed
2319
     * Setting the SYS_LASTCHANGED value in the pagerecord: This value will thus be set to the highest tstamp of records rendered on the page. This includes all records with no regard to hidden records, userprotection and so on.
2320
     *
2321
     * @see ContentObjectRenderer::lastChanged()
2322
     */
2323
    protected function setSysLastChanged()
2324
    {
2325
        // We only update the info if browsing the live workspace
2326
        if ($this->page['SYS_LASTCHANGED'] < (int)$this->register['SYS_LASTCHANGED'] && !$this->doWorkspacePreview()) {
2327
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)
2328
                ->getConnectionForTable('pages');
2329
            $pageId = $this->page['_PAGES_OVERLAY_UID'] ?? $this->id;
2330
            $connection->update(
2331
                'pages',
2332
                [
2333
                    'SYS_LASTCHANGED' => (int)$this->register['SYS_LASTCHANGED']
2334
                ],
2335
                [
2336
                    'uid' => (int)$pageId
2337
                ]
2338
            );
2339
        }
2340
    }
2341
2342
    /**
2343
     * Set the SYS_LASTCHANGED register value, is also called when a translated page is in use,
2344
     * so the register reflects the state of the translated page, not the page in the default language.
2345
     *
2346
     * @param array $page
2347
     * @internal
2348
     */
2349
    protected function setRegisterValueForSysLastChanged(array $page): void
2350
    {
2351
        $this->register['SYS_LASTCHANGED'] = (int)$page['tstamp'];
2352
        if ($this->register['SYS_LASTCHANGED'] < (int)$page['SYS_LASTCHANGED']) {
2353
            $this->register['SYS_LASTCHANGED'] = (int)$page['SYS_LASTCHANGED'];
2354
        }
2355
    }
2356
2357
    /**
2358
     * Release pending locks
2359
     *
2360
     * @internal
2361
     */
2362
    public function releaseLocks()
2363
    {
2364
        $this->releaseLock('pagesection');
2365
        $this->releaseLock('pages');
2366
    }
2367
2368
    /**
2369
     * Adds tags to this page's cache entry, you can then f.e. remove cache
2370
     * entries by tag
2371
     *
2372
     * @param array $tags An array of tag
2373
     */
2374
    public function addCacheTags(array $tags)
2375
    {
2376
        $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
2377
    }
2378
2379
    /**
2380
     * @return array
2381
     */
2382
    public function getPageCacheTags(): array
2383
    {
2384
        return $this->pageCacheTags;
2385
    }
2386
2387
    /********************************************
2388
     *
2389
     * Page generation; rendering and inclusion
2390
     *
2391
     *******************************************/
2392
    /**
2393
     * Does some processing BEFORE the page content is generated / built.
2394
     */
2395
    public function generatePage_preProcessing()
2396
    {
2397
        // Same codeline as in getFromCache(). But $this->all has been changed by
2398
        // \TYPO3\CMS\Core\TypoScript\TemplateService::start() in the meantime, so this must be called again!
2399
        $this->newHash = $this->getHash();
2400
2401
        // Used as a safety check in case a PHP script is falsely disabling $this->no_cache during page generation.
2402
        $this->no_cacheBeforePageGen = $this->no_cache;
2403
    }
2404
2405
    /**
2406
     * Check the value of "content_from_pid" of the current page record, and see if the current request
2407
     * should actually show content from another page.
2408
     *
2409
     * By using $TSFE->getPageAndRootline() on the cloned object, all rootline restrictions (extendToSubPages)
2410
     * are evaluated as well.
2411
     *
2412
     * @param ServerRequestInterface $request
2413
     * @return int the current page ID or another one if resolved properly - usually set to $this->contentPid
2414
     */
2415
    protected function resolveContentPid(ServerRequestInterface $request): int
2416
    {
2417
        if (!isset($this->page['content_from_pid']) || empty($this->page['content_from_pid'])) {
2418
            return (int)$this->id;
2419
        }
2420
        // make REAL copy of TSFE object - not reference!
2421
        $temp_copy_TSFE = clone $this;
2422
        // Set ->id to the content_from_pid value - we are going to evaluate this pid as was it a given id for a page-display!
2423
        $temp_copy_TSFE->id = $this->page['content_from_pid'];
2424
        $temp_copy_TSFE->MP = '';
2425
        $temp_copy_TSFE->getPageAndRootline($request);
2426
        return (int)$temp_copy_TSFE->id;
2427
    }
2428
    /**
2429
     * Sets up TypoScript "config." options and set properties in $TSFE.
2430
     *
2431
     * @param ServerRequestInterface $request
2432
     */
2433
    public function preparePageContentGeneration(ServerRequestInterface $request)
2434
    {
2435
        $this->getTimeTracker()->push('Prepare page content generation');
2436
        $this->contentPid = $this->resolveContentPid($request);
2437
        // Global vars...
2438
        $this->indexedDocTitle = $this->page['title'] ?? null;
2439
        // Base url:
2440
        if (isset($this->config['config']['baseURL'])) {
2441
            $this->baseUrl = $this->config['config']['baseURL'];
2442
        }
2443
        // Internal and External target defaults
2444
        $this->intTarget = (string)($this->config['config']['intTarget'] ?? '');
2445
        $this->extTarget = (string)($this->config['config']['extTarget'] ?? '');
2446
        $this->fileTarget = (string)($this->config['config']['fileTarget'] ?? '');
2447
        $this->spamProtectEmailAddresses = $this->config['config']['spamProtectEmailAddresses'] ?? 0;
2448
        if ($this->spamProtectEmailAddresses !== 'ascii') {
2449
            $this->spamProtectEmailAddresses = MathUtility::forceIntegerInRange($this->spamProtectEmailAddresses, -10, 10, 0);
2450
        }
2451
        // calculate the absolute path prefix
2452
        if (!empty($this->config['config']['absRefPrefix'])) {
2453
            $absRefPrefix = trim($this->config['config']['absRefPrefix']);
2454
            if ($absRefPrefix === 'auto') {
2455
                $this->absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
2456
            } else {
2457
                $this->absRefPrefix = $absRefPrefix;
2458
            }
2459
        } else {
2460
            $this->absRefPrefix = '';
2461
        }
2462
        $this->ATagParams = trim($this->config['config']['ATagParams'] ?? '') ? ' ' . trim($this->config['config']['ATagParams']) : '';
2463
        $this->initializeSearchWordData($request->getParsedBody()['sword_list'] ?? $request->getQueryParams()['sword_list'] ?? null);
2464
        // linkVars
2465
        $this->calculateLinkVars($request->getQueryParams());
2466
        // Setting XHTML-doctype from doctype
2467
        if (!isset($this->config['config']['xhtmlDoctype']) || !$this->config['config']['xhtmlDoctype']) {
2468
            $this->config['config']['xhtmlDoctype'] = $this->config['config']['doctype'] ?? '';
2469
        }
2470
        if ($this->config['config']['xhtmlDoctype']) {
2471
            $this->xhtmlDoctype = $this->config['config']['xhtmlDoctype'];
2472
            // Checking XHTML-docytpe
2473
            switch ((string)$this->config['config']['xhtmlDoctype']) {
2474
                case 'xhtml_trans':
2475
                case 'xhtml_strict':
2476
                    $this->xhtmlVersion = 100;
2477
                    break;
2478
                case 'xhtml_basic':
2479
                    $this->xhtmlVersion = 105;
2480
                    break;
2481
                case 'xhtml_11':
2482
                case 'xhtml+rdfa_10':
2483
                    $this->xhtmlVersion = 110;
2484
                    break;
2485
                default:
2486
                    $this->pageRenderer->setRenderXhtml(false);
2487
                    $this->xhtmlDoctype = '';
2488
                    $this->xhtmlVersion = 0;
2489
            }
2490
        } else {
2491
            $this->pageRenderer->setRenderXhtml(false);
2492
        }
2493
2494
        // Global content object
2495
        $this->newCObj();
2496
        $this->getTimeTracker()->pull();
2497
    }
2498
2499
    /**
2500
     * Fills the sWordList property and builds the regular expression in TSFE that can be used to split
2501
     * strings by the submitted search words.
2502
     *
2503
     * @param mixed $searchWords - usually an array, but we can't be sure (yet)
2504
     * @see sWordList
2505
     * @see sWordRegEx
2506
     */
2507
    protected function initializeSearchWordData($searchWords)
2508
    {
2509
        $this->sWordRegEx = '';
2510
        $this->sWordList = $searchWords ?? '';
2511
        if (is_array($this->sWordList)) {
2512
            $space = !empty($this->config['config']['sword_standAlone'] ?? null) ? '[[:space:]]' : '';
2513
            $regexpParts = [];
2514
            foreach ($this->sWordList as $val) {
2515
                if (trim($val) !== '') {
2516
                    $regexpParts[] = $space . preg_quote($val, '/') . $space;
2517
                }
2518
            }
2519
            $this->sWordRegEx = implode('|', $regexpParts);
2520
        }
2521
    }
2522
2523
    /**
2524
     * Does processing of the content after the page content was generated.
2525
     *
2526
     * This includes caching the page, indexing the page (if configured) and setting sysLastChanged
2527
     */
2528
    public function generatePage_postProcessing()
2529
    {
2530
        $this->setAbsRefPrefix();
2531
        // This is to ensure, that the page is NOT cached if the no_cache parameter was set before the page was generated. This is a safety precaution, as it could have been unset by some script.
2532
        if ($this->no_cacheBeforePageGen) {
2533
            $this->set_no_cache('no_cache has been set before the page was generated - safety check', true);
2534
        }
2535
        // Hook for post-processing of page content cached/non-cached:
2536
        $_params = ['pObj' => &$this];
2537
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] ?? [] as $_funcRef) {
2538
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2539
        }
2540
        // Processing if caching is enabled:
2541
        if (!$this->no_cache) {
2542
            // Hook for post-processing of page content before being cached:
2543
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] ?? [] as $_funcRef) {
2544
                GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2545
            }
2546
        }
2547
        // Convert charset for output. Any hooks before (including indexed search) will have to convert from UTF-8 to the target
2548
        // charset as well.
2549
        $this->content = $this->convOutputCharset($this->content);
2550
        // Storing for cache:
2551
        if (!$this->no_cache) {
2552
            $this->realPageCacheContent();
2553
        }
2554
        // Sets sys-last-change:
2555
        $this->setSysLastChanged();
2556
    }
2557
2558
    /**
2559
     * Generate the page title, can be called multiple times,
2560
     * as PageTitleProvider might have been modified by an uncached plugin etc.
2561
     *
2562
     * @return string the generated page title
2563
     */
2564
    public function generatePageTitle(): string
2565
    {
2566
        // Check for a custom pageTitleSeparator, and perform stdWrap on it
2567
        $pageTitleSeparator = (string)$this->cObj->stdWrapValue('pageTitleSeparator', $this->config['config'] ?? []);
2568
        if ($pageTitleSeparator !== '' && $pageTitleSeparator === ($this->config['config']['pageTitleSeparator'] ?? '')) {
2569
            $pageTitleSeparator .= ' ';
2570
        }
2571
2572
        $titleProvider = GeneralUtility::makeInstance(PageTitleProviderManager::class);
2573
        if (!empty($this->config['config']['pageTitleCache'])) {
2574
            $titleProvider->setPageTitleCache($this->config['config']['pageTitleCache']);
2575
        }
2576
        $pageTitle = $titleProvider->getTitle();
2577
        $this->config['config']['pageTitleCache'] = $titleProvider->getPageTitleCache();
2578
2579
        if ($pageTitle !== '') {
2580
            $this->indexedDocTitle = $pageTitle;
2581
        }
2582
2583
        $titleTagContent = $this->printTitle(
2584
            $pageTitle,
2585
            (bool)($this->config['config']['noPageTitle'] ?? false),
2586
            (bool)($this->config['config']['pageTitleFirst'] ?? false),
2587
            $pageTitleSeparator
2588
        );
2589
        $this->config['config']['pageTitle'] = $titleTagContent;
2590
        // stdWrap around the title tag
2591
        $titleTagContent = $this->cObj->stdWrapValue('pageTitle', $this->config['config']);
2592
2593
        // config.noPageTitle = 2 - means do not render the page title
2594
        if (isset($this->config['config']['noPageTitle']) && (int)$this->config['config']['noPageTitle'] === 2) {
2595
            $titleTagContent = '';
2596
        }
2597
        if ($titleTagContent !== '') {
2598
            $this->pageRenderer->setTitle($titleTagContent);
2599
        }
2600
        return (string)$titleTagContent;
2601
    }
2602
2603
    /**
2604
     * Compiles the content for the page <title> tag.
2605
     *
2606
     * @param string $pageTitle The input title string, typically the "title" field of a page's record.
2607
     * @param bool $noTitle If set, then only the site title is outputted
2608
     * @param bool $showTitleFirst If set, then website title and $title is swapped
2609
     * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
2610
     * @return string The page title on the form "[website title]: [input-title]". Not htmlspecialchar()'ed.
2611
     * @see generatePageTitle()
2612
     */
2613
    protected function printTitle(string $pageTitle, bool $noTitle = false, bool $showTitleFirst = false, string $pageTitleSeparator = ''): string
2614
    {
2615
        $websiteTitle = $this->getWebsiteTitle();
2616
        $pageTitle = $noTitle ? '' : $pageTitle;
2617
        if ($showTitleFirst) {
2618
            $temp = $websiteTitle;
2619
            $websiteTitle = $pageTitle;
2620
            $pageTitle = $temp;
2621
        }
2622
        // only show a separator if there are both site title and page title
2623
        if ($pageTitle === '' || $websiteTitle === '') {
2624
            $pageTitleSeparator = '';
2625
        } elseif (empty($pageTitleSeparator)) {
2626
            // use the default separator if non given
2627
            $pageTitleSeparator = ': ';
2628
        }
2629
        return $websiteTitle . $pageTitleSeparator . $pageTitle;
2630
    }
2631
2632
    /**
2633
     * @return string
2634
     */
2635
    protected function getWebsiteTitle(): string
2636
    {
2637
        if ($this->language instanceof SiteLanguage
2638
            && trim($this->language->getWebsiteTitle()) !== ''
2639
        ) {
2640
            return trim($this->language->getWebsiteTitle());
2641
        }
2642
        if ($this->site instanceof SiteInterface
2643
            && trim($this->site->getConfiguration()['websiteTitle']) !== ''
2644
        ) {
2645
            return trim($this->site->getConfiguration()['websiteTitle']);
2646
        }
2647
2648
        return '';
2649
    }
2650
2651
    /**
2652
     * Processes the INTinclude-scripts
2653
     */
2654
    public function INTincScript()
2655
    {
2656
        $this->additionalHeaderData = $this->config['INTincScript_ext']['additionalHeaderData'] ?? [];
2657
        $this->additionalFooterData = $this->config['INTincScript_ext']['additionalFooterData'] ?? [];
2658
        if (empty($this->config['INTincScript_ext']['pageRenderer'])) {
2659
            $this->initPageRenderer();
2660
        } else {
2661
            /** @var PageRenderer $pageRenderer */
2662
            $pageRenderer = unserialize($this->config['INTincScript_ext']['pageRenderer']);
2663
            $this->pageRenderer->updateState($pageRenderer->getState());
2664
        }
2665
        if (!empty($this->config['INTincScript_ext']['assetCollector'])) {
2666
            /** @var AssetCollector $assetCollector */
2667
            $assetCollector = unserialize($this->config['INTincScript_ext']['assetCollector'], ['allowed_classes' => [AssetCollector::class]]);
2668
            GeneralUtility::makeInstance(AssetCollector::class)->updateState($assetCollector->getState());
2669
        }
2670
2671
        $this->recursivelyReplaceIntPlaceholdersInContent();
2672
        $this->getTimeTracker()->push('Substitute header section');
2673
        $this->INTincScript_loadJSCode();
2674
        $this->generatePageTitle();
2675
2676
        $this->content = str_replace(
2677
            [
2678
                '<!--HD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
2679
                '<!--FD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
2680
            ],
2681
            [
2682
                $this->convOutputCharset(implode(LF, $this->additionalHeaderData)),
2683
                $this->convOutputCharset(implode(LF, $this->additionalFooterData)),
2684
            ],
2685
            $this->pageRenderer->renderJavaScriptAndCssForProcessingOfUncachedContentObjects($this->content, $this->config['INTincScript_ext']['divKey'])
2686
        );
2687
        // Replace again, because header and footer data and page renderer replacements may introduce additional placeholders (see #44825)
2688
        $this->recursivelyReplaceIntPlaceholdersInContent();
2689
        $this->setAbsRefPrefix();
2690
        $this->getTimeTracker()->pull();
2691
    }
2692
2693
    /**
2694
     * Replaces INT placeholders (COA_INT and USER_INT) in $this->content
2695
     * In case the replacement adds additional placeholders, it loops
2696
     * until no new placeholders are found any more.
2697
     */
2698
    protected function recursivelyReplaceIntPlaceholdersInContent()
2699
    {
2700
        do {
2701
            $nonCacheableData = $this->config['INTincScript'];
2702
            $this->processNonCacheableContentPartsAndSubstituteContentMarkers($nonCacheableData);
2703
            // Check if there were new items added to INTincScript during the previous execution:
2704
            // array_diff_assoc throws notices if values are arrays but not strings. We suppress this here.
2705
            $nonCacheableData = @array_diff_assoc($this->config['INTincScript'], $nonCacheableData);
2706
            $reprocess = count($nonCacheableData) > 0;
2707
        } while ($reprocess);
2708
    }
2709
2710
    /**
2711
     * Processes the INTinclude-scripts and substitute in content.
2712
     *
2713
     * Takes $this->content, and splits the content by <!--INT_SCRIPT.12345 --> and then puts the content
2714
     * back together.
2715
     *
2716
     * @param array $nonCacheableData $GLOBALS['TSFE']->config['INTincScript'] or part of it
2717
     * @see INTincScript()
2718
     */
2719
    protected function processNonCacheableContentPartsAndSubstituteContentMarkers(array $nonCacheableData)
2720
    {
2721
        $timeTracker = $this->getTimeTracker();
2722
        $timeTracker->push('Split content');
2723
        // Splits content with the key.
2724
        $contentSplitByUncacheableMarkers = explode('<!--INT_SCRIPT.', $this->content);
2725
        $this->content = '';
2726
        $timeTracker->setTSlogMessage('Parts: ' . count($contentSplitByUncacheableMarkers));
2727
        $timeTracker->pull();
2728
        foreach ($contentSplitByUncacheableMarkers as $counter => $contentPart) {
2729
            // If the split had a comment-end after 32 characters it's probably a split-string
2730
            if (substr($contentPart, 32, 3) === '-->') {
2731
                $nonCacheableKey = 'INT_SCRIPT.' . substr($contentPart, 0, 32);
2732
                if (is_array($nonCacheableData[$nonCacheableKey])) {
2733
                    $label = 'Include ' . $nonCacheableData[$nonCacheableKey]['type'];
2734
                    $timeTracker->push($label);
2735
                    $nonCacheableContent = '';
2736
                    $contentObjectRendererForNonCacheable = unserialize($nonCacheableData[$nonCacheableKey]['cObj']);
2737
                    /* @var ContentObjectRenderer $contentObjectRendererForNonCacheable */
2738
                    switch ($nonCacheableData[$nonCacheableKey]['type']) {
2739
                        case 'COA':
2740
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->cObjGetSingle('COA', $nonCacheableData[$nonCacheableKey]['conf']);
2741
                            break;
2742
                        case 'FUNC':
2743
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->cObjGetSingle('USER', $nonCacheableData[$nonCacheableKey]['conf']);
2744
                            break;
2745
                        case 'POSTUSERFUNC':
2746
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->callUserFunction($nonCacheableData[$nonCacheableKey]['postUserFunc'], $nonCacheableData[$nonCacheableKey]['conf'], $nonCacheableData[$nonCacheableKey]['content']);
2747
                            break;
2748
                    }
2749
                    $this->content .= $this->convOutputCharset($nonCacheableContent);
2750
                    $this->content .= substr($contentPart, 35);
2751
                    $timeTracker->pull($nonCacheableContent);
2752
                } else {
2753
                    $this->content .= substr($contentPart, 35);
2754
                }
2755
            } elseif ($counter) {
2756
                // If it's not the first entry (which would be "0" of the array keys), then re-add the INT_SCRIPT part
2757
                $this->content .= '<!--INT_SCRIPT.' . $contentPart;
2758
            } else {
2759
                $this->content .= $contentPart;
2760
            }
2761
        }
2762
    }
2763
2764
    /**
2765
     * Loads the JavaScript/CSS code for INTincScript, if there are non-cacheable content objects
2766
     * it prepares the placeholders, otherwise populates options directly.
2767
     *
2768
     * @internal this method should be renamed as it does not only handle JS, but all additional header data
2769
     */
2770
    public function INTincScript_loadJSCode()
2771
    {
2772
        // Prepare code and placeholders for additional header and footer files (and make sure that this isn't called twice)
2773
        if ($this->isINTincScript() && !isset($this->config['INTincScript_ext'])) {
2774
            $substituteHash = $this->uniqueHash();
2775
            $this->config['INTincScript_ext']['divKey'] = $substituteHash;
2776
            // Storing the header-data array
2777
            $this->config['INTincScript_ext']['additionalHeaderData'] = $this->additionalHeaderData;
2778
            // Storing the footer-data array
2779
            $this->config['INTincScript_ext']['additionalFooterData'] = $this->additionalFooterData;
2780
            // Clearing the array
2781
            $this->additionalHeaderData = ['<!--HD_' . $substituteHash . '-->'];
2782
            // Clearing the array
2783
            $this->additionalFooterData = ['<!--FD_' . $substituteHash . '-->'];
2784
        }
2785
    }
2786
2787
    /**
2788
     * Determines if there are any INTincScripts to include = "non-cacheable" parts
2789
     *
2790
     * @return bool Returns TRUE if scripts are found
2791
     */
2792
    public function isINTincScript()
2793
    {
2794
        return !empty($this->config['INTincScript']) && is_array($this->config['INTincScript']);
2795
    }
2796
2797
    /**
2798
     * Add HTTP headers to the response object.
2799
     *
2800
     * @param ResponseInterface $response
2801
     * @return ResponseInterface
2802
     */
2803
    public function applyHttpHeadersToResponse(ResponseInterface $response): ResponseInterface
2804
    {
2805
        // Set header for charset-encoding unless disabled
2806
        if (empty($this->config['config']['disableCharsetHeader'])) {
2807
            $response = $response->withHeader('Content-Type', $this->contentType . '; charset=' . trim($this->metaCharset));
2808
        }
2809
        // Set header for content language unless disabled
2810
        $contentLanguage = $this->language->getTwoLetterIsoCode();
2811
        if (empty($this->config['config']['disableLanguageHeader']) && !empty($contentLanguage)) {
2812
            $response = $response->withHeader('Content-Language', trim($contentLanguage));
2813
        }
2814
        // Set cache related headers to client (used to enable proxy / client caching!)
2815
        if (!empty($this->config['config']['sendCacheHeaders'])) {
2816
            $headers = $this->getCacheHeaders();
2817
            foreach ($headers as $header => $value) {
2818
                $response = $response->withHeader($header, $value);
2819
            }
2820
        }
2821
        // Set additional headers if any have been configured via TypoScript
2822
        $additionalHeaders = $this->getAdditionalHeaders();
2823
        foreach ($additionalHeaders as $headerConfig) {
2824
            [$header, $value] = GeneralUtility::trimExplode(':', $headerConfig['header'], false, 2);
2825
            if ($headerConfig['statusCode']) {
2826
                $response = $response->withStatus((int)$headerConfig['statusCode']);
2827
            }
2828
            if ($headerConfig['replace']) {
2829
                $response = $response->withHeader($header, $value);
2830
            } else {
2831
                $response = $response->withAddedHeader($header, $value);
2832
            }
2833
        }
2834
        return $response;
2835
    }
2836
2837
    /**
2838
     * Get cache headers good for client/reverse proxy caching.
2839
     *
2840
     * @return array
2841
     */
2842
    protected function getCacheHeaders(): array
2843
    {
2844
        // Getting status whether we can send cache control headers for proxy caching:
2845
        $doCache = $this->isStaticCacheble();
2846
        // This variable will be TRUE unless cache headers are configured to be sent ONLY if a branch does not allow logins and logins turns out to be allowed anyway...
2847
        $loginsDeniedCfg = empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch);
2848
        // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
2849
        $this->isClientCachable = $doCache && !$this->isBackendUserLoggedIn() && !$this->doWorkspacePreview() && $loginsDeniedCfg;
2850
        if ($this->isClientCachable) {
2851
            $headers = [
2852
                'Expires' => gmdate('D, d M Y H:i:s T', $this->cacheExpires),
2853
                'ETag' => '"' . md5($this->content) . '"',
2854
                'Cache-Control' => 'max-age=' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']),
2855
                // no-cache
2856
                'Pragma' => 'public'
2857
            ];
2858
        } else {
2859
            // "no-store" is used to ensure that the client HAS to ask the server every time, and is not allowed to store anything at all
2860
            $headers = [
2861
                'Cache-Control' => 'private, no-store'
2862
            ];
2863
            // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
2864
            if ($this->isBackendUserLoggedIn()) {
2865
                if ($doCache) {
2866
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers with max-age "' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']) . '" would have been sent');
2867
                } else {
2868
                    $reasonMsg = [];
2869
                    if ($this->no_cache) {
2870
                        $reasonMsg[] = 'Caching disabled (no_cache).';
2871
                    }
2872
                    if ($this->isINTincScript()) {
2873
                        $reasonMsg[] = '*_INT object(s) on page.';
2874
                    }
2875
                    if (is_array($this->fe_user->user)) {
2876
                        $reasonMsg[] = 'Frontend user logged in.';
2877
                    }
2878
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "' . implode(' ', $reasonMsg) . '"', 1);
2879
                }
2880
            }
2881
        }
2882
        return $headers;
2883
    }
2884
2885
    /**
2886
     * Reporting status whether we can send cache control headers for proxy caching or publishing to static files
2887
     *
2888
     * Rules are:
2889
     * no_cache cannot be set: If it is, the page might contain dynamic content and should never be cached.
2890
     * There can be no USER_INT objects on the page ("isINTincScript()") because they implicitly indicate dynamic content
2891
     * There can be no logged in user because user sessions are based on a cookie and thereby does not offer client caching a chance to know if the user is logged in. Actually, there will be a reverse problem here; If a page will somehow change when a user is logged in he may not see it correctly if the non-login version sent a cache-header! So do NOT use cache headers in page sections where user logins change the page content. (unless using such as realurl to apply a prefix in case of login sections)
2892
     *
2893
     * @return bool
2894
     */
2895
    public function isStaticCacheble()
2896
    {
2897
        return !$this->no_cache && !$this->isINTincScript() && !$this->isUserOrGroupSet();
2898
    }
2899
2900
    /********************************************
2901
     *
2902
     * Various internal API functions
2903
     *
2904
     *******************************************/
2905
    /**
2906
     * Creates an instance of ContentObjectRenderer in $this->cObj
2907
     * This instance is used to start the rendering of the TypoScript template structure
2908
     *
2909
     * @see RequestHandler
2910
     */
2911
    public function newCObj()
2912
    {
2913
        $this->cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class, $this);
2914
        $this->cObj->start($this->page, 'pages');
2915
    }
2916
2917
    /**
2918
     * Converts relative paths in the HTML source to absolute paths for fileadmin/, typo3conf/ext/ and media/ folders.
2919
     *
2920
     * @internal
2921
     * @see \TYPO3\CMS\Frontend\Http\RequestHandler
2922
     * @see INTincScript()
2923
     */
2924
    public function setAbsRefPrefix()
2925
    {
2926
        if (!$this->absRefPrefix) {
2927
            return;
2928
        }
2929
        $search = [
2930
            '"typo3temp/',
2931
            '"' . PathUtility::stripPathSitePrefix(Environment::getExtensionsPath()) . '/',
2932
            '"' . PathUtility::stripPathSitePrefix(Environment::getBackendPath()) . '/ext/',
2933
            '"' . PathUtility::stripPathSitePrefix(Environment::getFrameworkBasePath()) . '/',
2934
        ];
2935
        $replace = [
2936
            '"' . $this->absRefPrefix . 'typo3temp/',
2937
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getExtensionsPath()) . '/',
2938
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getBackendPath()) . '/ext/',
2939
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getFrameworkBasePath()) . '/',
2940
        ];
2941
        /** @var StorageRepository $storageRepository */
2942
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
2943
        $storages = $storageRepository->findAll();
2944
        foreach ($storages as $storage) {
2945
            if ($storage->getDriverType() === 'Local' && $storage->isPublic() && $storage->isOnline()) {
2946
                $folder = $storage->getPublicUrl($storage->getRootLevelFolder(), true);
2947
                $search[] = '"' . $folder;
2948
                $replace[] = '"' . $this->absRefPrefix . $folder;
2949
            }
2950
        }
2951
        // Process additional directories
2952
        $directories = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
2953
        foreach ($directories as $directory) {
2954
            $search[] = '"' . $directory;
2955
            $replace[] = '"' . $this->absRefPrefix . $directory;
2956
        }
2957
        $this->content = str_replace(
2958
            $search,
2959
            $replace,
2960
            $this->content
2961
        );
2962
    }
2963
2964
    /**
2965
     * Prefixing the input URL with ->baseUrl If ->baseUrl is set and the input url is not absolute in some way.
2966
     * Designed as a wrapper functions for use with all frontend links that are processed by JavaScript (for "realurl" compatibility!). So each time a URL goes into window.open, window.location.href or otherwise, wrap it with this function!
2967
     *
2968
     * @param string $url Input URL, relative or absolute
2969
     * @return string Processed input value.
2970
     */
2971
    public function baseUrlWrap($url)
2972
    {
2973
        if ($this->baseUrl) {
2974
            $urlParts = parse_url($url);
2975
            if (empty($urlParts['scheme']) && $url[0] !== '/') {
2976
                $url = $this->baseUrl . $url;
2977
            }
2978
        }
2979
        return $url;
2980
    }
2981
2982
    /**
2983
     * Logs access to deprecated TypoScript objects and properties.
2984
     *
2985
     * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
2986
     *
2987
     * @param string $typoScriptProperty Deprecated object or property
2988
     * @param string $explanation Message or additional information
2989
     */
2990
    public function logDeprecatedTyposcript($typoScriptProperty, $explanation = '')
2991
    {
2992
        $explanationText = $explanation !== '' ? ' - ' . $explanation : '';
2993
        $this->getTimeTracker()->setTSlogMessage($typoScriptProperty . ' is deprecated.' . $explanationText, 2);
2994
        trigger_error('TypoScript property ' . $typoScriptProperty . ' is deprecated' . $explanationText, E_USER_DEPRECATED);
2995
    }
2996
2997
    /********************************************
2998
     * PUBLIC ACCESSIBLE WORKSPACES FUNCTIONS
2999
     *******************************************/
3000
3001
    /**
3002
     * Returns TRUE if workspace preview is enabled
3003
     *
3004
     * @return bool Returns TRUE if workspace preview is enabled
3005
     */
3006
    public function doWorkspacePreview()
3007
    {
3008
        return $this->context->getPropertyFromAspect('workspace', 'isOffline', false);
3009
    }
3010
3011
    /**
3012
     * Returns the uid of the current workspace
3013
     *
3014
     * @return int returns workspace integer for which workspace is being preview. 0 if none (= live workspace).
3015
     */
3016
    public function whichWorkspace(): int
3017
    {
3018
        return $this->context->getPropertyFromAspect('workspace', 'id', 0);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->context->g...t('workspace', 'id', 0) could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
3019
    }
3020
3021
    /********************************************
3022
     *
3023
     * Various external API functions - for use in plugins etc.
3024
     *
3025
     *******************************************/
3026
3027
    /**
3028
     * Returns the pages TSconfig array based on the current ->rootLine
3029
     *
3030
     * @return array
3031
     */
3032
    public function getPagesTSconfig()
3033
    {
3034
        if (!is_array($this->pagesTSconfig)) {
3035
            $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
3036
            $loader = GeneralUtility::makeInstance(PageTsConfigLoader::class);
3037
            $tsConfigString = $loader->load(array_reverse($this->rootLine));
3038
            $parser = GeneralUtility::makeInstance(
3039
                PageTsConfigParser::class,
3040
                GeneralUtility::makeInstance(TypoScriptParser::class),
3041
                $contentHashCache
3042
            );
3043
            $this->pagesTSconfig = $parser->parse(
3044
                $tsConfigString,
3045
                GeneralUtility::makeInstance(ConditionMatcher::class, $this->context, $this->id, $this->rootLine),
3046
                $this->site
3047
            );
3048
        }
3049
        return $this->pagesTSconfig;
3050
    }
3051
3052
    /**
3053
     * Returns a unique md5 hash.
3054
     * There is no special magic in this, the only point is that you don't have to call md5(uniqid()) which is slow and by this you are sure to get a unique string each time in a little faster way.
3055
     *
3056
     * @param string $str Some string to include in what is hashed. Not significant at all.
3057
     * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
3058
     */
3059
    public function uniqueHash($str = '')
3060
    {
3061
        return md5($this->uniqueString . '_' . $str . $this->uniqueCounter++);
3062
    }
3063
3064
    /**
3065
     * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
3066
     *
3067
     * @param string $reason An optional reason to be written to the log.
3068
     * @param bool $internal Whether the call is done from core itself (should only be used by core).
3069
     */
3070
    public function set_no_cache($reason = '', $internal = false)
3071
    {
3072
        if ($reason !== '') {
3073
            $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
3074
        } else {
3075
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
3076
            // This is a hack to work around ___FILE___ resolving symbolic links
3077
            $realWebPath = PathUtility::dirname((string)realpath(Environment::getBackendPath())) . '/';
3078
            $file = $trace[0]['file'];
3079
            if (strpos($file, $realWebPath) === 0) {
3080
                $file = str_replace($realWebPath, '', $file);
3081
            } else {
3082
                $file = str_replace(Environment::getPublicPath() . '/', '', $file);
3083
            }
3084
            $line = $trace[0]['line'];
3085
            $trigger = $file . ' on line ' . $line;
3086
            $warning = '$GLOBALS[\'TSFE\']->set_no_cache() was triggered by ' . $trigger . '.';
3087
        }
3088
        if (!$internal && $GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
3089
            $warning .= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
3090
            $this->getTimeTracker()->setTSlogMessage($warning, 2);
3091
        } else {
3092
            $warning .= ' Caching is disabled!';
3093
            $this->disableCache();
3094
        }
3095
        if ($internal && $this->isBackendUserLoggedIn()) {
3096
            $this->logger->notice($warning);
3097
        } else {
3098
            $this->logger->warning($warning);
3099
        }
3100
    }
3101
3102
    /**
3103
     * Disables caching of the current page.
3104
     *
3105
     * @internal
3106
     */
3107
    protected function disableCache()
3108
    {
3109
        $this->no_cache = true;
3110
    }
3111
3112
    /**
3113
     * Sets the cache-timeout in seconds
3114
     *
3115
     * @param int $seconds Cache-timeout in seconds
3116
     */
3117
    public function set_cache_timeout_default($seconds)
3118
    {
3119
        $seconds = (int)$seconds;
3120
        if ($seconds > 0) {
3121
            $this->cacheTimeOutDefault = $seconds;
3122
        }
3123
    }
3124
3125
    /**
3126
     * Get the cache timeout for the current page.
3127
     *
3128
     * @return int The cache timeout for the current page.
3129
     */
3130
    public function get_cache_timeout()
3131
    {
3132
        /** @var \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend $runtimeCache */
3133
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3134
        $cachedCacheLifetimeIdentifier = 'core-tslib_fe-get_cache_timeout';
3135
        $cachedCacheLifetime = $runtimeCache->get($cachedCacheLifetimeIdentifier);
3136
        if ($cachedCacheLifetime === false) {
3137
            if ($this->page['cache_timeout']) {
3138
                // Cache period was set for the page:
3139
                $cacheTimeout = $this->page['cache_timeout'];
3140
            } else {
3141
                // Cache period was set via TypoScript "config.cache_period",
3142
                // otherwise it's the default of 24 hours
3143
                $cacheTimeout = $this->cacheTimeOutDefault;
3144
            }
3145
            if (!empty($this->config['config']['cache_clearAtMidnight'])) {
3146
                $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
3147
                $midnightTime = mktime(0, 0, 0, (int)date('m', $timeOutTime), (int)date('d', $timeOutTime), (int)date('Y', $timeOutTime));
3148
                // If the midnight time of the expire-day is greater than the current time,
3149
                // we may set the timeOutTime to the new midnighttime.
3150
                if ($midnightTime > $GLOBALS['EXEC_TIME']) {
3151
                    $cacheTimeout = $midnightTime - $GLOBALS['EXEC_TIME'];
3152
                }
3153
            }
3154
3155
            // Calculate the timeout time for records on the page and adjust cache timeout if necessary
3156
            $cacheTimeout = min($this->calculatePageCacheTimeout(), $cacheTimeout);
3157
3158
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['get_cache_timeout'] ?? [] as $_funcRef) {
3159
                $params = ['cacheTimeout' => $cacheTimeout];
3160
                $cacheTimeout = GeneralUtility::callUserFunction($_funcRef, $params, $this);
3161
            }
3162
            $runtimeCache->set($cachedCacheLifetimeIdentifier, $cacheTimeout);
3163
            $cachedCacheLifetime = $cacheTimeout;
3164
        }
3165
        return $cachedCacheLifetime;
3166
    }
3167
3168
    /*********************************************
3169
     *
3170
     * Localization and character set conversion
3171
     *
3172
     *********************************************/
3173
    /**
3174
     * Split Label function for front-end applications.
3175
     *
3176
     * @param string $input Key string. Accepts the "LLL:" prefix.
3177
     * @return string Label value, if any.
3178
     */
3179
    public function sL($input)
3180
    {
3181
        return $this->languageService->sL($input);
3182
    }
3183
3184
    /**
3185
     * Sets all internal measures what language the page should be rendered.
3186
     * This is not for records, but rather the HTML / charset and the locallang labels
3187
     */
3188
    protected function setOutputLanguage()
3189
    {
3190
        $this->languageService = LanguageService::createFromSiteLanguage($this->language);
3191
        // Always disable debugging for TSFE
3192
        $this->languageService->debugKey = false;
3193
    }
3194
3195
    /**
3196
     * Converts input string from utf-8 to metaCharset IF the two charsets are different.
3197
     *
3198
     * @param string $content Content to be converted.
3199
     * @return string Converted content string.
3200
     * @throws \RuntimeException if an invalid charset was configured
3201
     */
3202
    public function convOutputCharset($content)
3203
    {
3204
        if ($this->metaCharset !== 'utf-8') {
3205
            /** @var CharsetConverter $charsetConverter */
3206
            $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
3207
            try {
3208
                $content = $charsetConverter->conv($content, 'utf-8', $this->metaCharset);
3209
            } catch (UnknownCharsetException $e) {
3210
                throw new \RuntimeException('Invalid config.metaCharset: ' . $e->getMessage(), 1508916185);
3211
            }
3212
        }
3213
        return $content;
3214
    }
3215
3216
    /**
3217
     * Calculates page cache timeout according to the records with starttime/endtime on the page.
3218
     *
3219
     * @return int Page cache timeout or PHP_INT_MAX if cannot be determined
3220
     */
3221
    protected function calculatePageCacheTimeout()
3222
    {
3223
        $result = PHP_INT_MAX;
3224
        // Get the configuration
3225
        $tablesToConsider = $this->getCurrentPageCacheConfiguration();
3226
        // Get the time, rounded to the minute (do not pollute MySQL cache!)
3227
        // It is ok that we do not take seconds into account here because this
3228
        // value will be subtracted later. So we never get the time "before"
3229
        // the cache change.
3230
        $now = $GLOBALS['ACCESS_TIME'];
3231
        // Find timeout by checking every table
3232
        foreach ($tablesToConsider as $tableDef) {
3233
            $result = min($result, $this->getFirstTimeValueForRecord($tableDef, $now));
3234
        }
3235
        // We return + 1 second just to ensure that cache is definitely regenerated
3236
        return $result === PHP_INT_MAX ? PHP_INT_MAX : $result - $now + 1;
3237
    }
3238
3239
    /**
3240
     * Obtains a list of table/pid pairs to consider for page caching.
3241
     *
3242
     * TS configuration looks like this:
3243
     *
3244
     * The cache lifetime of all pages takes starttime and endtime of news records of page 14 into account:
3245
     * config.cache.all = tt_news:14
3246
     *
3247
     * The cache.lifetime of the current page allows to take records (e.g. fe_users) into account:
3248
     * config.cache.all = fe_users:current
3249
     *
3250
     * The cache lifetime of page 42 takes starttime and endtime of news records of page 15 and addresses of page 16 into account:
3251
     * config.cache.42 = tt_news:15,tt_address:16
3252
     *
3253
     * @return array Array of 'tablename:pid' pairs. There is at least a current page id in the array
3254
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
3255
     */
3256
    protected function getCurrentPageCacheConfiguration()
3257
    {
3258
        $result = ['tt_content:' . $this->id];
3259
        if (isset($this->config['config']['cache.'][$this->id])) {
3260
            $result = array_merge($result, GeneralUtility::trimExplode(',', str_replace(':current', ':' . $this->id, $this->config['config']['cache.'][$this->id])));
3261
        }
3262
        if (isset($this->config['config']['cache.']['all'])) {
3263
            $result = array_merge($result, GeneralUtility::trimExplode(',', str_replace(':current', ':' . $this->id, $this->config['config']['cache.']['all'])));
3264
        }
3265
        return array_unique($result);
3266
    }
3267
3268
    /**
3269
     * Find the minimum starttime or endtime value in the table and pid that is greater than the current time.
3270
     *
3271
     * @param string $tableDef Table definition (format tablename:pid)
3272
     * @param int $now "Now" time value
3273
     * @throws \InvalidArgumentException
3274
     * @return int Value of the next start/stop time or PHP_INT_MAX if not found
3275
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
3276
     */
3277
    protected function getFirstTimeValueForRecord($tableDef, $now)
3278
    {
3279
        $now = (int)$now;
3280
        $result = PHP_INT_MAX;
3281
        [$tableName, $pid] = GeneralUtility::trimExplode(':', $tableDef);
3282
        if (empty($tableName) || empty($pid)) {
3283
            throw new \InvalidArgumentException('Unexpected value for parameter $tableDef. Expected <tablename>:<pid>, got \'' . htmlspecialchars($tableDef) . '\'.', 1307190365);
3284
        }
3285
3286
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
3287
            ->getQueryBuilderForTable($tableName);
3288
        $queryBuilder->getRestrictions()
3289
            ->removeByType(StartTimeRestriction::class)
3290
            ->removeByType(EndTimeRestriction::class);
3291
        $timeFields = [];
3292
        $timeConditions = $queryBuilder->expr()->orX();
3293
        foreach (['starttime', 'endtime'] as $field) {
3294
            if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field])) {
3295
                $timeFields[$field] = $GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field];
3296
                $queryBuilder->addSelectLiteral(
3297
                    'MIN('
3298
                        . 'CASE WHEN '
3299
                        . $queryBuilder->expr()->lte(
3300
                            $timeFields[$field],
3301
                            $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
3302
                        )
3303
                        . ' THEN NULL ELSE ' . $queryBuilder->quoteIdentifier($timeFields[$field]) . ' END'
3304
                        . ') AS ' . $queryBuilder->quoteIdentifier($timeFields[$field])
3305
                );
3306
                $timeConditions->add(
3307
                    $queryBuilder->expr()->gt(
3308
                        $timeFields[$field],
3309
                        $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
3310
                    )
3311
                );
3312
            }
3313
        }
3314
3315
        // if starttime or endtime are defined, evaluate them
3316
        if (!empty($timeFields)) {
3317
            // find the timestamp, when the current page's content changes the next time
3318
            $row = $queryBuilder
3319
                ->from($tableName)
3320
                ->where(
3321
                    $queryBuilder->expr()->eq(
3322
                        'pid',
3323
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
3324
                    ),
3325
                    $timeConditions
3326
                )
3327
                ->execute()
3328
                ->fetch();
3329
3330
            if ($row) {
3331
                foreach ($timeFields as $timeField => $_) {
3332
                    // if a MIN value is found, take it into account for the
3333
                    // cache lifetime we have to filter out start/endtimes < $now,
3334
                    // as the SQL query also returns rows with starttime < $now
3335
                    // and endtime > $now (and using a starttime from the past
3336
                    // would be wrong)
3337
                    if ($row[$timeField] !== null && (int)$row[$timeField] > $now) {
3338
                        $result = min($result, (int)$row[$timeField]);
3339
                    }
3340
                }
3341
            }
3342
        }
3343
3344
        return $result;
3345
    }
3346
3347
    /**
3348
     * Fetches the originally requested id, falls back to $this->id
3349
     *
3350
     * @return int the originally requested page uid
3351
     * @see fetch_the_id()
3352
     */
3353
    public function getRequestedId()
3354
    {
3355
        return $this->requestedId ?: $this->id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->requestedId ?: $this->id also could return the type string which is incompatible with the documented return type integer.
Loading history...
3356
    }
3357
3358
    /**
3359
     * Acquire a page specific lock
3360
     *
3361
     *
3362
     * The schematics here is:
3363
     * - First acquire an access lock. This is using the type of the requested lock as key.
3364
     *   Since the number of types is rather limited we can use the type as key as it will only
3365
     *   eat up a limited number of lock resources on the system (files, semaphores)
3366
     * - Second, we acquire the actual lock (named page lock). We can be sure we are the only process at this
3367
     *   very moment, hence we either get the lock for the given key or we get an error as we request a non-blocking mode.
3368
     *
3369
     * Interleaving two locks is extremely important, because the actual page lock uses a hash value as key (see callers
3370
     * of this function). If we would simply employ a normal blocking lock, we would get a potentially unlimited
3371
     * (number of pages at least) number of different locks. Depending on the available locking methods on the system
3372
     * we might run out of available resources. (e.g. maximum limit of semaphores is a system setting and applies
3373
     * to the whole system)
3374
     * We therefore must make sure that page locks are destroyed again if they are not used anymore, such that
3375
     * we never use more locking resources than parallel requests to different pages (hashes).
3376
     * In order to ensure this, we need to guarantee that no other process is waiting on a page lock when
3377
     * the process currently having the lock on the page lock is about to release the lock again.
3378
     * This can only be achieved by using a non-blocking mode, such that a process is never put into wait state
3379
     * by the kernel, but only checks the availability of the lock. The access lock is our guard to be sure
3380
     * that no two processes are at the same time releasing/destroying a page lock, whilst the other one tries to
3381
     * get a lock for this page lock.
3382
     * The only drawback of this implementation is that we basically have to poll the availability of the page lock.
3383
     *
3384
     * Note that the access lock resources are NEVER deleted/destroyed, otherwise the whole thing would be broken.
3385
     *
3386
     * @param string $type
3387
     * @param string $key
3388
     * @throws \InvalidArgumentException
3389
     * @throws \RuntimeException
3390
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
3391
     */
3392
    protected function acquireLock($type, $key)
3393
    {
3394
        $lockFactory = GeneralUtility::makeInstance(LockFactory::class);
3395
        $this->locks[$type]['accessLock'] = $lockFactory->createLocker($type);
3396
3397
        $this->locks[$type]['pageLock'] = $lockFactory->createLocker(
3398
            $key,
3399
            LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
3400
        );
3401
3402
        do {
3403
            if (!$this->locks[$type]['accessLock']->acquire()) {
3404
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1294586098);
3405
            }
3406
3407
            try {
3408
                $locked = $this->locks[$type]['pageLock']->acquire(
3409
                    LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
3410
                );
3411
            } catch (LockAcquireWouldBlockException $e) {
3412
                // somebody else has the lock, we keep waiting
3413
3414
                // first release the access lock
3415
                $this->locks[$type]['accessLock']->release();
3416
                // now lets make a short break (100ms) until we try again, since
3417
                // the page generation by the lock owner will take a while anyways
3418
                usleep(100000);
3419
                continue;
3420
            }
3421
            $this->locks[$type]['accessLock']->release();
3422
            if ($locked) {
3423
                break;
3424
            }
3425
            throw new \RuntimeException('Could not acquire page lock for ' . $key . '.', 1460975877);
3426
        } while (true);
3427
    }
3428
3429
    /**
3430
     * Release a page specific lock
3431
     *
3432
     * @param string $type
3433
     * @throws \InvalidArgumentException
3434
     * @throws \RuntimeException
3435
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
3436
     */
3437
    protected function releaseLock($type)
3438
    {
3439
        if ($this->locks[$type]['accessLock']) {
3440
            if (!$this->locks[$type]['accessLock']->acquire()) {
3441
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1460975902);
3442
            }
3443
3444
            $this->locks[$type]['pageLock']->release();
3445
            $this->locks[$type]['pageLock']->destroy();
3446
            $this->locks[$type]['pageLock'] = null;
3447
3448
            $this->locks[$type]['accessLock']->release();
3449
            $this->locks[$type]['accessLock'] = null;
3450
        }
3451
    }
3452
3453
    /**
3454
     * Send additional headers from config.additionalHeaders
3455
     */
3456
    protected function getAdditionalHeaders(): array
3457
    {
3458
        if (!isset($this->config['config']['additionalHeaders.'])) {
3459
            return [];
3460
        }
3461
        $additionalHeaders = [];
3462
        ksort($this->config['config']['additionalHeaders.']);
3463
        foreach ($this->config['config']['additionalHeaders.'] as $options) {
3464
            if (!is_array($options)) {
3465
                continue;
3466
            }
3467
            $header = trim($options['header'] ?? '');
3468
            if ($header === '') {
3469
                continue;
3470
            }
3471
            $additionalHeaders[] = [
3472
                'header' => $header,
3473
                // "replace existing headers" is turned on by default, unless turned off
3474
                'replace' => ($options['replace'] ?? '') !== '0',
3475
                'statusCode' => (int)($options['httpResponseCode'] ?? 0) ?: null
3476
            ];
3477
        }
3478
        return $additionalHeaders;
3479
    }
3480
3481
    /**
3482
     * Returns the current BE user.
3483
     *
3484
     * @return \TYPO3\CMS\Backend\FrontendBackendUserAuthentication
3485
     */
3486
    protected function getBackendUser()
3487
    {
3488
        return $GLOBALS['BE_USER'];
3489
    }
3490
3491
    /**
3492
     * @return TimeTracker
3493
     */
3494
    protected function getTimeTracker()
3495
    {
3496
        return GeneralUtility::makeInstance(TimeTracker::class);
3497
    }
3498
3499
    /**
3500
     * Return the global instance of this class.
3501
     *
3502
     * Intended to be used as prototype factory for this class, see Services.yaml.
3503
     * This is required as long as TypoScriptFrontendController needs request
3504
     * dependent constructor parameters. Once that has been refactored this
3505
     * factory will be removed.
3506
     *
3507
     * @return TypoScriptFrontendController
3508
     * @internal
3509
     */
3510
    public static function getGlobalInstance(): ?self
3511
    {
3512
        if (($GLOBALS['TSFE'] ?? null) instanceof self) {
3513
            return $GLOBALS['TSFE'];
3514
        }
3515
3516
        if (!(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_FE)) {
3517
            // Return null for now (together with shared: false in Services.yaml) as TSFE might not be available in backend context
3518
            // That's not an error then
3519
            return null;
3520
        }
3521
3522
        throw new \LogicException('TypoScriptFrontendController was tried to be injected before initial creation', 1538370377);
3523
    }
3524
3525
    public function getLanguage(): SiteLanguage
3526
    {
3527
        return $this->language;
3528
    }
3529
3530
    public function getSite(): Site
3531
    {
3532
        return $this->site;
3533
    }
3534
3535
    public function getContext(): Context
3536
    {
3537
        return $this->context;
3538
    }
3539
3540
    public function getPageArguments(): PageArguments
3541
    {
3542
        return $this->pageArguments;
3543
    }
3544
}
3545