[BUGFIX] ErrorController is called via PSR-7 request
[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\DBALException;
18 use Psr\Http\Message\ResponseInterface;
19 use Psr\Http\Message\ServerRequestInterface;
20 use Psr\Log\LoggerAwareInterface;
21 use Psr\Log\LoggerAwareTrait;
22 use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
23 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
24 use TYPO3\CMS\Core\Cache\CacheManager;
25 use TYPO3\CMS\Core\Charset\CharsetConverter;
26 use TYPO3\CMS\Core\Charset\UnknownCharsetException;
27 use TYPO3\CMS\Core\Controller\ErrorPageController;
28 use TYPO3\CMS\Core\Database\ConnectionPool;
29 use TYPO3\CMS\Core\Database\Query\QueryHelper;
30 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
31 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
32 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
33 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
34 use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
35 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
36 use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
37 use TYPO3\CMS\Core\Localization\LanguageService;
38 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
39 use TYPO3\CMS\Core\Locking\LockFactory;
40 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
41 use TYPO3\CMS\Core\Log\LogManager;
42 use TYPO3\CMS\Core\Page\PageRenderer;
43 use TYPO3\CMS\Core\Resource\StorageRepository;
44 use TYPO3\CMS\Core\Service\DependencyOrderingService;
45 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
46 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
47 use TYPO3\CMS\Core\Type\Bitmask\Permission;
48 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
49 use TYPO3\CMS\Core\TypoScript\TemplateService;
50 use TYPO3\CMS\Core\Utility\ArrayUtility;
51 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
52 use TYPO3\CMS\Core\Utility\GeneralUtility;
53 use TYPO3\CMS\Core\Utility\HttpUtility;
54 use TYPO3\CMS\Core\Utility\MathUtility;
55 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
56 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
57 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
58 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
59 use TYPO3\CMS\Frontend\Page\PageRepository;
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 try {
847 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
848 $connection->connect();
849 } catch (DBALException $exception) {
850 // Cannot connect to current database
851 $message = sprintf(
852 'Cannot connect to the configured database. Connection failed with: "%s"',
853 $exception->getMessage()
854 );
855 $this->logger->emergency($message, ['exception' => $exception]);
856 try {
857 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
858 $this->sendResponseAndExit($response);
859 } catch (ServiceUnavailableException $e) {
860 throw new ServiceUnavailableException($message, 1301648782);
861 }
862 }
863 // Call post processing function for DB connection:
864 $_params = ['pObj' => &$this];
865 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] ?? [] as $_funcRef) {
866 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
867 }
868 }
869
870 /********************************************
871 *
872 * Initializing, resolving page id
873 *
874 ********************************************/
875 /**
876 * Initializes the caching system.
877 */
878 protected function initCaches()
879 {
880 $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
881 }
882
883 /**
884 * Initializes the front-end login user.
885 */
886 public function initFEuser()
887 {
888 $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
889 // List of pid's acceptable
890 $pid = GeneralUtility::_GP('pid');
891 $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
892 // Check if a session is transferred:
893 if (GeneralUtility::_GP('FE_SESSION_KEY')) {
894 $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
895 // If the session key hash check is OK:
896 if (md5($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) === (string)$fe_sParts[1]) {
897 $cookieName = FrontendUserAuthentication::getCookieName();
898 $_COOKIE[$cookieName] = $fe_sParts[0];
899 if (isset($_SERVER['HTTP_COOKIE'])) {
900 // See http://forge.typo3.org/issues/27740
901 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
902 }
903 $this->fe_user->forceSetCookie = true;
904 $this->fe_user->dontSetCookie = false;
905 unset($cookieName);
906 }
907 }
908 $this->fe_user->start();
909 $this->fe_user->unpack_uc();
910
911 // Call hook for possible manipulation of frontend user object
912 $_params = ['pObj' => &$this];
913 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] ?? [] as $_funcRef) {
914 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
915 }
916 }
917
918 /**
919 * Initializes the front-end user groups.
920 * Sets ->loginUser and ->gr_list based on front-end user status.
921 */
922 public function initUserGroups()
923 {
924 // This affects the hidden-flag selecting the fe_groups for the user!
925 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
926 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
927 $this->fe_user->fetchGroupData();
928 if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
929 // global flag!
930 $this->loginUser = true;
931 // 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!
932 $this->gr_list = '0,-2';
933 $gr_array = $this->fe_user->groupData['uid'];
934 } else {
935 $this->loginUser = false;
936 // 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!
937 $this->gr_list = '0,-1';
938 if ($this->loginAllowedInBranch) {
939 // 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.
940 $gr_array = $this->fe_user->groupData['uid'];
941 } else {
942 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
943 $gr_array = [];
944 }
945 }
946 // Clean up.
947 // Make unique...
948 $gr_array = array_unique($gr_array);
949 // sort
950 sort($gr_array);
951 if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
952 $this->gr_list .= ',' . implode(',', $gr_array);
953 }
954
955 // For every 60 seconds the is_online timestamp for a logged-in user is updated
956 if ($this->loginUser) {
957 $this->fe_user->updateOnlineTimestamp();
958 }
959
960 $this->logger->debug('Valid usergroups for TSFE: ' . $this->gr_list);
961 }
962
963 /**
964 * Checking if a user is logged in or a group constellation different from "0,-1"
965 *
966 * @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!)
967 */
968 public function isUserOrGroupSet()
969 {
970 return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
971 }
972
973 /**
974 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
975 *
976 * Two options:
977 * 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)
978 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
979 */
980 public function checkAlternativeIdMethods()
981 {
982 $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
983 // Call post processing function for custom URL methods.
984 $_params = ['pObj' => &$this];
985 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
986 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
987 }
988 }
989
990 /**
991 * Clears the preview-flags, sets sim_exec_time to current time.
992 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
993 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
994 */
995 public function clear_preview()
996 {
997 $this->showHiddenPage = false;
998 $this->showHiddenRecords = false;
999 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1000 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1001 $this->fePreview = 0;
1002 }
1003
1004 /**
1005 * Checks if a backend user is logged in
1006 *
1007 * @return bool whether a backend user is logged in
1008 */
1009 public function isBackendUserLoggedIn()
1010 {
1011 return (bool)$this->beUserLogin;
1012 }
1013
1014 /**
1015 * Creates the backend user object and returns it.
1016 *
1017 * @return FrontendBackendUserAuthentication the backend user object
1018 */
1019 public function initializeBackendUser()
1020 {
1021 // PRE BE_USER HOOK
1022 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] ?? [] as $_funcRef) {
1023 $_params = [];
1024 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1025 }
1026 $backendUserObject = null;
1027 // If the backend cookie is set,
1028 // we proceed and check if a backend user is logged in.
1029 if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1030 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1031 $this->getTimeTracker()->push('Back End user initialized', '');
1032 $this->beUserLogin = false;
1033 // New backend user object
1034 $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1035 $backendUserObject->start();
1036 $backendUserObject->unpack_uc();
1037 if (!empty($backendUserObject->user['uid'])) {
1038 $backendUserObject->fetchGroupData();
1039 }
1040 // Unset the user initialization if any setting / restriction applies
1041 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1042 $backendUserObject = null;
1043 } elseif (!empty($backendUserObject->user['uid'])) {
1044 // If the user is active now, let the controller know
1045 $this->beUserLogin = true;
1046 } else {
1047 $backendUserObject = null;
1048 }
1049 $this->getTimeTracker()->pull();
1050 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1051 }
1052 // POST BE_USER HOOK
1053 $_params = [
1054 'BE_USER' => &$backendUserObject
1055 ];
1056 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] ?? [] as $_funcRef) {
1057 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1058 }
1059 return $backendUserObject;
1060 }
1061
1062 /**
1063 * Determines the id and evaluates any preview settings
1064 * Basically this function is about determining whether a backend user is logged in,
1065 * if he has read access to the page and if he's previewing the page.
1066 * That all determines which id to show and how to initialize the id.
1067 */
1068 public function determineId()
1069 {
1070 // Call pre processing function for id determination
1071 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
1072 $parameters = ['parentObject' => $this];
1073 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1074 }
1075 // If there is a Backend login we are going to check for any preview settings
1076 $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
1077 // If the front-end is showing a preview, caching MUST be disabled.
1078 if ($this->fePreview) {
1079 $this->disableCache();
1080 }
1081 // Now, get the id, validate access etc:
1082 $this->fetch_the_id();
1083 // Check if backend user has read access to this page. If not, recalculate the id.
1084 if ($this->beUserLogin && $this->fePreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
1085 // Resetting
1086 $this->clear_preview();
1087 $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
1088 // Fetching the id again, now with the preview settings reset.
1089 $this->fetch_the_id();
1090 }
1091 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1092 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1093 // Logins are not allowed:
1094 if (!$this->loginAllowedInBranch) {
1095 // Only if there is a login will we run this...
1096 if ($this->isUserOrGroupSet()) {
1097 if ($this->loginAllowedInBranch_mode === 'all') {
1098 // Clear out user and group:
1099 $this->fe_user->hideActiveLogin();
1100 $this->gr_list = '0,-1';
1101 } else {
1102 $this->gr_list = '0,-2';
1103 }
1104 // Fetching the id again, now with the preview settings reset.
1105 $this->fetch_the_id();
1106 }
1107 }
1108 // Final cleaning.
1109 // Make sure it's an integer
1110 $this->id = ($this->contentPid = (int)$this->id);
1111 // Make sure it's an integer
1112 $this->type = (int)$this->type;
1113 // Call post processing function for id determination:
1114 $_params = ['pObj' => &$this];
1115 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1116 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1117 }
1118 }
1119
1120 /**
1121 * Evaluates admin panel or workspace settings to see if
1122 * visibility settings like
1123 * - $fePreview
1124 * - $showHiddenPage
1125 * - $showHiddenRecords
1126 * - $simUserGroup
1127 * should be applied to the current object.
1128 *
1129 * @param FrontendBackendUserAuthentication $backendUser
1130 * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
1131 * @private do not use this in your extension code.
1132 */
1133 protected function applyPreviewSettings($backendUser = null)
1134 {
1135 if (!$backendUser) {
1136 return null;
1137 }
1138 $originalFrontendUser = null;
1139 if ($this->fe_user->user) {
1140 $originalFrontendUser = $this->fe_user->user[$this->fe_user->usergroup_column];
1141 }
1142
1143 // The preview flag is set if the current page turns out to be hidden
1144 if ($this->id && $this->determineIdIsHiddenPage()) {
1145 $this->fePreview = 1;
1146 $this->showHiddenPage = true;
1147 }
1148 // The preview flag will be set if an offline workspace will be previewed
1149 if ($this->whichWorkspace() > 0) {
1150 $this->fePreview = 1;
1151 }
1152 return $this->simUserGroup ? $originalFrontendUser : null;
1153 }
1154
1155 /**
1156 * Checks if the page is hidden in the active workspace.
1157 * If it is hidden, preview flags will be set.
1158 *
1159 * @return bool
1160 */
1161 protected function determineIdIsHiddenPage()
1162 {
1163 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1164
1165 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1166 ->getQueryBuilderForTable('pages');
1167 $queryBuilder
1168 ->getRestrictions()
1169 ->removeAll()
1170 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1171
1172 $page = $queryBuilder
1173 ->select('uid', 'hidden', 'starttime', 'endtime')
1174 ->from('pages')
1175 ->where(
1176 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1177 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1178 )
1179 ->setMaxResults(1)
1180 ->execute()
1181 ->fetch();
1182
1183 if ($this->whichWorkspace() > 0) {
1184 // Fetch overlay of page if in workspace and check if it is hidden
1185 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1186 $pageSelectObject->versioningPreview = true;
1187 $pageSelectObject->init(false);
1188 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1189 $result = $targetPage === -1 || $targetPage === -2;
1190 } else {
1191 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1192 }
1193 return $result;
1194 }
1195
1196 /**
1197 * Resolves the page id and sets up several related properties.
1198 *
1199 * If $this->id is not set at all or is not a plain integer, the method
1200 * does it's best to set the value to an integer. Resolving is based on
1201 * this options:
1202 *
1203 * - Splitting $this->id if it contains an additional type parameter.
1204 * - Getting the id for an alias in $this->id
1205 * - Finding the domain record start page
1206 * - First visible page
1207 * - Relocating the id below the domain record if outside
1208 *
1209 * The following properties may be set up or updated:
1210 *
1211 * - id
1212 * - requestedId
1213 * - type
1214 * - domainStartPage
1215 * - sys_page
1216 * - sys_page->where_groupAccess
1217 * - sys_page->where_hid_del
1218 * - loginUser
1219 * - gr_list
1220 * - no_cache
1221 * - register['SYS_LASTCHANGED']
1222 * - pageNotFound
1223 *
1224 * Via getPageAndRootlineWithDomain()
1225 *
1226 * - rootLine
1227 * - page
1228 * - MP
1229 * - originalShortcutPage
1230 * - originalMountPointPage
1231 * - pageAccessFailureHistory['direct_access']
1232 * - pageNotFound
1233 *
1234 * @todo:
1235 *
1236 * On the first impression the method does to much. This is increased by
1237 * the fact, that is is called repeated times by the method determineId.
1238 * The reasons are manifold.
1239 *
1240 * 1.) The first part, the creation of sys_page, the type and alias
1241 * resolution don't need to be repeated. They could be separated to be
1242 * called only once.
1243 *
1244 * 2.) The user group setup could be done once on a higher level.
1245 *
1246 * 3.) The workflow of the resolution could be elaborated to be less
1247 * tangled. Maybe the check of the page id to be below the domain via the
1248 * root line doesn't need to be done each time, but for the final result
1249 * only.
1250 *
1251 * 4.) The root line does not need to be directly addressed by this class.
1252 * A root line is always related to one page. The rootline could be handled
1253 * indirectly by page objects. Page objects still don't exist.
1254 *
1255 * @throws ServiceUnavailableException
1256 * @access private
1257 */
1258 public function fetch_the_id()
1259 {
1260 $timeTracker = $this->getTimeTracker();
1261 $timeTracker->push('fetch_the_id initialize/', '');
1262 // Initialize the page-select functions.
1263 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1264 $this->sys_page->versioningPreview = $this->whichWorkspace() > 0 || (bool)GeneralUtility::_GP('ADMCMD_view');
1265 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1266 $this->sys_page->init($this->showHiddenPage);
1267 // Set the valid usergroups for FE
1268 $this->initUserGroups();
1269 // Sets sys_page where-clause
1270 $this->setSysPageWhereClause();
1271 // If $this->id is a string, it's an alias
1272 $this->checkAndSetAlias();
1273 // The id and type is set to the integer-value - just to be sure...
1274 $this->id = (int)$this->id;
1275 $this->type = (int)$this->type;
1276 $timeTracker->pull();
1277 // We find the first page belonging to the current domain
1278 $timeTracker->push('fetch_the_id domain/', '');
1279 if (!$this->id) {
1280 if ($this->domainStartPage) {
1281 // If the id was not previously set, set it to the id of the domain.
1282 $this->id = $this->domainStartPage;
1283 } else {
1284 // Find the first 'visible' page in that domain
1285 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1286 if ($theFirstPage) {
1287 $this->id = $theFirstPage['uid'];
1288 } else {
1289 $message = 'No pages are found on the rootlevel!';
1290 $this->logger->alert($message);
1291 try {
1292 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
1293 $this->sendResponseAndExit($response);
1294 } catch (ServiceUnavailableException $e) {
1295 throw new ServiceUnavailableException($message, 1301648975);
1296 }
1297 }
1298 }
1299 }
1300 $timeTracker->pull();
1301 $timeTracker->push('fetch_the_id rootLine/', '');
1302 // We store the originally requested id
1303 $this->requestedId = $this->id;
1304 try {
1305 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1306 } catch (ShortcutTargetPageNotFoundException $e) {
1307 $this->pageNotFound = 1;
1308 }
1309 $timeTracker->pull();
1310 // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1311 // Functional tests in workspaces currently
1312 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1313 $pNotFoundMsg = [
1314 1 => 'ID was not an accessible page',
1315 2 => 'Subsection was found and not accessible',
1316 3 => 'ID was outside the domain',
1317 4 => 'The requested page alias does not exist'
1318 ];
1319 $message = $pNotFoundMsg[$this->pageNotFound];
1320 if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1321 $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1322 } else {
1323 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1324 }
1325 $this->sendResponseAndExit($response);
1326 }
1327 // Init SYS_LASTCHANGED
1328 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1329 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1330 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1331 }
1332 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1333 $parameters = ['parentObject' => $this];
1334 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1335 }
1336 }
1337
1338 /**
1339 * Loads the page and root line records based on $this->id
1340 *
1341 * A final page and the matching root line are determined and loaded by
1342 * the algorithm defined by this method.
1343 *
1344 * First it loads the initial page from the page repository for $this->id.
1345 * If that can't be loaded directly, it gets the root line for $this->id.
1346 * It walks up the root line towards the root page until the page
1347 * repository can deliver a page record. (The loading restrictions of
1348 * the root line records are more liberal than that of the page record.)
1349 *
1350 * Now the page type is evaluated and handled if necessary. If the page is
1351 * a short cut, it is replaced by the target page. If the page is a mount
1352 * point in overlay mode, the page is replaced by the mounted page.
1353 *
1354 * After this potential replacements are done, the root line is loaded
1355 * (again) for this page record. It walks up the root line up to
1356 * the first viewable record.
1357 *
1358 * (While upon the first accessibility check of the root line it was done
1359 * by loading page by page from the page repository, this time the method
1360 * checkRootlineForIncludeSection() is used to find the most distant
1361 * accessible page within the root line.)
1362 *
1363 * Having found the final page id, the page record and the root line are
1364 * loaded for last time by this method.
1365 *
1366 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1367 * or root lines.
1368 *
1369 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1370 * instead of throwing an exception it's handled by a page unavailable
1371 * handler.
1372 *
1373 * May set or update this properties:
1374 *
1375 * @see TypoScriptFrontendController::$id
1376 * @see TypoScriptFrontendController::$MP
1377 * @see TypoScriptFrontendController::$page
1378 * @see TypoScriptFrontendController::$pageNotFound
1379 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1380 * @see TypoScriptFrontendController::$originalMountPointPage
1381 * @see TypoScriptFrontendController::$originalShortcutPage
1382 *
1383 * @throws ServiceUnavailableException
1384 * @throws PageNotFoundException
1385 * @access private
1386 */
1387 public function getPageAndRootline()
1388 {
1389 $this->resolveTranslatedPageId();
1390 if (empty($this->page)) {
1391 // If no page, we try to find the page before in the rootLine.
1392 // Page is 'not found' in case the id itself was not an accessible page. code 1
1393 $this->pageNotFound = 1;
1394 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1395 if (!empty($this->rootLine)) {
1396 $c = count($this->rootLine) - 1;
1397 while ($c > 0) {
1398 // Add to page access failure history:
1399 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1400 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1401 $c--;
1402 $this->id = $this->rootLine[$c]['uid'];
1403 $this->page = $this->sys_page->getPage($this->id);
1404 if (!empty($this->page)) {
1405 break;
1406 }
1407 }
1408 }
1409 // If still no page...
1410 if (empty($this->page)) {
1411 $message = 'The requested page does not exist!';
1412 $this->logger->error($message);
1413 try {
1414 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1415 $this->sendResponseAndExit($response);
1416 } catch (PageNotFoundException $e) {
1417 throw new PageNotFoundException($message, 1301648780);
1418 }
1419 }
1420 }
1421 // Spacer is not accessible in frontend
1422 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1423 $message = 'The requested page does not exist!';
1424 $this->logger->error($message);
1425 try {
1426 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1427 $this->sendResponseAndExit($response);
1428 } catch (PageNotFoundException $e) {
1429 throw new PageNotFoundException($message, 1301648781);
1430 }
1431 }
1432 // Is the ID a link to another page??
1433 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1434 // 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.
1435 $this->MP = '';
1436 // saving the page so that we can check later - when we know
1437 // about languages - whether we took the correct shortcut or
1438 // whether a translation of the page overwrites the shortcut
1439 // target and we need to follow the new target
1440 $this->originalShortcutPage = $this->page;
1441 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1442 $this->id = $this->page['uid'];
1443 }
1444 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1445 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1446 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1447 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1448 $this->originalMountPointPage = $this->page;
1449 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1450 if (empty($this->page)) {
1451 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1452 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1453 throw new PageNotFoundException($message, 1402043263);
1454 }
1455 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1456 $this->id = $this->page['uid'];
1457 }
1458 // Gets the rootLine
1459 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1460 // If not rootline we're off...
1461 if (empty($this->rootLine)) {
1462 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1463 $this->logger->error($message);
1464 try {
1465 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1466 $this->sendResponseAndExit($response);
1467 } catch (ServiceUnavailableException $e) {
1468 throw new ServiceUnavailableException($message, 1301648167);
1469 }
1470 }
1471 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1472 if ($this->checkRootlineForIncludeSection()) {
1473 if (empty($this->rootLine)) {
1474 $message = 'The requested page was not accessible!';
1475 try {
1476 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1477 $this->sendResponseAndExit($response);
1478 } catch (ServiceUnavailableException $e) {
1479 $this->logger->warning($message);
1480 throw new ServiceUnavailableException($message, 1301648234);
1481 }
1482 } else {
1483 $el = reset($this->rootLine);
1484 $this->id = $el['uid'];
1485 $this->page = $this->sys_page->getPage($this->id);
1486 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1487 }
1488 }
1489 }
1490
1491 /**
1492 * If $this->id contains a translated page record, this needs to be resolved to the default language
1493 * in order for all rootline functionality and access restrictions to be in place further on.
1494 *
1495 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1496 */
1497 protected function resolveTranslatedPageId()
1498 {
1499 $this->page = $this->sys_page->getPage($this->id);
1500 // Accessed a default language page record, nothing to resolve
1501 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1502 return;
1503 }
1504 $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1505 $this->sys_language_content = $this->sys_language_uid;
1506 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1507 $this->id = $this->page['uid'];
1508 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1509 $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1510 }
1511
1512 /**
1513 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1514 *
1515 * @param int $SC The value of the "shortcut" field from the pages record
1516 * @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
1517 * @param int $thisUid The current page UID of the page which is a shortcut
1518 * @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...)
1519 * @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.
1520 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1521 * @throws \RuntimeException
1522 * @throws ShortcutTargetPageNotFoundException
1523 * @return mixed Returns the page record of the page that the shortcut pointed to.
1524 * @access private
1525 * @see getPageAndRootline()
1526 */
1527 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1528 {
1529 $idArray = GeneralUtility::intExplode(',', $SC);
1530 // Find $page record depending on shortcut mode:
1531 switch ($mode) {
1532 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1533
1534 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1535 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1536 $pO = 0;
1537 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1538 $randval = (int)rand(0, count($pageArray) - 1);
1539 $pO = $randval;
1540 }
1541 $c = 0;
1542 $page = [];
1543 foreach ($pageArray as $pV) {
1544 if ($c === $pO) {
1545 $page = $pV;
1546 break;
1547 }
1548 $c++;
1549 }
1550 if (empty($page)) {
1551 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1552 throw new ShortcutTargetPageNotFoundException($message, 1301648328);
1553 }
1554 break;
1555 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1556 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1557 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1558 if (empty($page)) {
1559 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1560 throw new ShortcutTargetPageNotFoundException($message, 1301648358);
1561 }
1562 break;
1563 default:
1564 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1565 if (empty($page)) {
1566 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1567 throw new ShortcutTargetPageNotFoundException($message, 1301648404);
1568 }
1569 }
1570 // Check if short cut page was a shortcut itself, if so look up recursively:
1571 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1572 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1573 $pageLog[] = $page['uid'];
1574 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1575 } else {
1576 $pageLog[] = $page['uid'];
1577 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1578 $this->logger->error($message);
1579 throw new \RuntimeException($message, 1294587212);
1580 }
1581 }
1582 // Return resulting page:
1583 return $page;
1584 }
1585
1586 /**
1587 * Checks if visibility of the page is blocked upwards in the root line.
1588 *
1589 * If any page in the root line is blocking visibility, true is returend.
1590 *
1591 * All pages from the blocking page downwards are removed from the root
1592 * line, so that the remaning pages can be used to relocate the page up
1593 * to lowest visible page.
1594 *
1595 * The blocking feature of a page must be turned on by setting the page
1596 * record field 'extendToSubpages' to 1.
1597 *
1598 * The following fields are evaluated then:
1599 *
1600 * hidden, starttime, endtime, fe_group
1601 *
1602 * @todo Find a better name, i.e. checkVisibilityByRootLine
1603 * @todo Invert boolean return value. Return true if visible.
1604 *
1605 * @return bool
1606 * @access private
1607 */
1608 public function checkRootlineForIncludeSection(): bool
1609 {
1610 $c = count($this->rootLine);
1611 $removeTheRestFlag = false;
1612 for ($a = 0; $a < $c; $a++) {
1613 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1614 // Add to page access failure history:
1615 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1616 $removeTheRestFlag = true;
1617 }
1618
1619 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1620 // If there is a backend user logged in, check if he has read access to the page:
1621 if ($this->beUserLogin) {
1622 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1623 ->getQueryBuilderForTable('pages');
1624
1625 $queryBuilder
1626 ->getRestrictions()
1627 ->removeAll();
1628
1629 $row = $queryBuilder
1630 ->select('uid')
1631 ->from('pages')
1632 ->where(
1633 $queryBuilder->expr()->eq(
1634 'uid',
1635 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1636 ),
1637 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1638 )
1639 ->execute()
1640 ->fetch();
1641
1642 // versionOL()?
1643 if (!$row) {
1644 // 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...
1645 $removeTheRestFlag = true;
1646 }
1647 } else {
1648 // Don't go here, if there is no backend user logged in.
1649 $removeTheRestFlag = true;
1650 }
1651 }
1652 if ($removeTheRestFlag) {
1653 // Page is 'not found' in case a subsection was found and not accessible, code 2
1654 $this->pageNotFound = 2;
1655 unset($this->rootLine[$a]);
1656 }
1657 }
1658 return $removeTheRestFlag;
1659 }
1660
1661 /**
1662 * Checks page record for enableFields
1663 * Returns TRUE if enableFields does not disable the page record.
1664 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1665 *
1666 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1667 * @param bool $bypassGroupCheck Bypass group-check
1668 * @return bool TRUE, if record is viewable.
1669 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1670 */
1671 public function checkEnableFields($row, $bypassGroupCheck = false)
1672 {
1673 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1674 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1675 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1676 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1677 if ($return === false) {
1678 return false;
1679 }
1680 }
1681 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1682 return true;
1683 }
1684 return false;
1685 }
1686
1687 /**
1688 * Check group access against a page record
1689 *
1690 * @param array $row The page record to evaluate (needs field: fe_group)
1691 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1692 * @return bool TRUE, if group access is granted.
1693 * @access private
1694 */
1695 public function checkPageGroupAccess($row, $groupList = null)
1696 {
1697 if ($groupList === null) {
1698 $groupList = $this->gr_list;
1699 }
1700 if (!is_array($groupList)) {
1701 $groupList = explode(',', $groupList);
1702 }
1703 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1704 return count(array_intersect($groupList, $pageGroupList)) > 0;
1705 }
1706
1707 /**
1708 * Checks if the current page of the root line is visible.
1709 *
1710 * If the field extendToSubpages is 0, access is granted,
1711 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1712 *
1713 * @todo Find a better name, i.e. isVisibleRecord()
1714 *
1715 * @param array $row The page record
1716 * @return bool true if visible
1717 * @access private
1718 * @see checkEnableFields()
1719 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1720 * @see checkRootlineForIncludeSection()
1721 */
1722 public function checkPagerecordForIncludeSection(array $row): bool
1723 {
1724 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1725 }
1726
1727 /**
1728 * 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!)
1729 *
1730 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1731 */
1732 public function checkIfLoginAllowedInBranch()
1733 {
1734 // Initialize:
1735 $c = count($this->rootLine);
1736 $loginAllowed = true;
1737 // Traverse root line from root and outwards:
1738 for ($a = 0; $a < $c; $a++) {
1739 // If a value is set for login state:
1740 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1741 // Determine state from value:
1742 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1743 $loginAllowed = false;
1744 $this->loginAllowedInBranch_mode = 'all';
1745 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1746 $loginAllowed = false;
1747 $this->loginAllowedInBranch_mode = 'groups';
1748 } else {
1749 $loginAllowed = true;
1750 }
1751 }
1752 }
1753 return $loginAllowed;
1754 }
1755
1756 /**
1757 * 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
1758 *
1759 * @return array Summary of why page access was not allowed.
1760 */
1761 public function getPageAccessFailureReasons()
1762 {
1763 $output = [];
1764 $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'] : []);
1765 if (!empty($combinedRecords)) {
1766 foreach ($combinedRecords as $k => $pagerec) {
1767 // 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
1768 // 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!
1769 if (!$k || $pagerec['extendToSubpages']) {
1770 if ($pagerec['hidden']) {
1771 $output['hidden'][$pagerec['uid']] = true;
1772 }
1773 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1774 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1775 }
1776 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1777 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1778 }
1779 if (!$this->checkPageGroupAccess($pagerec)) {
1780 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1781 }
1782 }
1783 }
1784 }
1785 return $output;
1786 }
1787
1788 /**
1789 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1790 * If not inside domain, then default to first page in domain.
1791 *
1792 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1793 * @access private
1794 */
1795 public function getPageAndRootlineWithDomain($domainStartPage)
1796 {
1797 $this->getPageAndRootline();
1798 // 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.
1799 if ($domainStartPage && is_array($this->rootLine)) {
1800 $idFound = false;
1801 foreach ($this->rootLine as $key => $val) {
1802 if ($val['uid'] == $domainStartPage) {
1803 $idFound = true;
1804 break;
1805 }
1806 }
1807 if (!$idFound) {
1808 // Page is 'not found' in case the id was outside the domain, code 3
1809 $this->pageNotFound = 3;
1810 $this->id = $domainStartPage;
1811 // re-get the page and rootline if the id was not found.
1812 $this->getPageAndRootline();
1813 }
1814 }
1815 }
1816
1817 /**
1818 * Sets sys_page where-clause
1819 *
1820 * @access private
1821 */
1822 public function setSysPageWhereClause()
1823 {
1824 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1825 ->getConnectionForTable('pages')
1826 ->getExpressionBuilder();
1827 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1828 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1829 $expressionBuilder->lt('pages.doktype', 200)
1830 );
1831 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1832 }
1833
1834 /**
1835 * Page unavailable handler for use in frontend plugins from extensions.
1836 *
1837 * @param string $reason Reason text
1838 * @param string $header HTTP header to send
1839 * @deprecated
1840 */
1841 public function pageUnavailableAndExit($reason = '', $header = '')
1842 {
1843 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1844 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1845 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1846 die;
1847 }
1848
1849 /**
1850 * Page-not-found handler for use in frontend plugins from extensions.
1851 *
1852 * @param string $reason Reason text
1853 * @param string $header HTTP header to send
1854 * @deprecated
1855 */
1856 public function pageNotFoundAndExit($reason = '', $header = '')
1857 {
1858 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1859 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1860 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1861 die;
1862 }
1863
1864 /**
1865 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1866 * and devIPMask must not match the current visitor's IP address.
1867 *
1868 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1869 * @deprecated
1870 */
1871 public function checkPageUnavailableHandler()
1872 {
1873 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1874 if (
1875 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1876 && !GeneralUtility::cmpIP(
1877 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1878 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1879 )
1880 ) {
1881 $checkPageUnavailableHandler = true;
1882 } else {
1883 $checkPageUnavailableHandler = false;
1884 }
1885 return $checkPageUnavailableHandler;
1886 }
1887
1888 /**
1889 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1890 *
1891 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1892 * @param string $header If set, this is passed directly to the PHP function, header()
1893 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1894 * @deprecated
1895 */
1896 public function pageUnavailableHandler($code, $header, $reason)
1897 {
1898 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1899 $this->pageErrorHandler($code, $header, $reason);
1900 }
1901
1902 /**
1903 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1904 *
1905 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1906 * @param string $header If set, this is passed directly to the PHP function, header()
1907 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1908 * @deprecated
1909 */
1910 public function pageNotFoundHandler($code, $header = '', $reason = '')
1911 {
1912 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1913 $this->pageErrorHandler($code, $header, $reason);
1914 }
1915
1916 /**
1917 * Generic error page handler.
1918 * Exits.
1919 *
1920 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1921 * @param string $header If set, this is passed directly to the PHP function, header()
1922 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1923 * @throws \RuntimeException
1924 * @deprecated
1925 */
1926 public function pageErrorHandler($code, $header = '', $reason = '')
1927 {
1928 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1929 // Issue header in any case:
1930 if ($header) {
1931 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1932 foreach ($headerArr as $header) {
1933 header($header);
1934 }
1935 }
1936 // Create response:
1937 // Simply boolean; Just shows TYPO3 error page with reason:
1938 if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1939 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1940 'Page Not Found',
1941 'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1942 );
1943 } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1944 $funcRef = trim(substr($code, 14));
1945 $params = [
1946 'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1947 'reasonText' => $reason,
1948 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1949 ];
1950 try {
1951 echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1952 } catch (\Exception $e) {
1953 throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
1954 }
1955 } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
1956 $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
1957 if (@is_file($readFile)) {
1958 echo str_replace(
1959 [
1960 '###CURRENT_URL###',
1961 '###REASON###'
1962 ],
1963 [
1964 GeneralUtility::getIndpEnv('REQUEST_URI'),
1965 htmlspecialchars($reason)
1966 ],
1967 file_get_contents($readFile)
1968 );
1969 } else {
1970 throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
1971 }
1972 } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
1973 HttpUtility::redirect(substr($code, 9));
1974 } elseif ($code !== '') {
1975 // Check if URL is relative
1976 $url_parts = parse_url($code);
1977 // parse_url could return an array without the key "host", the empty check works better than strict check
1978 if (empty($url_parts['host'])) {
1979 $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1980 if ($code[0] === '/') {
1981 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
1982 } else {
1983 $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
1984 }
1985 $checkBaseTag = false;
1986 } else {
1987 $checkBaseTag = true;
1988 }
1989 // Check recursion
1990 if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
1991 if ($reason == '') {
1992 $reason = 'Page cannot be found.';
1993 }
1994 $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
1995 throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
1996 }
1997 // Prepare headers
1998 $headerArr = [
1999 'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2000 'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2001 ];
2002 $report = [];
2003 $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2004 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2005 throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2006 }
2007 // Header and content are separated by an empty line
2008 list($header, $content) = explode(CRLF . CRLF, $res, 2);
2009 $content .= CRLF;
2010 if (false === $res) {
2011 // Last chance -- redirect
2012 HttpUtility::redirect($code);
2013 } else {
2014 // Forward these response headers to the client
2015 $forwardHeaders = [
2016 'Content-Type:'
2017 ];
2018 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2019 foreach ($headerArr as $header) {
2020 foreach ($forwardHeaders as $h) {
2021 if (preg_match('/^' . $h . '/', $header)) {
2022 header($header);
2023 }
2024 }
2025 }
2026 // Put <base> if necessary
2027 if ($checkBaseTag) {
2028 // If content already has <base> tag, we do not need to do anything
2029 if (false === stristr($content, '<base ')) {
2030 // Generate href for base tag
2031 $base = $url_parts['scheme'] . '://';
2032 if ($url_parts['user'] != '') {
2033 $base .= $url_parts['user'];
2034 if ($url_parts['pass'] != '') {
2035 $base .= ':' . $url_parts['pass'];
2036 }
2037 $base .= '@';
2038 }
2039 $base .= $url_parts['host'];
2040 // Add path portion skipping possible file name
2041 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2042 // Put it into content (generate also <head> if necessary)
2043 $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2044 if (stristr($content, '<head>')) {
2045 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2046 } else {
2047 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2048 }
2049 }
2050 }
2051 // Output the content
2052 echo $content;
2053 }
2054 } else {
2055 echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2056 'Page Not Found',
2057 $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2058 );
2059 }
2060 die;
2061 }
2062
2063 /**
2064 * Fetches the integer page id for a page alias.
2065 * 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
2066 *
2067 * @access private
2068 */
2069 public function checkAndSetAlias()
2070 {
2071 if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2072 $aid = $this->sys_page->getPageIdFromAlias($this->id);
2073 if ($aid) {
2074 $this->id = $aid;
2075 } else {
2076 $this->pageNotFound = 4;
2077 }
2078 }
2079 }
2080
2081 /**
2082 * Merging values into the global $_GET
2083 *
2084 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2085 */
2086 public function mergingWithGetVars($GET_VARS)
2087 {
2088 if (is_array($GET_VARS)) {
2089 // Getting $_GET var, unescaped.
2090 $realGet = GeneralUtility::_GET();
2091 if (!is_array($realGet)) {
2092 $realGet = [];
2093 }
2094 // Merge new values on top:
2095 ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2096 // Write values back to $_GET:
2097 GeneralUtility::_GETset($realGet);
2098 // Setting these specifically (like in the init-function):
2099 if (isset($GET_VARS['type'])) {
2100 $this->type = (int)$GET_VARS['type'];
2101 }
2102 if (isset($GET_VARS['cHash'])) {
2103 $this->cHash = $GET_VARS['cHash'];
2104 }
2105 if (isset($GET_VARS['MP'])) {
2106 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2107 }
2108 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2109 $this->set_no_cache('no_cache is requested via GET parameter');
2110 }
2111 }
2112 }
2113
2114 /********************************************
2115 *
2116 * Template and caching related functions.
2117 *
2118 *******************************************/
2119 /**
2120 * Calculates a hash string based on additional parameters in the url.
2121 *
2122 * Calculated hash is stored in $this->cHash_array.
2123 * This is used to cache pages with more parameters than just id and type.
2124 *
2125 * @see reqCHash()
2126 */
2127 public function makeCacheHash()
2128 {
2129 // No need to test anything if caching was already disabled.
2130 if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2131 return;
2132 }
2133 $GET = GeneralUtility::_GET();
2134 if ($this->cHash && is_array($GET)) {
2135 // Make sure we use the page uid and not the page alias
2136 $GET['id'] = $this->id;
2137 $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2138 $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2139 if (!hash_equals($cHash_calc, $this->cHash)) {
2140 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2141 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Request parameters could not be validated (&cHash comparison failed)');
2142 $this->sendResponseAndExit($response);
2143 } else {
2144 $this->disableCache();
2145 $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);
2146 }
2147 }
2148 } elseif (is_array($GET)) {
2149 // No cHash is set, check if that is correct
2150 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2151 $this->reqCHash();
2152 }
2153 }
2154 }
2155
2156 /**
2157 * Will disable caching if the cHash value was not set.
2158 * 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)
2159 *
2160 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2161 */
2162 public function reqCHash()
2163 {
2164 if (!$this->cHash) {
2165 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2166 if ($this->tempContent) {
2167 $this->clearPageCacheContent();
2168 }
2169 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Request parameters could not be validated (&cHash empty)');
2170 $this->sendResponseAndExit($response);
2171 } else {
2172 $this->disableCache();
2173 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2174 }
2175 }
2176 }
2177
2178 /**
2179 * Initialize the TypoScript template parser
2180 */
2181 public function initTemplate()
2182 {
2183 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2184 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2185 $this->tmpl->init();
2186 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2187 }
2188
2189 /**
2190 * See if page is in cache and get it if so
2191 * Stores the page content in $this->content if something is found.
2192 *
2193 * @throws \InvalidArgumentException
2194 * @throws \RuntimeException
2195 */
2196 public function getFromCache()
2197 {
2198 // clearing the content-variable, which will hold the pagecontent
2199 $this->content = '';
2200 // Unsetting the lowlevel config
2201 $this->config = [];
2202 $this->cacheContentFlag = false;
2203
2204 if ($this->no_cache) {
2205 return;
2206 }
2207
2208 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2209 if (!is_array($pageSectionCacheContent)) {
2210 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2211 // We use the Registry to store this lock centrally,
2212 // but we protect the access again with a global exclusive lock to avoid race conditions
2213
2214 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2215 //
2216 // from this point on we're the only one working on that page ($key)
2217 //
2218
2219 // query the cache again to see if the page data are there meanwhile
2220 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2221 if (is_array($pageSectionCacheContent)) {
2222 // we have the content, nice that some other process did the work for us already
2223 $this->releaseLock('pagesection');
2224 }
2225 // We keep the lock set, because we are the ones generating the page now
2226 // and filling the cache.
2227 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2228 }
2229
2230 if (is_array($pageSectionCacheContent)) {
2231 // 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.
2232 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2233 // 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.
2234 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2235 ksort($pageSectionCacheContent);
2236 $this->all = $pageSectionCacheContent;
2237 }
2238 unset($pageSectionCacheContent);
2239
2240 // Look for page in cache only if a shift-reload is not sent to the server.
2241 $lockHash = $this->getLockHash();
2242 if (!$this->headerNoCache()) {
2243 if ($this->all) {
2244 // we got page section information
2245 $this->newHash = $this->getHash();
2246 $this->getTimeTracker()->push('Cache Row', '');
2247 $row = $this->getFromCache_queryRow();
2248 if (!is_array($row)) {
2249 // nothing in the cache, we acquire an exclusive lock now
2250
2251 $this->acquireLock('pages', $lockHash);
2252 //
2253 // from this point on we're the only one working on that page ($lockHash)
2254 //
2255
2256 // query the cache again to see if the data are there meanwhile
2257 $row = $this->getFromCache_queryRow();
2258 if (is_array($row)) {
2259 // we have the content, nice that some other process did the work for us
2260 $this->releaseLock('pages');
2261 }
2262 // We keep the lock set, because we are the ones generating the page now
2263 // and filling the cache.
2264 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2265 }
2266 if (is_array($row)) {
2267 // we have data from cache
2268
2269 // Call hook when a page is retrieved from cache:
2270 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2271 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2272 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2273 }
2274 // Fetches the lowlevel config stored with the cached data
2275 $this->config = $row['cache_data'];
2276 // Getting the content
2277 $this->content = $row['content'];
2278 // Flag for temp content
2279 $this->tempContent = $row['temp_content'];
2280 // Setting flag, so we know, that some cached content has been loaded
2281 $this->cacheContentFlag = true;
2282 $this->cacheExpires = $row['expires'];
2283
2284 // Restore page title information, this is needed to generate the page title for
2285 // partially cached pages.
2286 $this->page['title'] = $row['pageTitleInfo']['title'];
2287 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2288 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2289
2290 if (isset($this->config['config']['debug'])) {
2291 $debugCacheTime = (bool)$this->config['config']['debug'];
2292 } else {
2293 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2294 }
2295 if ($debugCacheTime) {
2296 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2297 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2298 $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $row['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $row['expires']) . ' -->';
2299 }
2300 }
2301 $this->getTimeTracker()->pull();
2302
2303 return;
2304 }
2305 }
2306 // the user forced rebuilding the page cache or there was no pagesection information
2307 // get a lock for the page content so other processes will not interrupt the regeneration
2308 $this->acquireLock('pages', $lockHash);
2309 }
2310
2311 /**
2312 * Returning the cached version of page with hash = newHash
2313 *
2314 * @return array Cached row, if any. Otherwise void.
2315 */
2316 public function getFromCache_queryRow()
2317 {
2318 $this->getTimeTracker()->push('Cache Query', '');
2319 $row = $this->pageCache->get($this->newHash);
2320 $this->getTimeTracker()->pull();
2321 return $row;
2322 }
2323
2324 /**
2325 * Detecting if shift-reload has been clicked
2326 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2327 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2328 *
2329 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2330 */
2331 public function headerNoCache()
2332 {
2333 $disableAcquireCacheData = false;
2334 if ($this->beUserLogin) {
2335 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2336 $disableAcquireCacheData = true;
2337 }
2338 }
2339 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2340 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2341 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2342 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2343 }
2344 return $disableAcquireCacheData;
2345 }
2346
2347 /**
2348 * Calculates the cache-hash
2349 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2350 * Used to get and later store the cached data.
2351 *
2352 * @return string MD5 hash of serialized hash base from createHashBase()
2353 * @access private
2354 * @see getFromCache(), getLockHash()
2355 */
2356 public function getHash()
2357 {
2358 return md5($this->createHashBase(false));
2359 }
2360
2361 /**
2362 * Calculates the lock-hash
2363 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2364 *
2365 * @return string MD5 hash
2366 * @access private
2367 * @see getFromCache(), getHash()
2368 */
2369 public function getLockHash()
2370 {
2371 $lockHash = $this->createHashBase(true);
2372 return md5($lockHash);
2373 }
2374
2375 /**
2376 * Calculates the cache-hash (or the lock-hash)
2377 * This hash is unique to the template,
2378 * the variables ->id, ->type, ->gr_list (list of groups),
2379 * ->MP (Mount Points) and cHash array
2380 * Used to get and later store the cached data.
2381 *
2382 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2383 * @return string the serialized hash base
2384 */
2385 protected function createHashBase($createLockHashBase = false)
2386 {
2387 // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
2388 // is not cached properly as we don't have any language-specific conditions anymore
2389 $siteBase = $this->getCurrentSiteLanguage() ? $this->getCurrentSiteLanguage()->getBase() : '';
2390 $hashParameters = [
2391 'id' => (int)$this->id,
2392 'type' => (int)$this->type,
2393 'gr_list' => (string)$this->gr_list,
2394 'MP' => (string)$this->MP,
2395 'siteBase' => $siteBase,
2396 'cHash' => $this->cHash_array,
2397 'domainStartPage' => $this->domainStartPage
2398 ];
2399 // Include the template information if we shouldn't create a lock hash
2400 if (!$createLockHashBase) {
2401 $hashParameters['all'] = $this->all;
2402 }
2403 // Call hook to influence the hash calculation
2404 $_params = [
2405 'hashParameters' => &$hashParameters,
2406 'createLockHashBase' => $createLockHashBase
2407 ];
2408 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2409 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2410 }
2411 return serialize($hashParameters);
2412 }
2413
2414 /**
2415 * Checks if config-array exists already but if not, gets it
2416 *
2417 * @throws ServiceUnavailableException
2418 */
2419 public function getConfigArray()
2420 {
2421 // 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
2422 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2423 $timeTracker = $this->getTimeTracker();
2424 $timeTracker->push('Parse template', '');
2425 // Force parsing, if set?:
2426 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2427 // Start parsing the TS template. Might return cached version.
2428 $this->tmpl->start($this->rootLine);
2429 $timeTracker->pull();
2430 if ($this->tmpl->loaded) {
2431 $timeTracker->push('Setting the config-array', '');
2432 // toplevel - objArrayName
2433 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2434 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2435 if (!is_array($this->pSetup)) {
2436 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2437 $this->logger->alert($message);
2438 try {
2439 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
2440 $this->sendResponseAndExit($response);
2441 } catch (ServiceUnavailableException $e) {
2442 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2443 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2444 }
2445 } else {
2446 if (!isset($this->config['config'])) {
2447 $this->config['config'] = [];
2448 }
2449 // Filling the config-array, first with the main "config." part
2450 if (is_array($this->tmpl->setup['config.'])) {
2451 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2452 $this->config['config'] = $this->tmpl->setup['config.'];
2453 }
2454 // override it with the page/type-specific "config."
2455 if (is_array($this->pSetup['config.'])) {
2456 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2457 }
2458 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2459 if ($this->config['config']['typolinkCheckRootline']) {
2460 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2461 }
2462 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2463 if (!isset($this->config['config']['removeDefaultJS'])) {
2464 $this->config['config']['removeDefaultJS'] = 'external';
2465 }
2466 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2467 $this->config['config']['inlineStyle2TempFile'] = 1;
2468 }
2469
2470 if (!isset($this->config['config']['compressJs'])) {
2471 $this->config['config']['compressJs'] = 0;
2472 }
2473 // Processing for the config_array:
2474 $this->config['rootLine'] = $this->tmpl->rootLine;
2475 // Class for render Header and Footer parts
2476 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2477 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2478 if ($file) {
2479 $this->pageRenderer->setTemplateFile($file);
2480 }
2481 }
2482 }
2483 $timeTracker->pull();
2484 } else {
2485 $message = 'No TypoScript template found!';
2486 $this->logger->alert($message);
2487 try {
2488 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
2489 $this->sendResponseAndExit($response);
2490 } catch (ServiceUnavailableException $e) {
2491 throw new ServiceUnavailableException($message, 1294587218);
2492 }
2493 }
2494 }
2495
2496 // No cache
2497 // Set $this->no_cache TRUE if the config.no_cache value is set!
2498 if ($this->config['config']['no_cache']) {
2499 $this->set_no_cache('config.no_cache is set');
2500 }
2501 // Merge GET with defaultGetVars
2502 if (!empty($this->config['config']['defaultGetVars.'])) {
2503 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2504 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2505 GeneralUtility::_GETset($modifiedGetVars);
2506 }
2507
2508 // Auto-configure settings when a site is configured
2509 if ($this->getCurrentSiteLanguage()) {
2510 $this->config['config']['absRefPrefix'] = $this->config['config']['absRefPrefix'] ?? 'auto';
2511 }
2512
2513 // Hook for postProcessing the configuration array
2514 $params = ['config' => &$this->config['config']];
2515 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2516 GeneralUtility::callUserFunction($funcRef, $params, $this);
2517 }
2518 }
2519
2520 /********************************************
2521 *
2522 * Further initialization and data processing
2523 *
2524 *******************************************/
2525
2526 /**
2527 * Setting the language key that will be used by the current page.
2528 * 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.
2529 *
2530 * @access private
2531 */
2532 public function settingLanguage()
2533 {
2534 $_params = [];
2535 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2536 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2537 }
2538
2539 $siteLanguage = $this->getCurrentSiteLanguage();
2540
2541 // Initialize charset settings etc.
2542 if ($siteLanguage) {
2543 $languageKey = $siteLanguage->getTypo3Language();
2544 } else {
2545 $languageKey = $this->config['config']['language'] ?? 'default';
2546 }
2547 $this->lang = $languageKey;
2548 $this->setOutputLanguage($languageKey);
2549
2550 // Rendering charset of HTML page.
2551 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2552 $this->metaCharset = $this->config['config']['metaCharset'];
2553 }
2554
2555 // Get values from site language
2556 if ($siteLanguage) {
2557 $this->sys_language_uid = ($this->sys_language_content = $siteLanguage->getLanguageId());
2558 $this->sys_language_mode = $siteLanguage->getFallbackType();
2559 if ($this->sys_language_mode === 'fallback') {
2560 $fallbackOrder = $siteLanguage->getFallbackLanguageIds();
2561 $fallbackOrder[] = 'pageNotFound';
2562 }
2563 } else {
2564 // Get values from TypoScript, if not set before
2565 if ($this->sys_language_uid === 0) {
2566 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2567 }
2568 list($this->sys_language_mode, $fallbackOrder) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2569 if (!empty($fallbackOrder)) {
2570 $fallBackOrder = GeneralUtility::trimExplode(',', $fallbackOrder);
2571 } else {
2572 $fallBackOrder = [0];
2573 }
2574 }
2575
2576 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2577 // If sys_language_uid is set to another language than default:
2578 if ($this->sys_language_uid > 0) {
2579 // check whether a shortcut is overwritten by a translated page
2580 // we can only do this now, as this is the place where we get
2581 // to know about translations
2582 $this->checkTranslatedShortcut();
2583 // Request the overlay record for the sys_language_uid:
2584 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2585 if (empty($olRec)) {
2586 // If no OL record exists and a foreign language is asked for...
2587 if ($this->sys_language_uid) {
2588 // If requested translation is not available:
2589 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2590 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language.');
2591 $this->sendResponseAndExit($response);
2592 } else {
2593 switch ((string)$this->sys_language_mode) {
2594 case 'strict':
2595 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language (strict).');
2596 $this->sendResponseAndExit($response);
2597 break;
2598 case 'fallback':
2599 case 'content_fallback':
2600 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2601 // value was found.
2602 foreach ($fallBackOrder ?? [] as $orderValue) {
2603 if ($orderValue === '0' || $orderValue === 0 || $orderValue === '') {
2604 $this->sys_language_content = 0;
2605 break;
2606 }
2607 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2608 $this->sys_language_content = (int)$orderValue;
2609 break;
2610 }
2611 if ($orderValue === 'pageNotFound') {
2612 // The existing fallbacks have not been found, but instead of continuing
2613 // page rendering with default language, a "page not found" message should be shown
2614 // instead.
2615 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language (fallbacks did not apply).');
2616 $this->sendResponseAndExit($response);
2617 }
2618 }
2619 break;
2620 case 'ignore':
2621 $this->sys_language_content = $this->sys_language_uid;
2622 break;
2623 default:
2624 // Default is that everything defaults to the default language...
2625 $this->sys_language_uid = ($this->sys_language_content = 0);
2626 }
2627 }
2628 }
2629 } else {
2630 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2631 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2632 }
2633 }
2634 // Setting sys_language_uid inside sys-page:
2635 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2636 // If default translation is not available:
2637 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2638 $message = 'Page is not available in default language.';
2639 $this->logger->error($message);
2640 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message);
2641 $this->sendResponseAndExit($response);
2642 }
2643 $this->updateRootLinesWithTranslations();
2644
2645 // Finding the ISO code for the currently selected language
2646 // fetched by the sys_language record when not fetching content from the default language
2647 if ($siteLanguage = $this->getCurrentSiteLanguage()) {
2648 $this->sys_language_isocode = $siteLanguage->getTwoLetterIsoCode();
2649 } elseif ($this->sys_language_content > 0) {
2650 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2651 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2652 // avoid versioning overlay to be applied as it generates an SQL error
2653 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2654 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2655 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2656 }
2657 // the DB value is overridden by TypoScript
2658 if (!empty($this->config['config']['sys_language_isocode'])) {
2659 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2660 }
2661 } else {
2662 // fallback to the TypoScript option when rendering with sys_language_uid=0
2663 // also: use "en" by default
2664 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2665 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2666 } else {
2667 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2668 }
2669 }
2670
2671 $_params = [];
2672 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2673 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2674 }
2675 }
2676
2677 /**
2678 * Updating content of the two rootLines IF the language key is set!
2679 */
2680 protected function updateRootLinesWithTranslations()
2681 {
2682 if ($this->sys_language_uid) {
2683 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2684 $this->tmpl->updateRootlineData($this->rootLine);
2685 }
2686 }
2687
2688 /**
2689 * Setting locale for frontend rendering
2690 */
2691 public function settingLocale()
2692 {
2693 // Setting locale
2694 $locale = $this->config['config']['locale_all'];
2695 $siteLanguage = $this->getCurrentSiteLanguage();
2696 if ($siteLanguage) {
2697 $locale = $siteLanguage->getLocale();
2698 }
2699 if ($locale) {
2700 $availableLocales = GeneralUtility::trimExplode(',', $locale, true);
2701 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2702 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2703 // @see https://bugs.php.net/bug.php?id=53711
2704 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2705 if ($locale) {
2706 // As str_* methods are locale aware and turkish has no upper case I
2707 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2708 // @see http://bugs.php.net/bug.php?id=35050
2709 if (substr($locale, 0, 2) !== 'tr') {
2710 setlocale(LC_CTYPE, ...$availableLocales);
2711 }
2712 setlocale(LC_MONETARY, ...$availableLocales);
2713 setlocale(LC_TIME, ...$availableLocales);
2714 } else {
2715 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($locale) . '" not found.', 3);
2716 }
2717 }
2718 }
2719
2720 /**
2721 * Checks whether a translated shortcut page has a different shortcut
2722 * target than the original language page.
2723 * If that is the case, things get corrected to follow that alternative
2724 * shortcut
2725 */
2726 protected function checkTranslatedShortcut()
2727 {
2728 if (!is_null($this->originalShortcutPage)) {
2729 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2730 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2731 // the translation of the original shortcut page has a different shortcut target!
2732 // set the correct page and id
2733 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2734 $this->id = ($this->contentPid = $shortcut['uid']);
2735 $this->page = $this->sys_page->getPage($this->id);
2736 // Fix various effects on things like menus f.e.
2737 $this->fetch_the_id();
2738 $this->tmpl->rootLine = array_reverse($this->rootLine);
2739 }
2740 }
2741 }
2742
2743 /**
2744 * Handle data submission
2745 * This is done at this point, because we need the config values
2746 */
2747 public function handleDataSubmission()
2748 {
2749 // Hook for processing data submission to extensions
2750 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2751 $_procObj = GeneralUtility::makeInstance($className);
2752 $_procObj->checkDataSubmission($this);
2753 }
2754 }
2755
2756 /**
2757 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2758 *
2759 * @see $activeRedirectUrlHandlers
2760 */
2761 public function initializeRedirectUrlHandlers()
2762 {
2763 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2764 if (!$urlHandlers) {
2765 return;
2766 }
2767
2768 foreach ($urlHandlers as $identifier => $configuration) {
2769 if (empty($configuration) || !is_array($configuration)) {
2770 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2771 }
2772 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2773 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2774 }
2775 }
2776
2777 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2778
2779 foreach ($orderedHandlers as $configuration) {
2780 /** @var UrlHandlerInterface $urlHandler */
2781 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2782 if ($urlHandler->canHandleCurrentUrl()) {
2783 $this->activeUrlHandlers[] = $urlHandler;
2784 }
2785 }
2786 }
2787
2788 /**
2789 * Loops over all registered URL handlers and lets them process the current URL.
2790 *
2791 * If no handler has stopped the current process (e.g. by redirecting) and a
2792 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2793 *
2794 * @internal Should be called by the FrontendRequestHandler only.
2795 * @return ResponseInterface|null
2796 */
2797 public function redirectToExternalUrl()
2798 {
2799 foreach ($this->activeUrlHandlers as $redirectHandler) {
2800 $response = $redirectHandler->handle();
2801 if ($response instanceof ResponseInterface) {
2802 return $response;
2803 }
2804 }
2805
2806 if (!empty($this->activeUrlHandlers)) {
2807 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2808 }
2809
2810 return null;
2811 }
2812
2813 /**
2814 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2815 * This feature allows sessions to use a GET-parameter instead of a cookie.
2816 *
2817 * @access private
2818 */
2819 public function setUrlIdToken()
2820 {
2821 if ($this->config['config']['ftu']) {
2822 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2823 } else {
2824 $this->getMethodUrlIdToken = '';
2825 }
2826 }
2827
2828 /**
2829 * Calculates and sets the internal linkVars based upon the current
2830 * $_GET parameters and the setting "config.linkVars".
2831 */
2832 public function calculateLinkVars()
2833 {
2834 $this->linkVars = '';
2835 if (empty($this->config['config']['linkVars'])) {
2836 return;
2837 }
2838
2839 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2840
2841 if (empty($linkVars)) {
2842 return;
2843 }
2844 $getData = GeneralUtility::_GET();
2845 foreach ($linkVars as $linkVar) {
2846 $test = $value = '';
2847 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2848 $linkVar = trim($match[1]);
2849 $test = trim($match[2]);
2850 }
2851
2852 $keys = explode('|', $linkVar);
2853 $numberOfLevels = count($keys);
2854 $rootKey = trim($keys[0]);
2855 if (!isset($getData[$rootKey])) {
2856 continue;
2857 }
2858 $value = $getData[$rootKey];
2859 for ($i = 1; $i < $numberOfLevels; $i++) {
2860 $currentKey = trim($keys[$i]);
2861 if (isset($value[$currentKey])) {
2862 $value = $value[$currentKey];
2863 } else {
2864 $value = false;
2865 break;
2866 }
2867 }
2868 if ($value !== false) {
2869 $parameterName = $keys[0];
2870 for ($i = 1; $i < $numberOfLevels; $i++) {
2871 $parameterName .= '[' . $keys[$i] . ']';
2872 }
2873 if (!is_array($value)) {
2874 $temp = rawurlencode($value);
2875 if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2876 // Error: This value was not allowed for this key
2877 continue;
2878 }
2879 $value = '&' . $parameterName . '=' . $temp;
2880 } else {
2881 if ($test !== '' && $test !== 'array') {
2882 // Error: This key must not be an array!
2883 continue;
2884 }
2885 $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2886 }
2887 $this->linkVars .= $value;
2888 }
2889 }
2890 }
2891
2892 /**
2893 * Split the link vars string by "," but not if the "," is inside of braces
2894 *
2895 * @param $string
2896 *
2897 * @return array
2898 */
2899 protected function splitLinkVarsString(string $string): array
2900 {
2901 $tempCommaReplacementString = '###KASPER###';
2902
2903 // replace every "," wrapped in "()" by a "unique" string
2904 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2905 return str_replace(',', $tempCommaReplacementString, $result[0]);
2906 }, $string);
2907
2908 $string = GeneralUtility::trimExplode(',', $string);
2909
2910 // replace all "unique" strings back to ","
2911 return str_replace($tempCommaReplacementString, ',', $string);
2912 }
2913
2914 /**
2915 * Checks if the value defined in "config.linkVars" contains an allowed value.
2916 * Otherwise, return FALSE which means the value will not be added to any links.
2917 *
2918 * @param string $haystack The string in which to find $needle
2919 * @param string $needle The string to find in $haystack
2920 * @return bool Returns TRUE if $needle matches or is found in $haystack
2921 */
2922 protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2923 {
2924 $isAllowed = false;
2925 // Integer
2926 if ($needle === 'int' || $needle === 'integer') {
2927 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2928 $isAllowed = true;
2929 }
2930 } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2931 // Regular expression, only "//" is allowed as delimiter
2932 if (@preg_match($needle, $haystack)) {
2933 $isAllowed = true;