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