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