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