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