TypoScriptFrontendController.php 150 KB
Newer Older
1
<?php
2

3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
7
8
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
9
 *
10
11
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
14
 * The TYPO3 project - inspiring people to share!
 */
Christian Kuhn's avatar
Christian Kuhn committed
15

16
17
namespace TYPO3\CMS\Frontend\Controller;

18
use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
21
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
22
23
24
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Charset\CharsetConverter;
25
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
26
27
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
28
29
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\DateTimeAspect;
30
31
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
32
33
34
use TYPO3\CMS\Core\Context\UserAspect;
use TYPO3\CMS\Core\Context\VisibilityAspect;
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
40
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
41
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
42
use TYPO3\CMS\Core\Error\Http\AbstractServerErrorException;
43
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
44
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
45
use TYPO3\CMS\Core\Exception\Page\RootLineException;
46
use TYPO3\CMS\Core\Http\ApplicationType;
47
use TYPO3\CMS\Core\Http\ImmediateResponseException;
48
use TYPO3\CMS\Core\Http\ServerRequestFactory;
49
use TYPO3\CMS\Core\Localization\LanguageService;
50
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
51
52
use TYPO3\CMS\Core\Locking\LockFactory;
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
53
use TYPO3\CMS\Core\Page\AssetCollector;
54
use TYPO3\CMS\Core\Page\PageRenderer;
Richard Haeser's avatar
Richard Haeser committed
55
use TYPO3\CMS\Core\PageTitle\PageTitleProviderManager;
56
use TYPO3\CMS\Core\Resource\Exception;
57
use TYPO3\CMS\Core\Resource\StorageRepository;
58
use TYPO3\CMS\Core\Routing\PageArguments;
59
use TYPO3\CMS\Core\Site\Entity\Site;
60
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
61
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
62
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
63
use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
64
use TYPO3\CMS\Core\Type\Bitmask\Permission;
65
66
67
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
use TYPO3\CMS\Core\TypoScript\TemplateService;
use TYPO3\CMS\Core\Utility\ArrayUtility;
68
69
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
70
use TYPO3\CMS\Core\Utility\MathUtility;
71
use TYPO3\CMS\Core\Utility\PathUtility;
72
use TYPO3\CMS\Core\Utility\RootlineUtility;
73
use TYPO3\CMS\Frontend\Aspect\PreviewAspect;
74
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
75
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
76
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
77
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
78
use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons;
79
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
80

81
/**
82
 * Class for the built TypoScript based frontend. Instantiated in
83
 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
84
 *
85
86
 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
 * as the global object TSFE.
87
88
 *
 * This class has a lot of functions and internal variable which are used from
89
 * \TYPO3\CMS\Frontend\Http\RequestHandler
90
 *
91
 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
92
93
 *
 * The use of this class should be inspired by the order of function calls as
94
 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
95
 */
96
class TypoScriptFrontendController implements LoggerAwareInterface
97
{
98
    use LoggerAwareTrait;
99

100
101
102
103
104
105
106
107
    /**
     * The page id (int)
     * @var string
     */
    public $id = '';

    /**
     * The type (read-only)
108
     * @var int|string
109
110
111
     */
    public $type = '';

112
113
114
115
116
117
118
119
120
121
    /**
     * @var Site
     */
    protected $site;

    /**
     * @var SiteLanguage
     */
    protected $language;

122
123
124
125
126
127
    /**
     * @var PageArguments
     * @internal
     */
    protected $pageArguments;

128
129
130
131
132
133
134
135
136
137
138
    /**
     * Page will not be cached. Write only TRUE. Never clear value (some other
     * code might have reasons to set it TRUE).
     * @var bool
     */
    public $no_cache = false;

    /**
     * The rootLine (all the way to tree root, not only the current site!)
     * @var array
     */
139
    public $rootLine = [];
140
141
142
143
144

    /**
     * The pagerecord
     * @var array
     */
145
    public $page = [];
146
147
148
149
150
151
152
153
154
155
156
157
158

    /**
     * This will normally point to the same value as id, but can be changed to
     * point to another page from which content will then be displayed instead.
     * @var int
     */
    public $contentPid = 0;

    /**
     * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
     * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
     * should be redirected to.
     *
159
     * @var array|null
160
     */
161
    protected $originalMountPointPage;
162
163
164
165
166
167

    /**
     * Gets set when we are processing a page of type shortcut in the early stages
     * of the request when we do not know about languages yet, used later in the request
     * to determine the correct shortcut in case a translation changes the shortcut
     * target
168
     * @var array|null
169
170
     * @see checkTranslatedShortcut()
     */
171
    protected $originalShortcutPage;
172
173
174
175

    /**
     * sys_page-object, pagefunctions
     *
176
     * @var PageRepository|string
177
178
179
180
181
182
     */
    public $sys_page = '';

    /**
     * Is set to 1 if a pageNotFound handler could have been called.
     * @var int
183
     * @internal
184
185
186
187
188
189
190
     */
    public $pageNotFound = 0;

    /**
     * Array containing a history of why a requested page was not accessible.
     * @var array
     */
191
    protected $pageAccessFailureHistory = [];
192
193
194

    /**
     * @var string
195
     * @internal
196
197
198
199
200
201
     */
    public $MP = '';

    /**
     * The frontend user
     *
202
     * @var FrontendUserAuthentication
203
     */
204
    public $fe_user;
205
206
207
208
209

    /**
     * Shows whether logins are allowed in branch
     * @var bool
     */
210
    protected $loginAllowedInBranch = true;
211
212
213
214

    /**
     * Shows specific mode (all or groups)
     * @var string
215
     * @internal
216
     */
217
    protected $loginAllowedInBranch_mode = '';
218
219
220
221

    /**
     * Value that contains the simulated usergroup if any
     * @var int
222
     * @internal only to be used in AdminPanel, and within TYPO3 Core
223
224
225
226
227
228
229
230
     */
    public $simUserGroup = 0;

    /**
     * "CONFIG" object from TypoScript. Array generated based on the TypoScript
     * configuration of the current page. Saved with the cached pages.
     * @var array
     */
231
    public $config = [];
232
233
234
235
236
237

    /**
     * The TypoScript template object. Used to parse the TypoScript template
     *
     * @var TemplateService
     */
238
    public $tmpl;
239
240

    /**
241
242
243
     * Is set to the time-to-live time of cached pages. Default is 60*60*24, which is 24 hours.
     *
     * @var int
244
     * @internal
245
     */
246
    protected $cacheTimeOutDefault = 86400;
247
248

    /**
249
     * Set internally if cached content is fetched from the database.
250
     *
251
252
253
     * @var bool
     * @internal
     */
254
    protected $cacheContentFlag = false;
255
256
257
258

    /**
     * Set to the expire time of cached content
     * @var int
259
     * @internal
260
     */
261
    protected $cacheExpires = 0;
262
263
264
265

    /**
     * Set if cache headers allowing caching are sent.
     * @var bool
266
     * @internal
267
     */
268
    protected $isClientCachable = false;
269
270
271
272
273
274

    /**
     * Used by template fetching system. 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.
     * @var array
275
     * @internal
276
     */
277
    public $all = [];
278
279
280
281

    /**
     * Toplevel - objArrayName, eg 'page'
     * @var string
282
     * @internal should only be used by TYPO3 Core
283
284
285
286
287
288
     */
    public $sPre = '';

    /**
     * TypoScript configuration of the page-object pointed to by sPre.
     * $this->tmpl->setup[$this->sPre.'.']
289
     * @var array|string
290
     * @internal should only be used by TYPO3 Core
291
292
293
294
295
     */
    public $pSetup = '';

    /**
     * This hash is unique to the template, the $this->id and $this->type vars and
296
     * the list of groups. Used to get and later store the cached data
297
     * @var string
298
     * @internal
299
300
301
302
     */
    public $newHash = '';

    /**
303
304
305
     * This flag is set before the page is generated IF $this->no_cache is set. If this
     * flag is set after the page content was generated, $this->no_cache is forced to be set.
     * This is done in order to make sure that PHP code from Plugins / USER scripts does not falsely
306
307
     * clear the no_cache flag.
     * @var bool
308
     * @internal
309
     */
310
    protected $no_cacheBeforePageGen = false;
311
312
313

    /**
     * May be set to the pagesTSconfig
314
     * @var array|string
315
     * @internal
316
     */
317
    protected $pagesTSconfig = '';
318
319
320
321
322
323
324
325
326
327
328
329
330
331

    /**
     * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
     * once. Use associative keys.
     *
     * Keys in use:
     *
     * used to accumulate additional HTML-code for the header-section,
     * <head>...</head>. Insert either associative keys (like
     * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
     * (like additionalHeaderData[] = '...')
     *
     * @var array
     */
332
    public $additionalHeaderData = [];
333
334
335
336
337

    /**
     * Used to accumulate additional HTML-code for the footer-section of the template
     * @var array
     */
338
    public $additionalFooterData = [];
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

    /**
     * Default internal target
     * @var string
     */
    public $intTarget = '';

    /**
     * Default external target
     * @var string
     */
    public $extTarget = '';

    /**
     * Default file link target
     * @var string
     */
    public $fileTarget = '';

    /**
359
     * If set, typolink() function encrypts email addresses.
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
     * @var string|int
     */
    public $spamProtectEmailAddresses = 0;

    /**
     * Absolute Reference prefix
     * @var string
     */
    public $absRefPrefix = '';

    /**
     * <A>-tag parameters
     * @var string
     */
    public $ATagParams = '';

    /**
     * Search word regex, calculated if there has been search-words send. This is
     * used to mark up the found search words on a page when jumped to from a link
     * in a search-result.
     * @var string
381
     * @internal
382
383
384
385
386
387
388
     */
    public $sWordRegEx = '';

    /**
     * Is set to the incoming array sword_list in case of a page-view jumped to from
     * a search-result.
     * @var string
389
     * @internal
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
     */
    public $sWordList = '';

    /**
     * A string prepared for insertion in all links on the page as url-parameters.
     * Based on configuration in TypoScript where you defined which GET_VARS you
     * would like to pass on.
     * @var string
     */
    public $linkVars = '';

    /**
     * If set, edit icons are rendered aside content records. Must be set only if
     * the ->beUserLogin flag is set and set_no_cache() must be called as well.
     * @var string
     */
    public $displayEditIcons = '';

    /**
     * If set, edit icons are rendered aside individual fields of content. Must be
     * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
     * well.
     * @var string
     */
    public $displayFieldEditIcons = '';

    /**
     * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
     * extensions.
     * @var array
     */
421
    public $applicationData = [];
422
423
424
425

    /**
     * @var array
     */
426
    public $register = [];
427
428
429
430
431
432

    /**
     * Stack used for storing array and retrieving register arrays (see
     * LOAD_REGISTER and RESTORE_REGISTER)
     * @var array
     */
433
    public $registerStack = [];
434
435
436
437
438
439
440
441
442
443
444
445
446

    /**
     * Checking that the function is not called eternally. This is done by
     * interrupting at a depth of 50
     * @var int
     */
    public $cObjectDepthCounter = 50;

    /**
     * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
     * rendered twice through it!
     * @var array
     */
447
    public $recordRegister = [];
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462

    /**
     * This is set to the [table]:[uid] of the latest record rendered. Note that
     * class ContentObjectRenderer has an equal value, but that is pointing to the
     * record delivered in the $data-array of the ContentObjectRenderer instance, if
     * the cObjects CONTENT or RECORD created that instance
     * @var string
     */
    public $currentRecord = '';

    /**
     * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
     * to keep track of access-keys.
     * @var array
     */
463
    public $accessKey = [];
464
465
466
467
468

    /**
     * Used to generate page-unique keys. Point is that uniqid() functions is very
     * slow, so a unikey key is made based on this, see function uniqueHash()
     * @var int
469
     * @internal
470
     */
471
    protected $uniqueCounter = 0;
472
473
474

    /**
     * @var string
475
     * @internal
476
     */
477
    protected $uniqueString = '';
478
479
480
481
482

    /**
     * This value will be used as the title for the page in the indexer (if
     * indexing happens)
     * @var string
483
     * @internal only used by TYPO3 Core, use PageTitle API instead.
484
485
486
487
488
489
490
491
492
493
494
495
     */
    public $indexedDocTitle = '';

    /**
     * The base URL set for the page header.
     * @var string
     */
    public $baseUrl = '';

    /**
     * Page content render object
     *
496
     * @var ContentObjectRenderer
497
     */
498
    public $cObj;
499
500

    /**
501
     * All page content is accumulated in this variable. See RequestHandler
502
503
504
505
506
507
     * @var string
     */
    public $content = '';

    /**
     * Output charset of the websites content. This is the charset found in the
508
509
     * header, meta tag etc. If different than utf-8 a conversion
     * happens before output to browser. Defaults to utf-8.
510
511
512
513
514
     * @var string
     */
    public $metaCharset = 'utf-8';

    /**
515
     * Internal calculations for labels
516
     *
517
     * @var LanguageService
518
     */
519
    protected $languageService;
520
521
522
523
524
525
526
527
528

    /**
     * @var LockingStrategyInterface[][]
     */
    protected $locks = [];

    /**
     * @var PageRenderer
     */
529
    protected $pageRenderer;
530
531
532
533
534

    /**
     * The page cache object, use this to save pages to the cache and to
     * retrieve them again
     *
535
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
536
537
538
539
540
541
     */
    protected $pageCache;

    /**
     * @var array
     */
542
    protected $pageCacheTags = [];
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571

    /**
     * Content type HTTP header being sent in the request.
     * @todo Ticket: #63642 Should be refactored to a request/response model later
     * @internal Should only be used by TYPO3 core for now
     *
     * @var string
     */
    protected $contentType = 'text/html';

    /**
     * Doctype to use
     *
     * @var string
     */
    public $xhtmlDoctype = '';

    /**
     * @var int
     */
    public $xhtmlVersion;

    /**
     * Originally requested id from the initial $_GET variable
     *
     * @var int
     */
    protected $requestedId;

572
573
574
575
576
577
578
579
    /**
     * The context for keeping the current state, mostly related to current page information,
     * backend user / frontend user access, workspaceId
     *
     * @var Context
     */
    protected $context;

580
    /**
581
582
583
584
585
586
     * Since TYPO3 v10.0, TSFE is composed out of
     *  - Context
     *  - Site
     *  - SiteLanguage
     *  - PageArguments (containing ID, Type, cHash and MP arguments)
     *
587
     * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
588
     *
589
590
591
592
593
     * @param Context $context the Context object to work with
     * @param SiteInterface $site The resolved site to work with
     * @param SiteLanguage $siteLanguage The resolved language to work with
     * @param PageArguments $pageArguments The PageArguments object containing Page ID, type and GET parameters
     * @param FrontendUserAuthentication $frontendUser a FrontendUserAuthentication object
594
     */
595
    public function __construct(Context $context, SiteInterface $site, SiteLanguage $siteLanguage, PageArguments $pageArguments, FrontendUserAuthentication $frontendUser)
596
    {
597
598
599
        $this->initializeContext($context);
        $this->site = $site;
        $this->language = $siteLanguage;
600
        $this->setPageArguments($pageArguments);
601
        $this->fe_user = $frontendUser;
602
603
604
        $this->uniqueString = md5(microtime());
        $this->initPageRenderer();
        $this->initCaches();
605
        // Initialize LLL behaviour
606
        $this->setOutputLanguage();
607
608
    }

609
    private function initializeContext(Context $context): void
610
    {
611
        $this->context = $context;
612
613
614
        if (!$this->context->hasAspect('frontend.preview')) {
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
        }
615
616
    }

617
618
619
620
621
622
623
624
625
626
    /**
     * Initializes the page renderer object
     */
    protected function initPageRenderer()
    {
        if ($this->pageRenderer !== null) {
            return;
        }
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
        $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
627
628
629
630
631
        // As initPageRenderer could be called in constructor and for USER_INTs, this information is only set
        // once - in order to not override any previous settings of PageRenderer.
        if ($this->language instanceof SiteLanguage) {
            $this->pageRenderer->setLanguage($this->language->getTypo3Language());
        }
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
    }

    /**
     * @param string $contentType
     * @internal Should only be used by TYPO3 core for now
     */
    public function setContentType($contentType)
    {
        $this->contentType = $contentType;
    }

    /********************************************
     *
     * Initializing, resolving page id
     *
     ********************************************/
    /**
     * Initializes the caching system.
     */
    protected function initCaches()
    {
653
        $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pages');
654
655
656
657
    }

    /**
     * Initializes the front-end user groups.
658
     * Sets frontend.user aspect based on front-end user status.
659
660
661
     */
    public function initUserGroups()
    {
662
663
        $userAspect = $this->fe_user->createUserAspect((bool)$this->loginAllowedInBranch);
        $this->context->setAspect('frontend.user', $userAspect);
664
665
666
667
668
669
670
671
672
    }

    /**
     * Checking if a user is logged in or a group constellation different from "0,-1"
     *
     * @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!)
     */
    public function isUserOrGroupSet()
    {
673
674
675
        /** @var UserAspect $userAspect */
        $userAspect = $this->context->getAspect('frontend.user');
        return $userAspect->isUserOrGroupSet();
676
677
678
679
680
681
682
683
684
    }

    /**
     * Clears the preview-flags, sets sim_exec_time to current time.
     * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
     * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
     */
    public function clear_preview()
    {
685
        if ($this->isInPreviewMode()) {
686
687
            $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
            $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
688
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
689
690
691
            $this->context->setAspect('date', GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $GLOBALS['SIM_EXEC_TIME'])));
            $this->context->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
        }
692
693
694
695
696
697
698
699
700
    }

    /**
     * Checks if a backend user is logged in
     *
     * @return bool whether a backend user is logged in
     */
    public function isBackendUserLoggedIn()
    {
701
        return (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
702
703
704
705
706
707
708
    }

    /**
     * Determines the id and evaluates any preview settings
     * Basically this function is about determining whether a backend user is logged in,
     * if he has read access to the page and if he's previewing the page.
     * That all determines which id to show and how to initialize the id.
709
710
     *
     * @param ServerRequestInterface|null $request
711
     */
712
    public function determineId(ServerRequestInterface $request = null)
713
    {
714
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
715
        // Call pre processing function for id determination
716
717
718
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
            $parameters = ['parentObject' => $this];
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
719
        }
720
721
722
        // If there is a Backend login we are going to check for any preview settings
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
        // If the front-end is showing a preview, caching MUST be disabled.
723
        $isPreview = $this->isInPreviewMode();
724
        if ($isPreview) {
725
            $this->disableCache();
726
727
        }
        // Now, get the id, validate access etc:
728
        $this->fetch_the_id($request);
729
        // Check if backend user has read access to this page. If not, recalculate the id.
730
        if ($this->isBackendUserLoggedIn() && $isPreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
731
            $this->unsetBackendUser();
732
733
            // Resetting
            $this->clear_preview();
734
            $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
735
            // Fetching the id again, now with the preview settings reset.
736
            $this->fetch_the_id($request);
737
738
739
        }
        // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
        $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
740
741
        // Logins are not allowed, but there is a login, so will we run this.
        if (!$this->loginAllowedInBranch && $this->isUserOrGroupSet()) {
742
743
            // Clear out user, and the group will be re-set in >initUserGroups() due to
            // $this->loginAllowedInBranch = false
744
745
            if ($this->loginAllowedInBranch_mode === 'all') {
                $this->fe_user->hideActiveLogin();
746
            }
747
            // Fetching the id again, now with the preview settings reset and respecting $this->loginAllowedInBranch = false
748
            $this->fetch_the_id($request);
749
750
751
752
753
754
        }
        // Final cleaning.
        // Make sure it's an integer
        $this->id = ($this->contentPid = (int)$this->id);
        // Make sure it's an integer
        $this->type = (int)$this->type;
755
756
        // Setting language and fetch translated page
        $this->settingLanguage($request);
757
        // Call post processing function for id determination:
758
759
760
        $_params = ['pObj' => &$this];
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
761
762
763
        }
    }

764
765
766
767
768
769
770
771
    protected function unsetBackendUser(): void
    {
        // Register an empty backend user as aspect
        unset($GLOBALS['BE_USER']);
        $this->context->setAspect('backend.user', GeneralUtility::makeInstance(UserAspect::class));
        $this->context->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class));
    }

772
773
774
    /**
     * Evaluates admin panel or workspace settings to see if
     * visibility settings like
775
     * - Preview Aspect: isPreview
776
     * - Visibility Aspect: includeHiddenPages
777
     * - Visibility Aspect: includeHiddenContent
778
779
780
781
782
     * - $simUserGroup
     * should be applied to the current object.
     *
     * @param FrontendBackendUserAuthentication $backendUser
     * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
783
     * @internal
784
785
786
787
788
789
     */
    protected function applyPreviewSettings($backendUser = null)
    {
        if (!$backendUser) {
            return null;
        }
790
        $originalFrontendUserGroup = null;
791
        if ($this->fe_user->user) {
792
            $originalFrontendUserGroup = $this->context->getPropertyFromAspect('frontend.user', 'groupIds');
793
        }
794

795
796
        // The preview flag is set if the current page turns out to be hidden
        if ($this->id && $this->determineIdIsHiddenPage()) {
797
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
798
799
800
801
            /** @var VisibilityAspect $aspect */
            $aspect = $this->context->getAspect('visibility');
            $newAspect = GeneralUtility::makeInstance(VisibilityAspect::class, true, $aspect->includeHiddenContent(), $aspect->includeDeletedRecords());
            $this->context->setAspect('visibility', $newAspect);
802
803
804
        }
        // The preview flag will be set if an offline workspace will be previewed
        if ($this->whichWorkspace() > 0) {
805
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
806
        }
807
        return $this->context->getPropertyFromAspect('frontend.preview', 'preview', false) ? $originalFrontendUserGroup : null;
808
809
    }

810
811
812
813
814
815
816
817
    /**
     * Checks if the page is hidden in the active workspace.
     * If it is hidden, preview flags will be set.
     *
     * @return bool
     */
    protected function determineIdIsHiddenPage()
    {
818
819
820
821
822
823
824
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('pages');
        $queryBuilder
            ->getRestrictions()
            ->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));

825
        $queryBuilder
826
827
828
            ->select('uid', 'hidden', 'starttime', 'endtime')
            ->from('pages')
            ->where(
829
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
830
            )
831
832
833
            ->setMaxResults(1);

        // $this->id always points to the ID of the default language page, so we check
834
        // the current site language to determine if we need to fetch a translation but consider fallbacks
835
        if ($this->language->getLanguageId() > 0) {
836
837
838
            $languagesToCheck = array_merge([$this->language->getLanguageId()], $this->language->getFallbackLanguageIds());
            // Check for the language and all its fallbacks
            $constraint = $queryBuilder->expr()->andX(
839
                $queryBuilder->expr()->eq('l10n_parent', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
840
                $queryBuilder->expr()->in('sys_language_uid', $queryBuilder->createNamedParameter(array_filter($languagesToCheck), Connection::PARAM_INT_ARRAY))
841
            );
842
843
844
845
846
847
848
849
850
851
852
853
854
            // If the fallback language Ids also contains the default language, this needs to be considered
            if (in_array(0, $languagesToCheck, true)) {
                $constraint = $queryBuilder->expr()->orX(
                    $constraint,
                    // Ensure to also fetch the default record
                    $queryBuilder->expr()->andX(
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
                        $queryBuilder->expr()->in('sys_language_uid', 0)
                    )
                );
            }
            // Ensure that the translated records are shown first (maxResults is set to 1)
            $queryBuilder->orderBy('sys_language_uid', 'DESC');
855
        } else {
856
            $constraint = $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT));
857
        }
858
        $queryBuilder->andWhere($constraint);
859
860

        $page = $queryBuilder->execute()->fetch();
861

862
        if ($this->whichWorkspace() > 0) {
863
            // Fetch overlay of page if in workspace and check if it is hidden
864
865
866
867
            $customContext = clone $this->context;
            $customContext->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class, $this->whichWorkspace()));
            $customContext->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
            $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class, $customContext);
868
            $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
869
870
            // Also checks if the workspace version is NOT hidden but the live version is in fact still hidden
            $result = $targetPage === -1 || $targetPage === -2 || (is_array($targetPage) && $targetPage['hidden'] == 0 && $page['hidden'] == 1);
871
872
873
874
875
876
877
        } else {
            $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
        }
        return $result;
    }

    /**
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
     * Resolves the page id and sets up several related properties.
     *
     * If $this->id is not set at all or is not a plain integer, the method
     * does it's best to set the value to an integer. Resolving is based on
     * this options:
     *
     * - Splitting $this->id if it contains an additional type parameter.
     * - Finding the domain record start page
     * - First visible page
     * - Relocating the id below the domain record if outside
     *
     * The following properties may be set up or updated:
     *
     * - id
     * - requestedId
     * - type
     * - sys_page
     * - sys_page->where_groupAccess
     * - sys_page->where_hid_del
897
     * - Context: FrontendUser Aspect
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
     * - no_cache
     * - register['SYS_LASTCHANGED']
     * - pageNotFound
     *
     * Via getPageAndRootlineWithDomain()
     *
     * - rootLine
     * - page
     * - MP
     * - originalShortcutPage
     * - originalMountPointPage
     * - pageAccessFailureHistory['direct_access']
     * - pageNotFound
     *
     * @todo:
     *
     * On the first impression the method does to much. This is increased by
     * the fact, that is is called repeated times by the method determineId.
     * The reasons are manifold.
     *
918
     * 1.) The first part, the creation of sys_page and the type
919
920
921
922
923
924
925
926
927
928
929
930
931
     * resolution don't need to be repeated. They could be separated to be
     * called only once.
     *
     * 2.) The user group setup could be done once on a higher level.
     *
     * 3.) The workflow of the resolution could be elaborated to be less
     * tangled. Maybe the check of the page id to be below the domain via the
     * root line doesn't need to be done each time, but for the final result
     * only.
     *
     * 4.) The root line does not need to be directly addressed by this class.
     * A root line is always related to one page. The rootline could be handled
     * indirectly by page objects. Page objects still don't exist.
932
     *
933
     * @internal
934
     * @param ServerRequestInterface|null $request
935
     */
936
    public function fetch_the_id(ServerRequestInterface $request = null)
937
    {
938
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
939
        $timeTracker = $this->getTimeTracker();
940
        $timeTracker->push('fetch_the_id initialize/');
941
942
        // Set the valid usergroups for FE
        $this->initUserGroups();
943
944
945
        // Initialize the PageRepository has to be done after the frontend usergroups are initialized / resolved, as
        // frontend group aspect is modified before
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
946
947
948
949
950
        // The id and type is set to the integer-value - just to be sure...
        $this->id = (int)$this->id;
        $this->type = (int)$this->type;
        $timeTracker->pull();
        // We find the first page belonging to the current domain
951
        $timeTracker->push('fetch_the_id domain/');
952
        if (!$this->id) {
953
954
            // If the id was not previously set, set it to the root page id of the site.
            $this->id = $this->site->getRootPageId();
955
956
        }
        $timeTracker->pull();
957
        $timeTracker->push('fetch_the_id rootLine/');
958
959
        // We store the originally requested id
        $this->requestedId = $this->id;
960
        try {
961
            $this->getPageAndRootlineWithDomain($this->site->getRootPageId(), $request);
962
963
964
        } catch (ShortcutTargetPageNotFoundException $e) {
            $this->pageNotFound = 1;
        }
965
        $timeTracker->pull();
966
        if ($this->pageNotFound) {
967
968
969
            switch ($this->pageNotFound) {
                case 1:
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
970
                        $request,
971
972
973
974
975
976
                        'ID was not an accessible page',
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_PAGE_NOT_RESOLVED)
                    );
                    break;
                case 2:
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
977
                        $request,
978
979
980
981
982
983
                        'Subsection was found and not accessible',
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_SUBSECTION_NOT_RESOLVED)
                    );
                    break;
                case 3:
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
984
                        $request,
985
986
987
988
989
990
                        'ID was outside the domain',
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_HOST_PAGE_MISMATCH)
                    );
                    break;
                default:
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
991
                        $request,
992
993
994
                        'Unspecified error',
                        $this->getPageAccessFailureReasons()
                    );
995
            }
996
            throw new ImmediateResponseException($response, 1533931329);
997
        }
998
999
1000

        $this->setRegisterValueForSysLastChanged($this->page);