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