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