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