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