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