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