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