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