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