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