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