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