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