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