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