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