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