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