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\Exception\ConnectionException
;
18 use Psr\Log\LoggerAwareInterface
;
19 use Psr\Log\LoggerAwareTrait
;
20 use TYPO3\CMS\Backend\FrontendBackendUserAuthentication
;
21 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication
;
22 use TYPO3\CMS\Core\Cache\CacheManager
;
23 use TYPO3\CMS\Core\Charset\CharsetConverter
;
24 use TYPO3\CMS\Core\Charset\UnknownCharsetException
;
25 use TYPO3\CMS\Core\Controller\ErrorPageController
;
26 use TYPO3\CMS\Core\Database\ConnectionPool
;
27 use TYPO3\CMS\Core\Database\Query\QueryHelper
;
28 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer
;
29 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction
;
30 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction
;
31 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction
;
32 use TYPO3\CMS\Core\Error\Http\PageNotFoundException
;
33 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException
;
34 use TYPO3\CMS\Core\Localization\LanguageService
;
35 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException
;
36 use TYPO3\CMS\Core\Locking\LockFactory
;
37 use TYPO3\CMS\Core\Locking\LockingStrategyInterface
;
38 use TYPO3\CMS\Core\Log\LogManager
;
39 use TYPO3\CMS\Core\Page\PageRenderer
;
40 use TYPO3\CMS\Core\
Resource\StorageRepository
;
41 use TYPO3\CMS\Core\Service\DependencyOrderingService
;
42 use TYPO3\CMS\Core\TimeTracker\TimeTracker
;
43 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
;
44 use TYPO3\CMS\Core\TypoScript\TemplateService
;
45 use TYPO3\CMS\Core\Utility\ArrayUtility
;
46 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
47 use TYPO3\CMS\Core\Utility\GeneralUtility
;
48 use TYPO3\CMS\Core\Utility\HttpUtility
;
49 use TYPO3\CMS\Core\Utility\MathUtility
;
50 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication
;
51 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer
;
52 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface
;
53 use TYPO3\CMS\Frontend\Page\CacheHashCalculator
;
54 use TYPO3\CMS\Frontend\Page\PageGenerator
;
55 use TYPO3\CMS\Frontend\Page\PageRepository
;
56 use TYPO3\CMS\Frontend\View\AdminPanelView
;
59 * Class for the built TypoScript based frontend. Instantiated in
60 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
62 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
63 * as the global object TSFE.
65 * This class has a lot of functions and internal variable which are used from
66 * \TYPO3\CMS\Frontend\Http\RequestHandler
68 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
70 * The use of this class should be inspired by the order of function calls as
71 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
73 class TypoScriptFrontendController
implements LoggerAwareInterface
84 * The type (read-only)
96 * Page will not be cached. Write only TRUE. Never clear value (some other
97 * code might have reasons to set it TRUE).
100 public $no_cache = false;
103 * The rootLine (all the way to tree root, not only the current site!)
106 public $rootLine = '';
115 * This will normally point to the same value as id, but can be changed to
116 * point to another page from which content will then be displayed instead.
119 public $contentPid = 0;
122 * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
123 * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
124 * should be redirected to.
128 protected $originalMountPointPage = null;
131 * Gets set when we are processing a page of type shortcut in the early stages
132 * of the request when we do not know about languages yet, used later in the request
133 * to determine the correct shortcut in case a translation changes the shortcut
136 * @see checkTranslatedShortcut()
138 protected $originalShortcutPage = null;
141 * sys_page-object, pagefunctions
143 * @var PageRepository
145 public $sys_page = '';
148 * Contains all URL handler instances that are active for the current request.
150 * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
152 * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
153 * @see initializeRedirectUrlHandlers()
155 protected $activeUrlHandlers = [];
158 * Is set to 1 if a pageNotFound handler could have been called.
161 public $pageNotFound = 0;
167 public $domainStartPage = 0;
170 * Array containing a history of why a requested page was not accessible.
173 public $pageAccessFailureHistory = [];
181 * This can be set from applications as a way to tag cached versions of a page
182 * and later perform some external cache management, like clearing only a part
183 * of the cache of a page...
186 public $page_cache_reg1 = 0;
189 * Contains the value of the current script path that activated the frontend.
190 * Typically "index.php" but by rewrite rules it could be something else! Used
191 * for Speaking Urls / Simulate Static Documents.
194 public $siteScript = '';
199 * @var FrontendUserAuthentication
201 public $fe_user = '';
204 * Global flag indicating that a frontend user is logged in. This is set only if
205 * a user really IS logged in. The group-list may show other groups (like added
206 * by IP filter or so) even though there is no user.
209 public $loginUser = false;
212 * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
213 * group, but other groups may be added by other means than a user being logged
217 public $gr_list = '';
220 * Flag that indicates if a backend user is logged in!
223 public $beUserLogin = false;
226 * Integer, that indicates which workspace is being previewed.
229 public $workspacePreview = 0;
232 * Shows whether logins are allowed in branch
235 public $loginAllowedInBranch = true;
238 * Shows specific mode (all or groups)
241 public $loginAllowedInBranch_mode = '';
244 * Set to backend user ID to initialize when keyword-based preview is used
247 public $ADMCMD_preview_BEUSER_uid = 0;
250 * Flag indication that preview is active. This is based on the login of a
251 * backend user and whether the backend user has read access to the current
252 * page. A value of 1 means ordinary preview, 2 means preview of a non-live
256 public $fePreview = 0;
259 * Flag indicating that hidden pages should be shown, selected and so on. This
260 * goes for almost all selection of pages!
263 public $showHiddenPage = false;
266 * Flag indicating that hidden records should be shown. This includes
267 * sys_template and even fe_groups in addition to all
268 * other regular content. So in effect, this includes everything except pages.
271 public $showHiddenRecords = false;
274 * Value that contains the simulated usergroup if any
277 public $simUserGroup = 0;
280 * "CONFIG" object from TypoScript. Array generated based on the TypoScript
281 * configuration of the current page. Saved with the cached pages.
287 * The TypoScript template object. Used to parse the TypoScript template
289 * @var TemplateService
294 * Is set to the time-to-live time of cached pages. If FALSE, default is
295 * 60*60*24, which is 24 hours.
298 public $cacheTimeOutDefault = false;
301 * Set internally if cached content is fetched from the database
305 public $cacheContentFlag = false;
308 * Set to the expire time of cached content
311 public $cacheExpires = 0;
314 * Set if cache headers allowing caching are sent.
317 public $isClientCachable = false;
320 * Used by template fetching system. This array is an identification of
321 * the template. If $this->all is empty it's because the template-data is not
322 * cached, which it must be.
328 * Toplevel - objArrayName, eg 'page'
334 * TypoScript configuration of the page-object pointed to by sPre.
335 * $this->tmpl->setup[$this->sPre.'.']
341 * This hash is unique to the template, the $this->id and $this->type vars and
342 * the gr_list (list of groups). Used to get and later store the cached data
345 public $newHash = '';
348 * If config.ftu (Frontend Track User) is set in TypoScript for the current
349 * page, the string value of this var is substituted in the rendered source-code
350 * with the string, '&ftu=[token...]' which enables GET-method usertracking as
351 * opposed to cookie based
354 public $getMethodUrlIdToken = '';
357 * This flag is set before inclusion of pagegen.php IF no_cache is set. If this
358 * flag is set after the inclusion of pagegen.php, no_cache is forced to be set.
359 * This is done in order to make sure that php-code from pagegen does not falsely
360 * clear the no_cache flag.
363 public $no_cacheBeforePageGen = false;
366 * This flag indicates if temporary content went into the cache during
370 public $tempContent = false;
373 * Passed to TypoScript template class and tells it to force template rendering
376 public $forceTemplateParsing = false;
379 * The array which cHash_calc is based on, see ->makeCacheHash().
382 public $cHash_array = [];
385 * May be set to the pagesTSconfig
388 public $pagesTSconfig = '';
391 * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
392 * once. Use associative keys.
396 * used to accumulate additional HTML-code for the header-section,
397 * <head>...</head>. Insert either associative keys (like
398 * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
399 * (like additionalHeaderData[] = '...')
403 public $additionalHeaderData = [];
406 * Used to accumulate additional HTML-code for the footer-section of the template
409 public $additionalFooterData = [];
412 * Used to accumulate additional JavaScript-code. Works like
413 * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
417 public $additionalJavaScript = [];
420 * Used to accumulate additional Style code. Works like additionalHeaderData.
424 public $additionalCSS = [];
437 * Used to accumulate DHTML-layers.
440 public $divSection = '';
443 * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
446 public $debug = false;
449 * Default internal target
452 public $intTarget = '';
455 * Default external target
458 public $extTarget = '';
461 * Default file link target
464 public $fileTarget = '';
467 * Keys are page ids and values are default &MP (mount point) values to set
468 * when using the linking features...)
471 public $MP_defaults = [];
474 * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
477 public $spamProtectEmailAddresses = 0;
480 * Absolute Reference prefix
483 public $absRefPrefix = '';
489 public $lockFilePath = '';
495 public $ATagParams = '';
498 * Search word regex, calculated if there has been search-words send. This is
499 * used to mark up the found search words on a page when jumped to from a link
500 * in a search-result.
503 public $sWordRegEx = '';
506 * Is set to the incoming array sword_list in case of a page-view jumped to from
510 public $sWordList = '';
513 * A string prepared for insertion in all links on the page as url-parameters.
514 * Based on configuration in TypoScript where you defined which GET_VARS you
515 * would like to pass on.
518 public $linkVars = '';
521 * If set, edit icons are rendered aside content records. Must be set only if
522 * the ->beUserLogin flag is set and set_no_cache() must be called as well.
525 public $displayEditIcons = '';
528 * If set, edit icons are rendered aside individual fields of content. Must be
529 * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
533 public $displayFieldEditIcons = '';
536 * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
537 * record. Should reflect which language menus, templates etc is displayed in
538 * (master language) - but not necessarily the content which could be falling
539 * back to default (see sys_language_content)
542 public $sys_language_uid = 0;
545 * Site language mode for content fall back.
548 public $sys_language_mode = '';
551 * Site content selection uid (can be different from sys_language_uid if content
552 * is to be selected from a fall-back language. Depends on sys_language_mode)
555 public $sys_language_content = 0;
558 * Site content overlay flag; If set - and sys_language_content is > 0 - ,
559 * records selected will try to look for a translation pointing to their uid. (If
560 * configured in [ctrl][languageField] / [ctrl][transOrigP...]
561 * Possible values: [0,1,hideNonTranslated]
562 * This flag is set based on TypoScript config.sys_language_overlay setting
566 public $sys_language_contentOL = 0;
569 * Is set to the iso code of the sys_language_content if that is properly defined
570 * by the sys_language record representing the sys_language_uid.
573 public $sys_language_isocode = '';
576 * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
580 public $applicationData = [];
585 public $register = [];
588 * Stack used for storing array and retrieving register arrays (see
589 * LOAD_REGISTER and RESTORE_REGISTER)
592 public $registerStack = [];
595 * Checking that the function is not called eternally. This is done by
596 * interrupting at a depth of 50
599 public $cObjectDepthCounter = 50;
602 * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
603 * rendered twice through it!
606 public $recordRegister = [];
609 * This is set to the [table]:[uid] of the latest record rendered. Note that
610 * class ContentObjectRenderer has an equal value, but that is pointing to the
611 * record delivered in the $data-array of the ContentObjectRenderer instance, if
612 * the cObjects CONTENT or RECORD created that instance
615 public $currentRecord = '';
618 * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
619 * to keep track of access-keys.
622 public $accessKey = [];
625 * Numerical array where image filenames are added if they are referenced in the
626 * rendered document. This includes only TYPO3 generated/inserted images.
629 public $imagesOnPage = [];
632 * Is set in ContentObjectRenderer->cImage() function to the info-array of the
633 * most recent rendered image. The information is used in ImageTextContentObject
636 public $lastImageInfo = [];
639 * Used to generate page-unique keys. Point is that uniqid() functions is very
640 * slow, so a unikey key is made based on this, see function uniqueHash()
643 public $uniqueCounter = 0;
648 public $uniqueString = '';
651 * This value will be used as the title for the page in the indexer (if
655 public $indexedDocTitle = '';
658 * Alternative page title (normally the title of the page record). Can be set
659 * from applications you make.
662 public $altPageTitle = '';
665 * The base URL set for the page header.
668 public $baseUrl = '';
671 * IDs we already rendered for this page (to make sure they are unique)
674 private $usedUniqueIds = [];
677 * Page content render object
679 * @var ContentObjectRenderer
684 * All page content is accumulated in this variable. See pagegen.php
687 public $content = '';
690 * Output charset of the websites content. This is the charset found in the
691 * header, meta tag etc. If different than utf-8 a conversion
692 * happens before output to browser. Defaults to utf-8.
695 public $metaCharset = 'utf-8';
698 * Set to the system language key (used on the site)
704 * Internal calculations for labels
706 * @var LanguageService
708 protected $languageService;
711 * @var LockingStrategyInterface[][]
713 protected $locks = [];
718 protected $pageRenderer = null;
721 * The page cache object, use this to save pages to the cache and to
722 * retrieve them again
724 * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
726 protected $pageCache;
731 protected $pageCacheTags = [];
734 * The cHash Service class used for cHash related functionality
736 * @var CacheHashCalculator
738 protected $cacheHash;
741 * Runtime cache of domains per processed page ids.
745 protected $domainDataCache = [];
748 * Content type HTTP header being sent in the request.
749 * @todo Ticket: #63642 Should be refactored to a request/response model later
750 * @internal Should only be used by TYPO3 core for now
754 protected $contentType = 'text/html';
761 public $xhtmlDoctype = '';
766 public $xhtmlVersion;
769 * Originally requested id from the initial $_GET variable
773 protected $requestedId;
777 * Takes a number of GET/POST input variable as arguments and stores them internally.
778 * The processing of these variables goes on later in this class.
779 * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
781 * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
782 * @param mixed $id The value of GeneralUtility::_GP('id')
783 * @param int $type The value of GeneralUtility::_GP('type')
784 * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0
785 * @param string $cHash The value of GeneralUtility::_GP('cHash')
786 * @param string $_2 previously was used to define the jumpURL
787 * @param string $MP The value of GeneralUtility::_GP('MP')
788 * @see \TYPO3\CMS\Frontend\Http\RequestHandler
790 public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '')
792 // Setting some variables:
796 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
797 $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
798 $this->getTimeTracker()->setTSlogMessage($warning, 2);
800 $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL') . '"';
801 $this->disableCache();
803 // note: we need to instantiate the logger manually here since the injection happens after the constructor
804 GeneralUtility
::makeInstance(LogManager
::class)->getLogger(__CLASS__
)->warning($warning);
806 $this->cHash
= $cHash;
807 $this->MP
= $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ?
(string)$MP : '';
808 $this->uniqueString
= md5(microtime());
809 $this->initPageRenderer();
810 // Call post processing function for constructor:
811 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
812 $_params = ['pObj' => &$this];
813 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
814 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
817 $this->cacheHash
= GeneralUtility
::makeInstance(CacheHashCalculator
::class);
822 * Initializes the page renderer object
824 protected function initPageRenderer()
826 if ($this->pageRenderer
!== null) {
829 $this->pageRenderer
= GeneralUtility
::makeInstance(PageRenderer
::class);
830 $this->pageRenderer
->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
834 * @param string $contentType
835 * @internal Should only be used by TYPO3 core for now
837 public function setContentType($contentType)
839 $this->contentType
= $contentType;
843 * Connect to SQL database. May exit after outputting an error message
844 * or some JavaScript redirecting to the install tool.
846 * @throws \RuntimeException
847 * @throws ServiceUnavailableException
849 public function connectToDB()
851 $connection = GeneralUtility
::makeInstance(ConnectionPool
::class)->getConnectionForTable('pages');
853 $connection->connect();
854 } catch (ConnectionException
$exception) {
855 // Cannot connect to current database
856 $message = 'Cannot connect to the configured database "' . $connection->getDatabase() . '"';
857 if ($this->checkPageUnavailableHandler()) {
858 $this->pageUnavailableAndExit($message);
860 $this->logger
->emergency($message, ['exception' => $exception]);
861 throw new ServiceUnavailableException($message, 1301648782);
864 // Call post processing function for DB connection:
865 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'])) {
866 $_params = ['pObj' => &$this];
867 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef) {
868 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
873 /********************************************
875 * Initializing, resolving page id
877 ********************************************/
879 * Initializes the caching system.
881 protected function initCaches()
883 $this->pageCache
= GeneralUtility
::makeInstance(CacheManager
::class)->getCache('cache_pages');
887 * Initializes the front-end login user.
889 public function initFEuser()
891 $this->fe_user
= GeneralUtility
::makeInstance(FrontendUserAuthentication
::class);
892 // List of pid's acceptable
893 $pid = GeneralUtility
::_GP('pid');
894 $this->fe_user
->checkPid_value
= $pid ?
implode(',', GeneralUtility
::intExplode(',', $pid)) : 0;
895 // Check if a session is transferred:
896 if (GeneralUtility
::_GP('FE_SESSION_KEY')) {
897 $fe_sParts = explode('-', GeneralUtility
::_GP('FE_SESSION_KEY'));
898 // If the session key hash check is OK:
899 if (md5(($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) === (string)$fe_sParts[1]) {
900 $cookieName = FrontendUserAuthentication
::getCookieName();
901 $_COOKIE[$cookieName] = $fe_sParts[0];
902 if (isset($_SERVER['HTTP_COOKIE'])) {
903 // See http://forge.typo3.org/issues/27740
904 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
906 $this->fe_user
->forceSetCookie
= 1;
907 $this->fe_user
->dontSetCookie
= false;
911 $this->fe_user
->start();
912 $this->fe_user
->unpack_uc();
914 // Call hook for possible manipulation of frontend user object
915 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'])) {
916 $_params = ['pObj' => &$this];
917 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef) {
918 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
921 // For every 60 seconds the is_online timestamp is updated.
922 if (is_array($this->fe_user
->user
) && $this->fe_user
->user
['uid'] && $this->fe_user
->user
['is_online'] < $GLOBALS['EXEC_TIME'] - 60) {
923 $dbConnection = GeneralUtility
::makeInstance(ConnectionPool
::class)
924 ->getConnectionForTable('fe_users');
925 $dbConnection->update(
928 'is_online' => $GLOBALS['EXEC_TIME']
931 'uid' => (int)$this->fe_user
->user
['uid']
938 * Initializes the front-end user groups.
939 * Sets ->loginUser and ->gr_list based on front-end user status.
941 public function initUserGroups()
943 // This affects the hidden-flag selecting the fe_groups for the user!
944 $this->fe_user
->showHiddenRecords
= $this->showHiddenRecords
;
945 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
946 $this->fe_user
->fetchGroupData();
947 if (is_array($this->fe_user
->user
) && !empty($this->fe_user
->groupData
['uid'])) {
949 $this->loginUser
= true;
950 // group -2 is not an existing group, but denotes a 'default' group when a user IS logged in. This is used to let elements be shown for all logged in users!
951 $this->gr_list
= '0,-2';
952 $gr_array = $this->fe_user
->groupData
['uid'];
954 $this->loginUser
= false;
955 // group -1 is not an existing group, but denotes a 'default' group when not logged in. This is used to let elements be hidden, when a user is logged in!
956 $this->gr_list
= '0,-1';
957 if ($this->loginAllowedInBranch
) {
958 // 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.
959 $gr_array = $this->fe_user
->groupData
['uid'];
961 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
967 $gr_array = array_unique($gr_array);
970 if (!empty($gr_array) && !$this->loginAllowedInBranch_mode
) {
971 $this->gr_list
.= ',' . implode(',', $gr_array);
973 $this->logger
->debug('Valid usergroups for TSFE: ' . $this->gr_list
);
977 * Checking if a user is logged in or a group constellation different from "0,-1"
979 * @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!)
981 public function isUserOrGroupSet()
983 return is_array($this->fe_user
->user
) ||
$this->gr_list
!== '0,-1';
987 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
990 * 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)
991 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
993 public function checkAlternativeIdMethods()
995 $this->siteScript
= GeneralUtility
::getIndpEnv('TYPO3_SITE_SCRIPT');
996 // Call post processing function for custom URL methods.
997 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
998 $_params = ['pObj' => &$this];
999 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef) {
1000 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1006 * Clears the preview-flags, sets sim_exec_time to current time.
1007 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
1008 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
1010 public function clear_preview()
1012 $this->showHiddenPage
= false;
1013 $this->showHiddenRecords
= false;
1014 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1015 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1016 $this->fePreview
= 0;
1020 * Checks if a backend user is logged in
1022 * @return bool whether a backend user is logged in
1024 public function isBackendUserLoggedIn()
1026 return (bool)$this->beUserLogin
;
1030 * Creates the backend user object and returns it.
1032 * @return FrontendBackendUserAuthentication the backend user object
1034 public function initializeBackendUser()
1037 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'])) {
1038 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] as $_funcRef) {
1040 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1043 $backendUserObject = null;
1044 // If the backend cookie is set,
1045 // we proceed and check if a backend user is logged in.
1046 if ($_COOKIE[BackendUserAuthentication
::getCookieName()]) {
1047 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1048 $this->getTimeTracker()->push('Back End user initialized', '');
1049 $this->beUserLogin
= false;
1050 // New backend user object
1051 $backendUserObject = GeneralUtility
::makeInstance(FrontendBackendUserAuthentication
::class);
1052 $backendUserObject->start();
1053 $backendUserObject->unpack_uc();
1054 if (!empty($backendUserObject->user
['uid'])) {
1055 $backendUserObject->fetchGroupData();
1057 // Unset the user initialization if any setting / restriction applies
1058 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1059 $backendUserObject = null;
1060 } elseif (!empty($backendUserObject->user
['uid'])) {
1061 // If the user is active now, let the controller know
1062 $this->beUserLogin
= true;
1064 $backendUserObject = null;
1066 $this->getTimeTracker()->pull();
1067 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1069 // POST BE_USER HOOK
1070 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'])) {
1072 'BE_USER' => &$backendUserObject
1074 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] as $_funcRef) {
1075 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1078 return $backendUserObject;
1082 * Determines the id and evaluates any preview settings
1083 * Basically this function is about determining whether a backend user is logged in,
1084 * if he has read access to the page and if he's previewing the page.
1085 * That all determines which id to show and how to initialize the id.
1087 public function determineId()
1089 // Call pre processing function for id determination
1090 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'])) {
1091 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] as $functionReference) {
1092 $parameters = ['parentObject' => $this];
1093 GeneralUtility
::callUserFunction($functionReference, $parameters, $this);
1096 // If there is a Backend login we are going to check for any preview settings:
1097 $this->getTimeTracker()->push('beUserLogin', '');
1098 $originalFrontendUser = null;
1099 $backendUser = $this->getBackendUser();
1100 if ($this->beUserLogin ||
$this->doWorkspacePreview()) {
1101 // Backend user preview features:
1102 if ($this->beUserLogin
&& $backendUser->adminPanel
instanceof AdminPanelView
) {
1103 $this->fePreview
= (int)$backendUser->adminPanel
->extGetFeAdminValue('preview');
1104 // If admin panel preview is enabled...
1105 if ($this->fePreview
) {
1106 if ($this->fe_user
->user
) {
1107 $originalFrontendUser = $this->fe_user
->user
;
1109 $this->showHiddenPage
= (bool)$backendUser->adminPanel
->extGetFeAdminValue('preview', 'showHiddenPages');
1110 $this->showHiddenRecords
= (bool)$backendUser->adminPanel
->extGetFeAdminValue('preview', 'showHiddenRecords');
1112 $simTime = $backendUser->adminPanel
->extGetFeAdminValue('preview', 'simulateDate');
1114 $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1115 $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime %
60;
1118 $simUserGroup = $backendUser->adminPanel
->extGetFeAdminValue('preview', 'simulateUserGroup');
1119 $this->simUserGroup
= $simUserGroup;
1120 if ($simUserGroup) {
1121 if ($this->fe_user
->user
) {
1122 $this->fe_user
->user
[$this->fe_user
->usergroup_column
] = $simUserGroup;
1124 $this->fe_user
->user
= [
1125 $this->fe_user
->usergroup_column
=> $simUserGroup
1129 if (!$simUserGroup && !$simTime && !$this->showHiddenPage
&& !$this->showHiddenRecords
) {
1130 $this->fePreview
= 0;
1134 if ($this->id
&& $this->determineIdIsHiddenPage()) {
1135 // The preview flag is set only if the current page turns out to actually be hidden!
1136 $this->fePreview
= 1;
1137 $this->showHiddenPage
= true;
1139 // The preview flag will be set if a backend user is in an offline workspace
1142 $backendUser->user
['workspace_preview']
1143 || GeneralUtility
::_GP('ADMCMD_view')
1144 ||
$this->doWorkspacePreview()
1147 $this->whichWorkspace() === -1
1148 ||
$this->whichWorkspace() > 0
1150 && !GeneralUtility
::_GP('ADMCMD_noBeUser')
1152 // Will show special preview message.
1153 $this->fePreview
= 2;
1155 // If the front-end is showing a preview, caching MUST be disabled.
1156 if ($this->fePreview
) {
1157 $this->disableCache();
1160 $this->getTimeTracker()->pull();
1161 // Now, get the id, validate access etc:
1162 $this->fetch_the_id();
1163 // Check if backend user has read access to this page. If not, recalculate the id.
1164 if ($this->beUserLogin
&& $this->fePreview
) {
1165 if (!$backendUser->doesUserHaveAccess($this->page
, 1)) {
1167 $this->clear_preview();
1168 $this->fe_user
->user
= $originalFrontendUser;
1169 // Fetching the id again, now with the preview settings reset.
1170 $this->fetch_the_id();
1173 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1174 $this->loginAllowedInBranch
= $this->checkIfLoginAllowedInBranch();
1175 // Logins are not allowed:
1176 if (!$this->loginAllowedInBranch
) {
1177 // Only if there is a login will we run this...
1178 if ($this->isUserOrGroupSet()) {
1179 if ($this->loginAllowedInBranch_mode
=== 'all') {
1180 // Clear out user and group:
1181 $this->fe_user
->hideActiveLogin();
1182 $this->gr_list
= '0,-1';
1184 $this->gr_list
= '0,-2';
1186 // Fetching the id again, now with the preview settings reset.
1187 $this->fetch_the_id();
1191 // Make sure it's an integer
1192 $this->id
= ($this->contentPid
= (int)$this->id
);
1193 // Make sure it's an integer
1194 $this->type
= (int)$this->type
;
1195 // Call post processing function for id determination:
1196 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
1197 $_params = ['pObj' => &$this];
1198 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef) {
1199 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1205 * Checks if the page is hidden in the active workspace.
1206 * If it is hidden, preview flags will be set.
1210 protected function determineIdIsHiddenPage()
1212 $field = MathUtility
::canBeInterpretedAsInteger($this->id
) ?
'uid' : 'alias';
1214 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1215 ->getQueryBuilderForTable('pages');
1219 ->add(GeneralUtility
::makeInstance(DeletedRestriction
::class));
1221 $page = $queryBuilder
1222 ->select('uid', 'hidden', 'starttime', 'endtime')
1225 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id
)),
1226 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO
::PARAM_INT
))
1232 $workspace = $this->whichWorkspace();
1233 if ($workspace !== 0 && $workspace !== false) {
1234 // Fetch overlay of page if in workspace and check if it is hidden
1235 $pageSelectObject = GeneralUtility
::makeInstance(PageRepository
::class);
1236 $pageSelectObject->versioningPreview
= true;
1237 $pageSelectObject->init(false);
1238 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1239 $result = $targetPage === -1 ||
$targetPage === -2;
1241 $result = is_array($page) && ($page['hidden'] ||
$page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] ||
$page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1247 * Resolves the page id and sets up several related properties.
1249 * If $this->id is not set at all or is not a plain integer, the method
1250 * does it's best to set the value to an integer. Resolving is based on
1253 * - Splitting $this->id if it contains an additional type parameter.
1254 * - Getting the id for an alias in $this->id
1255 * - Finding the domain record start page
1256 * - First visible page
1257 * - Relocating the id below the domain record if outside
1259 * The following properties may be set up or updated:
1266 * - sys_page->where_groupAccess
1267 * - sys_page->where_hid_del
1271 * - register['SYS_LASTCHANGED']
1274 * Via getPageAndRootlineWithDomain()
1279 * - originalShortcutPage
1280 * - originalMountPointPage
1281 * - pageAccessFailureHistory['direct_access']
1286 * On the first impression the method does to much. This is increased by
1287 * the fact, that is is called repeated times by the method determineId.
1288 * The reasons are manifold.
1290 * 1.) The first part, the creation of sys_page, the type and alias
1291 * resolution don't need to be repeated. They could be separated to be
1294 * 2.) The user group setup could be done once on a higher level.
1296 * 3.) The workflow of the resolution could be elaborated to be less
1297 * tangled. Maybe the check of the page id to be below the domain via the
1298 * root line doesn't need to be done each time, but for the final result
1301 * 4.) The root line does not need to be directly addressed by this class.
1302 * A root line is always related to one page. The rootline could be handled
1303 * indirectly by page objects. Page objects still don't exist.
1305 * @throws ServiceUnavailableException
1308 public function fetch_the_id()
1310 $timeTracker = $this->getTimeTracker();
1311 $timeTracker->push('fetch_the_id initialize/', '');
1312 // Initialize the page-select functions.
1313 $this->sys_page
= GeneralUtility
::makeInstance(PageRepository
::class);
1314 $this->sys_page
->versioningPreview
= $this->fePreview
=== 2 ||
(int)$this->workspacePreview ||
(bool)GeneralUtility
::_GP('ADMCMD_view');
1315 $this->sys_page
->versioningWorkspaceId
= $this->whichWorkspace();
1316 $this->sys_page
->init($this->showHiddenPage
);
1317 // Set the valid usergroups for FE
1318 $this->initUserGroups();
1319 // Sets sys_page where-clause
1320 $this->setSysPageWhereClause();
1321 // Splitting $this->id by a period (.).
1322 // First part is 'id' and second part (if exists) will overrule the &type param
1323 $idParts = explode('.', $this->id
, 2);
1324 $this->id
= $idParts[0];
1325 if (isset($idParts[1])) {
1326 $this->type
= $idParts[1];
1329 // If $this->id is a string, it's an alias
1330 $this->checkAndSetAlias();
1331 // The id and type is set to the integer-value - just to be sure...
1332 $this->id
= (int)$this->id
;
1333 $this->type
= (int)$this->type
;
1334 $timeTracker->pull();
1335 // We find the first page belonging to the current domain
1336 $timeTracker->push('fetch_the_id domain/', '');
1337 // The page_id of the current domain
1338 $this->domainStartPage
= $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1340 if ($this->domainStartPage
) {
1341 // If the id was not previously set, set it to the id of the domain.
1342 $this->id
= $this->domainStartPage
;
1344 // Find the first 'visible' page in that domain
1345 $theFirstPage = $this->sys_page
->getFirstWebPage($this->id
);
1346 if ($theFirstPage) {
1347 $this->id
= $theFirstPage['uid'];
1349 $message = 'No pages are found on the rootlevel!';
1350 if ($this->checkPageUnavailableHandler()) {
1351 $this->pageUnavailableAndExit($message);
1353 $this->logger
->alert($message);
1354 throw new ServiceUnavailableException($message, 1301648975);
1359 $timeTracker->pull();
1360 $timeTracker->push('fetch_the_id rootLine/', '');
1361 // We store the originally requested id
1362 $this->requestedId
= $this->id
;
1363 $this->getPageAndRootlineWithDomain($this->domainStartPage
);
1364 $timeTracker->pull();
1365 if ($this->pageNotFound
&& $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1367 1 => 'ID was not an accessible page',
1368 2 => 'Subsection was found and not accessible',
1369 3 => 'ID was outside the domain',
1370 4 => 'The requested page alias does not exist'
1372 $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound
]);
1374 // Init SYS_LASTCHANGED
1375 $this->register
['SYS_LASTCHANGED'] = (int)$this->page
['tstamp'];
1376 if ($this->register
['SYS_LASTCHANGED'] < (int)$this->page
['SYS_LASTCHANGED']) {
1377 $this->register
['SYS_LASTCHANGED'] = (int)$this->page
['SYS_LASTCHANGED'];
1379 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'])) {
1380 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] as $functionReference) {
1381 $parameters = ['parentObject' => $this];
1382 GeneralUtility
::callUserFunction($functionReference, $parameters, $this);
1388 * Loads the page and root line records based on $this->id
1390 * A final page and the matching root line are determined and loaded by
1391 * the algorithm defined by this method.
1393 * First it loads the initial page from the page repository for $this->id.
1394 * If that can't be loaded directly, it gets the root line for $this->id.
1395 * It walks up the root line towards the root page until the page
1396 * repository can deliver a page record. (The loading restrictions of
1397 * the root line records are more liberal than that of the page record.)
1399 * Now the page type is evaluated and handled if necessary. If the page is
1400 * a short cut, it is replaced by the target page. If the page is a mount
1401 * point in overlay mode, the page is replaced by the mounted page.
1403 * After this potential replacements are done, the root line is loaded
1404 * (again) for this page record. It walks up the root line up to
1405 * the first viewable record.
1407 * (While upon the first accessibility check of the root line it was done
1408 * by loading page by page from the page repository, this time the method
1409 * checkRootlineForIncludeSection() is used to find the most distant
1410 * accessible page within the root line.)
1412 * Having found the final page id, the page record and the root line are
1413 * loaded for last time by this method.
1415 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1418 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1419 * instead of throwing an exception it's handled by a page unavailable
1422 * May set or update this properties:
1424 * @see TypoScriptFrontendController::$id
1425 * @see TypoScriptFrontendController::$MP
1426 * @see TypoScriptFrontendController::$page
1427 * @see TypoScriptFrontendController::$pageNotFound
1428 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1429 * @see TypoScriptFrontendController::$originalMountPointPage
1430 * @see TypoScriptFrontendController::$originalShortcutPage
1432 * @throws ServiceUnavailableException
1433 * @throws PageNotFoundException
1436 public function getPageAndRootline()
1438 $this->page
= $this->sys_page
->getPage($this->id
);
1439 if (empty($this->page
)) {
1440 // If no page, we try to find the page before in the rootLine.
1441 // Page is 'not found' in case the id itself was not an accessible page. code 1
1442 $this->pageNotFound
= 1;
1443 $this->rootLine
= $this->sys_page
->getRootLine($this->id
, $this->MP
);
1444 if (!empty($this->rootLine
)) {
1445 $c = count($this->rootLine
) - 1;
1447 // Add to page access failure history:
1448 $this->pageAccessFailureHistory
['direct_access'][] = $this->rootLine
[$c];
1449 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1451 $this->id
= $this->rootLine
[$c]['uid'];
1452 $this->page
= $this->sys_page
->getPage($this->id
);
1453 if (!empty($this->page
)) {
1458 // If still no page...
1459 if (empty($this->page
)) {
1460 $message = 'The requested page does not exist!';
1461 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1462 $this->pageNotFoundAndExit($message);
1464 $this->logger
->error($message);
1465 throw new PageNotFoundException($message, 1301648780);
1469 // Spacer is not accessible in frontend
1470 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_SPACER
) {
1471 $message = 'The requested page does not exist!';
1472 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1473 $this->pageNotFoundAndExit($message);
1475 $this->logger
->error($message);
1476 throw new PageNotFoundException($message, 1301648781);
1479 // Is the ID a link to another page??
1480 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_SHORTCUT
) {
1481 // 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.
1483 // saving the page so that we can check later - when we know
1484 // about languages - whether we took the correct shortcut or
1485 // whether a translation of the page overwrites the shortcut
1486 // target and we need to follow the new target
1487 $this->originalShortcutPage
= $this->page
;
1488 $this->page
= $this->getPageShortcut($this->page
['shortcut'], $this->page
['shortcut_mode'], $this->page
['uid']);
1489 $this->id
= $this->page
['uid'];
1491 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1492 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1493 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1494 if ($this->page
['doktype'] == PageRepository
::DOKTYPE_MOUNTPOINT
&& $this->page
['mount_pid_ol']) {
1495 $this->originalMountPointPage
= $this->page
;
1496 $this->page
= $this->sys_page
->getPage($this->page
['mount_pid']);
1497 if (empty($this->page
)) {
1498 $message = 'This page (ID ' . $this->originalMountPointPage
['uid'] . ') is of type "Mount point" and '
1499 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage
['mount_pid'] . ').';
1500 throw new PageNotFoundException($message, 1402043263);
1502 $this->MP
= $this->page
['uid'] . '-' . $this->originalMountPointPage
['uid'];
1503 $this->id
= $this->page
['uid'];
1505 // Gets the rootLine
1506 $this->rootLine
= $this->sys_page
->getRootLine($this->id
, $this->MP
);
1507 // If not rootline we're off...
1508 if (empty($this->rootLine
)) {
1509 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1510 if ($this->checkPageUnavailableHandler()) {
1511 $this->pageUnavailableAndExit($message);
1513 $this->logger
->error($message);
1514 throw new ServiceUnavailableException($message, 1301648167);
1517 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1518 if ($this->checkRootlineForIncludeSection()) {
1519 if (empty($this->rootLine
)) {
1520 $message = 'The requested page was not accessible!';
1521 if ($this->checkPageUnavailableHandler()) {
1522 $this->pageUnavailableAndExit($message);
1524 $this->logger
->warning($message);
1525 throw new ServiceUnavailableException($message, 1301648234);
1528 $el = reset($this->rootLine
);
1529 $this->id
= $el['uid'];
1530 $this->page
= $this->sys_page
->getPage($this->id
);
1531 $this->rootLine
= $this->sys_page
->getRootLine($this->id
, $this->MP
);
1537 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1539 * @param int $SC The value of the "shortcut" field from the pages record
1540 * @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
1541 * @param int $thisUid The current page UID of the page which is a shortcut
1542 * @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...)
1543 * @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.
1544 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1545 * @throws \RuntimeException
1546 * @throws PageNotFoundException
1547 * @return mixed Returns the page record of the page that the shortcut pointed to.
1549 * @see getPageAndRootline()
1551 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1553 $idArray = GeneralUtility
::intExplode(',', $SC);
1554 // Find $page record depending on shortcut mode:
1556 case PageRepository
::SHORTCUT_MODE_FIRST_SUBPAGE
:
1558 case PageRepository
::SHORTCUT_MODE_RANDOM_SUBPAGE
:
1559 $pageArray = $this->sys_page
->getMenu($idArray[0] ?
$idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository
::DOKTYPE_BE_USER_SECTION
);
1561 if ($mode == PageRepository
::SHORTCUT_MODE_RANDOM_SUBPAGE
&& !empty($pageArray)) {
1562 $randval = (int)rand(0, count($pageArray) - 1);
1567 foreach ($pageArray as $pV) {
1575 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1576 throw new PageNotFoundException($message, 1301648328);
1579 case PageRepository
::SHORTCUT_MODE_PARENT_PAGE
:
1580 $parent = $this->sys_page
->getPage($idArray[0] ?
$idArray[0] : $thisUid, $disableGroupCheck);
1581 $page = $this->sys_page
->getPage($parent['pid'], $disableGroupCheck);
1583 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1584 throw new PageNotFoundException($message, 1301648358);
1588 $page = $this->sys_page
->getPage($idArray[0], $disableGroupCheck);
1590 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1591 throw new PageNotFoundException($message, 1301648404);
1594 // Check if short cut page was a shortcut itself, if so look up recursively:
1595 if ($page['doktype'] == PageRepository
::DOKTYPE_SHORTCUT
) {
1596 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1597 $pageLog[] = $page['uid'];
1598 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1600 $pageLog[] = $page['uid'];
1601 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1602 $this->logger
->error($message);
1603 throw new \
RuntimeException($message, 1294587212);
1606 // Return resulting page:
1611 * Checks the current rootline for defined sections.
1616 public function checkRootlineForIncludeSection()
1618 $c = count($this->rootLine
);
1619 $removeTheRestFlag = 0;
1620 for ($a = 0; $a < $c; $a++
) {
1621 if (!$this->checkPagerecordForIncludeSection($this->rootLine
[$a])) {
1622 // Add to page access failure history:
1623 $this->pageAccessFailureHistory
['sub_section'][] = $this->rootLine
[$a];
1624 $removeTheRestFlag = 1;
1627 if ($this->rootLine
[$a]['doktype'] == PageRepository
::DOKTYPE_BE_USER_SECTION
) {
1628 // If there is a backend user logged in, check if he has read access to the page:
1629 if ($this->beUserLogin
) {
1630 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1631 ->getQueryBuilderForTable('pages');
1637 $row = $queryBuilder
1641 $queryBuilder->expr()->eq(
1643 $queryBuilder->createNamedParameter($this->id
, \PDO
::PARAM_INT
)
1645 $this->getBackendUser()->getPagePermsClause(1)
1652 // 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...
1653 $removeTheRestFlag = 1;
1656 // Don't go here, if there is no backend user logged in.
1657 $removeTheRestFlag = 1;
1660 if ($removeTheRestFlag) {
1661 // Page is 'not found' in case a subsection was found and not accessible, code 2
1662 $this->pageNotFound
= 2;
1663 unset($this->rootLine
[$a]);
1666 return $removeTheRestFlag;
1670 * Checks page record for enableFields
1671 * Returns TRUE if enableFields does not disable the page record.
1672 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1674 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1675 * @param bool $bypassGroupCheck Bypass group-check
1676 * @return bool TRUE, if record is viewable.
1677 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1679 public function checkEnableFields($row, $bypassGroupCheck = false)
1681 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'])) {
1682 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1683 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] as $_funcRef) {
1684 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1685 $return = GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
1686 if ($return === false) {
1691 if ((!$row['hidden'] ||
$this->showHiddenPage
) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 ||
$row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck ||
$this->checkPageGroupAccess($row))) {
1698 * Check group access against a page record
1700 * @param array $row The page record to evaluate (needs field: fe_group)
1701 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1702 * @return bool TRUE, if group access is granted.
1705 public function checkPageGroupAccess($row, $groupList = null)
1707 if (is_null($groupList)) {
1708 $groupList = $this->gr_list
;
1710 if (!is_array($groupList)) {
1711 $groupList = explode(',', $groupList);
1713 $pageGroupList = explode(',', $row['fe_group'] ?
: 0);
1714 return count(array_intersect($groupList, $pageGroupList)) > 0;
1718 * Checks page record for include section
1720 * @param array $row The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
1721 * @return bool Returns TRUE if either extendToSubpages is not checked or if the enableFields does not disable the page record.
1723 * @see checkEnableFields(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkRootlineForIncludeSection()
1725 public function checkPagerecordForIncludeSection($row)
1727 return !$row['extendToSubpages'] ||
$this->checkEnableFields($row) ?
1 : 0;
1731 * 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!)
1733 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1735 public function checkIfLoginAllowedInBranch()
1738 $c = count($this->rootLine
);
1739 $loginAllowed = true;
1740 // Traverse root line from root and outwards:
1741 for ($a = 0; $a < $c; $a++
) {
1742 // If a value is set for login state:
1743 if ($this->rootLine
[$a]['fe_login_mode'] > 0) {
1744 // Determine state from value:
1745 if ((int)$this->rootLine
[$a]['fe_login_mode'] === 1) {
1746 $loginAllowed = false;
1747 $this->loginAllowedInBranch_mode
= 'all';
1748 } elseif ((int)$this->rootLine
[$a]['fe_login_mode'] === 3) {
1749 $loginAllowed = false;
1750 $this->loginAllowedInBranch_mode
= 'groups';
1752 $loginAllowed = true;
1756 return $loginAllowed;
1760 * 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
1762 * @return array Summary of why page access was not allowed.
1764 public function getPageAccessFailureReasons()
1767 $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'] : []);
1768 if (!empty($combinedRecords)) {
1769 foreach ($combinedRecords as $k => $pagerec) {
1770 // 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
1771 // 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!
1772 if (!$k ||
$pagerec['extendToSubpages']) {
1773 if ($pagerec['hidden']) {
1774 $output['hidden'][$pagerec['uid']] = true;
1776 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1777 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1779 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1780 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1782 if (!$this->checkPageGroupAccess($pagerec)) {
1783 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1792 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1793 * If not inside domain, then default to first page in domain.
1795 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1798 public function getPageAndRootlineWithDomain($domainStartPage)
1800 $this->getPageAndRootline();
1801 // 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.
1802 if ($domainStartPage && is_array($this->rootLine
)) {
1804 foreach ($this->rootLine
as $key => $val) {
1805 if ($val['uid'] == $domainStartPage) {
1811 // Page is 'not found' in case the id was outside the domain, code 3
1812 $this->pageNotFound
= 3;
1813 $this->id
= $domainStartPage;
1814 // re-get the page and rootline if the id was not found.
1815 $this->getPageAndRootline();
1821 * Sets sys_page where-clause
1825 public function setSysPageWhereClause()
1827 $expressionBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)
1828 ->getConnectionForTable('pages')
1829 ->getExpressionBuilder();
1830 $this->sys_page
->where_hid_del
= ' AND ' . (string)$expressionBuilder->andX(
1831 QueryHelper
::stripLogicalOperatorPrefix($this->sys_page
->where_hid_del
),
1832 $expressionBuilder->lt('pages.doktype', 200)
1834 $this->sys_page
->where_groupAccess
= $this->sys_page
->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1838 * Looking up a domain record based on HTTP_HOST
1840 * @param bool $recursive If set, it looks "recursively" meaning that a domain like "123.456.typo3.com" would find a domain record like "typo3.com" if "123.456.typo3.com" or "456.typo3.com" did not exist.
1841 * @return int Returns the page id of the page where the domain record was found.
1844 public function findDomainRecord($recursive = false)
1848 $host = explode('.', GeneralUtility
::getIndpEnv('HTTP_HOST'));
1849 while (count($host)) {
1850 $pageUid = $this->sys_page
->getDomainStartPage(implode('.', $host), GeneralUtility
::getIndpEnv('SCRIPT_NAME'), GeneralUtility
::getIndpEnv('REQUEST_URI'));
1858 return $this->sys_page
->getDomainStartPage(GeneralUtility
::getIndpEnv('HTTP_HOST'), GeneralUtility
::getIndpEnv('SCRIPT_NAME'), GeneralUtility
::getIndpEnv('REQUEST_URI'));
1862 * Page unavailable handler for use in frontend plugins from extensions.
1864 * @param string $reason Reason text
1865 * @param string $header HTTP header to send
1867 public function pageUnavailableAndExit($reason = '', $header = '')
1869 $header = $header ?
: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1870 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1875 * Page-not-found handler for use in frontend plugins from extensions.
1877 * @param string $reason Reason text
1878 * @param string $header HTTP header to send
1880 public function pageNotFoundAndExit($reason = '', $header = '')
1882 $header = $header ?
: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1883 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1888 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1889 * and devIPMask must not match the current visitor's IP address.
1891 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1893 public function checkPageUnavailableHandler()
1896 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1897 && !GeneralUtility
::cmpIP(
1898 GeneralUtility
::getIndpEnv('REMOTE_ADDR'),
1899 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1902 $checkPageUnavailableHandler = true;
1904 $checkPageUnavailableHandler = false;
1906 return $checkPageUnavailableHandler;
1910 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1912 * @param mixed $code Which type of handling; If a true PHP-boolean or TRUE then a \TYPO3\CMS\Core\Messaging\ErrorpageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
1913 * @param string $header If set, this is passed directly to the PHP function, header()
1914 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1916 public function pageUnavailableHandler($code, $header, $reason)
1918 $this->pageErrorHandler($code, $header, $reason);
1922 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1924 * @param mixed $code Which type of handling; If a true PHP-boolean or TRUE then a \TYPO3\CMS\Core\Messaging\ErrorpageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
1925 * @param string $header If set, this is passed directly to the PHP function, header()
1926 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1928 public function pageNotFoundHandler($code, $header = '', $reason = '')
1930 $this->pageErrorHandler($code, $header, $reason);
1934 * Generic error page handler.
1937 * @param mixed $code Which type of handling; If a true PHP-boolean or TRUE then a \TYPO3\CMS\Core\Messaging\ErrorpageMessage is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
1938 * @param string $header If set, this is passed directly to the PHP function, header()
1939 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1940 * @throws \RuntimeException
1942 public function pageErrorHandler($code, $header = '', $reason = '')
1944 // Issue header in any case:
1946 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY
);
1947 foreach ($headerArr as $header) {
1952 // Simply boolean; Just shows TYPO3 error page with reason:
1953 if (strtolower($code) === 'true' ||
(string)$code === '1' ||
gettype($code) === 'boolean') {
1954 echo GeneralUtility
::makeInstance(ErrorPageController
::class)->errorAction(
1956 'The page did not exist or was inaccessible.' . ($reason ?
' Reason: ' . $reason : '')
1958 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1959 $funcRef = trim(substr($code, 14));
1961 'currentUrl' => GeneralUtility
::getIndpEnv('REQUEST_URI'),
1962 'reasonText' => $reason,
1963 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1965 echo GeneralUtility
::callUserFunction($funcRef, $params, $this);
1966 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'READFILE:')) {
1967 $readFile = GeneralUtility
::getFileAbsFileName(trim(substr($code, 9)));
1968 if (@is_file
($readFile)) {
1971 '###CURRENT_URL###',
1975 GeneralUtility
::getIndpEnv('REQUEST_URI'),
1976 htmlspecialchars($reason)
1978 file_get_contents($readFile)
1981 throw new \
RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
1983 } elseif (GeneralUtility
::isFirstPartOfStr($code, 'REDIRECT:')) {
1984 HttpUtility
::redirect(substr($code, 9));
1985 } elseif ($code !== '') {
1986 // Check if URL is relative
1987 $url_parts = parse_url($code);
1988 // parse_url could return an array without the key "host", the empty check works better than strict check
1989 if (empty($url_parts['host'])) {
1990 $url_parts['host'] = GeneralUtility
::getIndpEnv('HTTP_HOST');
1991 if ($code[0] === '/') {
1992 $code = GeneralUtility
::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
1994 $code = GeneralUtility
::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
1996 $checkBaseTag = false;
1998 $checkBaseTag = true;
2001 if ($code == GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL')) {
2002 if ($reason == '') {
2003 $reason = 'Page cannot be found.';
2005 $reason .= LF
. LF
. 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2006 throw new \
RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2010 'User-agent: ' . GeneralUtility
::getIndpEnv('HTTP_USER_AGENT'),
2011 'Referer: ' . GeneralUtility
::getIndpEnv('TYPO3_REQUEST_URL')
2013 $res = GeneralUtility
::getUrl($code, 1, $headerArr);
2014 // Header and content are separated by an empty line
2015 list($header, $content) = explode(CRLF
. CRLF
, $res, 2);
2017 if (false === $res) {
2018 // Last chance -- redirect
2019 HttpUtility
::redirect($code);
2021 // Forward these response headers to the client
2025 $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY
);
2026 foreach ($headerArr as $header) {
2027 foreach ($forwardHeaders as $h) {
2028 if (preg_match('/^' . $h . '/', $header)) {
2033 // Put <base> if necessary
2034 if ($checkBaseTag) {
2035 // If content already has <base> tag, we do not need to do anything
2036 if (false === stristr($content, '<base ')) {
2037 // Generate href for base tag
2038 $base = $url_parts['scheme'] . '://';
2039 if ($url_parts['user'] != '') {
2040 $base .= $url_parts['user'];
2041 if ($url_parts['pass'] != '') {
2042 $base .= ':' . $url_parts['pass'];
2046 $base .= $url_parts['host'];
2047 // Add path portion skipping possible file name
2048 $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2049 // Put it into content (generate also <head> if necessary)
2050 $replacement = LF
. '<base href="' . htmlentities($base) . '" />' . LF
;
2051 if (stristr($content, '<head>')) {
2052 $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2054 $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2058 // Output the content
2062 echo GeneralUtility
::makeInstance(ErrorPageController
::class)->errorAction(
2064 $reason ?
'Reason: ' . $reason : 'Page cannot be found.'
2071 * Fetches the integer page id for a page alias.
2072 * 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
2076 public function checkAndSetAlias()
2078 if ($this->id
&& !MathUtility
::canBeInterpretedAsInteger($this->id
)) {
2079 $aid = $this->sys_page
->getPageIdFromAlias($this->id
);
2083 $this->pageNotFound
= 4;
2089 * Merging values into the global $_GET
2091 * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2093 public function mergingWithGetVars($GET_VARS)
2095 if (is_array($GET_VARS)) {
2096 // Getting $_GET var, unescaped.
2097 $realGet = GeneralUtility
::_GET();
2098 if (!is_array($realGet)) {
2101 // Merge new values on top:
2102 ArrayUtility
::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2103 // Write values back to $_GET:
2104 GeneralUtility
::_GETset($realGet);
2105 // Setting these specifically (like in the init-function):
2106 if (isset($GET_VARS['type'])) {
2107 $this->type
= (int)$GET_VARS['type'];
2109 if (isset($GET_VARS['cHash'])) {
2110 $this->cHash
= $GET_VARS['cHash'];
2112 if (isset($GET_VARS['MP'])) {
2113 $this->MP
= $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ?
$GET_VARS['MP'] : '';
2115 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2116 $this->set_no_cache('no_cache is requested via GET parameter');
2121 /********************************************
2123 * Template and caching related functions.
2125 *******************************************/
2127 * Calculates a hash string based on additional parameters in the url.
2129 * Calculated hash is stored in $this->cHash_array.
2130 * This is used to cache pages with more parameters than just id and type.
2134 public function makeCacheHash()
2136 // No need to test anything if caching was already disabled.
2137 if ($this->no_cache
&& !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2140 $GET = GeneralUtility
::_GET();
2141 if ($this->cHash
&& is_array($GET)) {
2142 // Make sure we use the page uid and not the page alias
2143 $GET['id'] = $this->id
;
2144 $this->cHash_array
= $this->cacheHash
->getRelevantParameters(GeneralUtility
::implodeArrayForUrl('', $GET));
2145 $cHash_calc = $this->cacheHash
->calculateCacheHash($this->cHash_array
);
2146 if ($cHash_calc != $this->cHash
) {
2147 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2148 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
2150 $this->disableCache();
2151 $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);
2154 } elseif (is_array($GET)) {
2155 // No cHash is set, check if that is correct
2156 if ($this->cacheHash
->doParametersRequireCacheHash(GeneralUtility
::implodeArrayForUrl('', $GET))) {
2163 * Will disable caching if the cHash value was not set.
2164 * 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)
2166 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2168 public function reqCHash()
2170 if (!$this->cHash
) {
2171 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2172 if ($this->tempContent
) {
2173 $this->clearPageCacheContent();
2175 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
2177 $this->disableCache();
2178 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2184 * Initialize the TypoScript template parser
2186 public function initTemplate()
2188 $this->tmpl
= GeneralUtility
::makeInstance(TemplateService
::class);
2189 $this->tmpl
->setVerbose((bool)$this->beUserLogin
);
2190 $this->tmpl
->init();
2191 $this->tmpl
->tt_track
= (bool)$this->beUserLogin
;
2195 * See if page is in cache and get it if so
2196 * Stores the page content in $this->content if something is found.
2198 * @throws \InvalidArgumentException
2199 * @throws \RuntimeException
2201 public function getFromCache()
2203 // clearing the content-variable, which will hold the pagecontent
2204 $this->content
= '';
2205 // Unsetting the lowlevel config
2207 $this->cacheContentFlag
= false;
2209 if ($this->no_cache
) {
2213 $pageSectionCacheContent = $this->tmpl
->getCurrentPageData();
2214 if (!is_array($pageSectionCacheContent)) {
2215 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2216 // We use the Registry to store this lock centrally,
2217 // but we protect the access again with a global exclusive lock to avoid race conditions
2219 $this->acquireLock('pagesection', $this->id
. '::' . $this->MP
);
2221 // from this point on we're the only one working on that page ($key)
2224 // query the cache again to see if the page data are there meanwhile
2225 $pageSectionCacheContent = $this->tmpl
->getCurrentPageData();
2226 if (is_array($pageSectionCacheContent)) {
2227 // we have the content, nice that some other process did the work for us already
2228 $this->releaseLock('pagesection');
2230 // We keep the lock set, because we are the ones generating the page now
2231 // and filling the cache.
2232 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2235 if (is_array($pageSectionCacheContent)) {
2236 // 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.
2237 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2238 // 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.
2239 $pageSectionCacheContent = $this->tmpl
->matching($pageSectionCacheContent);
2240 ksort($pageSectionCacheContent);
2241 $this->all
= $pageSectionCacheContent;
2243 unset($pageSectionCacheContent);
2245 // Look for page in cache only if a shift-reload is not sent to the server.
2246 $lockHash = $this->getLockHash();
2247 if (!$this->headerNoCache()) {
2249 // we got page section information
2250 $this->newHash
= $this->getHash();
2251 $this->getTimeTracker()->push('Cache Row', '');
2252 $row = $this->getFromCache_queryRow();
2253 if (!is_array($row)) {
2254 // nothing in the cache, we acquire an exclusive lock now
2256 $this->acquireLock('pages', $lockHash);
2258 // from this point on we're the only one working on that page ($lockHash)
2261 // query the cache again to see if the data are there meanwhile
2262 $row = $this->getFromCache_queryRow();
2263 if (is_array($row)) {
2264 // we have the content, nice that some other process did the work for us
2265 $this->releaseLock('pages');
2267 // We keep the lock set, because we are the ones generating the page now
2268 // and filling the cache.
2269 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2271 if (is_array($row)) {
2272 // we have data from cache
2274 // Call hook when a page is retrieved from cache:
2275 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'])) {
2276 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2277 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] as $_funcRef) {
2278 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2281 // Fetches the lowlevel config stored with the cached data
2282 $this->config
= $row['cache_data'];
2283 // Getting the content
2284 $this->content
= $row['content'];
2285 // Flag for temp content
2286 $this->tempContent
= $row['temp_content'];
2287 // Setting flag, so we know, that some cached content has been loaded
2288 $this->cacheContentFlag
= true;
2289 $this->cacheExpires
= $row['expires'];
2291 // Restore page title information, this is needed to generate the page title for
2292 // partially cached pages.
2293 $this->page
['title'] = $row['pageTitleInfo']['title'];
2294 $this->altPageTitle
= $row['pageTitleInfo']['altPageTitle'];
2295 $this->indexedDocTitle
= $row['pageTitleInfo']['indexedDocTitle'];
2297 if (isset($this->config
['config']['debug'])) {
2298 $debugCacheTime = (bool)$this->config
['config']['debug'];
2300 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2302 if ($debugCacheTime) {
2303 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2304 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2305 $this->content
.= LF
. '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2308 $this->getTimeTracker()->pull();
2313 // the user forced rebuilding the page cache or there was no pagesection information
2314 // get a lock for the page content so other processes will not interrupt the regeneration
2315 $this->acquireLock('pages', $lockHash);
2319 * Returning the cached version of page with hash = newHash
2321 * @return array Cached row, if any. Otherwise void.
2323 public function getFromCache_queryRow()
2325 $this->getTimeTracker()->push('Cache Query', '');
2326 $row = $this->pageCache
->get($this->newHash
);
2327 $this->getTimeTracker()->pull();
2332 * Detecting if shift-reload has been clicked
2333 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2334 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2336 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2338 public function headerNoCache()
2340 $disableAcquireCacheData = false;
2341 if ($this->beUserLogin
) {
2342 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' ||
strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2343 $disableAcquireCacheData = true;
2346 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2347 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'])) {
2348 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2349 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] as $_funcRef) {
2350 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2353 return $disableAcquireCacheData;
2357 * Calculates the cache-hash
2358 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2359 * Used to get and later store the cached data.
2361 * @return string MD5 hash of serialized hash base from createHashBase()
2363 * @see getFromCache(), getLockHash()
2365 public function getHash()
2367 return md5($this->createHashBase(false));
2371 * Calculates the lock-hash
2372 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2374 * @return string MD5 hash
2376 * @see getFromCache(), getHash()
2378 public function getLockHash()
2380 $lockHash = $this->createHashBase(true);
2381 return md5($lockHash);
2385 * Calculates the cache-hash (or the lock-hash)
2386 * This hash is unique to the template,
2387 * the variables ->id, ->type, ->gr_list (list of groups),
2388 * ->MP (Mount Points) and cHash array
2389 * Used to get and later store the cached data.
2391 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2392 * @return string the serialized hash base
2394 protected function createHashBase($createLockHashBase = false)
2397 'id' => (int)$this->id
,
2398 'type' => (int)$this->type
,
2399 'gr_list' => (string)$this->gr_list
,
2400 'MP' => (string)$this->MP
,
2401 'cHash' => $this->cHash_array
,
2402 'domainStartPage' => $this->domainStartPage
2404 // Include the template information if we shouldn't create a lock hash
2405 if (!$createLockHashBase) {
2406 $hashParameters['all'] = $this->all
;
2408 // Call hook to influence the hash calculation
2409 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'])) {
2411 'hashParameters' => &$hashParameters,
2412 'createLockHashBase' => $createLockHashBase
2414 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] as $_funcRef) {
2415 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2418 return serialize($hashParameters);
2422 * Checks if config-array exists already but if not, gets it
2424 * @throws ServiceUnavailableException
2426 public function getConfigArray()
2428 // 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
2429 if (empty($this->config
) ||
is_array($this->config
['INTincScript']) ||
$this->forceTemplateParsing
) {
2430 $timeTracker = $this->getTimeTracker();
2431 $timeTracker->push('Parse template', '');
2432 // Force parsing, if set?:
2433 $this->tmpl
->forceTemplateParsing
= $this->forceTemplateParsing
;
2434 // Start parsing the TS template. Might return cached version.
2435 $this->tmpl
->start($this->rootLine
);
2436 $timeTracker->pull();
2437 if ($this->tmpl
->loaded
) {
2438 $timeTracker->push('Setting the config-array', '');
2439 // toplevel - objArrayName
2440 $this->sPre
= $this->tmpl
->setup
['types.'][$this->type
];
2441 $this->pSetup
= $this->tmpl
->setup
[$this->sPre
. '.'];
2442 if (!is_array($this->pSetup
)) {
2443 $message = 'The page is not configured! [type=' . $this->type
. '][' . $this->sPre
. '].';
2444 if ($this->checkPageUnavailableHandler()) {
2445 $this->pageUnavailableAndExit($message);
2447 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type
. ' configured.';
2448 $this->logger
->alert($message);
2449 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2452 if (!isset($this->config
['config'])) {
2453 $this->config
['config'] = [];
2455 // Filling the config-array, first with the main "config." part
2456 if (is_array($this->tmpl
->setup
['config.'])) {
2457 ArrayUtility
::mergeRecursiveWithOverrule($this->tmpl
->setup
['config.'], $this->config
['config']);
2458 $this->config
['config'] = $this->tmpl
->setup
['config.'];
2460 // override it with the page/type-specific "config."
2461 if (is_array($this->pSetup
['config.'])) {
2462 ArrayUtility
::mergeRecursiveWithOverrule($this->config
['config'], $this->pSetup
['config.']);
2464 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2465 if ($this->config
['config']['typolinkCheckRootline']) {
2466 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2468 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2469 if (!isset($this->config
['config']['removeDefaultJS'])) {
2470 $this->config
['config']['removeDefaultJS'] = 'external';
2472 if (!isset($this->config
['config']['inlineStyle2TempFile'])) {
2473 $this->config
['config']['inlineStyle2TempFile'] = 1;
2476 if (!isset($this->config
['config']['compressJs'])) {
2477 $this->config
['config']['compressJs'] = 0;
2479 // Processing for the config_array:
2480 $this->config
['rootLine'] = $this->tmpl
->rootLine
;
2481 // Class for render Header and Footer parts
2482 if ($this->pSetup
['pageHeaderFooterTemplateFile']) {
2483 $file = $this->tmpl
->getFileName($this->pSetup
['pageHeaderFooterTemplateFile']);
2485 $this->pageRenderer
->setTemplateFile($file);
2489 $timeTracker->pull();
2491 if ($this->checkPageUnavailableHandler()) {
2492 $this->pageUnavailableAndExit('No TypoScript template found!');
2494 $message = 'No TypoScript template found!';
2495 $this->logger
->alert($message);
2496 throw new ServiceUnavailableException($message, 1294587218);
2502 // Set $this->no_cache TRUE if the config.no_cache value is set!
2503 if ($this->config
['config']['no_cache']) {
2504 $this->set_no_cache('config.no_cache is set');
2506 // Merge GET with defaultGetVars
2507 if (!empty($this->config
['config']['defaultGetVars.'])) {
2508 $modifiedGetVars = GeneralUtility
::removeDotsFromTS($this->config
['config']['defaultGetVars.']);
2509 ArrayUtility
::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility
::_GET());
2510 GeneralUtility
::_GETset($modifiedGetVars);
2512 // Hook for postProcessing the configuration array
2513 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'])) {
2514 $params = ['config' => &$this->config
['config']];
2515 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] as $funcRef) {
2516 GeneralUtility
::callUserFunction($funcRef, $params, $this);
2521 /********************************************
2523 * Further initialization and data processing
2525 *******************************************/
2528 * Setting the language key that will be used by the current page.
2529 * 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.
2533 public function settingLanguage()
2535 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'])) {
2537 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] as $_funcRef) {
2538 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2542 // Initialize charset settings etc.
2543 $languageKey = $this->config
['config']['language'] ??
'default';
2544 $this->lang
= $languageKey;
2545 $this->setOutputLanguage($languageKey);
2547 // Rendering charset of HTML page.
2548 if (isset($this->config
['config']['metaCharset']) && $this->config
['config']['metaCharset'] !== 'utf-8') {
2549 $this->metaCharset
= $this->config
['config']['metaCharset'];
2552 // Get values from TypoScript:
2553 $this->sys_language_uid
= ($this->sys_language_content
= (int)$this->config
['config']['sys_language_uid']);
2554 list($this->sys_language_mode
, $sys_language_content) = GeneralUtility
::trimExplode(';', $this->config
['config']['sys_language_mode']);
2555 $this->sys_language_contentOL
= $this->config
['config']['sys_language_overlay'];
2556 // If sys_language_uid is set to another language than default:
2557 if ($this->sys_language_uid
> 0) {
2558 // check whether a shortcut is overwritten by a translated page
2559 // we can only do this now, as this is the place where we get
2560 // to know about translations
2561 $this->checkTranslatedShortcut();
2562 // Request the overlay record for the sys_language_uid:
2563 $olRec = $this->sys_page
->getPageOverlay($this->id
, $this->sys_language_uid
);
2564 if (empty($olRec)) {
2565 // If no OL record exists and a foreign language is asked for...
2566 if ($this->sys_language_uid
) {
2567 // If requested translation is not available:
2568 if (GeneralUtility
::hideIfNotTranslated($this->page
['l18n_cfg'])) {
2569 $this->pageNotFoundAndExit('Page is not available in the requested language.');
2571 switch ((string)$this->sys_language_mode
) {
2573 $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
2575 case 'content_fallback':
2576 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2578 $fallBackOrder = GeneralUtility
::trimExplode(',', $sys_language_content);
2579 foreach ($fallBackOrder as $orderValue) {
2580 if ($orderValue === '0' ||
$orderValue === '') {
2581 $this->sys_language_content
= 0;
2584 if (MathUtility
::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page
->getPageOverlay($this->id
, (int)$orderValue))) {
2585 $this->sys_language_content
= (int)$orderValue;
2588 if ($orderValue === 'pageNotFound') {
2589 // The existing fallbacks have not been found, but instead of continuing
2590 // page rendering with default language, a "page not found" message should be shown
2592 $this->pageNotFoundAndExit('Page is not available in the requested language (fallbacks did not apply).');
2597 $this->sys_language_content
= $this->sys_language_uid
;
2600 // Default is that everything defaults to the default language...
2601 $this->sys_language_uid
= ($this->sys_language_content
= 0);
2606 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2607 $this->page
= $this->sys_page
->getPageOverlay($this->page
, $this->sys_language_uid
);
2610 // Setting sys_language_uid inside sys-page:
2611 $this->sys_page
->sys_language_uid
= $this->sys_language_uid
;
2612 // If default translation is not available:
2613 if ((!$this->sys_language_uid ||
!$this->sys_language_content
) && GeneralUtility
::hideIfDefaultLanguage($this->page
['l18n_cfg'])) {
2614 $message = 'Page is not available in default language.';
2615 $this->logger
->error($message);
2616 $this->pageNotFoundAndExit($message);
2618 $this->updateRootLinesWithTranslations();
2620 // Finding the ISO code for the currently selected language
2621 // fetched by the sys_language record when not fetching content from the default language
2622 if ($this->sys_language_content
> 0) {
2623 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2624 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2625 // avoid versioning overlay to be applied as it generates an SQL error
2626 $sys_language_row = $this->sys_page
->getRawRecord('sys_language', $this->sys_language_content
, 'language_isocode,static_lang_isocode');
2627 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2628 $this->sys_language_isocode
= $sys_language_row['language_isocode'];
2630 // the DB value is overridden by TypoScript
2631 if (!empty($this->config
['config']['sys_language_isocode'])) {
2632 $this->sys_language_isocode
= $this->config
['config']['sys_language_isocode'];
2635 // fallback to the TypoScript option when rendering with sys_language_uid=0
2636 // also: use "en" by default
2637 if (!empty($this->config
['config']['sys_language_isocode_default'])) {
2638 $this->sys_language_isocode
= $this->config
['config']['sys_language_isocode_default'];
2640 $this->sys_language_isocode
= $languageKey !== 'default' ?
$languageKey : 'en';
2644 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'])) {
2646 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] as $_funcRef) {
2647 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
2653 * Updating content of the two rootLines IF the language key is set!
2655 protected function updateRootLinesWithTranslations()
2657 if ($this->sys_language_uid
) {
2658 $this->rootLine
= $this->sys_page
->getRootLine($this->id
, $this->MP
);
2659 $this->tmpl
->updateRootlineData($this->rootLine
);
2664 * Setting locale for frontend rendering
2666 public function settingLocale()
2669 if ($this->config
['config']['locale_all']) {
2670 $availableLocales = GeneralUtility
::trimExplode(',', $this->config
['config']['locale_all'], true);
2671 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2672 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2673 // @see https://bugs.php.net/bug.php?id=53711
2674 $locale = setlocale(LC_COLLATE
, ...$availableLocales);
2676 // As str_* methods are locale aware and turkish has no upper case I
2677 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2678 // @see http://bugs.php.net/bug.php?id=35050
2679 if (substr($this->config
['config']['locale_all'], 0, 2) !== 'tr') {
2680 setlocale(LC_CTYPE
, ...$availableLocales);
2682 setlocale(LC_MONETARY
, ...$availableLocales);
2683 setlocale(LC_TIME
, ...$availableLocales);
2685 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config
['config']['locale_all']) . '" not found.', 3);
2691 * Checks whether a translated shortcut page has a different shortcut
2692 * target than the original language page.
2693 * If that is the case, things get corrected to follow that alternative
2696 protected function checkTranslatedShortcut()
2698 if (!is_null($this->originalShortcutPage
)) {
2699 $originalShortcutPageOverlay = $this->sys_page
->getPageOverlay($this->originalShortcutPage
['uid'], $this->sys_language_uid
);
2700 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id
) {
2701 // the translation of the original shortcut page has a different shortcut target!
2702 // set the correct page and id
2703 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2704 $this->id
= ($this->contentPid
= $shortcut['uid']);
2705 $this->page
= $this->sys_page
->getPage($this->id
);
2706 // Fix various effects on things like menus f.e.
2707 $this->fetch_the_id();
2708 $this->tmpl
->rootLine
= array_reverse($this->rootLine
);
2714 * Handle data submission
2715 * This is done at this point, because we need the config values
2717 public function handleDataSubmission()
2719 // Hook for processing data submission to extensions
2720 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'])) {
2721 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $className) {
2722 $_procObj = GeneralUtility
::makeInstance($className);
2723 $_procObj->checkDataSubmission($this);
2729 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2731 * @see $activeRedirectUrlHandlers
2733 public function initializeRedirectUrlHandlers()
2736 empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'])
2737 ||
!is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'])
2742 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'];
2743 foreach ($urlHandlers as $identifier => $configuration) {
2744 if (empty($configuration) ||
!is_array($configuration)) {
2745 throw new \
RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2747 if (!is_string($configuration['handler']) ||
empty($configuration['handler']) ||
!class_exists($configuration['handler']) ||
!is_subclass_of($configuration['handler'], UrlHandlerInterface
::class)) {
2748 throw new \
RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface
::class . '".', 1442052249);
2752 $orderedHandlers = GeneralUtility
::makeInstance(DependencyOrderingService
::class)->orderByDependencies($urlHandlers);
2754 foreach ($orderedHandlers as $configuration) {
2755 /** @var UrlHandlerInterface $urlHandler */
2756 $urlHandler = GeneralUtility
::makeInstance($configuration['handler']);
2757 if ($urlHandler->canHandleCurrentUrl()) {
2758 $this->activeUrlHandlers
[] = $urlHandler;
2764 * Loops over all registered URL handlers and lets them process the current URL.
2766 * If no handler has stopped the current process (e.g. by redirecting) and a
2767 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2769 * @internal Should be called by the FrontendRequestHandler only.
2771 public function redirectToExternalUrl()
2773 foreach ($this->activeUrlHandlers
as $redirectHandler) {
2774 $redirectHandler->handle();
2777 if (!empty($this->activeUrlHandlers
)) {
2778 throw new \
RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2783 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2784 * This feature allows sessions to use a GET-parameter instead of a cookie.
2788 public function setUrlIdToken()
2790 if ($this->config
['config']['ftu']) {
2791 $this->getMethodUrlIdToken
= $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2793 $this->getMethodUrlIdToken
= '';
2798 * Calculates and sets the internal linkVars based upon the current
2799 * $_GET parameters and the setting "config.linkVars".
2801 public function calculateLinkVars()
2803 $this->linkVars
= '';
2804 if (empty($this->config
['config']['linkVars'])) {
2808 $linkVars = $this->splitLinkVarsString((string)$this->config
['config']['linkVars']);
2810 if (empty($linkVars)) {
2813 $getData = GeneralUtility
::_GET();
2814 foreach ($linkVars as $linkVar) {
2815 $test = ($value = '');
2816 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2817 $linkVar = trim($match[1]);
2818 $test = trim($match[2]);
2820 if ($linkVar === '' ||
!isset($getData[$linkVar])) {
2823 if (!is_array($getData[$linkVar])) {
2824 $temp = rawurlencode($getData[$linkVar]);
2825 if ($test !== '' && !PageGenerator
::isAllowedLinkVarValue($temp, $test)) {
2826 // Error: This value was not allowed for this key
2829 $value = '&' . $linkVar . '=' . $temp;
2831 if ($test !== '' && $test !== 'array') {
2832 // Error: This key must not be an array!
2835 $value = GeneralUtility
::implodeArrayForUrl($linkVar, $getData[$linkVar]);
2837 $this->linkVars
.= $value;
2842 * Split the link vars string by "," but not if the "," is inside of braces
2848 protected function splitLinkVarsString(string $string): array
2850 $tempCommaReplacementString = '###KASPER###';
2852 // replace every "," wrapped in "()" by a "unique" string
2853 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2854 return str_replace(',', $tempCommaReplacementString, $result[0]);
2857 $string = GeneralUtility
::trimExplode(',', $string);
2859 // replace all "unique" strings back to ","
2860 return str_replace($tempCommaReplacementString, ',', $string);
2864 * Redirect to target page if the current page is an overlaid mountpoint.
2866 * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2867 * and is accessed directly, the user will be redirected to the mountpoint context.
2869 public function checkPageForMountpointRedirect()
2871 if (!empty($this->originalMountPointPage
) && $this->originalMountPointPage
['doktype'] == PageRepository
::DOKTYPE_MOUNTPOINT
) {
2872 $this->redirectToCurrentPage();
2877 * Redirect to target page, if the current page is a Shortcut.
2879 * If the current page is of type shortcut and accessed directly via its URL, this function redirects to the
2880 * Shortcut target using a Location header.
2882 public function checkPageForShortcutRedirect()
2884 if (!empty($this->originalShortcutPage
) && $this->originalShortcutPage
['doktype'] == PageRepository
::DOKTYPE_SHORTCUT
) {
2885 $this->redirectToCurrentPage();
2890 * Builds a typolink to the current page, appends the type paremeter if required
2891 * and redirects the user to the generated URL using a Location header.
2893 protected function redirectToCurrentPage()
2895 $this->calculateLinkVars();
2896 // Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
2897 /** @var $cObj ContentObjectRenderer */
2898 $cObj = GeneralUtility
::makeInstance(ContentObjectRenderer
::class);
2899 $parameter = $this->page
['uid'];
2900 $type = GeneralUtility
::_GET('type');
2901 if ($type && MathUtility
::canBeInterpretedAsInteger($type)) {
2902 $parameter .= ',' . $type;
2904 $redirectUrl = $cObj->typoLink_URL(['parameter' => $parameter, 'addQueryString' => true,
2905 'addQueryString.' => ['exclude' => 'id']]);
2907 // Prevent redirection loop
2908 if (!empty($redirectUrl)) {
2909 // redirect and exit
2910 HttpUtility
::redirect($redirectUrl, HttpUtility
::HTTP_STATUS_307
);
2914 /********************************************
2916 * Page generation; cache handling
2918 *******************************************/
2920 * Returns TRUE if the page should be generated.
2921 * That is if no URL handler is active and the cacheContentFlag is not set.
2925 public function isGeneratePage()
2927 return !$this->cacheContentFlag
&& empty($this->activeUrlHandlers
);
2931 * Temp cache content
2932 * The temporary cache will expire after a few seconds (typ. 30) or will be cleared by the rendered page, which will also clear and rewrite the cache.