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