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