[BUGFIX] Trigger 404 for subpage shortcuts w/o subpages
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Controller / TypoScriptFrontendController.php
1 <?php
2 namespace TYPO3\CMS\Frontend\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Doctrine\DBAL\Exception\ConnectionException;
18 use Psr\Http\Message\ResponseInterface;
19 use Psr\Log\LoggerAwareInterface;
20 use Psr\Log\LoggerAwareTrait;
21 use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
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\Controller\ErrorPageController;
27 use TYPO3\CMS\Core\Database\ConnectionPool;
28 use TYPO3\CMS\Core\Database\Query\QueryHelper;
29 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
30 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
31 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
32 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
33 use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
34 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
35 use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
36 use TYPO3\CMS\Core\Localization\LanguageService;
37 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
38 use TYPO3\CMS\Core\Locking\LockFactory;
39 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
40 use TYPO3\CMS\Core\Log\LogManager;
41 use TYPO3\CMS\Core\Page\PageRenderer;
42 use TYPO3\CMS\Core\Resource\StorageRepository;
43 use TYPO3\CMS\Core\Service\DependencyOrderingService;
44 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
45 use TYPO3\CMS\Core\Type\Bitmask\Permission;
46 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
47 use TYPO3\CMS\Core\TypoScript\TemplateService;
48 use TYPO3\CMS\Core\Utility\ArrayUtility;
49 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
50 use TYPO3\CMS\Core\Utility\GeneralUtility;
51 use TYPO3\CMS\Core\Utility\HttpUtility;
52 use TYPO3\CMS\Core\Utility\MathUtility;
53 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
54 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
55 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
56 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
57 use TYPO3\CMS\Frontend\Page\PageGenerator;
58 use TYPO3\CMS\Frontend\Page\PageRepository;
59 use TYPO3\CMS\Frontend\View\AdminPanelView;
60
61 /**
62 * Class for the built TypoScript based frontend. Instantiated in
63 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
64 *
65 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
66 * as the global object TSFE.
67 *
68 * This class has a lot of functions and internal variable which are used from
69 * \TYPO3\CMS\Frontend\Http\RequestHandler
70 *
71 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
72 *
73 * The use of this class should be inspired by the order of function calls as
74 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
75 */
76 class TypoScriptFrontendController implements LoggerAwareInterface
77 {
78 use LoggerAwareTrait;
79
80 /**
81 * The page id (int)
82 * @var string
83 */
84 public $id = '';
85
86 /**
87 * The type (read-only)
88 * @var int
89 */
90 public $type = '';
91
92 /**
93 * The submitted cHash
94 * @var string
95 */
96 public $cHash = '';
97
98 /**
99 * Page will not be cached. Write only TRUE. Never clear value (some other
100 * code might have reasons to set it TRUE).
101 * @var bool
102 */
103 public $no_cache = false;
104
105 /**
106 * The rootLine (all the way to tree root, not only the current site!)
107 * @var array
108 */
109 public $rootLine = '';
110
111 /**
112 * The pagerecord
113 * @var array
114 */
115 public $page = '';
116
117 /**
118 * This will normally point to the same value as id, but can be changed to
119 * point to another page from which content will then be displayed instead.
120 * @var int
121 */
122 public $contentPid = 0;
123
124 /**
125 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
126 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
127 * should be redirected to.
128 *
129 * @var array|null
130 */
131 protected $originalMountPointPage = null;
132
133 /**
134 * Gets set when we are processing a page of type shortcut in the early stages
135 * of the request when we do not know about languages yet, used later in the request
136 * to determine the correct shortcut in case a translation changes the shortcut
137 * target
138 * @var array|null
139 * @see checkTranslatedShortcut()
140 */
141 protected $originalShortcutPage = null;
142
143 /**
144 * sys_page-object, pagefunctions
145 *
146 * @var PageRepository
147 */
148 public $sys_page = '';
149
150 /**
151 * Contains all URL handler instances that are active for the current request.
152 *
153 * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
154 *
155 * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
156 * @see initializeRedirectUrlHandlers()
157 */
158 protected $activeUrlHandlers = [];
159
160 /**
161 * Is set to 1 if a pageNotFound handler could have been called.
162 * @var int
163 */
164 public $pageNotFound = 0;
165
166 /**
167 * Domain start page
168 * @var int
169 */
170 public $domainStartPage = 0;
171
172 /**
173 * Array containing a history of why a requested page was not accessible.
174 * @var array
175 */
176 public $pageAccessFailureHistory = [];
177
178 /**
179 * @var string
180 */
181 public $MP = '';
182
183 /**
184 * This can be set from applications as a way to tag cached versions of a page
185 * and later perform some external cache management, like clearing only a part
186 * of the cache of a page...
187 * @var int
188 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.
189 */
190 public $page_cache_reg1 = 0;
191
192 /**
193 * Contains the value of the current script path that activated the frontend.
194 * Typically "index.php" but by rewrite rules it could be something else! Used
195 * for Speaking Urls / Simulate Static Documents.
196 * @var string
197 */
198 public $siteScript = '';
199
200 /**
201 * The frontend user
202 *
203 * @var FrontendUserAuthentication
204 */
205 public $fe_user = '';
206
207 /**
208 * Global flag indicating that a frontend user is logged in. This is set only if
209 * a user really IS logged in. The group-list may show other groups (like added
210 * by IP filter or so) even though there is no user.
211 * @var bool
212 */
213 public $loginUser = false;
214
215 /**
216 * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
217 * group, but other groups may be added by other means than a user being logged
218 * in though...
219 * @var string
220 */
221 public $gr_list = '';
222
223 /**
224 * Flag that indicates if a backend user is logged in!
225 * @var bool
226 */
227 public $beUserLogin = false;
228
229 /**
230 * Integer, that indicates which workspace is being previewed.
231 * Not in use anymore, as this is part of the workspace preview functionality, use $TSFE->whichWorkspace() instead.
232 * @var int
233 */
234 public $workspacePreview = 0;
235
236 /**
237 * Shows whether logins are allowed in branch
238 * @var bool
239 */
240 public $loginAllowedInBranch = true;
241
242 /**
243 * Shows specific mode (all or groups)
244 * @var string
245 */
246 public $loginAllowedInBranch_mode = '';
247
248 /**
249 * Set to backend user ID to initialize when keyword-based preview is used
250 * @var int
251 */
252 public $ADMCMD_preview_BEUSER_uid = 0;
253
254 /**
255 * Flag indication that preview is active. This is based on the login of a
256 * backend user and whether the backend user has read access to the current
257 * page.
258 * @var int
259 */
260 public $fePreview = 0;
261
262 /**
263 * Flag indicating that hidden pages should be shown, selected and so on. This
264 * goes for almost all selection of pages!
265 * @var bool
266 */
267 public $showHiddenPage = false;
268
269 /**
270 * Flag indicating that hidden records should be shown. This includes
271 * sys_template and even fe_groups in addition to all
272 * other regular content. So in effect, this includes everything except pages.
273 * @var bool
274 */
275 public $showHiddenRecords = false;
276
277 /**
278 * Value that contains the simulated usergroup if any
279 * @var int
280 */
281 public $simUserGroup = 0;
282
283 /**
284 * "CONFIG" object from TypoScript. Array generated based on the TypoScript
285 * configuration of the current page. Saved with the cached pages.
286 * @var array
287 */
288 public $config = [];
289
290 /**
291 * The TypoScript template object. Used to parse the TypoScript template
292 *
293 * @var TemplateService
294 */
295 public $tmpl = null;
296
297 /**
298 * Is set to the time-to-live time of cached pages. If FALSE, default is
299 * 60*60*24, which is 24 hours.
300 * @var bool|int
301 */
302 public $cacheTimeOutDefault = false;
303
304 /**
305 * Set internally if cached content is fetched from the database
306 * @var bool
307 * @internal
308 */
309 public $cacheContentFlag = false;
310
311 /**
312 * Set to the expire time of cached content
313 * @var int
314 */
315 public $cacheExpires = 0;
316
317 /**
318 * Set if cache headers allowing caching are sent.
319 * @var bool
320 */
321 public $isClientCachable = false;
322
323 /**
324 * Used by template fetching system. This array is an identification of
325 * the template. If $this->all is empty it's because the template-data is not
326 * cached, which it must be.
327 * @var array
328 */
329 public $all = [];
330
331 /**
332 * Toplevel - objArrayName, eg 'page'
333 * @var string
334 */
335 public $sPre = '';
336
337 /**
338 * TypoScript configuration of the page-object pointed to by sPre.
339 * $this->tmpl->setup[$this->sPre.'.']
340 * @var array
341 */
342 public $pSetup = '';
343
344 /**
345 * This hash is unique to the template, the $this->id and $this->type vars and
346 * the gr_list (list of groups). Used to get and later store the cached data
347 * @var string
348 */
349 public $newHash = '';
350
351 /**
352 * If config.ftu (Frontend Track User) is set in TypoScript for the current
353 * page, the string value of this var is substituted in the rendered source-code
354 * with the string, '&ftu=[token...]' which enables GET-method usertracking as
355 * opposed to cookie based
356 * @var string
357 */
358 public $getMethodUrlIdToken = '';
359
360 /**
361 * This flag is set before inclusion of pagegen.php IF no_cache is set. If this
362 * flag is set after the inclusion of pagegen.php, no_cache is forced to be set.
363 * This is done in order to make sure that php-code from pagegen does not falsely
364 * clear the no_cache flag.
365 * @var bool
366 */
367 public $no_cacheBeforePageGen = false;
368
369 /**
370 * This flag indicates if temporary content went into the cache during
371 * page-generation.
372 * @var mixed
373 */
374 public $tempContent = false;
375
376 /**
377 * Passed to TypoScript template class and tells it to force template rendering
378 * @var bool
379 */
380 public $forceTemplateParsing = false;
381
382 /**
383 * The array which cHash_calc is based on, see ->makeCacheHash().
384 * @var array
385 */
386 public $cHash_array = [];
387
388 /**
389 * May be set to the pagesTSconfig
390 * @var array
391 */
392 public $pagesTSconfig = '';
393
394 /**
395 * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
396 * once. Use associative keys.
397 *
398 * Keys in use:
399 *
400 * used to accumulate additional HTML-code for the header-section,
401 * <head>...</head>. Insert either associative keys (like
402 * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
403 * (like additionalHeaderData[] = '...')
404 *
405 * @var array
406 */
407 public $additionalHeaderData = [];
408
409 /**
410 * Used to accumulate additional HTML-code for the footer-section of the template
411 * @var array
412 */
413 public $additionalFooterData = [];
414
415 /**
416 * Used to accumulate additional JavaScript-code. Works like
417 * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
418 *
419 * @var array
420 */
421 public $additionalJavaScript = [];
422
423 /**
424 * Used to accumulate additional Style code. Works like additionalHeaderData.
425 *
426 * @var array
427 */
428 public $additionalCSS = [];
429
430 /**
431 * @var string
432 */
433 public $JSCode;
434
435 /**
436 * @var string
437 */
438 public $inlineJS;
439
440 /**
441 * Used to accumulate DHTML-layers.
442 * @var string
443 */
444 public $divSection = '';
445
446 /**
447 * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
448 * @var bool
449 */
450 public $debug = false;
451
452 /**
453 * Default internal target
454 * @var string
455 */
456 public $intTarget = '';
457
458 /**
459 * Default external target
460 * @var string
461 */
462 public $extTarget = '';
463
464 /**
465 * Default file link target
466 * @var string
467 */
468 public $fileTarget = '';
469
470 /**
471 * Keys are page ids and values are default &MP (mount point) values to set
472 * when using the linking features...)
473 * @var array
474 */
475 public $MP_defaults = [];
476
477 /**
478 * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
479 * @var string|int
480 */
481 public $spamProtectEmailAddresses = 0;
482
483 /**
484 * Absolute Reference prefix
485 * @var string
486 */
487 public $absRefPrefix = '';
488
489 /**
490 * <A>-tag parameters
491 * @var string
492 */
493 public $ATagParams = '';
494
495 /**
496 * Search word regex, calculated if there has been search-words send. This is
497 * used to mark up the found search words on a page when jumped to from a link
498 * in a search-result.
499 * @var string
500 */
501 public $sWordRegEx = '';
502
503 /**
504 * Is set to the incoming array sword_list in case of a page-view jumped to from
505 * a search-result.
506 * @var string
507 */
508 public $sWordList = '';
509
510 /**
511 * A string prepared for insertion in all links on the page as url-parameters.
512 * Based on configuration in TypoScript where you defined which GET_VARS you
513 * would like to pass on.
514 * @var string
515 */
516 public $linkVars = '';
517
518 /**
519 * If set, edit icons are rendered aside content records. Must be set only if
520 * the ->beUserLogin flag is set and set_no_cache() must be called as well.
521 * @var string
522 */
523 public $displayEditIcons = '';
524
525 /**
526 * If set, edit icons are rendered aside individual fields of content. Must be
527 * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
528 * well.
529 * @var string
530 */
531 public $displayFieldEditIcons = '';
532
533 /**
534 * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
535 * record. Should reflect which language menus, templates etc is displayed in
536 * (master language) - but not necessarily the content which could be falling
537 * back to default (see sys_language_content)
538 * @var int
539 */
540 public $sys_language_uid = 0;
541
542 /**
543 * Site language mode for content fall back.
544 * @var string
545 */
546 public $sys_language_mode = '';
547
548 /**
549 * Site content selection uid (can be different from sys_language_uid if content
550 * is to be selected from a fall-back language. Depends on sys_language_mode)
551 * @var int
552 */
553 public $sys_language_content = 0;
554
555 /**
556 * Site content overlay flag; If set - and sys_language_content is > 0 - ,
557 * records selected will try to look for a translation pointing to their uid. (If
558 * configured in [ctrl][languageField] / [ctrl][transOrigP...]
559 * Possible values: [0,1,hideNonTranslated]
560 * This flag is set based on TypoScript config.sys_language_overlay setting
561 *
562 * @var int|string
563 */
564 public $sys_language_contentOL = 0;
565
566 /**
567 * Is set to the iso code of the sys_language_content if that is properly defined
568 * by the sys_language record representing the sys_language_uid.
569 * @var string
570 */
571 public $sys_language_isocode = '';
572
573 /**
574 * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
575 * extensions.
576 * @var array
577 */
578 public $applicationData = [];
579
580 /**
581 * @var array
582 */
583 public $register = [];
584
585 /**
586 * Stack used for storing array and retrieving register arrays (see
587 * LOAD_REGISTER and RESTORE_REGISTER)
588 * @var array
589 */
590 public $registerStack = [];
591
592 /**
593 * Checking that the function is not called eternally. This is done by
594 * interrupting at a depth of 50
595 * @var int
596 */
597 public $cObjectDepthCounter = 50;
598
599 /**
600 * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
601 * rendered twice through it!
602 * @var array
603 */
604 public $recordRegister = [];
605
606 /**
607 * This is set to the [table]:[uid] of the latest record rendered. Note that
608 * class ContentObjectRenderer has an equal value, but that is pointing to the
609 * record delivered in the $data-array of the ContentObjectRenderer instance, if
610 * the cObjects CONTENT or RECORD created that instance
611 * @var string
612 */
613 public $currentRecord = '';
614
615 /**
616 * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
617 * to keep track of access-keys.
618 * @var array
619 */
620 public $accessKey = [];
621
622 /**
623 * Numerical array where image filenames are added if they are referenced in the
624 * rendered document. This includes only TYPO3 generated/inserted images.
625 * @var array
626 */
627 public $imagesOnPage = [];
628
629 /**
630 * Is set in ContentObjectRenderer->cImage() function to the info-array of the
631 * most recent rendered image. The information is used in ImageTextContentObject
632 * @var array
633 */
634 public $lastImageInfo = [];
635
636 /**
637 * Used to generate page-unique keys. Point is that uniqid() functions is very
638 * slow, so a unikey key is made based on this, see function uniqueHash()
639 * @var int
640 */
641 public $uniqueCounter = 0;
642
643 /**
644 * @var string
645 */
646 public $uniqueString = '';
647
648 /**
649 * This value will be used as the title for the page in the indexer (if
650 * indexing happens)
651 * @var string
652 */
653 public $indexedDocTitle = '';
654
655 /**
656 * Alternative page title (normally the title of the page record). Can be set
657 * from applications you make.
658 * @var string
659 */
660 public $altPageTitle = '';
661
662 /**
663 * The base URL set for the page header.
664 * @var string
665 */
666 public $baseUrl = '';
667
668 /**
669 * IDs we already rendered for this page (to make sure they are unique)
670 * @var array
671 */
672 private $usedUniqueIds = [];
673
674 /**
675 * Page content render object
676 *
677 * @var ContentObjectRenderer
678 */
679 public $cObj = '';
680
681 /**
682 * All page content is accumulated in this variable. See pagegen.php
683 * @var string
684 */
685 public $content = '';
686
687 /**
688 * Output charset of the websites content. This is the charset found in the
689 * header, meta tag etc. If different than utf-8 a conversion
690 * happens before output to browser. Defaults to utf-8.
691 * @var string
692 */
693 public $metaCharset = 'utf-8';
694
695 /**
696 * Set to the system language key (used on the site)
697 * @var string
698 */
699 public $lang = '';
700
701 /**
702 * Internal calculations for labels
703 *
704 * @var LanguageService
705 */
706 protected $languageService;
707
708 /**
709 * @var LockingStrategyInterface[][]
710 */
711 protected $locks = [];
712
713 /**
714 * @var PageRenderer
715 */
716 protected $pageRenderer = null;
717
718 /**
719 * The page cache object, use this to save pages to the cache and to
720 * retrieve them again
721 *
722 * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
723 */
724 protected $pageCache;
725
726 /**
727 * @var array
728 */
729 protected $pageCacheTags = [];
730
731 /**
732 * The cHash Service class used for cHash related functionality
733 *
734 * @var CacheHashCalculator
735 */
736 protected $cacheHash;
737
738 /**
739 * Runtime cache of domains per processed page ids.
740 *
741 * @var array
742 */
743 protected $domainDataCache = [];
744
745 /**
746 * Content type HTTP header being sent in the request.
747 * @todo Ticket: #63642 Should be refactored to a request/response model later
748 * @internal Should only be used by TYPO3 core for now
749 *
750 * @var string
751 */
752 protected $contentType = 'text/html';
753
754 /**
755 * Doctype to use
756 *
757 * @var string
758 */
759 public $xhtmlDoctype = '';
760
761 /**
762 * @var int
763 */
764 public $xhtmlVersion;
765
766 /**
767 * Originally requested id from the initial $_GET variable
768 *
769 * @var int
770 */
771 protected $requestedId;
772
773 /**
774 * Class constructor
775 * Takes a number of GET/POST input variable as arguments and stores them internally.
776 * The processing of these variables goes on later in this class.
777 * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
778 *
779 * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
780 * @param mixed $id The value of GeneralUtility::_GP('id')
781 * @param int $type The value of GeneralUtility::_GP('type')
782 * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0
783 * @param string $cHash The value of GeneralUtility::_GP('cHash')
784 * @param string $_2 previously was used to define the jumpURL
785 * @param string $MP The value of GeneralUtility::_GP('MP')
786 * @see \TYPO3\CMS\Frontend\Http\RequestHandler
787 */
788 public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '')
789 {
790 // Setting some variables:
791 $this->id = $id;
792 $this->type = $type;
793 if ($no_cache) {
794 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
795 $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
796 $this->getTimeTracker()->setTSlogMessage($warning, 2);
797 } else {
798 $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL') . '"';
799 $this->disableCache();
800 }
801 // note: we need to instantiate the logger manually here since the injection happens after the constructor
802 GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__)->warning($warning);
803 }
804 $this->cHash = $cHash;
805 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? (string)$MP : '';
806 $this->uniqueString = md5(microtime());
807 $this->initPageRenderer();
808 // Call post processing function for constructor:
809 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] ?? [] as $_funcRef) {
810 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
811 }
812 $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
813 $this->initCaches();
814 }
815
816 /**
817 * Initializes the page renderer object
818 */
819 protected function initPageRenderer()
820 {
821 if ($this->pageRenderer !== null) {
822 return;
823 }
824 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
825 $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
826 }
827
828 /**
829 * @param string $contentType
830 * @internal Should only be used by TYPO3 core for now
831 */
832 public function setContentType($contentType)
833 {
834 $this->contentType = $contentType;
835 }
836
837 /**
838 * Connect to SQL database. May exit after outputting an error message
839 * or some JavaScript redirecting to the install tool.
840 *
841 * @throws \RuntimeException
842 * @throws ServiceUnavailableException
843 */
844 public function connectToDB()
845 {
846 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
847 try {
848 $connection->connect();
849 } catch (ConnectionException $exception) {
850 // Cannot connect to current database
851 $message = 'Cannot connect to the configured database "' . $connection->getDatabase() . '"';
852 $this->logger->emergency($message, ['exception' => $exception]);
853 try {
854 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
855 $this->sendResponseAndExit($response);
856 } catch (ServiceUnavailableException $e) {
857 throw new ServiceUnavailableException($message, 1301648782);
858 }
859 }
860 // Call post processing function for DB connection:
861 $_params = ['pObj' => &$this];
862 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] ?? [] as $_funcRef) {
863 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
864 }
865 }
866
867 /********************************************
868 *
869 * Initializing, resolving page id
870 *
871 ********************************************/
872 /**
873 * Initializes the caching system.
874 */
875 protected function initCaches()
876 {
877 $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
878 }
879
880 /**
881 * Initializes the front-end login user.
882 */
883 public function initFEuser()
884 {
885 $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
886 // List of pid's acceptable
887 $pid = GeneralUtility::_GP('pid');
888 $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
889 // Check if a session is transferred:
890 if (GeneralUtility::_GP('FE_SESSION_KEY')) {
891 $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
892 // If the session key hash check is OK:
893 if (md5(($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) === (string)$fe_sParts[1]) {
894 $cookieName = FrontendUserAuthentication::getCookieName();
895 $_COOKIE[$cookieName] = $fe_sParts[0];
896 if (isset($_SERVER['HTTP_COOKIE'])) {
897 // See http://forge.typo3.org/issues/27740
898 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
899 }
900 $this->fe_user->forceSetCookie = true;
901 $this->fe_user->dontSetCookie = false;
902 unset($cookieName);
903 }
904 }
905 $this->fe_user->start();
906 $this->fe_user->unpack_uc();
907
908 // Call hook for possible manipulation of frontend user object
909 $_params = ['pObj' => &$this];
910 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] ?? [] as $_funcRef) {
911 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
912 }
913 }
914
915 /**
916 * Initializes the front-end user groups.
917 * Sets ->loginUser and ->gr_list based on front-end user status.
918 */
919 public function initUserGroups()
920 {
921 // This affects the hidden-flag selecting the fe_groups for the user!
922 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
923 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
924 $this->fe_user->fetchGroupData();
925 if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
926 // global flag!
927 $this->loginUser = true;
928 // group -2 is not an existing group, but denotes a 'default' group when a user IS logged in. This is used to let elements be shown for all logged in users!
929 $this->gr_list = '0,-2';
930 $gr_array = $this->fe_user->groupData['uid'];
931 } else {
932 $this->loginUser = false;
933 // group -1 is not an existing group, but denotes a 'default' group when not logged in. This is used to let elements be hidden, when a user is logged in!
934 $this->gr_list = '0,-1';
935 if ($this->loginAllowedInBranch) {
936 // For cases where logins are not banned from a branch usergroups can be set based on IP masks so we should add the usergroups uids.
937 $gr_array = $this->fe_user->groupData['uid'];
938 } else {
939 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
940 $gr_array = [];
941 }
942 }
943 // Clean up.
944 // Make unique...
945 $gr_array = array_unique($gr_array);
946 // sort
947 sort($gr_array);
948 if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
949 $this->gr_list .= ',' . implode(',', $gr_array);
950 }
951
952 // For every 60 seconds the is_online timestamp for a logged-in user is updated
953 if ($this->loginUser) {
954 $this->fe_user->updateOnlineTimestamp();
955 }
956
957 $this->logger->debug('Valid usergroups for TSFE: ' . $this->gr_list);
958 }
959
960 /**
961 * Checking if a user is logged in or a group constellation different from "0,-1"
962 *
963 * @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!)
964 */
965 public function isUserOrGroupSet()
966 {
967 return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
968 }
969
970 /**
971 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
972 *
973 * Two options:
974 * 1) Use PATH_INFO (also Apache) to extract id and type from that var. Does not require any special modules compiled with apache. (less typical)
975 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
976 */
977 public function checkAlternativeIdMethods()
978 {
979 $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
980 // Call post processing function for custom URL methods.
981 $_params = ['pObj' => &$this];
982 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
983 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
984 }
985 }
986
987 /**
988 * Clears the preview-flags, sets sim_exec_time to current time.
989 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
990 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
991 */
992 public function clear_preview()
993 {
994 $this->showHiddenPage = false;
995 $this->showHiddenRecords = false;
996 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
997 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
998 $this->fePreview = 0;
999 }
1000
1001 /**
1002 * Checks if a backend user is logged in
1003 *
1004 * @return bool whether a backend user is logged in
1005 */
1006 public function isBackendUserLoggedIn()
1007 {
1008 return (bool)$this->beUserLogin;
1009 }
1010
1011 /**
1012 * Creates the backend user object and returns it.
1013 *
1014 * @return FrontendBackendUserAuthentication the backend user object
1015 */
1016 public function initializeBackendUser()
1017 {
1018 // PRE BE_USER HOOK
1019 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] ?? [] as $_funcRef) {
1020 $_params = [];
1021 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1022 }
1023 $backendUserObject = null;
1024 // If the backend cookie is set,
1025 // we proceed and check if a backend user is logged in.
1026 if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1027 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1028 $this->getTimeTracker()->push('Back End user initialized', '');
1029 $this->beUserLogin = false;
1030 // New backend user object
1031 $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1032 $backendUserObject->start();
1033 $backendUserObject->unpack_uc();
1034 if (!empty($backendUserObject->user['uid'])) {
1035 $backendUserObject->fetchGroupData();
1036 }
1037 // Unset the user initialization if any setting / restriction applies
1038 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1039 $backendUserObject = null;
1040 } elseif (!empty($backendUserObject->user['uid'])) {
1041 // If the user is active now, let the controller know
1042 $this->beUserLogin = true;
1043 } else {
1044 $backendUserObject = null;
1045 }
1046 $this->getTimeTracker()->pull();
1047 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1048 }
1049 // POST BE_USER HOOK
1050 $_params = [
1051 'BE_USER' => &$backendUserObject
1052 ];
1053 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] ?? [] as $_funcRef) {
1054 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1055 }
1056 return $backendUserObject;
1057 }
1058
1059 /**
1060 * Determines the id and evaluates any preview settings
1061 * Basically this function is about determining whether a backend user is logged in,
1062 * if he has read access to the page and if he's previewing the page.
1063 * That all determines which id to show and how to initialize the id.
1064 */
1065 public function determineId()
1066 {
1067 // Call pre processing function for id determination
1068 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
1069 $parameters = ['parentObject' => $this];
1070 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1071 }
1072 // If there is a Backend login we are going to check for any preview settings
1073 $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
1074 // If the front-end is showing a preview, caching MUST be disabled.
1075 if ($this->fePreview) {
1076 $this->disableCache();
1077 }
1078 // Now, get the id, validate access etc:
1079 $this->fetch_the_id();
1080 // Check if backend user has read access to this page. If not, recalculate the id.
1081 if ($this->beUserLogin && $this->fePreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
1082 // Resetting
1083 $this->clear_preview();
1084 $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
1085 // Fetching the id again, now with the preview settings reset.
1086 $this->fetch_the_id();
1087 }
1088 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1089 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1090 // Logins are not allowed:
1091 if (!$this->loginAllowedInBranch) {
1092 // Only if there is a login will we run this...
1093 if ($this->isUserOrGroupSet()) {
1094 if ($this->loginAllowedInBranch_mode === 'all') {
1095 // Clear out user and group:
1096 $this->fe_user->hideActiveLogin();
1097 $this->gr_list = '0,-1';
1098 } else {
1099 $this->gr_list = '0,-2';
1100 }
1101 // Fetching the id again, now with the preview settings reset.
1102 $this->fetch_the_id();
1103 }
1104 }
1105 // Final cleaning.
1106 // Make sure it's an integer
1107 $this->id = ($this->contentPid = (int)$this->id);
1108 // Make sure it's an integer
1109 $this->type = (int)$this->type;
1110 // Call post processing function for id determination:
1111 $_params = ['pObj' => &$this];
1112 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1113 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1114 }
1115 }
1116
1117 /**
1118 * Evaluates admin panel or workspace settings to see if
1119 * visibility settings like
1120 * - $fePreview
1121 * - $showHiddenPage
1122 * - $showHiddenRecords
1123 * - $simUserGroup
1124 * should be applied to the current object.
1125 *
1126 * @param FrontendBackendUserAuthentication $backendUser
1127 * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
1128 * @private do not use this in your extension code.
1129 */
1130 protected function applyPreviewSettings($backendUser = null)
1131 {
1132 if (!$backendUser) {
1133 return null;
1134 }
1135 $originalFrontendUser = null;
1136 // Backend user preview features:
1137 if ($backendUser->adminPanel instanceof AdminPanelView) {
1138 $this->fePreview = (int)$backendUser->adminPanel->extGetFeAdminValue('preview');
1139 // If admin panel preview is enabled...
1140 if ($this->fePreview) {
1141 if ($this->fe_user->user) {
1142 $originalFrontendUser = $this->fe_user->user[$this->fe_user->usergroup_column];
1143 }
1144 $this->showHiddenPage = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1145 $this->showHiddenRecords = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1146 // Simulate date
1147 $simTime = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1148 if ($simTime) {
1149 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1150 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1151 }
1152 // simulate user
1153 $this->simUserGroup = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1154 if ($this->simUserGroup) {
1155 if ($this->fe_user->user) {
1156 $this->fe_user->user[$this->fe_user->usergroup_column] = $this->simUserGroup;
1157 } else {
1158 $this->fe_user->user = [
1159 $this->fe_user->usergroup_column => $this->simUserGroup
1160 ];
1161 }
1162 }
1163 if (!$this->simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1164 $this->fePreview = 0;
1165 }
1166 }
1167 }
1168 // The preview flag is set if the current page turns out to be hidden
1169 if ($this->id && $this->determineIdIsHiddenPage()) {
1170 $this->fePreview = 1;
1171 $this->showHiddenPage = true;
1172 }
1173 // The preview flag will be set if an offline workspace will be previewed
1174 if ($this->whichWorkspace() > 0) {
1175 $this->fePreview = 1;
1176 }
1177 return $this->simUserGroup ? $originalFrontendUser : null;
1178 }
1179
1180 /**
1181 * Checks if the page is hidden in the active workspace.
1182 * If it is hidden, preview flags will be set.
1183 *
1184 * @return bool
1185 */
1186 protected function determineIdIsHiddenPage()
1187 {
1188 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1189
1190 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1191 ->getQueryBuilderForTable('pages');
1192 $queryBuilder
1193 ->getRestrictions()
1194 ->removeAll()
1195 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1196
1197 $page = $queryBuilder
1198 ->select('uid', 'hidden', 'starttime', 'endtime')
1199 ->from('pages')
1200 ->where(
1201 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1202 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1203 )
1204 ->setMaxResults(1)
1205 ->execute()
1206 ->fetch();
1207
1208 if ($this->whichWorkspace() > 0) {
1209 // Fetch overlay of page if in workspace and check if it is hidden
1210 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1211 $pageSelectObject->versioningPreview = true;
1212 $pageSelectObject->init(false);
1213 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1214 $result = $targetPage === -1 || $targetPage === -2;
1215 } else {
1216 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1217 }
1218 return $result;
1219 }
1220
1221 /**
1222 * Resolves the page id and sets up several related properties.
1223 *
1224 * If $this->id is not set at all or is not a plain integer, the method
1225 * does it's best to set the value to an integer. Resolving is based on
1226 * this options:
1227 *
1228 * - Splitting $this->id if it contains an additional type parameter.
1229 * - Getting the id for an alias in $this->id
1230 * - Finding the domain record start page
1231 * - First visible page
1232 * - Relocating the id below the domain record if outside
1233 *
1234 * The following properties may be set up or updated:
1235 *
1236 * - id
1237 * - requestedId
1238 * - type
1239 * - domainStartPage
1240 * - sys_page
1241 * - sys_page->where_groupAccess
1242 * - sys_page->where_hid_del
1243 * - loginUser
1244 * - gr_list
1245 * - no_cache
1246 * - register['SYS_LASTCHANGED']
1247 * - pageNotFound
1248 *
1249 * Via getPageAndRootlineWithDomain()
1250 *
1251 * - rootLine
1252 * - page
1253 * - MP
1254 * - originalShortcutPage
1255 * - originalMountPointPage
1256 * - pageAccessFailureHistory['direct_access']
1257 * - pageNotFound
1258 *
1259 * @todo:
1260 *
1261 * On the first impression the method does to much. This is increased by
1262 * the fact, that is is called repeated times by the method determineId.
1263 * The reasons are manifold.
1264 *
1265 * 1.) The first part, the creation of sys_page, the type and alias
1266 * resolution don't need to be repeated. They could be separated to be
1267 * called only once.
1268 *
1269 * 2.) The user group setup could be done once on a higher level.
1270 *
1271 * 3.) The workflow of the resolution could be elaborated to be less
1272 * tangled. Maybe the check of the page id to be below the domain via the
1273 * root line doesn't need to be done each time, but for the final result
1274 * only.
1275 *
1276 * 4.) The root line does not need to be directly addressed by this class.
1277 * A root line is always related to one page. The rootline could be handled
1278 * indirectly by page objects. Page objects still don't exist.
1279 *
1280 * @throws ServiceUnavailableException
1281 * @access private
1282 */
1283 public function fetch_the_id()
1284 {
1285 $timeTracker = $this->getTimeTracker();
1286 $timeTracker->push('fetch_the_id initialize/', '');
1287 // Initialize the page-select functions.
1288 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1289 $this->sys_page->versioningPreview = $this->whichWorkspace() > 0 || (bool)GeneralUtility::_GP('ADMCMD_view');
1290 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1291 $this->sys_page->init($this->showHiddenPage);
1292 // Set the valid usergroups for FE
1293 $this->initUserGroups();
1294 // Sets sys_page where-clause
1295 $this->setSysPageWhereClause();
1296 // If $this->id is a string, it's an alias
1297 $this->checkAndSetAlias();
1298 // The id and type is set to the integer-value - just to be sure...
1299 $this->id = (int)$this->id;
1300 $this->type = (int)$this->type;
1301 $timeTracker->pull();
1302 // We find the first page belonging to the current domain
1303 $timeTracker->push('fetch_the_id domain/', '');
1304 // The page_id of the current domain
1305 $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1306 if (!$this->id) {
1307 if ($this->domainStartPage) {
1308 // If the id was not previously set, set it to the id of the domain.
1309 $this->id = $this->domainStartPage;
1310 } else {
1311 // Find the first 'visible' page in that domain
1312 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1313 if ($theFirstPage) {
1314 $this->id = $theFirstPage['uid'];
1315 } else {
1316 $message = 'No pages are found on the rootlevel!';
1317 $this->logger->alert($message);
1318 try {
1319 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
1320 $this->sendResponseAndExit($response);
1321 } catch (ServiceUnavailableException $e) {
1322 throw new ServiceUnavailableException($message, 1301648975);
1323 }
1324 }
1325 }
1326 }
1327 $timeTracker->pull();
1328 $timeTracker->push('fetch_the_id rootLine/', '');
1329 // We store the originally requested id
1330 $this->requestedId = $this->id;
1331 try {
1332 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1333 } catch (ShortcutTargetPageNotFoundException $e) {
1334 $this->pageNotFound = 1;
1335 }
1336 $timeTracker->pull();
1337 // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1338 // Functional tests in workspaces currently
1339 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1340 $pNotFoundMsg = [
1341 1 => 'ID was not an accessible page',
1342 2 => 'Subsection was found and not accessible',
1343 3 => 'ID was outside the domain',
1344 4 => 'The requested page alias does not exist'
1345 ];
1346 $message = $pNotFoundMsg[$this->pageNotFound];
1347 if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1348 $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($message, $this->getPageAccessFailureReasons());
1349 } else {
1350 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1351 }
1352 $this->sendResponseAndExit($response);
1353 }
1354 // Init SYS_LASTCHANGED
1355 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1356 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1357 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1358 }
1359 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1360 $parameters = ['parentObject' => $this];
1361 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1362 }
1363 }
1364
1365 /**
1366 * Loads the page and root line records based on $this->id
1367 *
1368 * A final page and the matching root line are determined and loaded by
1369 * the algorithm defined by this method.
1370 *
1371 * First it loads the initial page from the page repository for $this->id.
1372 * If that can't be loaded directly, it gets the root line for $this->id.
1373 * It walks up the root line towards the root page until the page
1374 * repository can deliver a page record. (The loading restrictions of
1375 * the root line records are more liberal than that of the page record.)
1376 *
1377 * Now the page type is evaluated and handled if necessary. If the page is
1378 * a short cut, it is replaced by the target page. If the page is a mount
1379 * point in overlay mode, the page is replaced by the mounted page.
1380 *
1381 * After this potential replacements are done, the root line is loaded
1382 * (again) for this page record. It walks up the root line up to
1383 * the first viewable record.
1384 *
1385 * (While upon the first accessibility check of the root line it was done
1386 * by loading page by page from the page repository, this time the method
1387 * checkRootlineForIncludeSection() is used to find the most distant
1388 * accessible page within the root line.)
1389 *
1390 * Having found the final page id, the page record and the root line are
1391 * loaded for last time by this method.
1392 *
1393 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1394 * or root lines.
1395 *
1396 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1397 * instead of throwing an exception it's handled by a page unavailable
1398 * handler.
1399 *
1400 * May set or update this properties:
1401 *
1402 * @see TypoScriptFrontendController::$id
1403 * @see TypoScriptFrontendController::$MP
1404 * @see TypoScriptFrontendController::$page
1405 * @see TypoScriptFrontendController::$pageNotFound
1406 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1407 * @see TypoScriptFrontendController::$originalMountPointPage
1408 * @see TypoScriptFrontendController::$originalShortcutPage
1409 *
1410 * @throws ServiceUnavailableException
1411 * @throws PageNotFoundException
1412 * @access private
1413 */
1414 public function getPageAndRootline()
1415 {
1416 $this->resolveTranslatedPageId();
1417 if (empty($this->page)) {
1418 // If no page, we try to find the page before in the rootLine.
1419 // Page is 'not found' in case the id itself was not an accessible page. code 1
1420 $this->pageNotFound = 1;
1421 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1422 if (!empty($this->rootLine)) {
1423 $c = count($this->rootLine) - 1;
1424 while ($c > 0) {
1425 // Add to page access failure history:
1426 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1427 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1428 $c--;
1429 $this->id = $this->rootLine[$c]['uid'];
1430 $this->page = $this->sys_page->getPage($this->id);
1431 if (!empty($this->page)) {
1432 break;
1433 }
1434 }
1435 }
1436 // If still no page...
1437 if (empty($this->page)) {
1438 $message = 'The requested page does not exist!';
1439 $this->logger->error($message);
1440 try {
1441 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1442 $this->sendResponseAndExit($response);
1443 } catch (PageNotFoundException $e) {
1444 throw new PageNotFoundException($message, 1301648780);
1445 }
1446 }
1447 }
1448 // Spacer is not accessible in frontend
1449 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1450 $message = 'The requested page does not exist!';
1451 $this->logger->error($message);
1452 try {
1453 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1454 $this->sendResponseAndExit($response);
1455 } catch (PageNotFoundException $e) {
1456 throw new PageNotFoundException($message, 1301648781);
1457 }
1458 }
1459 // Is the ID a link to another page??
1460 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1461 // 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.
1462 $this->MP = '';
1463 // saving the page so that we can check later - when we know
1464 // about languages - whether we took the correct shortcut or
1465 // whether a translation of the page overwrites the shortcut
1466 // target and we need to follow the new target
1467 $this->originalShortcutPage = $this->page;
1468 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1469 $this->id = $this->page['uid'];
1470 }
1471 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1472 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1473 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1474 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1475 $this->originalMountPointPage = $this->page;
1476 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1477 if (empty($this->page)) {
1478 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1479 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1480 throw new PageNotFoundException($message, 1402043263);
1481 }
1482 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1483 $this->id = $this->page['uid'];
1484 }
1485 // Gets the rootLine
1486 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1487 // If not rootline we're off...
1488 if (empty($this->rootLine)) {
1489 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1490 $this->logger->error($message);
1491 try {
1492 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1493 $this->sendResponseAndExit($response);
1494 } catch (ServiceUnavailableException $e) {
1495 throw new ServiceUnavailableException($message, 1301648167);
1496 }
1497 }
1498 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1499 if ($this->checkRootlineForIncludeSection()) {
1500 if (empty($this->rootLine)) {
1501 $message = 'The requested page was not accessible!';
1502 try {
1503 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1504 $this->sendResponseAndExit($response);
1505 } catch (ServiceUnavailableException $e) {
1506 $this->logger->warning($message);
1507 throw new ServiceUnavailableException($message, 1301648234);
1508 }
1509 } else {
1510 $el = reset($this->rootLine);
1511 $this->id = $el['uid'];
1512 $this->page = $this->sys_page->getPage($this->id);
1513 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1514 }
1515 }
1516 }
1517
1518 /**
1519 * If $this->id contains a translated page record, this needs to be resolved to the default language
1520 * in order for all rootline functionality and access restrictions to be in place further on.
1521 *
1522 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1523 */
1524 protected function resolveTranslatedPageId()
1525 {
1526 $this->page = $this->sys_page->getPage($this->id);
1527 // Accessed a default language page record, nothing to resolve
1528 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1529 return;
1530 }
1531 $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1532 $this->sys_language_content = $this->sys_language_uid;
1533 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1534 $this->id = $this->page['uid'];
1535 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1536 $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1537 }
1538
1539 /**
1540 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1541 *
1542 * @param int $SC The value of the "shortcut" field from the pages record
1543 * @param int $mode The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC
1544 * @param int $thisUid The current page UID of the page which is a shortcut
1545 * @param int $itera Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
1546 * @param array $pageLog An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
1547 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1548 * @throws \RuntimeException
1549 * @throws ShortcutTargetPageNotFoundException
1550 * @return mixed Returns the page record of the page that the shortcut pointed to.
1551 * @access private
1552 * @see getPageAndRootline()
1553 */
1554 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1555 {
1556 $idArray = GeneralUtility::intExplode(',', $SC);
1557 // Find $page record depending on shortcut mode:
1558 switch ($mode) {
1559 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1560
1561 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1562 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1563 $pO = 0;
1564 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1565 $randval = (int)rand(0, count($pageArray) - 1);
1566 $pO = $randval;
1567 }
1568 $c = 0;
1569 $page = [];
1570 foreach ($pageArray as $pV) {
1571 if ($c === $pO) {
1572 $page = $pV;
1573 break;
1574 }
1575 $c++;
1576 }
1577 if (empty($page)) {
1578 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1579 throw new ShortcutTargetPageNotFoundException($message, 1301648328);
1580 }
1581 break;
1582 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1583 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1584 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1585 if (empty($page)) {
1586 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1587 throw new ShortcutTargetPageNotFoundException($message, 1301648358);
1588 }
1589 break;
1590 default:
1591 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1592 if (empty($page)) {
1593 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1594 throw new ShortcutTargetPageNotFoundException($message, 1301648404);
1595 }
1596 }
1597 // Check if short cut page was a shortcut itself, if so look up recursively:
1598 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1599 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1600 $pageLog[] = $page['uid'];
1601 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1602 } else {
1603 $pageLog[] = $page['uid'];
1604 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1605 $this->logger->error($message);
1606 throw new \RuntimeException($message, 1294587212);
1607 }
1608 }
1609 // Return resulting page:
1610 return $page;
1611 }
1612
1613 /**
1614 * Checks if visibility of the page is blocked upwards in the root line.
1615 *
1616 * If any page in the root line is blocking visibility, true is returend.
1617 *
1618 * All pages from the blocking page downwards are removed from the root
1619 * line, so that the remaning pages can be used to relocate the page up
1620 * to lowest visible page.
1621 *
1622 * The blocking feature of a page must be turned on by setting the page
1623 * record field 'extendToSubpages' to 1.
1624 *
1625 * The following fields are evaluated then:
1626 *
1627 * hidden, starttime, endtime, fe_group
1628 *
1629 * @todo Find a better name, i.e. checkVisibilityByRootLine
1630 * @todo Invert boolean return value. Return true if visible.
1631 *
1632 * @return bool
1633 * @access private
1634 */
1635 public function checkRootlineForIncludeSection(): bool
1636 {
1637 $c = count($this->rootLine);
1638 $removeTheRestFlag = false;
1639 for ($a = 0; $a < $c; $a++) {
1640 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1641 // Add to page access failure history:
1642 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1643 $removeTheRestFlag = true;
1644 }
1645
1646 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1647 // If there is a backend user logged in, check if he has read access to the page:
1648 if ($this->beUserLogin) {
1649 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1650 ->getQueryBuilderForTable('pages');
1651
1652 $queryBuilder
1653 ->getRestrictions()
1654 ->removeAll();
1655
1656 $row = $queryBuilder
1657 ->select('uid')
1658 ->from('pages')
1659 ->where(
1660 $queryBuilder->expr()->eq(
1661 'uid',
1662 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1663 ),
1664 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1665 )
1666 ->execute()
1667 ->fetch();
1668
1669 // versionOL()?
1670 if (!$row) {
1671 // 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...
1672 $removeTheRestFlag = true;
1673 }
1674 } else {
1675 // Don't go here, if there is no backend user logged in.
1676 $removeTheRestFlag = true;
1677 }
1678 }
1679 if ($removeTheRestFlag) {
1680 // Page is 'not found' in case a subsection was found and not accessible, code 2
1681 $this->pageNotFound = 2;
1682 unset($this->rootLine[$a]);
1683 break;
1684 }
1685 }
1686 return $removeTheRestFlag;
1687 }
1688
1689 /**
1690 * Checks page record for enableFields
1691 * Returns TRUE if enableFields does not disable the page record.
1692 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1693 *
1694 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1695 * @param bool $bypassGroupCheck Bypass group-check
1696 * @return bool TRUE, if record is viewable.
1697 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1698 */
1699 public function checkEnableFields($row, $bypassGroupCheck = false)
1700 {
1701 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1702 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1703 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1704 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1705 if ($return === false) {
1706 return false;
1707 }
1708 }
1709 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1710 return true;
1711 }
1712 return false;
1713 }
1714
1715 /**
1716 * Check group access against a page record
1717 *
1718 * @param array $row The page record to evaluate (needs field: fe_group)
1719 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1720 * @return bool TRUE, if group access is granted.
1721 * @access private
1722 */
1723 public function checkPageGroupAccess($row, $groupList = null)
1724 {
1725 if (is_null($groupList)) {
1726 $groupList = $this->gr_list;
1727 }
1728 if (!is_array($groupList)) {
1729 $groupList = explode(',', $groupList);
1730 }
1731 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1732 return count(array_intersect($groupList, $pageGroupList)) > 0;
1733 }
1734
1735 /**
1736 * Checks if the current page of the root line is visible.
1737 *
1738 * If the field extendToSubpages is 0, access is granted,
1739 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1740 *
1741 * @todo Find a better name, i.e. isVisibleRecord()
1742 *
1743 * @param array $row The page record
1744 * @return bool true if visible
1745 * @access private
1746 * @see checkEnableFields()
1747 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1748 * @see checkRootlineForIncludeSection()
1749 */
1750 public function checkPagerecordForIncludeSection(array $row): bool
1751 {
1752 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1753 }
1754
1755 /**
1756 * 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!)
1757 *
1758 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1759 */
1760 public function checkIfLoginAllowedInBranch()
1761 {
1762 // Initialize:
1763 $c = count($this->rootLine);
1764 $loginAllowed = true;
1765 // Traverse root line from root and outwards:
1766 for ($a = 0; $a < $c; $a++) {
1767 // If a value is set for login state:
1768 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1769 // Determine state from value:
1770 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1771 $loginAllowed = false;
1772 $this->loginAllowedInBranch_mode = 'all';
1773 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1774 $loginAllowed = false;
1775 $this->loginAllowedInBranch_mode = 'groups';
1776 } else {
1777 $loginAllowed = true;
1778 }
1779 }
1780 }
1781 return $loginAllowed;
1782 }
1783
1784 /**
1785 * 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
1786 *
1787 * @return array Summary of why page access was not allowed.
1788 */
1789 public function getPageAccessFailureReasons()
1790 {
1791 $output = [];
1792 $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'] : []);
1793 if (!empty($combinedRecords)) {
1794 foreach ($combinedRecords as $k => $pagerec) {
1795 // 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
1796 // 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!
1797 if (!$k || $pagerec['extendToSubpages']) {
1798 if ($pagerec['hidden']) {
1799 $output['hidden'][$pagerec['uid']] = true;
1800 }
1801 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1802 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1803 }
1804 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1805 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1806 }
1807 if (!$this->checkPageGroupAccess($pagerec)) {
1808 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1809 }
1810 }
1811 }
1812 }
1813 return $output;
1814 }
1815
1816 /**
1817 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1818 * If not inside domain, then default to first page in domain.
1819 *
1820 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1821 * @access private
1822 */
1823 public function getPageAndRootlineWithDomain($domainStartPage)
1824 {
1825 $this->getPageAndRootline();
1826 // Checks if the $domain-startpage is in the rootLine. This is necessary so that references to page-id's from other domains are not possible.
1827 if ($domainStartPage && is_array($this->rootLine)) {
1828 $idFound = false;
1829 foreach ($this->rootLine as $key => $val) {
1830 if ($val['uid'] == $domainStartPage) {
1831 $idFound = true;
1832 break;
1833 }
1834 }
1835 if (!$idFound) {
1836 // Page is 'not found' in case the id was outside the domain, code 3
1837 $this->pageNotFound = 3;
1838 $this->id = $domainStartPage;
1839 // re-get the page and rootline if the id was not found.
1840 $this->getPageAndRootline();
1841 }
1842 }
1843 }
1844
1845 /**
1846 * Sets sys_page where-clause
1847 *
1848 * @access private
1849 */
1850 public function setSysPageWhereClause()
1851 {
1852 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1853 ->getConnectionForTable('pages')
1854 ->getExpressionBuilder();
1855 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1856 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1857 $expressionBuilder->lt('pages.doktype', 200)
1858 );
1859 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1860 }
1861
1862 /**
1863 * Looking up a domain record based on HTTP_HOST
1864 *
1865 * @param bool $recursive If set, it looks "recursively" meaning that a domain like "123.456.typo3.com" would find a domain record like "typo3.com" if "123.456.typo3.com" or "456.typo3.com" did not exist.
1866 * @return int Returns the page id of the page where the domain record was found.
1867 * @access private
1868 */
1869 public function findDomainRecord($recursive = false)
1870 {
1871 if ($recursive) {
1872 $pageUid = 0;
1873 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1874 while (count($host)) {
1875 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'));
1876 if ($pageUid) {
1877 return $pageUid;
1878 }
1879 array_shift($host);
1880 }
1881 return $pageUid;
1882 }
1883 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'));
1884 }
1885
1886 /**
1887 * Page unavailable handler for use in frontend plugins from extensions.
1888 *
1889 * @param string $reason Reason text
1890 * @param string $header HTTP header to send
1891 * @deprecated
1892 */
1893 public function pageUnavailableAndExit($reason = '', $header = '')
1894 {
1895 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1896 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1897 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1898 die;
1899 }
1900
1901 /**
1902 * Page-not-found handler for use in frontend plugins from extensions.
1903 *
1904 * @param string $reason Reason text
1905 * @param string $header HTTP header to send
1906 * @deprecated
1907 */
1908 public function pageNotFoundAndExit($reason = '', $header = '')
1909 {
1910 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1911 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1912 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1913 die;
1914 }
1915
1916 /**
1917 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1918 * and devIPMask must not match the current visitor's IP address.
1919 *
1920 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1921 * @deprecated
1922 */
1923 public function checkPageUnavailableHandler()
1924 {
1925 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1926 if (
1927 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1928 && !GeneralUtility::cmpIP(
1929 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1930 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1931 )
1932 ) {
1933 $checkPageUnavailableHandler = true;
1934 } else {
1935 $checkPageUnavailableHandler = false;
1936 }
1937 return $checkPageUnavailableHandler;
1938 }
1939
1940 /**
1941 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1942 *
1943 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1944 * @param string $header If set, this is passed directly to the PHP function, header()
1945 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1946 * @deprecated
1947 */
1948 public function pageUnavailableHandler($code, $header, $reason)
1949 {
1950 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1951 $this->pageErrorHandler($code, $header, $reason);
1952 }
1953
1954 /**
1955 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1956 *
1957 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1958 * @param string $header If set, this is passed directly to the PHP function, header()
1959 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1960 * @deprecated
1961 */
1962 public function pageNotFoundHandler($code, $header = '', $reason = '')
1963 {
1964 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1965 $this->pageErrorHandler($code, $header, $reason);
1966 }
1967
1968 /**
1969 * Generic error page handler.
1970 * Exits.
1971 *
1972 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1973 * @param string $header If set, this is passed directly to the PHP function, header()
1974 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1975 * @throws \RuntimeException
1976 * @deprecated
1977 */
1978 public function pageErrorHandler($code, $header = '', $reason = '')
1979 {
1980 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1981 // Issue header in any case:
1982 if ($header) {
1983 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1984 foreach ($headerArr as $header) {
1985 header($header);
1986 }
1987 }
1988 // Create response:
1989 // Simply boolean; Just shows TYPO3 error page with reason:
1990 if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1991 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1992 'Page Not Found',
1993 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1994 );
1995 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1996 $funcRef = trim(substr($code, 14));
1997 $params = [
1998 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1999 'reasonText' => $reason,
2000 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
2001 ];
2002 try {
2003 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
2004 } catch (\Exception $e) {
2005 throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
2006 }
2007 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
2008 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
2009 if (@is_file($readFile)) {
2010 echo str_replace(
2011 [
2012 '###CURRENT_URL###',
2013 '###REASON###'
2014 ],
2015 [
2016 GeneralUtility::getIndpEnv('REQUEST_URI'),
2017 htmlspecialchars($reason)
2018 ],
2019 file_get_contents($readFile)
2020 );
2021 } else {
2022 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2023 }
2024 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
2025 HttpUtility::redirect(substr($code, 9));
2026 } elseif ($code !== '') {
2027 // Check if URL is relative
2028 $url_parts = parse_url($code);
2029 // parse_url could return an array without the key "host", the empty check works better than strict check
2030 if (empty($url_parts['host'])) {
2031 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
2032 if ($code[0] === '/') {
2033 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2034 } else {
2035 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2036 }
2037 $checkBaseTag = false;
2038 } else {
2039 $checkBaseTag = true;
2040 }
2041 // Check recursion
2042 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2043 if ($reason == '') {
2044 $reason = 'Page cannot be found.';
2045 }
2046 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2047 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2048 }
2049 // Prepare headers
2050 $headerArr = [
2051 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2052 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2053 ];
2054 $report = [];
2055 $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2056 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2057 throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2058 }
2059 // Header and content are separated by an empty line
2060 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2061 $content .= CRLF;
2062 if (false === $res) {
2063 // Last chance -- redirect
2064 HttpUtility::redirect($code);
2065 } else {
2066 // Forward these response headers to the client
2067 $forwardHeaders = [
2068 'Content-Type:'
2069 ];
2070 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2071 foreach ($headerArr as $header) {
2072 foreach ($forwardHeaders as $h) {
2073 if (preg_match('/^' . $h . '/', $header)) {
2074 header($header);
2075 }
2076 }
2077 }
2078 // Put <base> if necessary
2079 if ($checkBaseTag) {
2080 // If content already has <base> tag, we do not need to do anything
2081 if (false === stristr($content, '<base ')) {
2082 // Generate href for base tag
2083 $base = $url_parts['scheme'] . '://';
2084 if ($url_parts['user'] != '') {
2085 $base .= $url_parts['user'];
2086 if ($url_parts['pass'] != '') {
2087 $base .= ':' . $url_parts['pass'];
2088 }
2089 $base .= '@';
2090 }
2091 $base .= $url_parts['host'];
2092 // Add path portion skipping possible file name
2093 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2094 // Put it into content (generate also <head> if necessary)
2095 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2096 if (stristr($content, '<head>')) {
2097 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2098 } else {
2099 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2100 }
2101 }
2102 }
2103 // Output the content
2104 echo $content;
2105 }
2106 } else {
2107 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2108 'Page Not Found',
2109 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2110 );
2111 }
2112 die;
2113 }
2114
2115 /**
2116 * Fetches the integer page id for a page alias.
2117 * Looks if ->id is not an integer and if so it will search for a page alias and if found the page uid of that page is stored in $this->id
2118 *
2119 * @access private
2120 */
2121 public function checkAndSetAlias()
2122 {
2123 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2124 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2125 if ($aid) {
2126 $this->id = $aid;
2127 } else {
2128 $this->pageNotFound = 4;
2129 }
2130 }
2131 }
2132
2133 /**
2134 * Merging values into the global $_GET
2135 *
2136 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2137 */
2138 public function mergingWithGetVars($GET_VARS)
2139 {
2140 if (is_array($GET_VARS)) {
2141 // Getting $_GET var, unescaped.
2142 $realGet = GeneralUtility::_GET();
2143 if (!is_array($realGet)) {
2144 $realGet = [];
2145 }
2146 // Merge new values on top:
2147 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2148 // Write values back to $_GET:
2149 GeneralUtility::_GETset($realGet);
2150 // Setting these specifically (like in the init-function):
2151 if (isset($GET_VARS['type'])) {
2152 $this->type = (int)$GET_VARS['type'];
2153 }
2154 if (isset($GET_VARS['cHash'])) {
2155 $this->cHash = $GET_VARS['cHash'];
2156 }
2157 if (isset($GET_VARS['MP'])) {
2158 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2159 }
2160 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2161 $this->set_no_cache('no_cache is requested via GET parameter');
2162 }
2163 }
2164 }
2165
2166 /********************************************
2167 *
2168 * Template and caching related functions.
2169 *
2170 *******************************************/
2171 /**
2172 * Calculates a hash string based on additional parameters in the url.
2173 *
2174 * Calculated hash is stored in $this->cHash_array.
2175 * This is used to cache pages with more parameters than just id and type.
2176 *
2177 * @see reqCHash()
2178 */
2179 public function makeCacheHash()
2180 {
2181 // No need to test anything if caching was already disabled.
2182 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2183 return;
2184 }
2185 $GET = GeneralUtility::_GET();
2186 if ($this->cHash && is_array($GET)) {
2187 // Make sure we use the page uid and not the page alias
2188 $GET['id'] = $this->id;
2189 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2190 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2191 if (!hash_equals($cHash_calc, $this->cHash)) {
2192 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2193 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash comparison failed)');
2194 $this->sendResponseAndExit($response);
2195 } else {
2196 $this->disableCache();
2197 $this->getTimeTracker()->setTSlogMessage('The incoming cHash "' . $this->cHash . '" and calculated cHash "' . $cHash_calc . '" did not match, so caching was disabled. The fieldlist used was "' . implode(',', array_keys($this->cHash_array)) . '"', 2);
2198 }
2199 }
2200 } elseif (is_array($GET)) {
2201 // No cHash is set, check if that is correct
2202 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2203 $this->reqCHash();
2204 }
2205 }
2206 }
2207
2208 /**
2209 * Will disable caching if the cHash value was not set.
2210 * This function should be called to check the _existence_ of "&cHash" whenever a plugin generating cacheable output is using extra GET variables. If there _is_ a cHash value the validation of it automatically takes place in makeCacheHash() (see above)
2211 *
2212 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2213 */
2214 public function reqCHash()
2215 {
2216 if (!$this->cHash) {
2217 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2218 if ($this->tempContent) {
2219 $this->clearPageCacheContent();
2220 }
2221 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash empty)');
2222 $this->sendResponseAndExit($response);
2223 } else {
2224 $this->disableCache();
2225 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2226 }
2227 }
2228 }
2229
2230 /**
2231 * Initialize the TypoScript template parser
2232 */
2233 public function initTemplate()
2234 {
2235 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2236 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2237 $this->tmpl->init();
2238 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2239 }
2240
2241 /**
2242 * See if page is in cache and get it if so
2243 * Stores the page content in $this->content if something is found.
2244 *
2245 * @throws \InvalidArgumentException
2246 * @throws \RuntimeException
2247 */
2248 public function getFromCache()
2249 {
2250 // clearing the content-variable, which will hold the pagecontent
2251 $this->content = '';
2252 // Unsetting the lowlevel config
2253 $this->config = [];
2254 $this->cacheContentFlag = false;
2255
2256 if ($this->no_cache) {
2257 return;
2258 }
2259
2260 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2261 if (!is_array($pageSectionCacheContent)) {
2262 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2263 // We use the Registry to store this lock centrally,
2264 // but we protect the access again with a global exclusive lock to avoid race conditions
2265
2266 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2267 //
2268 // from this point on we're the only one working on that page ($key)
2269 //
2270
2271 // query the cache again to see if the page data are there meanwhile
2272 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2273 if (is_array($pageSectionCacheContent)) {
2274 // we have the content, nice that some other process did the work for us already
2275 $this->releaseLock('pagesection');
2276 }
2277 // We keep the lock set, because we are the ones generating the page now
2278 // and filling the cache.
2279 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2280 }
2281
2282 if (is_array($pageSectionCacheContent)) {
2283 // 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.
2284 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2285 // 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.
2286 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2287 ksort($pageSectionCacheContent);
2288 $this->all = $pageSectionCacheContent;
2289 }
2290 unset($pageSectionCacheContent);
2291
2292 // Look for page in cache only if a shift-reload is not sent to the server.
2293 $lockHash = $this->getLockHash();
2294 if (!$this->headerNoCache()) {
2295 if ($this->all) {
2296 // we got page section information
2297 $this->newHash = $this->getHash();
2298 $this->getTimeTracker()->push('Cache Row', '');
2299 $row = $this->getFromCache_queryRow();
2300 if (!is_array($row)) {
2301 // nothing in the cache, we acquire an exclusive lock now
2302
2303 $this->acquireLock('pages', $lockHash);
2304 //
2305 // from this point on we're the only one working on that page ($lockHash)
2306 //
2307
2308 // query the cache again to see if the data are there meanwhile
2309 $row = $this->getFromCache_queryRow();
2310 if (is_array($row)) {
2311 // we have the content, nice that some other process did the work for us
2312 $this->releaseLock('pages');
2313 }
2314 // We keep the lock set, because we are the ones generating the page now
2315 // and filling the cache.
2316 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2317 }
2318 if (is_array($row)) {
2319 // we have data from cache
2320
2321 // Call hook when a page is retrieved from cache:
2322 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2323 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2324 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2325 }
2326 // Fetches the lowlevel config stored with the cached data
2327 $this->config = $row['cache_data'];
2328 // Getting the content
2329 $this->content = $row['content'];
2330 // Flag for temp content
2331 $this->tempContent = $row['temp_content'];
2332 // Setting flag, so we know, that some cached content has been loaded
2333 $this->cacheContentFlag = true;
2334 $this->cacheExpires = $row['expires'];
2335
2336 // Restore page title information, this is needed to generate the page title for
2337 // partially cached pages.
2338 $this->page['title'] = $row['pageTitleInfo']['title'];
2339 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2340 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2341
2342 if (isset($this->config['config']['debug'])) {
2343 $debugCacheTime = (bool)$this->config['config']['debug'];
2344 } else {
2345 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2346 }
2347 if ($debugCacheTime) {
2348 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2349 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2350 $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2351 }
2352 }
2353 $this->getTimeTracker()->pull();
2354
2355 return;
2356 }
2357 }
2358 // the user forced rebuilding the page cache or there was no pagesection information
2359 // get a lock for the page content so other processes will not interrupt the regeneration
2360 $this->acquireLock('pages', $lockHash);
2361 }
2362
2363 /**
2364 * Returning the cached version of page with hash = newHash
2365 *
2366 * @return array Cached row, if any. Otherwise void.
2367 */
2368 public function getFromCache_queryRow()
2369 {
2370 $this->getTimeTracker()->push('Cache Query', '');
2371 $row = $this->pageCache->get($this->newHash);
2372 $this->getTimeTracker()->pull();
2373 return $row;
2374 }
2375
2376 /**
2377 * Detecting if shift-reload has been clicked
2378 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2379 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2380 *
2381 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2382 */
2383 public function headerNoCache()
2384 {
2385 $disableAcquireCacheData = false;
2386 if ($this->beUserLogin) {
2387 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2388 $disableAcquireCacheData = true;
2389 }
2390 }
2391 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2392 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2393 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2394 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2395 }
2396 return $disableAcquireCacheData;
2397 }
2398
2399 /**
2400 * Calculates the cache-hash
2401 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2402 * Used to get and later store the cached data.
2403 *
2404 * @return string MD5 hash of serialized hash base from createHashBase()
2405 * @access private
2406 * @see getFromCache(), getLockHash()
2407 */
2408 public function getHash()
2409 {
2410 return md5($this->createHashBase(false));
2411 }
2412
2413 /**
2414 * Calculates the lock-hash
2415 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2416 *
2417 * @return string MD5 hash
2418 * @access private
2419 * @see getFromCache(), getHash()
2420 */
2421 public function getLockHash()
2422 {
2423 $lockHash = $this->createHashBase(true);
2424 return md5($lockHash);
2425 }
2426
2427 /**
2428 * Calculates the cache-hash (or the lock-hash)
2429 * This hash is unique to the template,
2430 * the variables ->id, ->type, ->gr_list (list of groups),
2431 * ->MP (Mount Points) and cHash array
2432 * Used to get and later store the cached data.
2433 *
2434 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2435 * @return string the serialized hash base
2436 */
2437 protected function createHashBase($createLockHashBase = false)
2438 {
2439 $hashParameters = [
2440 'id' => (int)$this->id,
2441 'type' => (int)$this->type,
2442 'gr_list' => (string)$this->gr_list,
2443 'MP' => (string)$this->MP,
2444 'cHash' => $this->cHash_array,
2445 'domainStartPage' => $this->domainStartPage
2446 ];
2447 // Include the template information if we shouldn't create a lock hash
2448 if (!$createLockHashBase) {
2449 $hashParameters['all'] = $this->all;
2450 }
2451 // Call hook to influence the hash calculation
2452 $_params = [
2453 'hashParameters' => &$hashParameters,
2454 'createLockHashBase' => $createLockHashBase
2455 ];
2456 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2457 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2458 }
2459 return serialize($hashParameters);
2460 }
2461
2462 /**
2463 * Checks if config-array exists already but if not, gets it
2464 *
2465 * @throws ServiceUnavailableException
2466 */
2467 public function getConfigArray()
2468 {
2469 // 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
2470 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2471 $timeTracker = $this->getTimeTracker();
2472 $timeTracker->push('Parse template', '');
2473 // Force parsing, if set?:
2474 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2475 // Start parsing the TS template. Might return cached version.
2476 $this->tmpl->start($this->rootLine);
2477 $timeTracker->pull();
2478 if ($this->tmpl->loaded) {
2479 $timeTracker->push('Setting the config-array', '');
2480 // toplevel - objArrayName
2481 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2482 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2483 if (!is_array($this->pSetup)) {
2484 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2485 $this->logger->alert($message);
2486 try {
2487 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2488 $this->sendResponseAndExit($response);
2489 } catch (ServiceUnavailableException $e) {
2490 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2491 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2492 }
2493 } else {
2494 if (!isset($this->config['config'])) {
2495 $this->config['config'] = [];
2496 }
2497 // Filling the config-array, first with the main "config." part
2498 if (is_array($this->tmpl->setup['config.'])) {
2499 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2500 $this->config['config'] = $this->tmpl->setup['config.'];
2501 }
2502 // override it with the page/type-specific "config."
2503 if (is_array($this->pSetup['config.'])) {
2504 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2505 }
2506 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2507 if ($this->config['config']['typolinkCheckRootline']) {
2508 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2509 }
2510 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2511 if (!isset($this->config['config']['removeDefaultJS'])) {
2512 $this->config['config']['removeDefaultJS'] = 'external';
2513 }
2514 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2515 $this->config['config']['inlineStyle2TempFile'] = 1;
2516 }
2517
2518 if (!isset($this->config['config']['compressJs'])) {
2519 $this->config['config']['compressJs'] = 0;
2520 }
2521 // Processing for the config_array:
2522 $this->config['rootLine'] = $this->tmpl->rootLine;
2523 // Class for render Header and Footer parts
2524 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2525 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2526 if ($file) {
2527 $this->pageRenderer->setTemplateFile($file);
2528 }
2529 }
2530 }
2531 $timeTracker->pull();
2532 } else {
2533 $message = 'No TypoScript template found!';
2534 $this->logger->alert($message);
2535 try {
2536 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2537 $this->sendResponseAndExit($response);
2538 } catch (ServiceUnavailableException $e) {
2539 throw new ServiceUnavailableException($message, 1294587218);
2540 }
2541 }
2542 }
2543
2544 // No cache
2545 // Set $this->no_cache TRUE if the config.no_cache value is set!
2546 if ($this->config['config']['no_cache']) {
2547 $this->set_no_cache('config.no_cache is set');
2548 }
2549 // Merge GET with defaultGetVars
2550 if (!empty($this->config['config']['defaultGetVars.'])) {
2551 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2552 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2553 GeneralUtility::_GETset($modifiedGetVars);
2554 }
2555 // Hook for postProcessing the configuration array
2556 $params = ['config' => &$this->config['config']];
2557 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2558 GeneralUtility::callUserFunction($funcRef, $params, $this);
2559 }
2560 }
2561
2562 /********************************************
2563 *
2564 * Further initialization and data processing
2565 *
2566 *******************************************/
2567
2568 /**
2569 * Setting the language key that will be used by the current page.
2570 * 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.
2571 *
2572 * @access private
2573 */
2574 public function settingLanguage()
2575 {
2576 $_params = [];
2577 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2578 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2579 }
2580
2581 // Initialize charset settings etc.
2582 $languageKey = $this->config['config']['language'] ?? 'default';
2583 $this->lang = $languageKey;
2584 $this->setOutputLanguage($languageKey);
2585
2586 // Rendering charset of HTML page.
2587 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2588 $this->metaCharset = $this->config['config']['metaCharset'];
2589 }
2590
2591 // Get values from TypoScript, if not set before
2592 if ($this->sys_language_uid === 0) {
2593 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2594 }
2595 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2596 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2597 // If sys_language_uid is set to another language than default:
2598 if ($this->sys_language_uid > 0) {
2599 // check whether a shortcut is overwritten by a translated page
2600 // we can only do this now, as this is the place where we get
2601 // to know about translations
2602 $this->checkTranslatedShortcut();
2603 // Request the overlay record for the sys_language_uid:
2604 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2605 if (empty($olRec)) {
2606 // If no OL record exists and a foreign language is asked for...
2607 if ($this->sys_language_uid) {
2608 // If requested translation is not available:
2609 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2610 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language.');
2611 $this->sendResponseAndExit($response);
2612 } else {
2613 switch ((string)$this->sys_language_mode) {
2614 case 'strict':
2615 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (strict).');
2616 $this->sendResponseAndExit($response);
2617 break;
2618 case 'content_fallback':
2619 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2620 // value was found.
2621 $fallBackOrder = GeneralUtility::trimExplode(',', $sys_language_content);
2622 foreach ($fallBackOrder as $orderValue) {
2623 if ($orderValue === '0' || $orderValue === '') {
2624 $this->sys_language_content = 0;
2625 break;
2626 }
2627 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2628 $this->sys_language_content = (int)$orderValue;
2629 break;
2630 }
2631 if ($orderValue === 'pageNotFound') {
2632 // The existing fallbacks have not been found, but instead of continuing
2633 // page rendering with default language, a "page not found" message should be shown
2634 // instead.
2635 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (fallbacks did not apply).');
2636 $this->sendResponseAndExit($response);
2637 }
2638 }
2639 break;
2640 case 'ignore':
2641 $this->sys_language_content = $this->sys_language_uid;
2642 break;
2643 default:
2644 // Default is that everything defaults to the default language...
2645 $this->sys_language_uid = ($this->sys_language_content = 0);
2646 }
2647 }
2648 }
2649 } else {
2650 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2651 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2652 }
2653 }
2654 // Setting sys_language_uid inside sys-page:
2655 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2656 // If default translation is not available:
2657 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2658 $message = 'Page is not available in default language.';
2659 $this->logger->error($message);
2660 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message);
2661 $this->sendResponseAndExit($response);
2662 }
2663 $this->updateRootLinesWithTranslations();
2664
2665 // Finding the ISO code for the currently selected language
2666 // fetched by the sys_language record when not fetching content from the default language
2667 if ($this->sys_language_content > 0) {
2668 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2669 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2670 // avoid versioning overlay to be applied as it generates an SQL error
2671 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2672 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2673 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2674 }
2675 // the DB value is overridden by TypoScript
2676 if (!empty($this->config['config']['sys_language_isocode'])) {
2677 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2678 }
2679 } else {
2680 // fallback to the TypoScript option when rendering with sys_language_uid=0
2681 // also: use "en" by default
2682 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2683 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2684 } else {
2685 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2686 }
2687 }
2688
2689 $_params = [];
2690 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2691 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2692 }
2693 }
2694
2695 /**
2696 * Updating content of the two rootLines IF the language key is set!
2697 */
2698 protected function updateRootLinesWithTranslations()
2699 {
2700 if ($this->sys_language_uid) {
2701 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2702 $this->tmpl->updateRootlineData($this->rootLine);
2703 }
2704 }
2705
2706 /**
2707 * Setting locale for frontend rendering
2708 */
2709 public function settingLocale()
2710 {
2711 // Setting locale
2712 if ($this->config['config']['locale_all']) {
2713 $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2714 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2715 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2716 // @see https://bugs.php.net/bug.php?id=53711
2717 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2718 if ($locale) {
2719 // As str_* methods are locale aware and turkish has no upper case I
2720 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2721 // @see http://bugs.php.net/bug.php?id=35050
2722 if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2723 setlocale(LC_CTYPE, ...$availableLocales);
2724 }
2725 setlocale(LC_MONETARY, ...$availableLocales);
2726 setlocale(LC_TIME, ...$availableLocales);
2727 } else {
2728 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2729 }
2730 }
2731 }
2732
2733 /**
2734 * Checks whether a translated shortcut page has a different shortcut
2735 * target than the original language page.
2736 * If that is the case, things get corrected to follow that alternative
2737 * shortcut
2738 */
2739 protected function checkTranslatedShortcut()
2740 {
2741 if (!is_null($this->originalShortcutPage)) {
2742 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2743 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2744 // the translation of the original shortcut page has a different shortcut target!
2745 // set the correct page and id
2746 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2747 $this->id = ($this->contentPid = $shortcut['uid']);
2748 $this->page = $this->sys_page->getPage($this->id);
2749 // Fix various effects on things like menus f.e.
2750 $this->fetch_the_id();
2751 $this->tmpl->rootLine = array_reverse($this->rootLine);
2752 }
2753 }
2754 }
2755
2756 /**
2757 * Handle data submission
2758 * This is done at this point, because we need the config values
2759 */
2760 public function handleDataSubmission()
2761 {
2762 // Hook for processing data submission to extensions
2763 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2764 $_procObj = GeneralUtility::makeInstance($className);
2765 $_procObj->checkDataSubmission($this);
2766 }
2767 }
2768
2769 /**
2770 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2771 *
2772 * @see $activeRedirectUrlHandlers
2773 */
2774 public function initializeRedirectUrlHandlers()
2775 {
2776 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2777 if (!$urlHandlers) {
2778 return;
2779 }
2780
2781 foreach ($urlHandlers as $identifier => $configuration) {
2782 if (empty($configuration) || !is_array($configuration)) {
2783 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2784 }
2785 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2786 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2787 }
2788 }
2789
2790 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2791
2792 foreach ($orderedHandlers as $configuration) {
2793 /** @var UrlHandlerInterface $urlHandler */
2794 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2795 if ($urlHandler->canHandleCurrentUrl()) {
2796 $this->activeUrlHandlers[] = $urlHandler;
2797 }
2798 }
2799 }
2800
2801 /**
2802 * Loops over all registered URL handlers and lets them process the current URL.
2803 *
2804 * If no handler has stopped the current process (e.g. by redirecting) and a
2805 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2806 *
2807 * @internal Should be called by the FrontendRequestHandler only.
2808 * @return ResponseInterface|null
2809 */
2810 public function redirectToExternalUrl()
2811 {
2812 foreach ($this->activeUrlHandlers as $redirectHandler) {
2813 $response = $redirectHandler->handle();
2814 if ($response instanceof ResponseInterface) {
2815 return $response;
2816 }
2817 }
2818
2819 if (!empty($this->activeUrlHandlers)) {
2820 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2821 }
2822
2823 return null;
2824 }
2825
2826 /**
2827 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2828 * This feature allows sessions to use a GET-parameter instead of a cookie.
2829 *
2830 * @access private
2831 */
2832 public function setUrlIdToken()
2833 {
2834 if ($this->config['config']['ftu']) {
2835 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2836 } else {
2837 $this->getMethodUrlIdToken = '';
2838 }
2839 }
2840
2841 /**
2842 * Calculates and sets the internal linkVars based upon the current
2843 * $_GET parameters and the setting "config.linkVars".
2844 */
2845 public function calculateLinkVars()
2846 {
2847 $this->linkVars = '';
2848 if (empty($this->config['config']['linkVars'])) {
2849 return;
2850 }
2851
2852 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2853
2854 if (empty($linkVars)) {
2855 return;
2856 }
2857 $getData = GeneralUtility::_GET();
2858 foreach ($linkVars as $linkVar) {
2859 $test = $value = '';
2860 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2861 $linkVar = trim($match[1]);
2862 $test = trim($match[2]);
2863 }
2864
2865 $keys = explode('|', $linkVar);
2866 $numberOfLevels = count($keys);
2867 $rootKey = trim($keys[0]);
2868 if (!isset($getData[$rootKey])) {
2869 continue;
2870 }
2871 $value = $getData[$rootKey];
2872 for ($i = 1; $i < $numberOfLevels; $i++) {
2873 $currentKey = trim($keys[$i]);
2874 if (isset($value[$currentKey])) {
2875 $value = $value[$currentKey];
2876 } else {
2877 $value = false;
2878 break;
2879 }
2880 }
2881 if ($value !== false) {
2882 $parameterName = $keys[0];
2883 for ($i = 1; $i < $numberOfLevels; $i++) {
2884 $parameterName .= '[' . $keys[$i] . ']';
2885 }
2886 if (!is_array($value)) {
2887 $temp = rawurlencode($value);
2888 if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2889 // Error: This value was not allowed for this key
2890 continue;
2891 }
2892 $value = '&' . $parameterName . '=' . $temp;
2893 } else {
2894 if ($test !== '' && $test !== 'array') {
2895 // Error: This key must not be an array!
2896 continue;
2897 }
2898 $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2899 }
2900 $this->linkVars .= $value;
2901 }
2902 }
2903 }
2904
2905 /**
2906 * Split the link vars string by "," but not if the "," is inside of braces
2907 *
2908 * @param $string
2909 *
2910 * @return array
2911 */
2912 protected function splitLinkVarsString(string $string): array
2913 {
2914 $tempCommaReplacementString = '###KASPER###';
2915
2916 // replace every "," wrapped in "()" by a "unique" string
2917 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2918 return str_replace(',', $tempCommaReplacementString, $result[0]);
2919 }, $string);
2920
2921 $string = GeneralUtility::trimExplode(',', $string);
2922
2923 // replace all "unique" strings back to ","
2924 return str_replace($tempCommaReplacementString, ',', $string);
2925 }
2926
2927 /**
2928 * Checks if the value defined in "config.linkVars" contains an allowed value.
2929 * Otherwise, return FALSE which means the value will not be added to any links.
2930 *
2931 * @param string $haystack The string in which to find $needle
2932 * @param string $needle The string to find in $haystack
2933 * @return bool Returns TRUE if $needle matches or is found in $haystack
2934 */
2935 protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2936 {
2937 $isAllowed = false;
2938 // Integer
2939 if ($needle === 'int' || $needle === 'integer') {
2940 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2941 $isAllowed = true;
2942 }
2943 } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2944 // Regular expression, only "//" is allowed as delimiter
2945 if (@preg_match($needle, $haystack)) {
2946 $isAllowed = true;
2947 }
2948 } elseif (strstr($needle, '-')) {
2949 // Range
2950 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2951 $range = explode('-', $needle);
2952 if ($range[0] <= $haystack && $range[1] >= $haystack) {
2953 $isAllowed = true;
2954 }
2955 }
2956 } elseif (strstr($needle, '|')) {
2957 // List
2958 // Trim the input
2959 $haystack =