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