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