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