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