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