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