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