2 namespace TYPO3\CMS\Frontend\Controller
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
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\Compatibility\PublicMethodDeprecationTrait
;
28 use TYPO3\CMS\Core\Context\Context
;
29 use TYPO3\CMS\Core\Context\DateTimeAspect
;
30 use TYPO3\CMS\Core\Context\LanguageAspect
;
31 use TYPO3\CMS\Core\Context\LanguageAspectFactory
;
32 use TYPO3\CMS\Core\Context\UserAspect
;
33 use TYPO3\CMS\Core\Context\VisibilityAspect
;
34 use TYPO3\CMS\Core\Context\WorkspaceAspect
;
35 use TYPO3\CMS\Core\Controller\ErrorPageController
;
36 use TYPO3\CMS\Core\Core\Environment
;
37 use TYPO3\CMS\Core\Database\ConnectionPool
;
38 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
;
39 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction
;
40 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction
;
41 use TYPO3\CMS\Core\Error\Http\PageNotFoundException
;
42 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException
;
43 use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException
;
44 use TYPO3\CMS\Core\Exception\Page\RootLineException
;
45 use TYPO3\CMS\Core\Http\ImmediateResponseException
;
46 use TYPO3\CMS\Core\Http\ServerRequestFactory
;
47 use TYPO3\CMS\Core\Localization\LanguageService
;
48 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException
;
49 use TYPO3\CMS\Core\Locking\LockFactory
;
50 use TYPO3\CMS\Core\Locking\LockingStrategyInterface
;
51 use TYPO3\CMS\Core\Log\LogManager
;
52 use TYPO3\CMS\Core\Page\PageRenderer
;
53 use TYPO3\CMS\Core\PageTitle\PageTitleProviderManager
;
54 use TYPO3\CMS\Core\
Resource\StorageRepository
;
55 use TYPO3\CMS\Core\Routing\PageArguments
;
56 use TYPO3\CMS\Core\Service\DependencyOrderingService
;
57 use TYPO3\CMS\Core\Site\Entity\Site
;
58 use TYPO3\CMS\Core\Site\Entity\SiteLanguage
;
59 use TYPO3\CMS\Core\TimeTracker\TimeTracker
;
60 use TYPO3\CMS\Core\Type\Bitmask\Permission
;
61 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
;
62 use TYPO3\CMS\Core\TypoScript\TemplateService
;
63 use TYPO3\CMS\Core\Utility\ArrayUtility
;
64 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
65 use TYPO3\CMS\Core\Utility\GeneralUtility
;
66 use TYPO3\CMS\Core\Utility\HttpUtility
;
67 use TYPO3\CMS\Core\Utility\MathUtility
;
68 use TYPO3\CMS\Core\Utility\PathUtility
;
69 use TYPO3\CMS\Core\Utility\RootlineUtility
;
70 use TYPO3\CMS\Extbase\
Object\ObjectManager
;
71 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication
;
72 use TYPO3\CMS\Frontend\Compatibility\LegacyDomainResolver
;
73 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
;
74 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface
;
75 use TYPO3\CMS\Frontend\Page\CacheHashCalculator
;
76 use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons
;
77 use TYPO3\CMS\Frontend\Page\PageRepository
;
78 use TYPO3\CMS\Frontend\
Resource\FilePathSanitizer
;
81 * Class for the built TypoScript based frontend. Instantiated in
82 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
84 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
85 * as the global object TSFE.
87 * This class has a lot of functions and internal variable which are used from
88 * \TYPO3\CMS\Frontend\Http\RequestHandler
90 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
92 * The use of this class should be inspired by the order of function calls as
93 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
95 class TypoScriptFrontendController
implements LoggerAwareInterface
98 use PublicMethodDeprecationTrait
;
100 protected $deprecatedPublicMethods = [
101 'tempPageCacheContent' => 'Using $TSFE->tempPageCacheContent() has been marked as internal as its purpose is to be managed from within TSFE directly.',
102 'realPageCacheContent' => 'Using $TSFE->realPageCacheContent() has been marked as internal as its purpose is to be managed from within TSFE directly.',
103 'setPageCacheContent' => 'Using $TSFE->setPageCacheContent() has been marked as internal as its purpose is to be managed from within TSFE directly.',
104 'clearPageCacheContent_pidList' => 'Using $TSFE->clearPageCacheContent_pidList() has been marked as internal as its purpose is to be managed from within TSFE directly.',
105 'setSysLastChanged' => 'Using $TSFE->setSysLastChanged() has been marked as internal as its purpose is to be managed from within TSFE directly.',
106 'contentStrReplace' => 'Using $TSFE->contentStrReplace() has been marked as internal as its purpose is to be managed from within TSFE directly.',
107 'mergingWithGetVars' => '$TSFE->mergingWithGetVars() will be removed in TYPO3 v10.0. Use a middleware instead to override the PSR-7 request object AND set $_GET on top to achieve the same result.',
117 * The type (read-only)
123 * The submitted cHash
133 protected $pageArguments;
136 * Page will not be cached. Write only TRUE. Never clear value (some other
137 * code might have reasons to set it TRUE).
140 public $no_cache = false;
143 * The rootLine (all the way to tree root, not only the current site!)
146 public $rootLine = '';
155 * This will normally point to the same value as id, but can be changed to
156 * point to another page from which content will then be displayed instead.
159 public $contentPid = 0;
162 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
163 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
164 * should be redirected to.
168 protected $originalMountPointPage;
171 * Gets set when we are processing a page of type shortcut in the early stages
172 * of the request when we do not know about languages yet, used later in the request
173 * to determine the correct shortcut in case a translation changes the shortcut
176 * @see checkTranslatedShortcut()
178 protected $originalShortcutPage;
181 * sys_page-object, pagefunctions
183 * @var PageRepository
185 public $sys_page = '';
188 * Contains all URL handler instances that are active for the current request.
190 * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
192 * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
193 * @see initializeRedirectUrlHandlers()
194 * @deprecated since TYPO3 v9.3, will be removed in TYPO3 v10.0.
196 protected $activeUrlHandlers = [];
199 * Is set to 1 if a pageNotFound handler could have been called.
203 public $pageNotFound = 0;
210 public $domainStartPage = 0;
213 * Array containing a history of why a requested page was not accessible.
215 * @deprecated this value has a protected visibility now, as it is only used for internal purpose. Use "getPageAccessFailureReasons()" instead.
217 protected $pageAccessFailureHistory = [];
226 * This can be set from applications as a way to tag cached versions of a page
227 * and later perform some external cache management, like clearing only a part
228 * of the cache of a page...
230 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
232 public $page_cache_reg1 = 0;
235 * Contains the value of the current script path that activated the frontend.
236 * Typically "index.php" but by rewrite rules it could be something else! Used
237 * for Speaking Urls / Simulate Static Documents.
241 public $siteScript = '';
246 * @var FrontendUserAuthentication
248 public $fe_user = '';
251 * Global flag indicating that a frontend user is logged in. This is set only if
252 * a user really IS logged in. The group-list may show other groups (like added
253 * by IP filter or so) even though there is no user.
255 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "frontend.user" aspect.
257 protected $loginUser = false;
260 * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
261 * group, but other groups may be added by other means than a user being logged
264 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "frontend.user" aspect.
266 protected $gr_list = '';
269 * Flag that indicates if a backend user is logged in!
271 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "backend.user" aspect.
273 protected $beUserLogin = false;
276 * Integer, that indicates which workspace is being previewed.
277 * Not in use anymore, as this is part of the workspace preview functionality, use $TSFE->whichWorkspace() instead.
279 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "workspace" aspect.
281 protected $workspacePreview = 0;
284 * Shows whether logins are allowed in branch
287 protected $loginAllowedInBranch = true;
290 * Shows specific mode (all or groups)
294 protected $loginAllowedInBranch_mode = '';
297 * Set to backend user ID to initialize when keyword-based preview is used
299 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "backend.user" aspect.
301 protected $ADMCMD_preview_BEUSER_uid = 0;
304 * Flag indication that preview is active. This is based on the login of a
305 * backend user and whether the backend user has read access to the current
310 public $fePreview = 0;
313 * Flag indicating that hidden pages should be shown, selected and so on. This
314 * goes for almost all selection of pages!
316 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "visibility" aspect.
318 protected $showHiddenPage = false;
321 * Flag indicating that hidden records should be shown. This includes
322 * sys_template and even fe_groups in addition to all
323 * other regular content. So in effect, this includes everything except pages.
325 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. User the information within the context "visibility" aspect.
327 protected $showHiddenRecords = false;
330 * Value that contains the simulated usergroup if any
332 * @internal only to be used in AdminPanel, and within TYPO3 Core
334 public $simUserGroup = 0;
337 * "CONFIG" object from TypoScript. Array generated based on the TypoScript
338 * configuration of the current page. Saved with the cached pages.
344 * The TypoScript template object. Used to parse the TypoScript template
346 * @var TemplateService
351 * Is set to the time-to-live time of cached pages. If FALSE, default is
352 * 60*60*24, which is 24 hours.
356 protected $cacheTimeOutDefault = false;
359 * Set internally if cached content is fetched from the database. No matter if it is temporary
360 * content (tempContent) or already generated page content.
365 protected $cacheContentFlag = false;
368 * Set to the expire time of cached content
372 protected $cacheExpires = 0;
375 * Set if cache headers allowing caching are sent.
379 protected $isClientCachable = false;
382 * Used by template fetching system. This array is an identification of
383 * the template. If $this->all is empty it's because the template-data is not
384 * cached, which it must be.
390 * Toplevel - objArrayName, eg 'page'
396 * TypoScript configuration of the page-object pointed to by sPre.
397 * $this->tmpl->setup[$this->sPre.'.']
403 * This hash is unique to the template, the $this->id and $this->type vars and
404 * the gr_list (list of groups). Used to get and later store the cached data
408 public $newHash = '';
411 * If config.ftu (Frontend Track User) is set in TypoScript for the current
412 * page, the string value of this var is substituted in the rendered source-code
413 * with the string, '&ftu=[token...]' which enables GET-method usertracking as
414 * opposed to cookie based
418 public $getMethodUrlIdToken = '';
421 * This flag is set before inclusion of RequestHandler IF no_cache is set. If this
422 * flag is set after the inclusion of RequestHandler, no_cache is forced to be set.
423 * This is done in order to make sure that php-code from pagegen does not falsely
424 * clear the no_cache flag.
428 protected $no_cacheBeforePageGen = false;
431 * This flag indicates if temporary content went into the cache during page-generation.
432 * When the message is set to "this page is being generated", TYPO3 Frontend indicates this way
433 * that the current page request is fully cached, and needs no page generation.
437 protected $tempContent = false;
440 * Passed to TypoScript template class and tells it to force template rendering
443 public $forceTemplateParsing = false;
446 * The array which cHash_calc is based on, see PageArgumentValidator class.
450 public $cHash_array = [];
453 * May be set to the pagesTSconfig
457 protected $pagesTSconfig = '';
460 * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
461 * once. Use associative keys.
465 * used to accumulate additional HTML-code for the header-section,
466 * <head>...</head>. Insert either associative keys (like
467 * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
468 * (like additionalHeaderData[] = '...')
472 public $additionalHeaderData = [];
475 * Used to accumulate additional HTML-code for the footer-section of the template
478 public $additionalFooterData = [];
481 * Used to accumulate additional JavaScript-code. Works like
482 * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
486 public $additionalJavaScript = [];
489 * Used to accumulate additional Style code. Works like additionalHeaderData.
493 public $additionalCSS = [];
506 * Used to accumulate DHTML-layers.
509 public $divSection = '';
512 * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
514 * @deprecated this property is not in use anymore and will be removed in TYPO3 v10.0.
516 protected $debug = false;
519 * Default internal target
522 public $intTarget = '';
525 * Default external target
528 public $extTarget = '';
531 * Default file link target
534 public $fileTarget = '';
537 * Keys are page ids and values are default &MP (mount point) values to set
538 * when using the linking features...)
540 * @deprecated this property is not in use anymore and will be removed in TYPO3 v10.0.
542 protected $MP_defaults = [];
545 * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
548 public $spamProtectEmailAddresses = 0;
551 * Absolute Reference prefix
554 public $absRefPrefix = '';
560 public $ATagParams = '';
563 * Search word regex, calculated if there has been search-words send. This is
564 * used to mark up the found search words on a page when jumped to from a link
565 * in a search-result.
569 public $sWordRegEx = '';
572 * Is set to the incoming array sword_list in case of a page-view jumped to from
577 public $sWordList = '';
580 * A string prepared for insertion in all links on the page as url-parameters.
581 * Based on configuration in TypoScript where you defined which GET_VARS you
582 * would like to pass on.
585 public $linkVars = '';
588 * If set, edit icons are rendered aside content records. Must be set only if
589 * the ->beUserLogin flag is set and set_no_cache() must be called as well.
592 public $displayEditIcons = '';
595 * If set, edit icons are rendered aside individual fields of content. Must be
596 * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
600 public $displayFieldEditIcons = '';
603 * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
604 * record. Should reflect which language menus, templates etc is displayed in
605 * (master language) - but not necessarily the content which could be falling
606 * back to default (see sys_language_content)
608 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0 - use LanguageAspect->getId() instead.
610 protected $sys_language_uid = 0;
613 * Site language mode for content fall back.
615 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0 - use LanguageAspect->getFallbackChain() instead.
617 protected $sys_language_mode = '';
620 * Site content selection uid (can be different from sys_language_uid if content
621 * is to be selected from a fall-back language. Depends on sys_language_mode)
623 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0 - use LanguageAspect->getContentId() instead.
625 protected $sys_language_content = 0;
628 * Site content overlay flag; If set - and sys_language_content is > 0 - ,
629 * records selected will try to look for a translation pointing to their uid. (If
630 * configured in [ctrl][languageField] / [ctrl][transOrigP...]
631 * Possible values: [0,1,hideNonTranslated]
632 * This flag is set based on TypoScript config.sys_language_overlay setting
635 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0 - use LanguageAspect->getOverlayType() instead.
637 protected $sys_language_contentOL = 0;
640 * Is set to the iso code of the sys_language_content if that is properly defined
641 * by the sys_language record representing the sys_language_uid.
644 public $sys_language_isocode = '';
647 * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
651 public $applicationData = [];
656 public $register = [];
659 * Stack used for storing array and retrieving register arrays (see
660 * LOAD_REGISTER and RESTORE_REGISTER)
663 public $registerStack = [];
666 * Checking that the function is not called eternally. This is done by
667 * interrupting at a depth of 50
670 public $cObjectDepthCounter = 50;
673 * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
674 * rendered twice through it!
677 public $recordRegister = [];
680 * This is set to the [table]:[uid] of the latest record rendered. Note that
681 * class ContentObjectRenderer has an equal value, but that is pointing to the
682 * record delivered in the $data-array of the ContentObjectRenderer instance, if
683 * the cObjects CONTENT or RECORD created that instance
686 public $currentRecord = '';
689 * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
690 * to keep track of access-keys.
693 public $accessKey = [];
696 * Numerical array where image filenames are added if they are referenced in the
697 * rendered document. This includes only TYPO3 generated/inserted images.
700 public $imagesOnPage = [];
703 * Is set in ContentObjectRenderer->cImage() function to the info-array of the
704 * most recent rendered image. The information is used in ImageTextContentObject
707 public $lastImageInfo = [];
710 * Used to generate page-unique keys. Point is that uniqid() functions is very
711 * slow, so a unikey key is made based on this, see function uniqueHash()
715 protected $uniqueCounter = 0;
721 protected $uniqueString = '';
724 * This value will be used as the title for the page in the indexer (if
728 public $indexedDocTitle = '';
731 * Alternative page title (normally the title of the page record). Can be set
732 * from applications you make.
736 public $altPageTitle = '';
739 * The base URL set for the page header.
742 public $baseUrl = '';
745 * IDs we already rendered for this page (to make sure they are unique)
747 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0
749 private $usedUniqueIds = [];
752 * Page content render object
754 * @var ContentObjectRenderer
759 * All page content is accumulated in this variable. See RequestHandler
762 public $content = '';
765 * Output charset of the websites content. This is the charset found in the
766 * header, meta tag etc. If different than utf-8 a conversion
767 * happens before output to browser. Defaults to utf-8.
770 public $metaCharset = 'utf-8';
773 * Set to the system language key (used on the site)
777 protected $lang = '';
780 * Internal calculations for labels
782 * @var LanguageService
784 protected $languageService;
787 * @var LockingStrategyInterface[][]
789 protected $locks = [];
794 protected $pageRenderer;
797 * The page cache object, use this to save pages to the cache and to
798 * retrieve them again
800 * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
802 protected $pageCache;
807 protected $pageCacheTags = [];
810 * The cHash Service class used for cHash related functionality
812 * @var CacheHashCalculator
814 protected $cacheHash;
817 * Content type HTTP header being sent in the request.
818 * @todo Ticket: #63642 Should be refactored to a request/response model later
819 * @internal Should only be used by TYPO3 core for now
823 protected $contentType = 'text/html';
830 public $xhtmlDoctype = '';
835 public $xhtmlVersion;
838 * Originally requested id from the initial $_GET variable
842 protected $requestedId;
845 * The context for keeping the current state, mostly related to current page information,
846 * backend user / frontend user access, workspaceId
854 * Takes a number of GET/POST input variable as arguments and stores them internally.
855 * The processing of these variables goes on later in this class.
856 * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
858 * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
859 * @param mixed $id The value of GeneralUtility::_GP('id')
860 * @param int $type The value of GeneralUtility::_GP('type')
861 * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0, will be unused in TYPO3 v10.0.
862 * @param string $cHash The value of GeneralUtility::_GP('cHash')
863 * @param string $_2 previously was used to define the jumpURL
864 * @param string $MP The value of GeneralUtility::_GP('MP')
866 public function __construct($_ = null, $id, $type, $no_cache = null, $cHash = '', $_2 = null, $MP = '')
868 // Setting some variables:
871 if ($no_cache !== null) {
872 trigger_error('Calling TypoScriptFrontendController->__construct() with $no_cache argument set will be removed in TYPO3 v10.0. Use ->set_no_cache() instead.', E_USER_DEPRECATED
);
874 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
875 $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
876 $this->getTimeTracker()->setTSlogMessage($warning, 2);
878 $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL') . '"';
879 $this->disableCache();
881 // note: we need to instantiate the logger manually here since the injection happens after the constructor
882 GeneralUtility
::makeInstance(LogManager
::class)->getLogger(__CLASS__
)->warning($warning);
885 $this->cHash
= $cHash;
886 $this->MP
= $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ?
(string)$MP : '';
887 $this->uniqueString
= md5(microtime());
888 $this->initPageRenderer();
889 // Call post processing function for constructor:
890 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
891 trigger_error('The "tslib_fe-PostProc" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED
);
892 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
893 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
896 $this->cacheHash
= GeneralUtility
::makeInstance(CacheHashCalculator
::class);
898 // Use the global context for now
899 $this->context
= GeneralUtility
::makeInstance(Context
::class);
903 * Initializes the page renderer object
905 protected function initPageRenderer()
907 if ($this->pageRenderer
!== null) {
910 $this->pageRenderer
= GeneralUtility
::makeInstance(PageRenderer
::class);
911 $this->pageRenderer
->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
915 * @param string $contentType
916 * @internal Should only be used by TYPO3 core for now
918 public function setContentType($contentType)
920 $this->contentType
= $contentType;
924 * Connect to SQL database. May exit after outputting an error message
925 * or some JavaScript redirecting to the install tool.
927 * @throws \RuntimeException
928 * @throws ServiceUnavailableException
929 * @deprecated since TYPO3 v9.3, will be removed in TYPO3 v10.0.
931 public function connectToDB()
933 trigger_error('The method "' . __METHOD__
. '" will be removed in TYPO3 v10.0, as the database connection is checked in the TypoScriptFrontendInitialization middleware.', E_USER_DEPRECATED
);
935 $connection = GeneralUtility
::makeInstance(ConnectionPool
::class)->getConnectionForTable('pages');
936 $connection->connect();
937 } catch (DBALException
$exception) {
938 // Cannot connect to current database
940 'Cannot connect to the configured database. Connection failed with: "%s"',
941 $exception->getMessage()
943 $this->logger
->emergency($message, ['exception' => $exception]);
945 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
946 $GLOBALS['TYPO3_REQUEST'],
948 ['code' => PageAccessFailureReasons
::DATABASE_CONNECTION_FAILED
]
950 throw new ImmediateResponseException($response, 1533931298);
951 } catch (ServiceUnavailableException
$e) {
952 throw new ServiceUnavailableException($message, 1301648782);
955 // Call post processing function for DB connection
956 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'])) {
957 trigger_error('The "connectToDB" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED
);
958 $_params = ['pObj' => &$this];
959 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef) {
960 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
965 /********************************************
967 * Initializing, resolving page id
969 ********************************************/
971 * Initializes the caching system.
973 protected function initCaches()
975 $this->pageCache
= GeneralUtility
::makeInstance(CacheManager
::class)->getCache('cache_pages');
979 * Initializes the front-end login user.
980 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0. Use the PSR-15 middleware instead to set up the Frontend User object.
982 public function initFEuser()
984 trigger_error('$TSFE->initFEuser() will be removed in TYPO3 v10.0. Use the FrontendUserAuthenticator middleware instead to initialize a Frontend User object.', E_USER_DEPRECATED
);
985 $this->fe_user
= GeneralUtility
::makeInstance(FrontendUserAuthentication
::class);
986 // List of pid's acceptable
987 $pid = GeneralUtility
::_GP('pid');
988 $this->fe_user
->checkPid_value
= $pid ?
implode(',', GeneralUtility
::intExplode(',', $pid)) : 0;
989 // Check if a session is transferred:
990 if (GeneralUtility
::_GP('FE_SESSION_KEY')) {
991 $fe_sParts = explode('-', GeneralUtility
::_GP('FE_SESSION_KEY'));
992 // If the session key hash check is OK:
993 if (md5($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) === (string)$fe_sParts[1]) {
994 $cookieName = FrontendUserAuthentication
::getCookieName();
995 $_COOKIE[$cookieName] = $fe_sParts[0];
996 if (isset($_SERVER['HTTP_COOKIE'])) {
997 // See http://forge.typo3.org/issues/27740
998 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
1000 $this->fe_user
->forceSetCookie
= true;
1001 $this->fe_user
->dontSetCookie
= false;
1005 $this->fe_user
->start();
1006 $this->fe_user
->unpack_uc();
1008 // Call hook for possible manipulation of frontend user object
1009 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'])) {
1010 trigger_error('The "initFEuser" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED
);
1011 $_params = ['pObj' => &$this];
1012 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef) {
1013 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1019 * Initializes the front-end user groups.
1020 * Sets frontend.user aspect based on front-end user status.
1022 public function initUserGroups()
1025 // This affects the hidden-flag selecting the fe_groups for the user!
1026 $this->fe_user
->showHiddenRecords
= $this->context
->getPropertyFromAspect('visibility', 'includeHiddenContent', false);
1027 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
1028 $this->fe_user
->fetchGroupData();
1029 $isUserAndGroupSet = is_array($this->fe_user
->user
) && !empty($this->fe_user
->groupData
['uid']);
1030 if ($isUserAndGroupSet) {
1031 // group -2 is not an existing group, but denotes a 'default' group when a user IS logged in.
1032 // This is used to let elements be shown for all logged in users!
1034 $groupsFromUserRecord = $this->fe_user
->groupData
['uid'];
1036 // group -1 is not an existing group, but denotes a 'default' group when not logged in.
1037 // This is used to let elements be hidden, when a user is logged in!
1039 if ($this->loginAllowedInBranch
) {
1040 // 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.
1041 $groupsFromUserRecord = $this->fe_user
->groupData
['uid'];
1043 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
1044 $groupsFromUserRecord = [];
1048 // Make unique and sort the groups
1049 $groupsFromUserRecord = array_unique($groupsFromUserRecord);
1050 if (!empty($groupsFromUserRecord) && !$this->loginAllowedInBranch_mode
) {
1051 sort($groupsFromUserRecord);
1052 $userGroups = array_merge($userGroups, array_map('intval', $groupsFromUserRecord));
1055 $this->context
->setAspect('frontend.user', GeneralUtility
::makeInstance(UserAspect
::class, $this->fe_user ?
: null, $userGroups));
1057 // For every 60 seconds the is_online timestamp for a logged-in user is updated
1058 if ($isUserAndGroupSet) {
1059 $this->fe_user
->updateOnlineTimestamp();
1062 $this->logger
->debug('Valid usergroups for TSFE: ' . implode(',', $userGroups));
1066 * Checking if a user is logged in or a group constellation different from "0,-1"
1068 * @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!)
1070 public function isUserOrGroupSet()
1072 /** @var UserAspect $userAspect */
1073 $userAspect = $this->context
->getAspect('frontend.user');
1074 return $userAspect->isUserOrGroupSet();
1078 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
1081 * 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)
1082 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
1084 * @deprecated since TYPO3 v9.3, will be removed in TYPO3 v10.0.
1086 public function checkAlternativeIdMethods()
1088 trigger_error('$TSFE->checkAlternativeIdMethods() will removed in TYPO3 v10.0, extensions should use a Frontend PSR-15-based middleware to hook into the frontend process. There is no need to call this method directly.', E_USER_DEPRECATED
);
1089 $this->siteScript
= GeneralUtility
::getIndpEnv('TYPO3_SITE_SCRIPT');
1090 // Call post processing function for custom URL methods.
1091 $_params = ['pObj' => &$this];
1092 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ??
[] as $_funcRef) {
1093 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1098 * Clears the preview-flags, sets sim_exec_time to current time.
1099 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
1100 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
1102 public function clear_preview()
1104 if ($this->fePreview
1105 ||
$GLOBALS['EXEC_TIME'] !== $GLOBALS['SIM_EXEC_TIME']
1106 ||
$this->context
->getPropertyFromAspect('visibility', 'includeHiddenPages', false)
1107 ||
$this->context
->getPropertyFromAspect('visibility', 'includeHiddenContent', false)
1109 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1110 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1111 $this->fePreview
= 0;
1112 $this->context
->setAspect('date', GeneralUtility
::makeInstance(DateTimeAspect
::class, new \
DateTimeImmutable('@' . $GLOBALS['SIM_EXEC_TIME'])));
1113 $this->context
->setAspect('visibility', GeneralUtility
::makeInstance(VisibilityAspect
::class));
1118 * Checks if a backend user is logged in
1120 * @return bool whether a backend user is logged in
1122 public function isBackendUserLoggedIn()
1124 return (bool)$this->context
->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
1128 * Creates the backend user object and returns it.
1130 * @return FrontendBackendUserAuthentication the backend user object
1131 * @deprecated since TYPO3 v9.3, will be removed in TYPO3 v10.0.
1133 public function initializeBackendUser()
1135 trigger_error('$TSFE->initializeBackendUser() will be removed in TYPO3 v10.0. Extensions should ensure that the BackendAuthenticator middleware is run to load a backend user.', E_USER_DEPRECATED
);
1137 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'])) {
1138 trigger_error('The "preBeUser" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED
);
1139 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] as $_funcRef) {
1141 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1144 $backendUserObject = null;
1145 // If the backend cookie is set,
1146 // we proceed and check if a backend user is logged in.
1147 if ($_COOKIE[BackendUserAuthentication
::getCookieName()]) {
1148 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1149 $this->getTimeTracker()->push('Back End user initialized');
1150 $this->beUserLogin
= false;
1151 // New backend user object
1152 $backendUserObject = GeneralUtility
::makeInstance(FrontendBackendUserAuthentication
::class);
1153 $backendUserObject->start();
1154 $backendUserObject->unpack_uc();
1155 if (!empty($backendUserObject->user
['uid'])) {
1156 $backendUserObject->fetchGroupData();
1158 // Unset the user initialization if any setting / restriction applies
1159 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp() ||
empty($backendUserObject->user
['uid'])) {
1160 $backendUserObject = null;
1162 $this->getTimeTracker()->pull();
1163 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1165 $this->context
->setAspect('backend.user', GeneralUtility
::makeInstance(UserAspect
::class, $backendUserObject));
1166 $this->context
->setAspect('workspace', GeneralUtility
::makeInstance(WorkspaceAspect
::class, $backendUserObject ?
$backendUserObject->workspace
: 0));
1167 // POST BE_USER HOOK
1168 if (!empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'])) {
1169 trigger_error('The "postBeUser" hook will be removed in TYPO3 v10.0 in favor of PSR-15. Use a middleware instead.', E_USER_DEPRECATED
);
1170 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'])) {
1172 'BE_USER' => &$backendUserObject
1174 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] as $_funcRef) {
1175 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1177 // Set the aspect again, in case it got changed
1178 $this->context
->setAspect('backend.user', GeneralUtility
::makeInstance(UserAspect
::class, $backendUserObject));
1179 $this->context
->setAspect('workspace', GeneralUtility
::makeInstance(WorkspaceAspect
::class, $backendUserObject ?
$backendUserObject->workspace
: 0));
1182 return $backendUserObject;
1186 * Determines the id and evaluates any preview settings
1187 * Basically this function is about determining whether a backend user is logged in,
1188 * if he has read access to the page and if he's previewing the page.
1189 * That all determines which id to show and how to initialize the id.
1191 public function determineId()
1193 // Call pre processing function for id determination
1194 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ??
[] as $functionReference) {
1195 $parameters = ['parentObject' => $this];
1196 GeneralUtility
::callUserFunction($functionReference, $parameters, $this);
1198 // If there is a Backend login we are going to check for any preview settings
1199 $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
1200 // If the front-end is showing a preview, caching MUST be disabled.
1201 if ($this->fePreview
) {
1202 $this->disableCache();
1204 // Now, get the id, validate access etc:
1205 $this->fetch_the_id();
1206 // Check if backend user has read access to this page. If not, recalculate the id.
1207 if ($this->isBackendUserLoggedIn() && $this->fePreview
&& !$this->getBackendUser()->doesUserHaveAccess($this->page
, Permission
::PAGE_SHOW
)) {
1209 $this->clear_preview();
1210 $this->fe_user
->user
[$this->fe_user
->usergroup_column
] = $originalFrontendUserGroups;
1211 // Fetching the id again, now with the preview settings reset.
1212 $this->fetch_the_id();
1214 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1215 $this->loginAllowedInBranch
= $this->checkIfLoginAllowedInBranch();
1216 // Logins are not allowed, but there is a login, so will we run this.
1217 if (!$this->loginAllowedInBranch
&& $this->isUserOrGroupSet()) {
1218 if ($this->loginAllowedInBranch_mode
=== 'all') {
1219 // Clear out user and group:
1220 $this->fe_user
->hideActiveLogin();
1221 $userGroups = [0, -1];
1223 $userGroups = [0, -2];
1225 $this->context
->setAspect('frontend.user', GeneralUtility
::makeInstance(UserAspect
::class, $this->fe_user ?
: null, $userGroups));
1226 // Fetching the id again, now with the preview settings reset.
1227 $this->fetch_the_id();
1230 // Make sure it's an integer
1231 $this->id
= ($this->contentPid
= (int)$this->id
);
1232 // Make sure it's an integer
1233 $this->type
= (int)$this->type
;
1234 // Call post processing function for id determination:
1235 $_params = ['pObj' => &$this];
1236 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ??
[] as $_funcRef) {
1237 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1242 * Evaluates admin panel or workspace settings to see if
1243 * visibility settings like
1245 * - Visibility Aspect: includeHiddenPages
1246 * - Visibility Aspect: includeHiddenPontent
1248 * should be applied to the current object.
1250 * @param FrontendBackendUserAuthentication $backendUser
1251 * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
1254 protected function applyPreviewSettings($backendUser = null)
1256 if (!$backendUser) {
1259 $originalFrontendUserGroup = null;
1260 if ($this->fe_user
->user
) {
1261 $originalFrontendUserGroup = $this->fe_user
->user
[$this->fe_user
->usergroup_column
];
1264 // The preview flag is set if the current page turns out to be hidden
1265 if ($this->id
&& $this->determineIdIsHiddenPage()) {
1266 $this->fePreview
= 1;
1267 /** @var VisibilityAspect $aspect */
1268 $aspect = $this->context
->getAspect('visibility');
1269 $newAspect = GeneralUtility
::makeInstance(VisibilityAspect
::class, true, $aspect->includeHiddenContent(), $aspect->includeDeletedRecords());
1270 $this->context
->setAspect('visibility', $newAspect);
1272 // The preview flag will be set if an offline workspace will be previewed
1273 if ($this->whichWorkspace() > 0) {
1274 $this->fePreview
= 1;
1276 return $this->simUserGroup ?
$originalFrontendUserGroup : null;
1280 * Checks if the page is hidden in the active workspace.
1281 * If it is hidden, preview flags will be set.
1285 protected function determineIdIsHiddenPage()
1287 $field = MathUtility
::canBeInterpretedAsInteger($this->id
) ?
'uid' : 'alias';
1289 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1290 ->getQueryBuilderForTable('pages');
1294 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1296 $page = $queryBuilder
1297 ->select('uid', 'hidden', 'starttime', 'endtime')
1300 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id
)),
1301 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
))
1307 if ($this->whichWorkspace() > 0) {
1308 // Fetch overlay of page if in workspace and check if it is hidden
1309 $customContext = clone $this->context
;
1310 $customContext->setAspect('workspace', GeneralUtility
::makeInstance(WorkspaceAspect
::class, $this->whichWorkspace()));
1311 $customContext->setAspect('visibility', GeneralUtility
::makeInstance(VisibilityAspect
::class));
1312 $pageSelectObject = GeneralUtility
::makeInstance(PageRepository
::class, $customContext);
1313 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1314 $result = $targetPage === -1 ||
$targetPage === -2;
1316 $result = is_array($page) && ($page['hidden'] ||
$page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] ||
$page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1322 * Resolves the page id and sets up several related properties.
1324 * If $this->id is not set at all or is not a plain integer, the method
1325 * does it's best to set the value to an integer. Resolving is based on
1328 * - Splitting $this->id if it contains an additional type parameter.
1329 * - Getting the id for an alias in $this->id
1330 * - Finding the domain record start page
1331 * - First visible page
1332 * - Relocating the id below the domain record if outside
1334 * The following properties may be set up or updated:
1341 * - sys_page->where_groupAccess
1342 * - sys_page->where_hid_del
1343 * - Context: FrontendUser Aspect
1345 * - register['SYS_LASTCHANGED']
1348 * Via getPageAndRootlineWithDomain()
1353 * - originalShortcutPage
1354 * - originalMountPointPage
1355 * - pageAccessFailureHistory['direct_access']
1360 * On the first impression the method does to much. This is increased by
1361 * the fact, that is is called repeated times by the method determineId.
1362 * The reasons are manifold.
1364 * 1.) The first part, the creation of sys_page, the type and alias
1365 * resolution don't need to be repeated. They could be separated to be
1368 * 2.) The user group setup could be done once on a higher level.
1370 * 3.) The workflow of the resolution could be elaborated to be less
1371 * tangled. Maybe the check of the page id to be below the domain via the
1372 * root line doesn't need to be done each time, but for the final result
1375 * 4.) The root line does not need to be directly addressed by this class.
1376 * A root line is always related to one page. The rootline could be handled
1377 * indirectly by page objects. Page objects still don't exist.
1379 * @throws ServiceUnavailableException
1382 public function fetch_the_id()
1384 $timeTracker = $this->getTimeTracker();
1385 $timeTracker->push('fetch_the_id initialize/');
1386 // Set the valid usergroups for FE
1387 $this->initUserGroups();
1388 // Initialize the PageRepository has to be done after the frontend usergroups are initialized / resolved, as
1389 // frontend group aspect is modified before
1390 $this->sys_page
= GeneralUtility
::makeInstance(PageRepository
::class, $this->context
);
1391 // If $this->id is a string, it's an alias
1392 $this->checkAndSetAlias();
1393 // The id and type is set to the integer-value - just to be sure...
1394 $this->id
= (int)$this->id
;
1395 $this->type
= (int)$this->type
;
1396 $timeTracker->pull();
1397 // We find the first page belonging to the current domain
1398 $timeTracker->push('fetch_the_id domain/');
1400 if ($this->domainStartPage
) {
1401 // If the id was not previously set, set it to the id of the domain.
1402 $this->id
= $this->domainStartPage
;
1404 // Find the first 'visible' page in that domain
1405 $rootLevelPages = $this->sys_page
->getMenu([0], 'uid', 'sorting', '', false);
1406 if (!empty($rootLevelPages)) {
1407 $theFirstPage = reset($rootLevelPages);
1408 $this->id
= $theFirstPage['uid'];
1410 $message = 'No pages are found on the rootlevel!';
1411 $this->logger
->alert($message);
1413 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
1414 $GLOBALS['TYPO3_REQUEST'],
1416 ['code' => PageAccessFailureReasons
::NO_PAGES_FOUND
]
1418 throw new ImmediateResponseException($response, 1533931299);
1419 } catch (ServiceUnavailableException
$e) {
1420 throw new ServiceUnavailableException($message, 1301648975);
1425 $timeTracker->pull();
1426 $timeTracker->push('fetch_the_id rootLine/');
1427 // We store the originally requested id
1428 $this->requestedId
= $this->id
;
1430 $this->getPageAndRootlineWithDomain($this->domainStartPage
);
1431 } catch (ShortcutTargetPageNotFoundException
$e) {
1432 $this->pageNotFound
= 1;
1434 $timeTracker->pull();
1435 if ($this->pageNotFound
) {
1436 switch ($this->pageNotFound
) {
1438 $response = GeneralUtility
::makeInstance(ErrorController
::class)->accessDeniedAction(
1439 $GLOBALS['TYPO3_REQUEST'],
1440 'ID was not an accessible page',
1441 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ACCESS_DENIED_PAGE_NOT_RESOLVED
)
1445 $response = GeneralUtility
::makeInstance(ErrorController
::class)->accessDeniedAction(
1446 $GLOBALS['TYPO3_REQUEST'],
1447 'Subsection was found and not accessible',
1448 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ACCESS_DENIED_SUBSECTION_NOT_RESOLVED
)
1452 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
1453 $GLOBALS['TYPO3_REQUEST'],
1454 'ID was outside the domain',
1455 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ACCESS_DENIED_HOST_PAGE_MISMATCH
)
1459 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
1460 $GLOBALS['TYPO3_REQUEST'],
1461 'The requested page alias does not exist',
1462 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::PAGE_ALIAS_NOT_FOUND
)
1466 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
1467 $GLOBALS['TYPO3_REQUEST'],
1468 'Unspecified error',
1469 $this->getPageAccessFailureReasons()
1472 throw new ImmediateResponseException($response, 1533931329);
1474 // Init SYS_LASTCHANGED
1475 $this->register
['SYS_LASTCHANGED'] = (int)$this->page
['tstamp'];
1476 if ($this->register
['SYS_LASTCHANGED'] < (int)$this->page
['SYS_LASTCHANGED']) {
1477 $this->register
['SYS_LASTCHANGED'] = (int)$this->page
['SYS_LASTCHANGED'];
1479 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ??
[] as $functionReference) {
1480 $parameters = ['parentObject' => $this];
1481 GeneralUtility
::callUserFunction($functionReference, $parameters, $this);
1486 * Loads the page and root line records based on $this->id
1488 * A final page and the matching root line are determined and loaded by
1489 * the algorithm defined by this method.
1491 * First it loads the initial page from the page repository for $this->id.
1492 * If that can't be loaded directly, it gets the root line for $this->id.
1493 * It walks up the root line towards the root page until the page
1494 * repository can deliver a page record. (The loading restrictions of
1495 * the root line records are more liberal than that of the page record.)
1497 * Now the page type is evaluated and handled if necessary. If the page is
1498 * a short cut, it is replaced by the target page. If the page is a mount
1499 * point in overlay mode, the page is replaced by the mounted page.
1501 * After this potential replacements are done, the root line is loaded
1502 * (again) for this page record. It walks up the root line up to
1503 * the first viewable record.
1505 * (While upon the first accessibility check of the root line it was done
1506 * by loading page by page from the page repository, this time the method
1507 * checkRootlineForIncludeSection() is used to find the most distant
1508 * accessible page within the root line.)
1510 * Having found the final page id, the page record and the root line are
1511 * loaded for last time by this method.
1513 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1516 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1517 * instead of throwing an exception it's handled by a page unavailable
1520 * May set or update this properties:
1522 * @see TypoScriptFrontendController::$id
1523 * @see TypoScriptFrontendController::$MP
1524 * @see TypoScriptFrontendController::$page
1525 * @see TypoScriptFrontendController::$pageNotFound
1526 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1527 * @see TypoScriptFrontendController::$originalMountPointPage
1528 * @see TypoScriptFrontendController::$originalShortcutPage
1530 * @throws ServiceUnavailableException
1531 * @throws PageNotFoundException
1533 protected function getPageAndRootline()
1535 $this->resolveTranslatedPageId();
1536 if (empty($this->page
)) {
1537 // If no page, we try to find the page before in the rootLine.
1538 // Page is 'not found' in case the id itself was not an accessible page. code 1
1539 $this->pageNotFound
= 1;
1541 $this->rootLine
= GeneralUtility
::makeInstance(RootlineUtility
::class, $this->id
, $this->MP
, $this->context
)->get();
1542 if (!empty($this->rootLine
)) {
1543 $c = count($this->rootLine
) - 1;
1545 // Add to page access failure history:
1546 $this->pageAccessFailureHistory
['direct_access'][] = $this->rootLine
[$c];
1547 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1549 $this->id
= $this->rootLine
[$c]['uid'];
1550 $this->page
= $this->sys_page
->getPage($this->id
);
1551 if (!empty($this->page
)) {
1556 } catch (RootLineException
$e) {
1557 $this->rootLine
= [];
1559 // If still no page...
1560 if (empty($this->page
)) {
1561 $message = 'The requested page does not exist!';
1562 $this->logger
->error($message);
1564 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
1565 $GLOBALS['TYPO3_REQUEST'],
1567 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::PAGE_NOT_FOUND
)
1569 throw new ImmediateResponseException($response, 1533931330);
1570 } catch (PageNotFoundException
$e) {
1571 throw new PageNotFoundException($message, 1301648780);
1575 // Spacer is not accessible in frontend
1576 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_SPACER
) {
1577 $message = 'The requested page does not exist!';
1578 $this->logger
->error($message);
1580 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
1581 $GLOBALS['TYPO3_REQUEST'],
1583 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ACCESS_DENIED_INVALID_PAGETYPE
)
1585 throw new ImmediateResponseException($response, 1533931343);
1586 } catch (PageNotFoundException
$e) {
1587 throw new PageNotFoundException($message, 1301648781);
1590 // Is the ID a link to another page??
1591 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_SHORTCUT
) {
1592 // 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.
1594 // saving the page so that we can check later - when we know
1595 // about languages - whether we took the correct shortcut or
1596 // whether a translation of the page overwrites the shortcut
1597 // target and we need to follow the new target
1598 $this->originalShortcutPage
= $this->page
;
1599 $this->page
= $this->sys_page
->getPageShortcut($this->page
['shortcut'], $this->page
['shortcut_mode'], $this->page
['uid']);
1600 $this->id
= $this->page
['uid'];
1602 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1603 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1604 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1605 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_MOUNTPOINT
&& $this->page
['mount_pid_ol']) {
1606 $this->originalMountPointPage
= $this->page
;
1607 $this->page
= $this->sys_page
->getPage($this->page
['mount_pid']);
1608 if (empty($this->page
)) {
1609 $message = 'This page (ID ' . $this->originalMountPointPage
['uid'] . ') is of type "Mount point" and '
1610 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage
['mount_pid'] . ').';
1611 throw new PageNotFoundException($message, 1402043263);
1613 if ($this->MP
=== '') {
1614 $this->MP
= $this->page
['uid'] . '-' . $this->originalMountPointPage
['uid'];
1616 $this->MP
.= ',' . $this->page
['uid'] . '-' . $this->originalMountPointPage
['uid'];
1618 $this->id
= $this->page
['uid'];
1620 // Gets the rootLine
1622 $this->rootLine
= GeneralUtility
::makeInstance(RootlineUtility
::class, $this->id
, $this->MP
, $this->context
)->get();
1623 } catch (RootLineException
$e) {
1624 $this->rootLine
= [];
1626 // If not rootline we're off...
1627 if (empty($this->rootLine
)) {
1628 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1629 $this->logger
->error($message);
1631 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
1632 $GLOBALS['TYPO3_REQUEST'],
1634 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ROOTLINE_BROKEN
)
1636 throw new ImmediateResponseException($response, 1533931350);
1637 } catch (ServiceUnavailableException
$e) {
1638 throw new ServiceUnavailableException($message, 1301648167);
1641 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1642 if ($this->checkRootlineForIncludeSection()) {
1643 if (empty($this->rootLine
)) {
1644 $message = 'The requested page was not accessible!';
1646 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
1647 $GLOBALS['TYPO3_REQUEST'],
1649 $this->getPageAccessFailureReasons(PageAccessFailureReasons
::ACCESS_DENIED_GENERAL
)
1651 throw new ImmediateResponseException($response, 1533931351);
1652 } catch (ServiceUnavailableException
$e) {
1653 $this->logger
->warning($message);
1654 throw new ServiceUnavailableException($message, 1301648234);
1657 $el = reset($this->rootLine
);
1658 $this->id
= $el['uid'];
1659 $this->page
= $this->sys_page
->getPage($this->id
);
1661 $this->rootLine
= GeneralUtility
::makeInstance(RootlineUtility
::class, $this->id
, $this->MP
, $this->context
)->get();
1662 } catch (RootLineException
$e) {
1663 $this->rootLine
= [];
1670 * If $this->id contains a translated page record, this needs to be resolved to the default language
1671 * in order for all rootline functionality and access restrictions to be in place further on.
1673 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1675 protected function resolveTranslatedPageId()
1677 $this->page
= $this->sys_page
->getPage($this->id
);
1678 // Accessed a default language page record, nothing to resolve
1679 if (empty($this->page
) ||
(int)$this->page
[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1682 $languageId = (int)$this->page
[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1683 $this->page
= $this->sys_page
->getPage($this->page
[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1684 $this->context
->setAspect('language', GeneralUtility
::makeInstance(LanguageAspect
::class, $languageId));
1685 $this->id
= $this->page
['uid'];
1686 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1687 if (!$this->getCurrentSiteLanguage()) {
1688 $_GET['L'] = $languageId;
1689 $GLOBALS['HTTP_GET_VARS']['L'] = $languageId;
1694 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value).
1696 * @param int $SC The value of the "shortcut" field from the pages record
1697 * @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
1698 * @param int $thisUid The current page UID of the page which is a shortcut
1699 * @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...)
1700 * @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.
1701 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1702 * @throws \RuntimeException
1703 * @throws ShortcutTargetPageNotFoundException
1704 * @return mixed Returns the page record of the page that the shortcut pointed to.
1706 * @see getPageAndRootline()
1707 * @deprecated As this method conceptually belongs to PageRepository, it is moved in PageRepository, and will be removed in TYPO3 v10.0.
1709 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1711 trigger_error('$TSFE->getPageShortcut() has been moved to PageRepository, use the PageRepository directly to call this functionality, as this method will be removed in TYPO3 v10.0.', E_USER_DEPRECATED
);
1712 return $this->sys_page
->getPageShortcut($SC, $mode, $thisUid, $itera, $pageLog, $disableGroupCheck);
1716 * Checks if visibility of the page is blocked upwards in the root line.
1718 * If any page in the root line is blocking visibility, true is returend.
1720 * All pages from the blocking page downwards are removed from the root
1721 * line, so that the remaining pages can be used to relocate the page up
1722 * to lowest visible page.
1724 * The blocking feature of a page must be turned on by setting the page
1725 * record field 'extendToSubpages' to 1 in case of hidden, starttime,
1726 * endtime or fe_group restrictions.
1728 * Additionally this method checks for backend user sections in root line
1729 * and if found evaluates if a backend user is logged in and has access.
1731 * Recyclers are also checked and trigger page not found if found in root
1734 * @todo Find a better name, i.e. checkVisibilityByRootLine
1735 * @todo Invert boolean return value. Return true if visible.
1739 protected function checkRootlineForIncludeSection(): bool
1741 $c = count($this->rootLine
);
1742 $removeTheRestFlag = false;
1743 for ($a = 0; $a < $c; $a++
) {
1744 if (!$this->checkPagerecordForIncludeSection($this->rootLine
[$a])) {
1745 // Add to page access failure history:
1746 $this->pageAccessFailureHistory
['sub_section'][] = $this->rootLine
[$a];
1747 $removeTheRestFlag = true;
1750 if ($this->rootLine
[$a]['doktype'] == PageRepository
::DOKTYPE_BE_USER_SECTION
) {
1751 // If there is a backend user logged in, check if he has read access to the page:
1752 if ($this->isBackendUserLoggedIn()) {
1753 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1754 ->getQueryBuilderForTable('pages');
1760 $row = $queryBuilder
1764 $queryBuilder->expr()->eq(
1766 $queryBuilder->createNamedParameter($this->id
, \PDO
::PARAM_INT
)
1768 $this->getBackendUser()->getPagePermsClause(Permission
::PAGE_SHOW
)
1775 // 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...
1776 $removeTheRestFlag = true;
1779 // Don't go here, if there is no backend user logged in.
1780 $removeTheRestFlag = true;
1782 } elseif ((int)$this->rootLine
[$a]['doktype'] === PageRepository
::DOKTYPE_RECYCLER
) {
1783 // page is in a recycler
1784 $removeTheRestFlag = true;
1786 if ($removeTheRestFlag) {
1787 // Page is 'not found' in case a subsection was found and not accessible, code 2
1788 $this->pageNotFound
= 2;
1789 unset($this->rootLine
[$a]);
1792 return $removeTheRestFlag;
1796 * Checks page record for enableFields
1797 * Returns TRUE if enableFields does not disable the page record.
1798 * Takes notice of the includeHiddenPages visibility aspect flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1800 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1801 * @param bool $bypassGroupCheck Bypass group-check
1802 * @return bool TRUE, if record is viewable.
1803 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1805 public function checkEnableFields($row, $bypassGroupCheck = false)
1807 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1808 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ??
[] as $_funcRef) {
1809 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1810 $return = GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1811 if ($return === false) {
1815 if ((!$row['hidden'] ||
$this->context
->getPropertyFromAspect('visibility', 'includeHiddenPages', false))
1816 && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME']
1817 && ($row['endtime'] == 0 ||
$row['endtime'] > $GLOBALS['SIM_ACCESS_TIME'])
1818 && ($bypassGroupCheck ||
$this->checkPageGroupAccess($row))) {
1825 * Check group access against a page record
1827 * @param array $row The page record to evaluate (needs field: fe_group)
1828 * @return bool TRUE, if group access is granted.
1831 public function checkPageGroupAccess($row)
1833 /** @var UserAspect $userAspect */
1834 $userAspect = $this->context
->getAspect('frontend.user');
1835 $pageGroupList = explode(',', $row['fe_group'] ?
: 0);
1836 return count(array_intersect($userAspect->getGroupIds(), $pageGroupList)) > 0;
1840 * Checks if the current page of the root line is visible.
1842 * If the field extendToSubpages is 0, access is granted,
1843 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1845 * @todo Find a better name, i.e. isVisibleRecord()
1847 * @param array $row The page record
1848 * @return bool true if visible
1850 * @see checkEnableFields()
1851 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1852 * @see checkRootlineForIncludeSection()
1854 public function checkPagerecordForIncludeSection(array $row): bool
1856 return !$row['extendToSubpages'] ||
$this->checkEnableFields($row);
1860 * 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!)
1862 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1864 public function checkIfLoginAllowedInBranch()
1867 $c = count($this->rootLine
);
1868 $loginAllowed = true;
1869 // Traverse root line from root and outwards:
1870 for ($a = 0; $a < $c; $a++
) {
1871 // If a value is set for login state:
1872 if ($this->rootLine
[$a]['fe_login_mode'] > 0) {
1873 // Determine state from value:
1874 if ((int)$this->rootLine
[$a]['fe_login_mode'] === 1) {
1875 $loginAllowed = false;
1876 $this->loginAllowedInBranch_mode
= 'all';
1877 } elseif ((int)$this->rootLine
[$a]['fe_login_mode'] === 3) {
1878 $loginAllowed = false;
1879 $this->loginAllowedInBranch_mode
= 'groups';
1881 $loginAllowed = true;
1885 return $loginAllowed;
1889 * 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
1891 * @param string $failureReasonCode the error code to be attached (optional), see PageAccessFailureReasons list for details
1892 * @return array Summary of why page access was not allowed.
1894 public function getPageAccessFailureReasons(string $failureReasonCode = null)
1897 if ($failureReasonCode) {
1898 $output['code'] = $failureReasonCode;
1900 $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'] : []);
1901 if (!empty($combinedRecords)) {
1902 foreach ($combinedRecords as $k => $pagerec) {
1903 // 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
1904 // 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!
1905 if (!$k ||
$pagerec['extendToSubpages']) {
1906 if ($pagerec['hidden']) {
1907 $output['hidden'][$pagerec['uid']] = true;
1909 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1910 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1912 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1913 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1915 if (!$this->checkPageGroupAccess($pagerec)) {
1916 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1925 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1926 * If not inside domain, then default to first page in domain.
1928 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1931 public function getPageAndRootlineWithDomain($domainStartPage)
1933 $this->getPageAndRootline();
1934 // 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.
1935 if ($domainStartPage && is_array($this->rootLine
)) {
1937 foreach ($this->rootLine
as $key => $val) {
1938 if ($val['uid'] == $domainStartPage) {
1944 // Page is 'not found' in case the id was outside the domain, code 3
1945 $this->pageNotFound
= 3;
1946 $this->id
= $domainStartPage;
1947 // re-get the page and rootline if the id was not found.
1948 $this->getPageAndRootline();
1954 * Page unavailable handler for use in frontend plugins from extensions.
1956 * @param string $reason Reason text
1957 * @param string $header HTTP header to send
1958 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1960 public function pageUnavailableAndExit($reason = '', $header = '')
1962 trigger_error('$TSFE->pageUnavailableAndExit() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
1963 $header = $header ?
: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1964 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1969 * Page-not-found handler for use in frontend plugins from extensions.
1971 * @param string $reason Reason text
1972 * @param string $header HTTP header to send
1973 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1975 public function pageNotFoundAndExit($reason = '', $header = '')
1977 trigger_error('$TSFE->pageNotFoundAndExit() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
1978 $header = $header ?
: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1979 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1984 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1985 * and devIPMask must not match the current visitor's IP address.
1987 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1988 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
1990 public function checkPageUnavailableHandler()
1992 trigger_error('$TSFE->checkPageUnavailableHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
1994 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1995 && !GeneralUtility
::cmpIP(
1996 GeneralUtility
::getIndpEnv('REMOTE_ADDR'),
1997 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
2000 $checkPageUnavailableHandler = true;
2002 $checkPageUnavailableHandler = false;
2004 return $checkPageUnavailableHandler;
2008 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
2010 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
2011 * @param string $header If set, this is passed directly to the PHP function, header()
2012 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2013 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2015 public function pageUnavailableHandler($code, $header, $reason)
2017 trigger_error('$TSFE->pageUnavailableHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
2018 $this->pageErrorHandler($code, $header, $reason);
2022 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
2024 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
2025 * @param string $header If set, this is passed directly to the PHP function, header()
2026 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2027 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2029 public function pageNotFoundHandler($code, $header = '', $reason = '')
2031 trigger_error('$TSFE->pageNotFoundHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
2032 $this->pageErrorHandler($code, $header, $reason);
2036 * Generic error page handler.
2039 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
2040 * @param string $header If set, this is passed directly to the PHP function, header()
2041 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
2042 * @throws \RuntimeException
2043 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.
2045 public function pageErrorHandler($code, $header = '', $reason = '')
2047 trigger_error('$TSFE->pageErrorHandler() will be removed in TYPO3 v10.0. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED
);
2048 // Issue header in any case:
2050 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY
);
2051 foreach ($headerArr as $header) {
2056 // Simply boolean; Just shows TYPO3 error page with reason:
2057 if (strtolower($code) === 'true' ||
(string)$code === '1' ||
is_bool($code)) {
2058 echo GeneralUtility
::makeInstance(ErrorPageController
::class)->errorAction(
2060 'The page did not exist or was inaccessible.' . ($reason ?
' Reason: ' . $reason : '')
2062 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
2063 $funcRef = trim(substr($code, 14));
2065 'currentUrl' => GeneralUtility
::getIndpEnv('REQUEST_URI'),
2066 'reasonText' => $reason,
2067 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
2070 echo GeneralUtility
::callUserFunction($funcRef, $params, $this);
2071 } catch (\Exception
$e) {
2072 throw new \
RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
2074 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'READFILE:')) {
2075 $readFile = GeneralUtility
::getFileAbsFileName(trim(substr($code, 9)));
2076 if (@is_file
($readFile)) {
2079 '###CURRENT_URL###',
2083 GeneralUtility
::getIndpEnv('REQUEST_URI'),
2084 htmlspecialchars($reason)
2086 file_get_contents($readFile)
2089 throw new \
RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
2091 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'REDIRECT:')) {
2092 HttpUtility
::redirect(substr($code, 9));
2093 } elseif ($code !== '') {
2094 // Check if URL is relative
2095 $url_parts = parse_url($code);
2096 // parse_url could return an array without the key "host", the empty check works better than strict check
2097 if (empty($url_parts['host'])) {
2098 $url_parts['host'] = GeneralUtility
::getIndpEnv('HTTP_HOST');
2099 if ($code[0] === '/') {
2100 $code = GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
2102 $code = GeneralUtility
::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
2104 $checkBaseTag = false;
2106 $checkBaseTag = true;
2109 if ($code == GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL')) {
2110 if ($reason == '') {
2111 $reason = 'Page cannot be found.';
2113 $reason .= LF
. LF
. 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2114 throw new \
RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2118 'User-agent: ' . GeneralUtility
::getIndpEnv('HTTP_USER_AGENT'),
2119 'Referer: ' . GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL')
2122 $res = GeneralUtility
::getUrl($code, 1, $headerArr, $report);
2123 if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2124 throw new \
RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2126 // Header and content are separated by an empty line
2127 list($header, $content) = explode(CRLF
. CRLF
, $res, 2);
2129 if (false === $res) {
2130 // Last chance -- redirect
2131 HttpUtility
::redirect($code);
2133 // Forward these response headers to the client
2137 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY
);
2138 foreach ($headerArr as $header) {
2139 foreach ($forwardHeaders as $h) {
2140 if (preg_match('/^' . $h . '/', $header)) {
2145 // Put <base> if necessary
2146 if ($checkBaseTag) {
2147 // If content already has <base> tag, we do not need to do anything
2148 if (false === stristr($content, '<base ')) {
2149 // Generate href for base tag
2150 $base = $url_parts['scheme'] . '://';
2151 if ($url_parts['user'] != '') {
2152 $base .= $url_parts['user'];
2153 if ($url_parts['pass'] != '') {
2154 $base .= ':' . $url_parts['pass'];
2158 $base .= $url_parts['host'];
2159 // Add path portion skipping possible file name
2160 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2161 // Put it into content (generate also <head> if necessary)
2162 $replacement = LF
. '<base href="' . htmlentities($base) . '" />' . LF
;
2163 if (stristr($content, '<head>')) {
2164 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2166 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2170 // Output the content
2174 echo GeneralUtility
::makeInstance(ErrorPageController
::class)->errorAction(
2176 $reason ?
'Reason: ' . $reason : 'Page cannot be found.'
2183 * Fetches the integer page id for a page alias.
2184 * 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
2186 protected function checkAndSetAlias()
2188 if ($this->id
&& !MathUtility
::canBeInterpretedAsInteger($this->id
)) {
2189 $aid = $this->sys_page
->getPageIdFromAlias($this->id
);
2193 $this->pageNotFound
= 4;
2199 * Merging values into the global $_GET
2201 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2202 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0. This was mainly used in RealURL to set $id etc. but should be done manually instead.
2204 protected function mergingWithGetVars($GET_VARS)
2206 if (is_array($GET_VARS)) {
2207 // Getting $_GET var, unescaped.
2208 $realGet = GeneralUtility
::_GET();
2209 if (!is_array($realGet)) {
2212 // Merge new values on top:
2213 ArrayUtility
::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2214 // Write values back to $_GET
2216 $GLOBALS['HTTP_GET_VARS'] = $realGet;
2217 // Setting these specifically (like in the init-function):
2218 if (isset($GET_VARS['type'])) {
2219 $this->type
= (int)$GET_VARS['type'];
2221 if (isset($GET_VARS['cHash'])) {
2222 $this->cHash
= $GET_VARS['cHash'];
2224 if (isset($GET_VARS['MP'])) {
2225 $this->MP
= $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ?
$GET_VARS['MP'] : '';
2227 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2228 $this->set_no_cache('no_cache is requested via GET parameter');
2233 /********************************************
2235 * Template and caching related functions.
2237 *******************************************/
2239 * Calculates a hash string based on additional parameters in the url.
2241 * Calculated hash is stored in $this->cHash_array.
2242 * This is used to cache pages with more parameters than just id and type.
2245 * @deprecated since TYPO3 v9.5, will be removed in TYPO3 v10.0. This validation is done in the PageParameterValidator PSR-15 middleware.
2247 public function makeCacheHash()
2249 trigger_error('$TSFE->makeCacheHash() will be removed in TYPO3 v10.0, as this is now handled in the PSR-15 middleware.', E_USER_DEPRECATED
);
2250 // No need to test anything if caching was already disabled.
2251 if ($this->no_cache
&& !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2254 $GET = GeneralUtility
::_GET();
2255 if ($this->cHash
&& is_array($GET)) {
2256 // Make sure we use the page uid and not the page alias
2257 $GET['id'] = $this->id
;
2258 $this->cHash_array
= $this->cacheHash
->getRelevantParameters(HttpUtility
::buildQueryString($GET));
2259 $cHash_calc = $this->cacheHash
->calculateCacheHash($this->cHash_array
);
2260 if (!hash_equals($cHash_calc, $this->cHash
)) {
2261 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2262 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2263 $GLOBALS['TYPO3_REQUEST'],
2264 'Request parameters could not be validated (&cHash comparison failed)',
2265 ['code' => PageAccessFailureReasons
::CACHEHASH_COMPARISON_FAILED
]
2267 throw new ImmediateResponseException($response, 1533931352);
2269 $this->disableCache();
2270 $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);
2272 } elseif (is_array($GET)) {
2273 // No cHash is set, check if that is correct
2274 if ($this->cacheHash
->doParametersRequireCacheHash(HttpUtility
::buildQueryString($GET))) {
2281 * Will disable caching if the cHash value was not set when having dynamic arguments in GET query parameters.
2282 * 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)
2284 * @see \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2286 public function reqCHash()
2288 $skip = $this->pageArguments
!== null && empty($this->pageArguments
->getDynamicArguments());
2289 if ($this->cHash ||
$skip) {
2292 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2293 if ($this->tempContent
) {
2294 $this->clearPageCacheContent();
2296 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2297 $GLOBALS['TYPO3_REQUEST'],
2298 'Request parameters could not be validated (&cHash empty)',
2299 ['code' => PageAccessFailureReasons
::CACHEHASH_EMPTY
]
2301 throw new ImmediateResponseException($response, 1533931354);
2303 $this->disableCache();
2304 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2308 * @param PageArguments $pageArguments
2311 public function setPageArguments(PageArguments
$pageArguments)
2313 $this->pageArguments
= $pageArguments;
2317 * Initialize the TypoScript template parser
2318 * @deprecated since TYPO3 v9.4 will be removed in TYPO3 v10.0. Either instantiate $TSFE->tmpl yourself, if really necessary.
2320 public function initTemplate()
2322 trigger_error('$TSFE->initTemplate() will be removed in TYPO3 v10.0. Instantiating TemplateService is done implicitly on usage within $TSFE directly.', E_USER_DEPRECATED
);
2323 $this->tmpl
= GeneralUtility
::makeInstance(TemplateService
::class, $this->context
);
2327 * See if page is in cache and get it if so
2328 * Stores the page content in $this->content if something is found.
2330 * @throws \InvalidArgumentException
2331 * @throws \RuntimeException
2333 public function getFromCache()
2335 // clearing the content-variable, which will hold the pagecontent
2336 $this->content
= '';
2337 // Unsetting the lowlevel config
2339 $this->cacheContentFlag
= false;
2341 if ($this->no_cache
) {
2345 if (!($this->tmpl
instanceof TemplateService
)) {
2346 $this->tmpl
= GeneralUtility
::makeInstance(TemplateService
::class, $this->context
);
2349 $pageSectionCacheContent = $this->tmpl
->getCurrentPageData();
2350 if (!is_array($pageSectionCacheContent)) {
2351 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2352 // We use the Registry to store this lock centrally,
2353 // but we protect the access again with a global exclusive lock to avoid race conditions
2355 $this->acquireLock('pagesection', $this->id
. '::' . $this->MP
);
2357 // from this point on we're the only one working on that page ($key)
2360 // query the cache again to see if the page data are there meanwhile
2361 $pageSectionCacheContent = $this->tmpl
->getCurrentPageData();
2362 if (is_array($pageSectionCacheContent)) {
2363 // we have the content, nice that some other process did the work for us already
2364 $this->releaseLock('pagesection');
2366 // We keep the lock set, because we are the ones generating the page now
2367 // and filling the cache.
2368 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2371 if (is_array($pageSectionCacheContent)) {
2372 // 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.
2373 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2374 // 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.
2375 $pageSectionCacheContent = $this->tmpl
->matching($pageSectionCacheContent);
2376 ksort($pageSectionCacheContent);
2377 $this->all
= $pageSectionCacheContent;
2379 unset($pageSectionCacheContent);
2381 // Look for page in cache only if a shift-reload is not sent to the server.
2382 $lockHash = $this->getLockHash();
2383 if (!$this->headerNoCache()) {
2385 // we got page section information
2386 $this->newHash
= $this->getHash();
2387 $this->getTimeTracker()->push('Cache Row');
2388 $row = $this->getFromCache_queryRow();
2389 if (!is_array($row)) {
2390 // nothing in the cache, we acquire an exclusive lock now
2392 $this->acquireLock('pages', $lockHash);
2394 // from this point on we're the only one working on that page ($lockHash)
2397 // query the cache again to see if the data are there meanwhile
2398 $row = $this->getFromCache_queryRow();
2399 if (is_array($row)) {
2400 // we have the content, nice that some other process did the work for us
2401 $this->releaseLock('pages');
2403 // We keep the lock set, because we are the ones generating the page now
2404 // and filling the cache.
2405 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2407 if (is_array($row)) {
2408 // we have data from cache
2410 // Call hook when a page is retrieved from cache:
2411 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2412 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ??
[] as $_funcRef) {
2413 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2415 // Fetches the lowlevel config stored with the cached data
2416 $this->config
= $row['cache_data'];
2417 // Getting the content
2418 $this->content
= $row['content'];
2419 // Flag for temp content
2420 $this->tempContent
= $row['temp_content'];
2421 // Setting flag, so we know, that some cached content has been loaded
2422 $this->cacheContentFlag
= true;
2423 $this->cacheExpires
= $row['expires'];
2425 // Restore page title information, this is needed to generate the page title for
2426 // partially cached pages.
2427 $this->page
['title'] = $row['pageTitleInfo']['title'];
2428 $this->altPageTitle
= $row['pageTitleInfo']['altPageTitle'];
2429 $this->indexedDocTitle
= $row['pageTitleInfo']['indexedDocTitle'];
2431 if (isset($this->config
['config']['debug'])) {
2432 $debugCacheTime = (bool)$this->config
['config']['debug'];
2434 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2436 if ($debugCacheTime) {
2437 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2438 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2439 $this->content
.= LF
. '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $row['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $row['expires']) . ' -->';
2442 $this->getTimeTracker()->pull();
2447 // the user forced rebuilding the page cache or there was no pagesection information
2448 // get a lock for the page content so other processes will not interrupt the regeneration
2449 $this->acquireLock('pages', $lockHash);
2453 * Returning the cached version of page with hash = newHash
2455 * @return array Cached row, if any. Otherwise void.
2457 public function getFromCache_queryRow()
2459 $this->getTimeTracker()->push('Cache Query');
2460 $row = $this->pageCache
->get($this->newHash
);
2461 $this->getTimeTracker()->pull();
2466 * Detecting if shift-reload has been clicked
2467 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2468 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2470 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2472 public function headerNoCache()
2474 $disableAcquireCacheData = false;
2475 if ($this->isBackendUserLoggedIn()) {
2476 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' ||
strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2477 $disableAcquireCacheData = true;
2480 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2481 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2482 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ??
[] as $_funcRef) {
2483 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2485 return $disableAcquireCacheData;
2489 * Calculates the cache-hash
2490 * This hash is unique to the template, the variables ->id, ->type, list of fe user groups, ->MP (Mount Points) and cHash array
2491 * Used to get and later store the cached data.
2493 * @return string MD5 hash of serialized hash base from createHashBase()
2494 * @see getFromCache(), getLockHash()
2496 protected function getHash()
2498 return md5($this->createHashBase(false));
2502 * Calculates the lock-hash
2503 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2505 * @return string MD5 hash
2506 * @see getFromCache(), getHash()
2508 protected function getLockHash()
2510 $lockHash = $this->createHashBase(true);
2511 return md5($lockHash);
2515 * Calculates the cache-hash (or the lock-hash)
2516 * This hash is unique to the template,
2517 * the variables ->id, ->type, list of frontend user groups,
2518 * ->MP (Mount Points) and cHash array
2519 * Used to get and later store the cached data.
2521 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2522 * @return string the serialized hash base
2524 protected function createHashBase($createLockHashBase = false)
2526 // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
2527 // is not cached properly as we don't have any language-specific conditions anymore
2528 $siteBase = $this->getCurrentSiteLanguage() ?
(string)$this->getCurrentSiteLanguage()->getBase() : '';
2530 // Fetch the list of user groups
2531 /** @var UserAspect $userAspect */
2532 $userAspect = $this->context
->getAspect('frontend.user');
2534 'id' => (int)$this->id
,
2535 'type' => (int)$this->type
,
2536 'gr_list' => (string)implode(',', $userAspect->getGroupIds()),
2537 'MP' => (string)$this->MP
,
2538 'siteBase' => $siteBase,
2539 // cHash_array includes dynamic route arguments (if route was resolved)
2540 'cHash' => $this->cHash_array
,
2541 // additional variation trigger for static routes
2542 'staticRouteArguments' => $this->pageArguments
!== null ?
$this->pageArguments
->getStaticArguments() : null,
2543 'domainStartPage' => $this->domainStartPage
2545 // Include the template information if we shouldn't create a lock hash
2546 if (!$createLockHashBase) {
2547 $hashParameters['all'] = $this->all
;
2549 // Call hook to influence the hash calculation
2551 'hashParameters' => &$hashParameters,
2552 'createLockHashBase' => $createLockHashBase
2554 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ??
[] as $_funcRef) {
2555 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2557 return serialize($hashParameters);
2561 * Checks if config-array exists already but if not, gets it
2563 * @throws ServiceUnavailableException
2565 public function getConfigArray()
2567 if (!($this->tmpl
instanceof TemplateService
)) {
2568 $this->tmpl
= GeneralUtility
::makeInstance(TemplateService
::class, $this->context
);
2571 // 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
2572 if (empty($this->config
) ||
is_array($this->config
['INTincScript']) ||
$this->forceTemplateParsing
) {
2573 $timeTracker = $this->getTimeTracker();
2574 $timeTracker->push('Parse template');
2575 // Force parsing, if set?:
2576 $this->tmpl
->forceTemplateParsing
= $this->forceTemplateParsing
;
2577 // Start parsing the TS template. Might return cached version.
2578 $this->tmpl
->start($this->rootLine
);
2579 $timeTracker->pull();
2580 if ($this->tmpl
->loaded
) {
2581 $timeTracker->push('Setting the config-array');
2582 // toplevel - objArrayName
2583 $this->sPre
= $this->tmpl
->setup
['types.'][$this->type
];
2584 $this->pSetup
= $this->tmpl
->setup
[$this->sPre
. '.'];
2585 if (!is_array($this->pSetup
)) {
2586 $message = 'The page is not configured! [type=' . $this->type
. '][' . $this->sPre
. '].';
2587 $this->logger
->alert($message);
2589 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
2590 $GLOBALS['TYPO3_REQUEST'],
2592 ['code' => PageAccessFailureReasons
::RENDERING_INSTRUCTIONS_NOT_CONFIGURED
]
2594 throw new ImmediateResponseException($response, 1533931374);
2595 } catch (ServiceUnavailableException
$e) {
2596 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type
. ' configured.';
2597 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2600 if (!isset($this->config
['config'])) {
2601 $this->config
['config'] = [];
2603 // Filling the config-array, first with the main "config." part
2604 if (is_array($this->tmpl
->setup
['config.'])) {
2605 ArrayUtility
::mergeRecursiveWithOverrule($this->tmpl
->setup
['config.'], $this->config
['config']);
2606 $this->config
['config'] = $this->tmpl
->setup
['config.'];
2608 // override it with the page/type-specific "config."
2609 if (is_array($this->pSetup
['config.'])) {
2610 ArrayUtility
::mergeRecursiveWithOverrule($this->config
['config'], $this->pSetup
['config.']);
2612 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10.0
2613 if ($this->config
['config']['typolinkCheckRootline']) {
2614 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2616 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2617 if (!isset($this->config
['config']['removeDefaultJS'])) {
2618 $this->config
['config']['removeDefaultJS'] = 'external';
2620 if (!isset($this->config
['config']['inlineStyle2TempFile'])) {
2621 $this->config
['config']['inlineStyle2TempFile'] = 1;
2624 if (!isset($this->config
['config']['compressJs'])) {
2625 $this->config
['config']['compressJs'] = 0;
2627 // Processing for the config_array:
2628 $this->config
['rootLine'] = $this->tmpl
->rootLine
;
2629 // Class for render Header and Footer parts
2630 if ($this->pSetup
['pageHeaderFooterTemplateFile']) {
2632 $file = GeneralUtility
::makeInstance(FilePathSanitizer
::class)
2633 ->sanitize((string)$this->pSetup
['pageHeaderFooterTemplateFile']);
2634 $this->pageRenderer
->setTemplateFile($file);
2635 } catch (\TYPO3\CMS\Core\
Resource\Exception
$e) {
2640 $timeTracker->pull();
2642 $message = 'No TypoScript template found!';
2643 $this->logger
->alert($message);
2645 $response = GeneralUtility
::makeInstance(ErrorController
::class)->unavailableAction(
2646 $GLOBALS['TYPO3_REQUEST'],
2648 ['code' => PageAccessFailureReasons
::RENDERING_INSTRUCTIONS_NOT_FOUND
]
2650 throw new ImmediateResponseException($response, 1533931380);
2651 } catch (ServiceUnavailableException
$e) {
2652 throw new ServiceUnavailableException($message, 1294587218);
2658 // Set $this->no_cache TRUE if the config.no_cache value is set!
2659 if ($this->config
['config']['no_cache']) {
2660 $this->set_no_cache('config.no_cache is set');
2662 // Merge GET with defaultGetVars
2663 // Please note that this code will get removed in TYPO3 v10.0 as it is done in the PSR-15 middleware.
2664 if (!empty($this->config
['config']['defaultGetVars.'])) {
2665 $modifiedGetVars = GeneralUtility
::removeDotsFromTS($this->config
['config']['defaultGetVars.']);
2666 ArrayUtility
::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility
::_GET());
2667 $_GET = $modifiedGetVars;
2668 $GLOBALS['HTTP_GET_VARS'] = $modifiedGetVars;
2671 // Auto-configure settings when a site is configured
2672 if ($this->getCurrentSiteLanguage()) {
2673 $this->config
['config']['absRefPrefix'] = $this->config
['config']['absRefPrefix'] ??
'auto';
2676 $this->setUrlIdToken();
2678 // Hook for postProcessing the configuration array
2679 $params = ['config' => &$this->config
['config']];
2680 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ??
[] as $funcRef) {
2681 GeneralUtility
::callUserFunction($funcRef, $params, $this);
2685 /********************************************
2687 * Further initialization and data processing
2689 *******************************************/
2692 * Setting the language key that will be used by the current page.
2693 * 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.
2697 public function settingLanguage()
2700 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ??
[] as $_funcRef) {
2701 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2704 $siteLanguage = $this->getCurrentSiteLanguage();
2706 // Initialize charset settings etc.
2707 if ($siteLanguage) {
2708 $languageKey = $siteLanguage->getTypo3Language();
2710 $languageKey = $this->config
['config']['language'] ??
'default';
2712 $this->lang
= $languageKey;
2713 $this->setOutputLanguage($languageKey);
2715 // Rendering charset of HTML page.
2716 if (isset($this->config
['config']['metaCharset']) && $this->config
['config']['metaCharset'] !== 'utf-8') {
2717 $this->metaCharset
= $this->config
['config']['metaCharset'];
2720 // Get values from site language
2721 if ($siteLanguage) {
2722 $languageAspect = LanguageAspectFactory
::createFromSiteLanguage($siteLanguage);
2724 $languageAspect = LanguageAspectFactory
::createFromTypoScript($this->config
['config'] ??
[]);
2727 $languageId = $languageAspect->getId();
2728 $languageContentId = $languageAspect->getContentId();
2730 // If sys_language_uid is set to another language than default:
2731 if ($languageAspect->getId() > 0) {
2732 // check whether a shortcut is overwritten by a translated page
2733 // we can only do this now, as this is the place where we get
2734 // to know about translations
2735 $this->checkTranslatedShortcut($languageAspect->getId());
2736 // Request the overlay record for the sys_language_uid:
2737 $olRec = $this->sys_page
->getPageOverlay($this->id
, $languageAspect->getId());
2738 if (empty($olRec)) {
2739 // If requested translation is not available:
2740 if (GeneralUtility
::hideIfNotTranslated($this->page
['l18n_cfg'])) {
2741 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2742 $GLOBALS['TYPO3_REQUEST'],
2743 'Page is not available in the requested language.',
2744 ['code' => PageAccessFailureReasons
::LANGUAGE_NOT_AVAILABLE
]
2746 throw new ImmediateResponseException($response, 1533931388);
2748 switch ((string)$languageAspect->getLegacyLanguageMode()) {
2750 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2751 $GLOBALS['TYPO3_REQUEST'],
2752 'Page is not available in the requested language (strict).',
2753 ['code' => PageAccessFailureReasons
::LANGUAGE_NOT_AVAILABLE_STRICT_MODE
]
2755 throw new ImmediateResponseException($response, 1533931395);
2758 case 'content_fallback':
2759 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2761 foreach ($languageAspect->getFallbackChain() ??
[] as $orderValue) {
2762 if ($orderValue === '0' ||
$orderValue === 0 ||
$orderValue === '') {
2763 $languageContentId = 0;
2766 if (MathUtility
::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page
->getPageOverlay($this->id
, (int)$orderValue))) {
2767 $languageContentId = (int)$orderValue;
2770 if ($orderValue === 'pageNotFound') {
2771 // The existing fallbacks have not been found, but instead of continuing
2772 // page rendering with default language, a "page not found" message should be shown
2774 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2775 $GLOBALS['TYPO3_REQUEST'],
2776 'Page is not available in the requested language (fallbacks did not apply).',
2777 ['code' => PageAccessFailureReasons
::LANGUAGE_AND_FALLBACKS_NOT_AVAILABLE
]
2779 throw new ImmediateResponseException($response, 1533931402);
2784 $languageContentId = $languageAspect->getId();
2787 // Default is that everything defaults to the default language...
2788 $languageId = ($languageContentId = 0);
2791 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2792 $this->page
= $this->sys_page
->getPageOverlay($this->page
, $languageAspect->getId());
2795 // Define the language aspect again now
2796 $languageAspect = GeneralUtility
::makeInstance(
2797 LanguageAspect
::class,
2800 $languageAspect->getOverlayType(),
2801 $languageAspect->getFallbackChain()
2805 // Set the language aspect
2806 $this->context
->setAspect('language', $languageAspect);
2808 // Setting sys_language_uid inside sys-page by creating a new page repository
2809 $this->sys_page
= GeneralUtility
::makeInstance(PageRepository
::class, $this->context
);
2810 // If default translation is not available:
2811 if ((!$languageAspect->getContentId() ||
!$languageAspect->getId())
2812 && GeneralUtility
::hideIfDefaultLanguage($this->page
['l18n_cfg'] ??
0)
2814 $message = 'Page is not available in default language.';
2815 $this->logger
->error($message);
2816 $response = GeneralUtility
::makeInstance(ErrorController
::class)->pageNotFoundAction(
2817 $GLOBALS['TYPO3_REQUEST'],
2819 ['code' => PageAccessFailureReasons
::LANGUAGE_DEFAULT_NOT_AVAILABLE
]
2821 throw new ImmediateResponseException($response, 1533931423);
2824 if ($languageAspect->getId() > 0) {
2825 $this->updateRootLinesWithTranslations();
2828 // Finding the ISO code for the currently selected language
2829 // fetched by the sys_language record when not fetching content from the default language
2830 if ($siteLanguage = $this->getCurrentSiteLanguage()) {
2831 $this->sys_language_isocode
= $siteLanguage->getTwoLetterIsoCode();
2832 } elseif ($languageAspect->getContentId() > 0) {
2833 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2834 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2835 // avoid versioning overlay to be applied as it generates an SQL error
2836 $sys_language_row = $this->sys_page
->getRawRecord('sys_language', $languageAspect->getContentId(), 'language_isocode,static_lang_isocode');
2837 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2838 $this->sys_language_isocode
= $sys_language_row['language_isocode'];
2840 // the DB value is overridden by TypoScript
2841 if (!empty($this->config
['config']['sys_language_isocode'])) {
2842 $this->sys_language_isocode
= $this->config
['config']['sys_language_isocode'];
2845 // fallback to the TypoScript option when rendering with sys_language_uid=0
2846 // also: use "en" by default
2847 if (!empty($this->config
['config']['sys_language_isocode_default'])) {
2848 $this->sys_language_isocode
= $this->config
['config']['sys_language_isocode_default'];
2850 $this->sys_language_isocode
= $languageKey !== 'default' ?
$languageKey : 'en';
2855 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ??
[] as $_funcRef) {
2856 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2861 * Updating content of the two rootLines IF the language key is set!
2863 protected function updateRootLinesWithTranslations()
2866 $this->rootLine
= GeneralUtility
::makeInstance(RootlineUtility
::class, $this->id
, $this->MP
, $this->context
)->get();
2867 } catch (RootLineException
$e) {
2868 $this->rootLine
= [];
2870 $this->tmpl
->updateRootlineData($this->rootLine
);
2874 * Setting locale for frontend rendering
2876 public function settingLocale()
2879 $locale = $this->config
['config']['locale_all'];
2880 $siteLanguage = $this->getCurrentSiteLanguage();
2881 if ($siteLanguage) {
2882 $locale = $siteLanguage->getLocale();
2885 $availableLocales = GeneralUtility
::trimExplode(',', $locale, true);
2886 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2887 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2888 // @see https://bugs.php.net/bug.php?id=53711
2889 $locale = setlocale(LC_COLLATE
, ...$availableLocales);
2891 // As str_* methods are locale aware and turkish has no upper case I
2892 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2893 // @see http://bugs.php.net/bug.php?id=35050
2894 if (strpos($locale, 'tr') !== 0) {
2895 setlocale(LC_CTYPE
, ...$availableLocales);
2897 setlocale(LC_MONETARY
, ...$availableLocales);
2898 setlocale(LC_TIME
, ...$availableLocales);
2900 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($locale) . '" not found.', 3);
2906 * Checks whether a translated shortcut page has a different shortcut
2907 * target than the original language page.
2908 * If that is the case, things get corrected to follow that alternative
2910 * @param int $languageId
2912 protected function checkTranslatedShortcut(int $languageId)
2914 if (!is_null($this->originalShortcutPage
)) {
2915 $originalShortcutPageOverlay = $this->sys_page
->getPageOverlay($this->originalShortcutPage
['uid'], $languageId);
2916 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id
) {
2917 // the translation of the original shortcut page has a different shortcut target!
2918 // set the correct page and id
2919 $shortcut = $this->sys_page
->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2920 $this->id
= ($this->contentPid
= $shortcut['uid']);
2921 $this->page
= $this->sys_page
->getPage($this->id
);
2922 // Fix various effects on things like menus f.e.
2923 $this->fetch_the_id();
2924 $this->tmpl
->rootLine
= array_reverse($this->rootLine
);
2930 * Handle data submission
2931 * This is done at this point, because we need the config values
2932 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.0.