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