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