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