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