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