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