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