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