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