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