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