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