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