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