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