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