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