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