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