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