/
TypoScriptFrontendController.php
3678 lines (3429 loc) · 157 KB
/
TypoScriptFrontendController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the TYPO3 CMS project.
*
* 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.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
namespace TYPO3\CMS\Frontend\Controller;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LogLevel;
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
use TYPO3\CMS\Core\Cache\CacheManager;
use TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
use TYPO3\CMS\Core\Charset\CharsetConverter;
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\DateTimeAspect;
use TYPO3\CMS\Core\Context\LanguageAspect;
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
use TYPO3\CMS\Core\Context\UserAspect;
use TYPO3\CMS\Core\Context\VisibilityAspect;
use TYPO3\CMS\Core\Context\WorkspaceAspect;
use TYPO3\CMS\Core\Core\Environment;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
use TYPO3\CMS\Core\Error\Http\AbstractServerErrorException;
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
use TYPO3\CMS\Core\Exception\Page\RootLineException;
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
use TYPO3\CMS\Core\Http\ApplicationType;
use TYPO3\CMS\Core\Http\ImmediateResponseException;
use TYPO3\CMS\Core\Http\NormalizedParams;
use TYPO3\CMS\Core\Http\PropagateResponseException;
use TYPO3\CMS\Core\Http\ServerRequestFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Localization\LanguageServiceFactory;
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
use TYPO3\CMS\Core\Locking\LockFactory;
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
use TYPO3\CMS\Core\Page\AssetCollector;
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\PageTitle\PageTitleProviderManager;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Routing\PageArguments;
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
use TYPO3\CMS\Core\Type\Bitmask\Permission;
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
use TYPO3\CMS\Core\TypoScript\TemplateService;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\HttpUtility;
use TYPO3\CMS\Core\Utility\MathUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Core\Utility\RootlineUtility;
use TYPO3\CMS\Frontend\Aspect\PreviewAspect;
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons;
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
/**
* Class for the built TypoScript based frontend. Instantiated in
* \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
*
* Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
* as the global object TSFE.
*
* This class has a lot of functions and internal variable which are used from
* \TYPO3\CMS\Frontend\Http\RequestHandler
*
* The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
*
* The use of this class should be inspired by the order of function calls as
* found in \TYPO3\CMS\Frontend\Http\RequestHandler.
*/
class TypoScriptFrontendController implements LoggerAwareInterface
{
use LoggerAwareTrait;
use PublicPropertyDeprecationTrait;
/**
* List previously publicly accessible variables
*/
private array $deprecatedPublicProperties = [
'ATagParams' => 'Using ATagParams will not be possible anymore in TYPO3 v12.0. Use TSFE->config[config][ATagParams] instead.',
];
/**
* The page id (int)
* @var string|int
*/
public $id = '';
/**
* The type (read-only)
* @var int|string
*/
public $type = '';
/**
* @var SiteInterface
*/
protected $site;
/**
* @var SiteLanguage
*/
protected $language;
/**
* @var PageArguments
* @internal
*/
protected $pageArguments;
/**
* 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
*/
public $rootLine = [];
/**
* The pagerecord
* @var array
*/
public $page = [];
/**
* 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.
*
* @var array|null
*/
protected $originalMountPointPage;
/**
* 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
* @var array|null
* @see checkTranslatedShortcut()
*/
protected $originalShortcutPage;
/**
* sys_page-object, pagefunctions
*
* @var PageRepository|string
*/
public $sys_page = '';
/**
* Is set to 1 if a pageNotFound handler could have been called.
* @var int
* @internal
*/
public $pageNotFound = 0;
/**
* Array containing a history of why a requested page was not accessible.
* @var array
*/
protected $pageAccessFailureHistory = [];
/**
* @var string
* @internal
*/
public $MP = '';
/**
* The frontend user
*
* @var FrontendUserAuthentication
*/
public $fe_user;
/**
* Shows whether logins are allowed in branch
* @var bool
*/
protected $loginAllowedInBranch = true;
/**
* Shows specific mode (all or groups)
* @var string
* @internal
*/
protected $loginAllowedInBranch_mode = '';
/**
* Value that contains the simulated usergroup if any
* @var int
* @internal only to be used in AdminPanel, and within TYPO3 Core
*/
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
*/
public $config = [];
/**
* The TypoScript template object. Used to parse the TypoScript template
*
* @var TemplateService
*/
public $tmpl;
/**
* Is set to the time-to-live time of cached pages. Default is 60*60*24, which is 24 hours.
*
* @var int
* @internal
*/
protected $cacheTimeOutDefault = 86400;
/**
* Set internally if cached content is fetched from the database.
*
* @var bool
* @internal
*/
protected $cacheContentFlag = false;
/**
* Set to the expire time of cached content
* @var int
* @internal
*/
protected $cacheExpires = 0;
/**
* Set if cache headers allowing caching are sent.
* @var bool
* @internal
*/
protected $isClientCachable = false;
/**
* 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
* @internal
*/
public $all = [];
/**
* Toplevel - objArrayName, eg 'page'
* @var string
* @internal should only be used by TYPO3 Core
*/
public $sPre = '';
/**
* TypoScript configuration of the page-object pointed to by sPre.
* $this->tmpl->setup[$this->sPre.'.']
* @var array|string
* @internal should only be used by TYPO3 Core
*/
public $pSetup = '';
/**
* This hash is unique to the template, the $this->id and $this->type vars and
* the list of groups. Used to get and later store the cached data
* @var string
* @internal
*/
public $newHash = '';
/**
* 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
* clear the no_cache flag.
* @var bool
* @internal
*/
protected $no_cacheBeforePageGen = false;
/**
* May be set to the pagesTSconfig
* @var array|string
* @internal
*/
protected $pagesTSconfig = '';
/**
* 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
*/
public $additionalHeaderData = [];
/**
* Used to accumulate additional HTML-code for the footer-section of the template
* @var array
*/
public $additionalFooterData = [];
/**
* Default internal target
* @var string
*/
public $intTarget = '';
/**
* Default external target
* @var string
*/
public $extTarget = '';
/**
* Default file link target
* @var string
*/
public $fileTarget = '';
/**
* If set, typolink() function encrypts email addresses.
* @var string|int
*/
public $spamProtectEmailAddresses = 0;
/**
* Absolute Reference prefix
* @var string
*/
public $absRefPrefix = '';
/**
* <A>-tag parameters
* @var string
* @deprecated will be removed in TYPO3 v12.0. Use TSFE->config[config][ATagParams] directly.
*/
protected $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
* @internal
*/
public $sWordRegEx = '';
/**
* Is set to the incoming array sword_list in case of a page-view jumped to from
* a search-result.
* @var string
* @internal
*/
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
* @deprecated since v11, will be removed with v12. Drop together with editPanel removal.
*/
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
* @deprecated since v11, will be removed with v12. Drop together with editIcons removal.
*/
public $displayFieldEditIcons = '';
/**
* 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
* extensions.
* @var array
*/
public $applicationData = [];
/**
* @var array
*/
public $register = [];
/**
* Stack used for storing array and retrieving register arrays (see
* LOAD_REGISTER and RESTORE_REGISTER)
* @var array
*/
public $registerStack = [];
/**
* Checking that the function is not called eternally. This is done by
* interrupting at a depth of 50
* @var int
* @deprecated since v11, will be removed in v12.
*/
public $cObjectDepthCounter = 50;
/**
* Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
* rendered twice through it!
* @var array
*/
public $recordRegister = [];
/**
* 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
*/
public $accessKey = [];
/**
* 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
* @internal
*/
protected $uniqueCounter = 0;
/**
* @var string
* @internal
*/
protected $uniqueString = '';
/**
* This value will be used as the title for the page in the indexer (if
* indexing happens)
* @var string
* @internal only used by TYPO3 Core, use PageTitle API instead.
*/
public $indexedDocTitle = '';
/**
* The base URL set for the page header.
* @var string
*/
public $baseUrl = '';
/**
* Page content render object
*
* @var ContentObjectRenderer
*/
public $cObj;
/**
* All page content is accumulated in this variable. See RequestHandler
* @var string
*/
public $content = '';
/**
* Info-array of the last resulting image resource of content object
* IMG_RESOURCE (if any), containing width, height and so on.
*/
public ?array $lastImgResourceInfo = null;
/**
* Output charset of the websites content. This is the charset found in the
* header, meta tag etc. If different than utf-8 a conversion
* happens before output to browser. Defaults to utf-8.
* @var string
*/
public $metaCharset = 'utf-8';
/**
* Internal calculations for labels
*
* @var LanguageService
*/
protected $languageService;
/**
* @var LockingStrategyInterface[][]
*/
protected $locks = [];
/**
* @var PageRenderer
*/
protected $pageRenderer;
/**
* The page cache object, use this to save pages to the cache and to
* retrieve them again
*
* @var FrontendInterface
*/
protected $pageCache;
/**
* @var array
*/
protected $pageCacheTags = [];
/**
* 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;
/**
* The context for keeping the current state, mostly related to current page information,
* backend user / frontend user access, workspaceId
*
* @var Context
*/
protected $context;
/**
* If debug mode is enabled, this contains the information if a page is fetched from cache,
* and sent as HTTP Response Header.
*/
protected string $debugInformationHeader = '';
/**
* Since TYPO3 v10.0, TSFE is composed out of
* - Context
* - Site
* - SiteLanguage
* - PageArguments (containing ID, Type, cHash and MP arguments)
*
* Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
*
* @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
*/
public function __construct(Context $context, SiteInterface $site, SiteLanguage $siteLanguage, PageArguments $pageArguments, FrontendUserAuthentication $frontendUser)
{
$this->initializeContext($context);
$this->site = $site;
$this->language = $siteLanguage;
$this->setPageArguments($pageArguments);
$this->fe_user = $frontendUser;
$this->uniqueString = md5(microtime());
$this->initPageRenderer();
$this->initCaches();
// Initialize LLL behaviour
$this->setOutputLanguage();
}
private function initializeContext(Context $context): void
{
$this->context = $context;
if (!$this->context->hasAspect('frontend.preview')) {
$this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
}
}
/**
* 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');
// 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());
}
}
/**
* @param string $contentType
* @internal Must only be used by TYPO3 core
*/
public function setContentType($contentType)
{
$this->contentType = $contentType;
}
/********************************************
*
* Initializing, resolving page id
*
********************************************/
/**
* Initializes the caching system.
*/
protected function initCaches()
{
$this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pages');
}
/**
* Initializes the front-end user groups.
* Sets frontend.user aspect based on front-end user status.
*/
public function initUserGroups()
{
$userAspect = $this->fe_user->createUserAspect((bool)$this->loginAllowedInBranch);
$this->context->setAspect('frontend.user', $userAspect);
}
/**
* 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()
{
/** @var UserAspect $userAspect */
$userAspect = $this->context->getAspect('frontend.user');
return $userAspect->isUserOrGroupSet();
}
/**
* 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()
{
if ($this->isInPreviewMode()) {
$GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
$GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
$this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
$this->context->setAspect('date', GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $GLOBALS['SIM_EXEC_TIME'])));
$this->context->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
}
}
/**
* Checks if a backend user is logged in
*
* @return bool whether a backend user is logged in
*/
public function isBackendUserLoggedIn()
{
return (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
}
/**
* 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.
*
* @param ServerRequestInterface|null $request
*/
public function determineId(ServerRequestInterface $request = null)
{
$request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
// Call pre processing function for id determination
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
$parameters = ['parentObject' => $this];
GeneralUtility::callUserFunction($functionReference, $parameters, $this);
}
// 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.
$isPreview = $this->isInPreviewMode();
if ($isPreview) {
$this->disableCache();
}
// Now, get the id, validate access etc:
$this->fetch_the_id($request);
// Check if backend user has read access to this page. If not, recalculate the id.
if ($this->isBackendUserLoggedIn() && $isPreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
$this->unsetBackendUser();
// Resetting
$this->clear_preview();
$this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
// Fetching the id again, now with the preview settings reset.
$this->fetch_the_id($request);
}
// 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();
// Logins are not allowed, but there is a login, so will we run this.
if (!$this->loginAllowedInBranch && $this->isUserOrGroupSet()) {
// Clear out user, and the group will be re-set in >initUserGroups() due to
// $this->loginAllowedInBranch = false
if ($this->loginAllowedInBranch_mode === 'all') {
$this->fe_user->hideActiveLogin();
}
// Fetching the id again, now with the preview settings reset and respecting $this->loginAllowedInBranch = false
$this->fetch_the_id($request);
}
// 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;
// Setting language and fetch translated page
$this->settingLanguage($request);
// Call post processing function for id determination:
$_params = ['pObj' => &$this];
foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
GeneralUtility::callUserFunction($_funcRef, $_params, $this);
}
}
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));
}
/**
* Evaluates admin panel or workspace settings to see if
* visibility settings like
* - Preview Aspect: isPreview
* - Visibility Aspect: includeHiddenPages
* - Visibility Aspect: includeHiddenContent
* - $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
* @internal
*/
protected function applyPreviewSettings($backendUser = null)
{
if (!$backendUser) {
return null;
}
$originalFrontendUserGroup = null;
if ($this->fe_user->user) {
$originalFrontendUserGroup = $this->context->getPropertyFromAspect('frontend.user', 'groupIds');
}
// The preview flag is set if the current page turns out to be hidden
if ($this->id && $this->determineIdIsHiddenPage()) {
$this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
/** @var VisibilityAspect $aspect */
$aspect = $this->context->getAspect('visibility');
$newAspect = GeneralUtility::makeInstance(VisibilityAspect::class, true, $aspect->includeHiddenContent(), $aspect->includeDeletedRecords());
$this->context->setAspect('visibility', $newAspect);
}
// The preview flag will be set if an offline workspace will be previewed
if ($this->whichWorkspace() > 0) {
$this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
}
return $this->context->getPropertyFromAspect('frontend.preview', 'preview', false) ? $originalFrontendUserGroup : null;
}
/**
* Checks if the page is hidden in the active workspace.
* If it is hidden, preview flags will be set.
*
* @return bool
*/
protected function determineIdIsHiddenPage()
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('pages');
$queryBuilder
->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$queryBuilder
->select('uid', 'hidden', 'starttime', 'endtime')
->from('pages')
->where(
$queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, Connection::PARAM_INT))
)
->setMaxResults(1);
// $this->id always points to the ID of the default language page, so we check
// the current site language to determine if we need to fetch a translation but consider fallbacks
if ($this->language->getLanguageId() > 0) {
$languagesToCheck = array_merge([$this->language->getLanguageId()], $this->language->getFallbackLanguageIds());
// Check for the language and all its fallbacks
$constraint = $queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('l10n_parent', $queryBuilder->createNamedParameter($this->id, Connection::PARAM_INT)),
$queryBuilder->expr()->in('sys_language_uid', $queryBuilder->createNamedParameter(array_filter($languagesToCheck), Connection::PARAM_INT_ARRAY))
);
// 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, Connection::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');
} else {
$constraint = $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, Connection::PARAM_INT));
}
$queryBuilder->andWhere($constraint);
$page = $queryBuilder->executeQuery()->fetchAssociative();
if ($this->whichWorkspace() > 0) {
// Fetch overlay of page if in workspace and check if it is hidden
$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);
$targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
// 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);
} else {
$result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
}
return $result;
}
/**
* 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
* - Context: FrontendUser Aspect
* - 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.
*
* 1.) The first part, the creation of sys_page and the type
* 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.
*
* @internal
* @param ServerRequestInterface|null $request
*/
protected function fetch_the_id(ServerRequestInterface $request = null)
{
$request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
$timeTracker = $this->getTimeTracker();
$timeTracker->push('fetch_the_id initialize/');
// Set the valid usergroups for FE
$this->initUserGroups();
// 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);
// 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
$timeTracker->push('fetch_the_id domain/');
if (!$this->id) {
// If the id was not previously set, set it to the root page id of the site.
$this->id = $this->site->getRootPageId();
}
$timeTracker->pull();
$timeTracker->push('fetch_the_id rootLine/');
// We store the originally requested id
$this->requestedId = $this->id;
try {
$this->getPageAndRootlineWithDomain($this->site->getRootPageId(), $request);
} catch (ShortcutTargetPageNotFoundException $e) {
$this->pageNotFound = 1;
}
$timeTracker->pull();
if ($this->pageNotFound) {
switch ($this->pageNotFound) {
case 1:
$response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
$request,