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