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