2 /***************************************************************
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Class for the built TypoScript based Front End
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.
35 * Revised for TYPO3 3.6 June/2003 by Kasper Skaarhoj
38 * @author Kasper Skaarhoj <kasper@typo3.com>
41 * [CLASS/FUNCTION INDEX of SCRIPT]
46 * 332: function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='')
47 * 362: function connectToMySQL()
48 * 398: function sendRedirect()
50 * SECTION: Initializing, resolving page id
51 * 436: function initFEuser()
52 * 490: function checkAlternativeIdMethods()
53 * 543: function clear_preview()
54 * 556: function determineId()
55 * 637: function fetch_the_id()
56 * 743: function getPageAndRootline()
57 * 805: function getPageShortcut($SC,$mode,$thisUid,$itera=20,$pageLog=array())
58 * 850: function checkRootlineForIncludeSection()
59 * 883: function checkEnableFields($row)
60 * 901: function checkPagerecordForIncludeSection($row)
61 * 913: function setIDfromArgV()
62 * 929: function getPageAndRootlineWithDomain($domainStartPage)
63 * 957: function findDomainRecord($recursive=0)
64 * 978: function pageNotFoundHandler($code,$header='')
65 * 1000: function checkAndSetAlias()
66 * 1015: function idPartsAnalyze($str)
67 * 1040: function mergingWithGetVars($GET_VARS)
69 * SECTION: Template and caching related functions.
70 * 1088: function makeCacheHash()
71 * 1110: function cHashParams($addQueryParams)
72 * 1131: function initTemplate()
73 * 1143: function getFromCache()
74 * 1201: function getHash()
75 * 1220: function getConfigArray()
77 * SECTION: Further initialization and data processing
78 * 1334: function getCompressedTCarray()
79 * 1371: function includeTCA($TCAloaded=1)
80 * 1397: function settingLanguage()
81 * 1437: function checkDataSubmission()
82 * 1464: function fe_tce()
83 * 1478: function locDataCheck($locationData)
84 * 1494: function sendFormmail()
85 * 1512: function checkJumpUrl()
86 * 1594: function jumpUrl()
87 * 1637: function setUrlIdToken()
89 * SECTION: Page generation; cache handling
90 * 1680: function isGeneratePage()
91 * 1690: function tempPageCacheContent()
92 * 1721: function realPageCacheContent()
93 * 1743: function setPageCacheContent($c,$d,$t)
94 * 1766: function clearPageCacheContent()
95 * 1776: function clearPageCacheContent_pidList($pidList)
96 * 1787: function setSysLastChanged()
98 * SECTION: Page generation; rendering and inclusion
99 * 1823: function generatePage_preProcessing()
100 * 1859: function generatePage_whichScript()
101 * 1871: function generatePage_postProcessing()
102 * 1929: function INTincScript()
103 * 1987: function INTincScript_loadJSCode()
104 * 2028: function isINTincScript()
105 * 2037: function isSearchIndexPage()
106 * 2046: function doXHTML_cleaning()
108 * SECTION: Finished off; outputting, storing session data, statistics...
109 * 2078: function isOutputting()
110 * 2089: function processOutput()
111 * 2141: function isEXTincScript()
112 * 2150: function storeSessionData()
113 * 2160: function setParseTime()
114 * 2172: function statistics()
115 * 2266: function previewInfo()
116 * 2287: function beLoginLinkIPList()
118 * SECTION: Various internal API functions
119 * 2342: function makeSimulFileName($inTitle,$page,$type,$addParams='',$no_cache='')
120 * 2389: function simulateStaticDocuments_pEnc_onlyP_proc($linkVars)
121 * 2417: function getSimulFileName()
122 * 2430: function encryptEmail($string,$back=0)
123 * 2447: function checkFileInclude($incFile)
124 * 2462: function newCObj()
125 * 2475: function setAbsRefPrefix()
126 * 2491: function printError($label,$header='Error!')
127 * 2502: function updateMD5paramsRecord($hash)
128 * 2513: function tidyHTML($content)
130 * SECTION: Various external API functions - for use in plugins etc.
131 * 2574: function getStorageSiterootPids()
132 * 2589: function getPagesTSconfig()
133 * 2622: function setJS($key,$content='')
134 * 2660: function setCSS($key,$content)
135 * 2675: function make_seed()
136 * 2688: function uniqueHash($str='')
137 * 2697: function set_no_cache()
138 * 2707: function set_cache_timeout_default($seconds)
139 * 2723: function plainMailEncoded($email,$subject,$message,$headers='')
140 * 2746: function sL($input)
141 * 2783: function csConv($str,$from='')
142 * 2802: function readLLfile($fileRef)
143 * 2817: function getLLL($index,$LOCAL_LANG)
144 * 2831: function initLLvars()
146 * TOTAL FUNCTIONS: 83
147 * (This index is automatically created/updated by the extension "extdeveval")
172 * Main frontend class, instantiated in the index_ts.php script as the global object TSFE
174 * @author Kasper Skaarhoj <kasper@typo3.com>
181 var $id=''; // The page id (int)
182 var $type=''; // RO The type (int)
183 var $idParts=array(); // Loaded with the id, exploded by ','
184 var $cHash=''; // The submitted cHash
185 var $no_cache=''; // Page will not be cached. Write only true. Never clear value (some other code might have reasons to set it true)
186 var $rootLine=''; // The rootLine (all the way to tree root, not only the current site!) (array)
187 var $page=''; // The pagerecord (array)
188 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.
189 var $sys_page=''; // The object with pagefunctions (object)
191 var $pageNotFound=0; // Is set to 1 if a pageNotFound handler could have been called.
192 var $domainStartPage=0; // Domain start page
195 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...
198 var $fe_user=''; // The user (object)
199 var $loginUser=''; // Global falg indicating that a front-end user is logged in. This is set only if a user really IS logged in. The group-list may show other groups (like added by IP filter or so) even though there is no user.
200 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...
201 var $beUserLogin=''; // Flag that indicates if a Backend user is logged in!
204 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.
205 var $showHiddenPage=''; // Flag indicating that hidden pages should be shown, selected and so on. This goes for almost all selection of pages!
206 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.
207 var $simUserGroup='0'; // Value that contains the simulated usergroup if any
210 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.
211 var $config=''; // 'CONFIG' object from TypoScript. Array generated based on the TypoScript configuration of the current page. Saved with the cached pages.
214 var $tmpl=''; // The TypoScript template object. Used to parse the TypoScript template
215 var $cacheTimeOutDefault=''; // Is set to the time-to-live time of cached pages. If false, default is 60*60*24, which is 24 hours.
216 var $cacheContentFlag=''; // Set internally if cached content is fetched from the database
217 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.
218 var $sPre=''; // toplevel - objArrayName, eg 'page'
219 var $pSetup=''; // TypoScript configuration of the page-object pointed to by sPre. $this->tmpl->setup[$this->sPre.'.']
220 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
221 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
222 var $noCacheBeforePageGen=''; // This flag is set before inclusion of pagegen.php IF no_cache is set. If this flag is set after the inclusion of pagegen.php, no_cache is forced to be set. This is done in order to make sure that php-code from pagegen does not falsely clear the no_cache flag.
223 var $tempContent=''; // This flag indicates if temporary content went into the cache during page-generation.
224 var $forceTemplateParsing=''; // Boolean, passed to TypoScript template class and tells it to render the template forcibly
225 var $cHash_array=array(); // The array which cHash_calc is based on, see ->makeCacheHash().
226 var $hash_base=''; // Loaded with the serialized array that is used for generating a hashstring for the cache
227 var $pagesTSconfig=''; // May be set to the pagesTSconfig
228 // PAGE-GENERATION / cOBJ
230 Eg. insert JS-functions in this array ($additionalHeaderData) to include them once. Use associative keys.
232 JSFormValidate : <script type="text/javascript" src="'.$GLOBALS["TSFE"]->absRefPrefix.'t3lib/jsfunc.validateform.js"></script>
233 JSincludeFormupdate : <script type="text/javascript" src="t3lib/jsfunc.updateform.js"></script>
234 JSMenuCode, JSMenuCode_menu : JavaScript for the JavaScript menu
238 var $defaultBodyTag='<body bgcolor="#FFFFFF">'; // Default bodytag, if nothing else is set. This can be overridden by applications like TemplaVoila.
239 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[] = '...')
240 var $additionalJavaScript=array(); // used to accumulate additional JavaScript-code. Works like additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
241 var $additionalCSS=array(); // used to accumulate additional Style code. Works like additionalHeaderData.
242 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
243 'onmousemove' => array(),
244 'onmouseup' => array(),
247 var $JSCode=''; // Depreciated, use additionalJavaScript instead.
248 var $JSImgCode=''; // Used to accumulate JavaScript loaded images (by menus)
249 var $divSection=''; // Used to accumulate DHTML-layers.
251 // RENDERING configuration, settings from TypoScript is loaded into these vars. See pagegen.php
252 var $debug=''; // Debug flag, may output special debug html-code.
253 var $intTarget=''; // Default internal target
254 var $extTarget=''; // Default external target
255 var $MP_defaults=array(); // Keys are page ids and values are default &MP (mount point) values to set when using the linking features...)
256 var $spamProtectEmailAddresses=0; // If set, typolink() function encrypts email addresses. Is set in pagegen-class.
257 var $absRefPrefix=''; // Absolute Reference prefix
258 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 '/'
259 var $compensateFieldWidth=''; // Factor for form-field widths compensation
260 var $lockFilePath=''; // Lock file path
261 var $ATagParams=''; // <A>-tag parameters
262 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.
263 var $sWordList=''; // Is set to the incoming array sword_list in case of a page-view jumped to from a search-result.
264 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.
265 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.
266 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.
267 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.
268 var $sys_language_uid=0; // Site language, 0 (zero) is default, int+ is uid pointing to a sys_language record.
269 var $sys_language_isocode = ''; // Is set to the iso code of the sys_language if that is properly defined by the sys_language record representing the sys_language_uid. (Requires the extension "static_info_tables")
272 var $applicationData=Array(); // 'Global' Storage for various applications. Keys should be 'tx_'.extKey for extensions.
273 var $register=Array();
274 var $registerStack=Array(); // Stack used for storing array and retrieving register arrays (see LOAD_REGISTER and CLEAR_REGISTER)
275 var $cObjectDepthCounter = 50; // Checking that the function is not called eternally. This is done by interrupting at a depth of 50
276 var $recordRegister = Array(); // used by cObj->RECORDS and cObj->CONTENT to ensure the a records is NOT rendered twice through it!
277 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
278 var $accessKey =array(); // Used by class tslib_menu to keep track of access-keys.
279 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.
280 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
281 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()
282 var $uniqueString='';
283 var $indexedDocTitle=''; // This value will be used as the title for the page in the indexer (if indexing happens)
284 var $altPageTitle=''; // Alternative page title (normally the title of the page record). Can be set from applications you make.
285 var $pEncAllowedParamNames=array(); // An array that holds parameter names (keys) of GET parameters which MAY be MD5/base64 encoded with simulate_static_documents method.
287 // Page content render object
288 var $cObj =''; // is instantiated object of tslib_cObj
290 // Character set (charset) conversion object:
291 var $csConvObj; // An instance of the "t3lib_cs" class. May be used by any application.
292 var $defaultCharSet='iso-8859-1'; // The default charset used in the frontend if nothing else is set.
294 // CONTENT accumulation
295 var $content=''; // All page content is accumulated in this variable. See pagegen.php
298 var $clientInfo=''; // Set to the browser: net / msie if 4+ browsers
299 var $scriptParseTime=0;
300 var $TCAloaded = 0; // Set ONLY if the full TCA is loaded
303 var $lang=''; // Set to the system language key (used on the site)
304 var $langSplitIndex=0; // Set to the index number of the language key
305 var $labelsCharset=''; // Charset of the labels from locallang (based on $this->lang)
306 var $siteCharset=''; // Charset of the website.
307 var $convCharsetToFrom=''; // Set to the charsets to convert from/to IF there are any difference. Otherwise this stays a string
308 var $LL_labels_cache=array();
309 var $LL_files_cache=array();
317 * Takes a number of GET/POST input variable as arguments and stores them internally.
318 * The processing of these variables goes on later in this class.
319 * Also sets internal clientInfo array (browser information) and a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
321 * @param array The global $TYPO3_CONF_VARS array. Will be set internally in ->TYPO3_CONF_VARS
322 * @param mixed The value of t3lib_div::_GP('id')
323 * @param integer The value of t3lib_div::_GP('type')
324 * @param boolean The value of t3lib_div::_GP('no_cache'), evaluated to 1/0
325 * @param string The value of t3lib_div::_GP('cHash')
326 * @param string The value of t3lib_div::_GP('jumpurl')
327 * @param string The value of t3lib_div::_GP('MP')
328 * @param string The value of t3lib_div::_GP('RDCT')
332 function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='') {
333 // Setting some variables:
336 $this->no_cache
= $no_cache ?
1 : 0;
337 $this->cHash
= $cHash;
338 $this->jumpurl
= $jumpurl;
339 $this->MP
= $TYPO3_CONF_VARS['FE']['enable_mount_pids'] ?
$MP : '';
341 $this->TYPO3_CONF_VARS
= $TYPO3_CONF_VARS;
342 $this->clientInfo
= t3lib_div
::clientInfo();
343 $this->uniqueString
=md5(microtime());
345 $this->csConvObj
= t3lib_div
::makeInstance('t3lib_cs');
347 // Call post processing function for constructor:
348 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
349 $_params = array('pObj' => &$this);
350 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
351 t3lib_div
::callUserFunction($_funcRef,$_params,$this);
357 * Connect to SQL database
358 * May exit after outputting an error message or some JavaScript redirecting to the install tool.
362 function connectToMySQL() {
363 if ($GLOBALS['TYPO3_DB']->sql_pconnect(TYPO3_db_host
, TYPO3_db_username
, TYPO3_db_password
)) {
365 $this->printError('No database selected','Database Error');
366 // Redirects to the Install Tool:
367 echo '<script type="text/javascript">
369 document.location = "'.TYPO3_mainDir
.'install/index.php?mode=123&step=1&password=joh316";
373 } elseif (!$GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db
)) {
374 $this->printError('Cannot connect to the current database, "'.TYPO3_db
.'"','Database Error');
379 // Redirects to the Install Tool:
380 echo '<script type="text/javascript">
382 document.location = "'.TYPO3_mainDir
.'install/index.php?mode=123&step=1&password=joh316";
387 $this->printError('The current username, password or host was not accepted when the connection to the database was attempted to be established!','Database Error');
393 * 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
394 * May exit after sending a location-header.
398 function sendRedirect() {
399 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($this->RDCT
, 'cache_md5params').'"');
400 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
401 $this->updateMD5paramsRecord($this->RDCT
);
402 header('Location: '.$row['params']);
424 /********************************************
426 * Initializing, resolving page id
428 ********************************************/
432 * Initializes the front-end login user.
436 function initFEuser() {
437 $this->fe_user
= t3lib_div
::makeInstance('tslib_feUserAuth');
439 $this->fe_user
->lockIP
= $this->TYPO3_CONF_VARS
['FE']['lockIP'];
440 $this->fe_user
->checkPid
= $this->TYPO3_CONF_VARS
['FE']['checkFeUserPid'];
441 $this->fe_user
->checkPid_value
= $GLOBALS['TYPO3_DB']->cleanIntList(t3lib_div
::_GP('pid')); // List of pid's acceptable
443 // Check if a session is transferred:
444 if (t3lib_div
::_GP('FE_SESSION_KEY')) {
445 $fe_sParts = explode('-',t3lib_div
::_GP('FE_SESSION_KEY'));
446 if (!strcmp(md5($fe_sParts[0].'/'.$this->TYPO3_CONF_VARS
['SYS']['encryptionKey']), $fe_sParts[1])) { // If the session key hash check is OK:
447 $GLOBALS['HTTP_COOKIE_VARS'][$this->fe_user
->name
]=$fe_sParts[0];
448 $this->fe_user
->forceSetCookie
=1;
452 if ($this->TYPO3_CONF_VARS
['FE']['dontSetCookie']) {
453 $this->fe_user
->dontSetCookie
=1;
456 $this->fe_user
->start();
457 $this->fe_user
->unpack_uc('');
458 $this->fe_user
->fetchSessionData(); // Gets session data
459 $recs = t3lib_div
::_GP('recs');
460 if (is_array($recs)) { // If any record registration is submitted, register the record.
461 $this->fe_user
->record_registration($recs);
464 // For every 60 seconds the is_online timestamp is updated.
465 if (is_array($this->fe_user
->user
) && $this->fe_user
->user
['is_online']<($GLOBALS['EXEC_TIME']-60)) {
466 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('fe_users', 'uid='.intval($this->fe_user
->user
['uid']), array('is_online' => $GLOBALS['EXEC_TIME']));
471 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
474 * 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.
475 * 2) Use PATH_INFO (also Apache) to extract id and type from that var. Does not require any special modules compiled with apache.
477 * Support for RewriteRule to generate (simulateStaticDocuments)
478 * With the mod_rewrite compiled into apache, put these lines into a .htaccess in this directory:
480 * RewriteRule ^[^/]*\.html$ index.php
481 * The url must end with '.html' and the format must comply with either of these:
482 * 1: '[title].[id].[type].html' - title is just for easy recognition in the logfile!; no practical use of the title for TYPO3.
483 * 2: '[id].[type].html' - above, but title is omitted; no practical use of the title for TYPO3.
484 * 3: '[id].html' - only id, type is set to the default, zero!
485 * NOTE: In all case 'id' may be the uid-number OR the page alias (if any)
488 * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&cHash=4ad9d7acb4
490 function checkAlternativeIdMethods() {
491 global $TYPO3_CONF_VARS;
493 # IF (TYPO3_OS=='WIN') return; # Commenting out this line will make it work for windows Apache mod_rewrite as well.
495 // Redirect by mod_rewrite:
496 if ($GLOBALS['HTTP_SERVER_VARS']['REDIRECT_URL']) { // 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.
497 $uParts = parse_url($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI']);
498 $requestFilename = trim(ereg_replace('.*\/','',$uParts['path'])); // This is the filename of the script/simulated html-file.
499 if ($requestFilename && substr($requestFilename,-4)!='.php') {
500 $parts = explode('.',ereg_replace('.*\/','',$requestFilename));
501 $pCount = count($parts);
502 if ($parts[$pCount-1]='html') {
504 $this->type
= intval($parts[$pCount-2]);
505 $this->id
= $parts[$pCount-3];
508 $this->id
= $parts[0];
514 if (t3lib_div
::getIndpEnv('PATH_INFO')) { // If pathinfo contains stuff...
515 $parts=t3lib_div
::trimExplode('/',t3lib_div
::getIndpEnv('PATH_INFO'),1);
517 $pCount = count($parts);
519 $this->type
= intval($parts[$pCount-2]);
520 $this->id
= $parts[$pCount-3];
523 $this->id
= $parts[0];
525 $this->absRefPrefix_force
=1;
528 // Call post processing function for custom URL methods.
529 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
530 $_params = array('pObj' => &$this);
531 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef) {
532 t3lib_div
::callUserFunction($_funcRef,$_params,$this);
538 * Clears the preview-flags, sets sim_exec_time to current time.
539 * 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.
543 function clear_preview() {
544 $this->showHiddenPage
= 0;
545 $this->showHiddenRecords
= 0;
546 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
547 $this->fePreview
= 0;
551 * Determines the id and evaluates any preview settings
552 * 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.
556 function determineId() {
557 global $TYPO3_CONF_VARS;
559 // Getting ARG-v values if some
560 $this->setIDfromArgV();
562 // If there is a Backend login we are going to check for any preview settings:
563 $GLOBALS['TT']->push('beUserLogin','');
564 if ($this->beUserLogin
) {
565 $this->fePreview
= $GLOBALS['BE_USER']->extGetFeAdminValue('preview');
567 // If admin panel preview is enabled...
568 if ($this->fePreview
) {
569 $fe_user_OLD_USERGROUP = $this->fe_user
->user
['usergroup'];
571 $this->showHiddenPage
= $GLOBALS['BE_USER']->extGetFeAdminValue('preview','showHiddenPages');
572 $this->showHiddenRecords
= $GLOBALS['BE_USER']->extGetFeAdminValue('preview','showHiddenRecords');
574 $simTime = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','simulateDate');
575 if ($simTime) $GLOBALS['SIM_EXEC_TIME']=$simTime;
577 $simUserGroup = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','simulateUserGroup');
578 $this->simUserGroup
= $simUserGroup;
579 if ($simUserGroup) $this->fe_user
->user
['usergroup']=$simUserGroup;
580 if (!$simUserGroup && !$simTime && !$this->showHiddenPage
&& !$this->showHiddenRecords
) {
585 // Now it's investigated if the raw page-id points to a hidden page and if so, the flag is set.
586 // This does not require the preview flag to be set in the admin panel
588 $idQ = t3lib_div
::testInt($this->id
) ?
'uid="'.intval($this->id
).'"' : 'alias="'.$GLOBALS['TYPO3_DB']->quoteStr($this->id
, 'pages').'"';
589 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('hidden', 'pages', $idQ.' AND hidden AND NOT deleted');
590 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
591 $this->fePreview
= 1; // The preview flag is set only if the current page turns out to actually be hidden!
592 $this->showHiddenPage
= 1;
596 if ($this->fePreview
) { // If the front-end is showing a preview, caching MUST be disabled.
597 $this->set_no_cache();
600 $GLOBALS['TT']->pull();
602 // Now, get the id, validate access etc:
603 $this->fetch_the_id();
605 // Check if backend user has read access to this page. If not, recalculate the id.
606 if ($this->beUserLogin
&& $this->fePreview
) {
607 if (!$GLOBALS['BE_USER']->doesUserHaveAccess($this->page
,1)) {
609 $this->clear_preview();
610 $this->fe_user
->user
['usergroup'] = $fe_user_OLD_USERGROUP;
611 // Fetching the id again, now with the preview settings reset.
612 $this->fetch_the_id();
616 $this->id
=$this->contentPid
=intval($this->id
); // Make sure it's an integer
617 $this->type
=intval($this->type
); // Make sure it's an integer
620 // Call post processing function for id determination:
621 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
622 $_params = array('pObj' => &$this);
623 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef) {
624 t3lib_div
::callUserFunction($_funcRef,$_params,$this);
631 * This gets the id of the page, checks if the page is in the domain and if the page is accessible
632 * Sets variables such as $this->sys_page, $this->loginUser, $this->gr_list, $this->id, $this->type, $this->domainStartPage, $this->idParts
637 function fetch_the_id() {
638 $GLOBALS['TT']->push('fetch_the_id initialize/','');
640 // Initialize the page-select functions.
641 $this->sys_page
= t3lib_div
::makeInstance('t3lib_pageSelect');
642 $this->sys_page
->init($this->showHiddenPage
);
644 // Sets ->loginUser and ->gr_list based on front-end user status.
645 $this->fe_user
->showHiddenRecords
= $this->showHiddenRecords
; // This affects the hidden-flag selecting the fe_groups for the user!
646 if (is_array($this->fe_user
->user
) && $this->fe_user
->fetchGroupData()) {
647 $this->loginUser
=1; // global flag!
648 $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!
649 $gr_array = $this->fe_user
->groupData
['uid'];
652 $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!
656 // ADD group-numbers if the IPmask matches.
657 if (is_array($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'])) {
658 reset($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups']);
659 while(list(,$IPel)=each($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'])) {
660 if (t3lib_div
::getIndpEnv('REMOTE_ADDR') && $IPel[0] && t3lib_div
::cmpIP(t3lib_div
::getIndpEnv('REMOTE_ADDR'),$IPel[0])) {$gr_array[]=intval($IPel[1]);}
665 $gr_array = array_unique($gr_array); // Make unique...
666 sort($gr_array); // sort
667 if (count($gr_array)) {
668 $this->gr_list
.=','.implode(',',$gr_array);
671 // Sets sys_page where-clause
672 $this->sys_page
->where_hid_del
.=' AND doktype<200 AND fe_group IN ('.$this->gr_list
.')';
674 // Splitting $this->id by a period (.). First part is 'id' and second part - if exists - will overrule the &type param if given
675 $pParts = explode('.',$this->id
);
676 $this->id
= $pParts[0]; // Set it.
677 if (isset($pParts[1])) {$this->type
=$pParts[1];}
679 // Splitting $this->id by a comma (,). First part is 'id' and other parts are just stored for use in scripts.
680 $this->idParts
= explode(',',$this->id
);
682 // Splitting by a '+' sign - used for base64/md5 methods of parameter encryption for simulate static documents.
683 list($pgID,$SSD_p)=explode('+',$this->idParts
[0],2);
684 if ($SSD_p) { $this->idPartsAnalyze($SSD_p); }
685 $this->id
= $pgID; // Set id
687 // If $this->id is a string, it's an alias
688 $this->checkAndSetAlias();
690 // The id and type is set to the integer-value - just to be sure...
691 $this->id
= intval($this->id
);
692 $this->type
= intval($this->type
);
693 $GLOBALS['TT']->pull();
695 // We find the first page belonging to the current domain
696 $GLOBALS['TT']->push('fetch_the_id domain/','');
697 $this->domainStartPage
= $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']); // the page_id of the current domain
699 if ($this->domainStartPage
) {
700 $this->id
= $this->domainStartPage
; // If the id was not previously set, set it to the id of the domain.
702 $theFirstPage = $this->sys_page
->getFirstWebPage($this->id
); // Find the first 'visible' page in that domain
704 $this->id
= $theFirstPage['uid'];
706 $this->printError('No pages are found on the rootlevel!');
711 $GLOBALS['TT']->pull();
713 $GLOBALS['TT']->push('fetch_the_id rootLine/','');
714 $requestedId = $this->id
; // We store the originally requested id
715 $this->getPageAndRootlineWithDomain($this->domainStartPage
);
716 $GLOBALS['TT']->pull();
718 if ($this->pageNotFound
&& $this->TYPO3_CONF_VARS
['FE']['pageNotFound_handling']) {
719 $this->pageNotFoundHandler($this->TYPO3_CONF_VARS
['FE']['pageNotFound_handling'],$this->TYPO3_CONF_VARS
['FE']['pageNotFound_handling_statheader']);
722 // set no_cache if set
723 if ($this->page
['no_cache']) {
724 $this->set_no_cache();
726 // Init SYS_LASTCHANGED
727 $this->register
['SYS_LASTCHANGED'] = intval($this->page
['tstamp']);
731 * Gets the page and rootline arrays based on the id, $this->id
733 * If the id does not correspond to a proper page, the 'previous' valid page in the rootline is found
734 * If the page is a shortcut (doktype=4), the ->id is loaded with that id
736 * 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.
738 * Sets or manipulates internal variables such as: $this->id, $this->page, $this->rootLine, $this->MP, $this->pageNotFound
743 function getPageAndRootline() {
744 $this->page
= $this->sys_page
->getPage($this->id
);
745 if (!count($this->page
)) {
746 // If no page, we try to find the page before in the rootLine.
747 $this->pageNotFound
=1; // Page is 'not found' in case the id itself was not an accessible page. code 1
748 $this->rootLine
= $this->sys_page
->getRootLine($this->id
,$this->MP
);
749 if (count($this->rootLine
)) {
750 $c=count($this->rootLine
)-1;
753 $this->id
=$this->rootLine
[$c]['uid'];
754 $this->page
= $this->sys_page
->getPage($this->id
);
755 if (count($this->page
)){break;}
758 // If still no page...
759 if (!count($this->page
)) {
760 $this->printError('The requested page does not exist!');
764 // Is the ID a link to another page??
765 if ($this->page
['doktype']==4) {
766 $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.
767 $this->page
= $this->getPageShortcut($this->page
['shortcut'],$this->page
['shortcut_mode'],$this->page
['uid']);
768 $this->id
= $this->page
['uid'];
771 $this->rootLine
= $this->sys_page
->getRootLine($this->id
,$this->MP
);
773 // If not rootline we're off...
774 if (!count($this->rootLine
)) {
775 $this->printError('The requested page didn\'t have a proper connection to the tree-root!');
779 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
780 if ($this->checkRootlineForIncludeSection()) {
781 if (!count($this->rootLine
)) {
782 $this->printError('The requested page was not accessible!');
785 $el = reset($this->rootLine
);
786 $this->id
= $el['uid'];
787 $this->page
= $this->sys_page
->getPage($this->id
);
788 $this->rootLine
= $this->sys_page
->getRootLine($this->id
,$this->MP
);
794 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
796 * @param integer The value of the "shortcut" field from the pages record
797 * @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
798 * @param integer The current page UID of the page which is a shortcut
799 * @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...)
800 * @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.
801 * @return mixed Returns the page record of the page that the shortcut pointed to.
803 * @see getPageAndRootline()
805 function getPageShortcut($SC,$mode,$thisUid,$itera=20,$pageLog=array()) {
806 $idArray = t3lib_div
::intExplode(',',$SC);
810 $pageArray = $this->sys_page
->getMenu($idArray[0]?
$idArray[0]:$thisUid,'*','sorting','AND pages.doktype<199 AND pages.doktype!=6');
812 if ($mode==2 && count($pageArray)) { // random
814 $randval = intval(rand(0,count($pageArray)-1));
819 while(list(,$pV)=each($pageArray)) {
828 $page = $this->sys_page
->getPage($idArray[0]);
831 if ($page['doktype']==4) {
832 if (!in_array($page['uid'],$pageLog) && $itera>0) {
833 $pageLog[] = $page['uid'];
834 $page = $this->getPageShortcut($page['shortcut'],$page['shortcut_mode'],$page['uid'],$itera-1,$pageLog);
836 $pageLog[] = $page['uid'];
837 $this->printError('Page shortcuts were looping in uids '.implode(',',$pageLog).'...!');
845 * Checks the current rootline for defined sections.
850 function checkRootlineForIncludeSection() {
851 $c=count($this->rootLine
);
852 $removeTheRestFlag=0;
853 for ($a=0;$a<$c;$a++
) {
854 if (!$this->checkPagerecordForIncludeSection($this->rootLine
[$a])) {
855 $removeTheRestFlag=1;
857 if ($this->rootLine
[$a]['doktype']==6) {
858 if ($this->beUserLogin
) { // If there is a backend user logged in, check if he has read access to the page:
859 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($this->id
).' AND '.$GLOBALS['BE_USER']->getPagePermsClause(1));
860 list($isPage) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
861 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...
862 } else { // Dont go here, if there is no backend user logged in.
863 $removeTheRestFlag=1;
866 if ($removeTheRestFlag) {
867 $this->pageNotFound
=2; // Page is 'not found' in case a subsection was found and not accessible, code 2
868 unset($this->rootLine
[$a]);
871 return $removeTheRestFlag;
875 * Checks page record for enableFields
876 * Returns true if enableFields does not disable the page record.
877 * Takes notice of the ->showHiddenPage flag and uses SIM_EXEC_TIME for start/endtime evaluation
879 * @param array The page record to evaluate (needs fields; hidden, starttime, endtime, fe_group)
880 * @return boolean True, if record is viewable.
881 * @see tslib_cObj::getTreeList(), checkPagerecordForIncludeSection()
883 function checkEnableFields($row) {
884 if ((!$row['hidden'] ||
$this->showHiddenPage
)
885 && $row['starttime']<=$GLOBALS['SIM_EXEC_TIME']
886 && ($row['endtime']==0 ||
$row['endtime']>$GLOBALS['SIM_EXEC_TIME'])
887 && t3lib_div
::inList($this->gr_list
,$row['fe_group'])
894 * Checks page record for include section
896 * @param array The page record to evaluate (needs fields;extendToSubpages + hidden, starttime, endtime, fe_group)
897 * @return boolean Returns true if either extendToSubpages is not checked or if the enableFields does not disable the page record.
899 * @see checkEnableFields(), tslib_cObj::getTreeList(), checkRootlineForIncludeSection()
901 function checkPagerecordForIncludeSection($row) {
902 return (!$row['extendToSubpages'] ||
$this->checkEnableFields($row)) ?
1 : 0;
906 * This checks if there are ARGV-parameters in the QUERY_STRING and if so, those are used for the id
907 * $this->id must be 'false' in order for any processing to happen in here
908 * If an id/alias value is extracted from the QUERY_STRING it is set in $this->id
913 function setIDfromArgV() {
915 list($theAlias) = explode('&',t3lib_div
::getIndpEnv('QUERY_STRING'));
916 $theAlias = trim($theAlias);
917 $this->id
= $theAlias ?
$theAlias : 0;
922 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
923 * If not inside domain, then default to first page in domain.
925 * @param integer Page uid of the page where the found domain record is (pid of the domain record)
929 function getPageAndRootlineWithDomain($domainStartPage) {
930 $this->getPageAndRootline();
932 // 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.
933 if ($domainStartPage && is_array($this->rootLine
)) {
934 reset ($this->rootLine
);
936 while(list($key,$val)=each($this->rootLine
)) {
937 if ($val['uid']==$domainStartPage) {
943 $this->pageNotFound
=3; // Page is 'not found' in case the id was outside the domain, code 3
944 $this->id
= $domainStartPage;
945 $this->getPageAndRootline(); //re-get the page and rootline if the id was not found.
951 * Looking up a domain record based on HTTP_HOST
953 * @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.
954 * @return integer Returns the page id of the page where the domain record was found.
957 function findDomainRecord($recursive=0) {
959 $host = explode('.',t3lib_div
::getIndpEnv('HTTP_HOST'));
960 while(count($host)) {
961 $pageUid = $this->sys_page
->getDomainStartPage(implode('.',$host),t3lib_div
::getIndpEnv('SCRIPT_NAME'),t3lib_div
::getIndpEnv('REQUEST_URI'));
962 if ($pageUid) return $pageUid; else array_shift($host);
966 return $this->sys_page
->getDomainStartPage(t3lib_div
::getIndpEnv('HTTP_HOST'),t3lib_div
::getIndpEnv('SCRIPT_NAME'),t3lib_div
::getIndpEnv('REQUEST_URI'));
971 * Page not found handler.
974 * @param mixed Which type of handling; If a true PHP-boolean and TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
975 * @param string If set, this is passed directly to the PHP function, header()
976 * @return void (The function exists!)
978 function pageNotFoundHandler($code,$header='') {
979 if ($header) {header($header);}
981 if (gettype($code)=='boolean' ||
!strcmp($code,1)) {
982 $this->printError('The page did not exist or was inaccessible.');
984 } else if (t3lib_div
::testInt($code)) {
985 $this->printError('Error '.$code);
988 header('Location: '.t3lib_div
::locationHeaderUrl($code));
994 * Fetches the integer page id for a page alias.
995 * 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
1000 function checkAndSetAlias() {
1001 if ($this->id
&& !t3lib_div
::testInt($this->id
)) {
1002 $aid = $this->sys_page
->getPageIdFromAlias($this->id
);
1003 if ($aid) {$this->id
=$aid;}
1008 * 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 (but NOT $_GET - yet)
1009 * If values for ->cHash, ->no_cache, ->jumpurl and ->MP is found, they are also loaded into the internal vars of this class.
1011 * @param string String to analyze
1015 function idPartsAnalyze($str) {
1017 switch(substr($str,0,2)) {
1019 $addParams = base64_decode(str_replace('_','=',str_replace('-','/',substr($str,2))));
1020 parse_str($addParams,$GET_VARS);
1023 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr(substr($str,2), 'cache_md5params').'"');
1024 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
1026 $this->updateMD5paramsRecord(substr($str,2));
1027 parse_str($row['params'],$GET_VARS);
1031 $this->mergingWithGetVars($GET_VARS);
1035 * Merging values into the global $HTTP_GET_VARS/$_GET
1037 * @param array Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
1040 function mergingWithGetVars($GET_VARS) {
1041 if (is_array($GET_VARS)) {
1042 $realGet = t3lib_div
::_GET(); // Getting $_GET var, unescaped.
1043 if (!is_array($realGet)) $realGet = array();
1045 // Merge new values on top:
1046 $realGet = t3lib_div
::array_merge_recursive_overrule($realGet,$GET_VARS);
1048 // Write values back to $_GET:
1049 t3lib_div
::_GETset($realGet);
1051 // Setting these specifically (like in the init-function):
1052 if (isset($GET_VARS['type'])) $this->type
= intval($GET_VARS['type']);
1053 if (isset($GET_VARS['cHash'])) $this->cHash
= $GET_VARS['cHash'];
1054 if (isset($GET_VARS['jumpurl'])) $this->jumpurl
= $GET_VARS['jumpurl'];
1055 if (isset($GET_VARS['MP'])) $this->MP
= $this->TYPO3_CONF_VARS
['FE']['enable_mount_pids'] ?
$GET_VARS['MP'] : '';
1057 if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) $this->set_no_cache();
1077 /********************************************
1079 * Template and caching related functions.
1081 *******************************************/
1084 * 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
1088 function makeCacheHash() {
1089 $GET = t3lib_div
::_GET();
1090 if ($this->cHash
&& is_array($GET)) {
1091 $pA = $this->cHashParams(t3lib_div
::implodeArrayForUrl('',$GET));
1092 $this->cHash_array
= $pA;
1093 $cHash_calc = t3lib_div
::shortMD5(serialize($this->cHash_array
));
1094 #debug(array($cHash_calc,$this->cHash,$pA));
1095 if ($cHash_calc!=$this->cHash
) {
1096 $this->set_no_cache();
1097 $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($pA),',').'"',2);
1103 * Splits the input query-parameters into an array with certain parameters filtered out.
1104 * Used to create the cHash value
1106 * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
1107 * @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
1109 * @see makeCacheHash(), tslib_cObj::typoLink()
1111 function cHashParams($addQueryParams) {
1112 $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
1116 foreach($params as $theP) {
1117 $pKV = explode('=', $theP); // SPlitting single param by '=' sign
1118 if (!t3lib_div
::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0])) {
1119 $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
1122 $pA['encryptionKey'] = $this->TYPO3_CONF_VARS
['SYS']['encryptionKey'];
1128 * Initialize the TypoScript template parser
1132 function initTemplate() {
1133 $this->tmpl
= t3lib_div
::makeInstance('t3lib_TStemplate');
1134 $this->tmpl
->init();
1135 $this->tmpl
->tt_track
= $this->beUserLogin ?
1 : 0;
1139 * See if page is in cache and get it if so
1140 * Stores the page content in $this->content if something is found.
1144 function getFromCache() {
1145 $this->tmpl
->getCurrentPageData();
1147 if (is_array($this->tmpl
->currentPageData
)) {
1148 // 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.
1149 // If this hash is not the same in here in this section and after page-generation the page will not be properly cached!
1151 $cc['all'] = $this->tmpl
->currentPageData
['all'];
1152 $cc['rowSum'] = $this->tmpl
->currentPageData
['rowSum'];
1153 $cc['rootLine'] = $this->tmpl
->currentPageData
['rootLine']; // This rootline is used with templates only (matching()-function)
1154 $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.
1158 $this->content
=''; // clearing the content-variable, which will hold the pagecontent
1159 unset($this->config
); // Unsetting the lowlevel config
1160 $this->cacheContentFlag
=0;
1161 if ($this->all
&& !$this->no_cache
) {
1162 $this->newHash
= $this->getHash();
1164 $GLOBALS['TT']->push('Cache Query','');
1165 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1167 'cache_pages AS S,pages AS P',
1168 'S.hash="'.$GLOBALS['TYPO3_DB']->quoteStr($this->newHash
, 'cache_pages').'"
1170 AND S.expires > '.intval($GLOBALS['EXEC_TIME']).'
1173 AND P.starttime<='.intval($GLOBALS['EXEC_TIME']).'
1174 AND (P.endtime=0 OR P.endtime>'.intval($GLOBALS['EXEC_TIME']).')'
1176 $GLOBALS['TT']->pull();
1177 $GLOBALS['TT']->push('Cache Row','');
1178 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1179 $this->config
= unserialize($row['cache_data']); // Fetches the lowlevel config stored with the cached data
1180 $this->content
= $row['HTML']; // Getting the content
1181 $this->cacheContentFlag
=1; // Setting flag, so we know, that some cached content is gotten.
1183 if ($this->TYPO3_CONF_VARS
['FE']['debug'] ||
$this->config
['config']['debug']) {
1184 $this->content
.=chr(10).'<!-- Cached page generated '.Date('d/m Y H:i', $row['tstamp']).'. Expires '.Date('d/m Y H:i', $row['expires']).' -->';
1187 $GLOBALS['TT']->pull();
1189 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1194 * Calculates the cache-hash
1195 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
1196 * Used to get and later store the cached data.
1198 * @return string MD5 hash of $this->hash_base which is a serialized version of there variables.
1200 * @see getFromCache()
1202 function getHash() {
1203 $this->hash_base
= serialize(
1205 'all' => $this->all
,
1206 'id' => intval($this->id
),
1207 'type' => intval($this->type
),
1208 'gr_list' => $this->gr_list
,
1210 'cHash' => $this->cHash_array
1213 return md5($this->hash_base
);
1217 * Checks if config-array exists already but if not, gets it
1221 function getConfigArray() {
1222 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
1223 $GLOBALS['TT']->push('Parse template','');
1225 // Force parsing, if set?:
1226 $this->tmpl
->forceTemplateParsing
= $this->forceTemplateParsing
;
1228 // Start parsing the TS template. Might return cached version.
1229 $this->tmpl
->start($this->rootLine
);
1230 $GLOBALS['TT']->pull();
1232 if ($this->tmpl
->loaded
) {
1233 $GLOBALS['TT']->push('Setting the config-array','');
1234 // t3lib_div::print_array($this->tmpl->setup);
1235 $this->sPre
= $this->tmpl
->setup
['types.'][$this->type
]; // toplevel - objArrayName
1236 $this->pSetup
= $this->tmpl
->setup
[$this->sPre
.'.'];
1238 if (!is_array($this->pSetup
)) {
1239 $this->printError('The page is not configured! [type= '.$this->type
.']['.$this->sPre
.']');
1242 $this->config
['config']=Array();
1244 // Filling the config-array.
1245 if (is_array($this->tmpl
->setup
['config.'])) {
1246 $this->config
['config'] = $this->tmpl
->setup
['config.'];
1248 if (is_array($this->pSetup
['config.'])) {
1249 reset($this->pSetup
['config.']);
1250 while(list($theK,$theV)=each($this->pSetup
['config.'])) {
1251 $this->config
['config'][$theK] = $theV;
1254 // if .simulateStaticDocuments was not present, the default value will rule.
1255 if (!isset($this->config
['config']['simulateStaticDocuments'])) {
1256 $this->config
['config']['simulateStaticDocuments'] = $this->TYPO3_CONF_VARS
['FE']['simulateStaticDocuments'];
1259 // Processing for the config_array:
1260 $this->config
['rootLine'] = $this->tmpl
->rootLine
;
1261 $this->config
['mainScript'] = trim($this->config
['config']['mainScript']) ?
trim($this->config
['config']['mainScript']) : 'index.php';
1264 $theLogFile = $this->TYPO3_CONF_VARS
['FE']['logfile_dir'].$this->config
['config']['stat_apache_logfile'];
1265 if ($this->config
['config']['stat_apache'] &&
1266 $this->config
['config']['stat_apache_logfile'] &&
1267 !strstr($this->config
['config']['stat_apache_logfile'],'/') &&
1268 @is_dir
($this->TYPO3_CONF_VARS
['FE']['logfile_dir']) && @is_file
($theLogFile) && @is_writeable
($theLogFile)) {
1269 $this->config
['stat_vars']['logFile'] = $theLogFile;
1270 $shortTitle = substr(ereg_replace('[^\.[:alnum:]_-]','_',$this->page
['title']),0,30);
1271 $pageName = $this->config
['config']['stat_apache_pagenames'] ?
$this->config
['config']['stat_apache_pagenames'] : '[path][title]--[uid].html';
1272 $pageName = str_replace('[title]', $shortTitle ,$pageName);
1273 $pageName = str_replace('[uid]',$this->page
['uid'],$pageName);
1274 $pageName = str_replace('[alias]',$this->page
['alias'],$pageName);
1275 $pageName = str_replace('[type]',$this->page
['type'],$pageName);
1276 $temp = $this->config
['rootLine'];
1278 $len = t3lib_div
::intInRange($this->config
['config']['stat_titleLen'],1,100,20);
1279 $pageName = str_replace('[path]', ereg_replace('[^\.[:alnum:]\/_-]','_',$this->sys_page
->getPathFromRootline($temp,$len)).'/' ,$pageName);
1280 $this->config
['stat_vars']['pageName'] = $pageName;
1282 $this->config
['FEData'] = $this->tmpl
->setup
['FEData'];
1283 $this->config
['FEData.'] = $this->tmpl
->setup
['FEData.'];
1285 $GLOBALS['TT']->pull();
1287 $this->printError('No template found!');
1292 if ($this->config
['config']['no_cache']) {$this->set_no_cache();} // Set $this->no_cache true if the config.no_cache value is set!
1294 // Check PATH_INFO url
1295 if ($this->absRefPrefix_force
&& strcmp($this->config
['config']['simulateStaticDocuments'],'PATH_INFO')) {
1296 $redirectUrl = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').'index.php?id='.$this->id
.'&type='.$this->type
;
1297 if ($this->config
['config']['simulateStaticDocuments_dontRedirectPathInfoError']) {
1298 $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');
1300 header('Location: '.t3lib_div
::locationHeaderUrl($redirectUrl));
1303 // $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.
1320 /********************************************
1322 * Further initialization and data processing
1323 * (jumpurl/submission of forms)
1325 *******************************************/
1328 * Get the compressed $TCA array for use in the front-end
1329 * 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.
1330 * Operates on the global variable, $TCA
1335 function getCompressedTCarray() {
1338 $GLOBALS['TT']->push('Get Compressed TC array');
1339 if (!$this->TCAloaded
) {
1340 $tempHash = md5('tables.php:'.
1341 filemtime(TYPO3_extTableDef_script ? PATH_typo3conf
.TYPO3_extTableDef_script
: PATH_t3lib
.'stddb/tables.php').
1342 (TYPO3_extTableDef_script?
filemtime(PATH_typo3conf
.TYPO3_extTableDef_script
):'').
1343 ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'] ?
filemtime(PATH_typo3conf
.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php') : '')
1345 $TCA = unserialize($this->sys_page
->getHash($tempHash, 0));
1347 $this->includeTCA(0);
1350 while(list($key,$val)=each($TCA)) {
1351 $newTc[$key]['ctrl'] = $val['ctrl'];
1352 $newTc[$key]['feInterface']=$val['feInterface'];
1355 $this->sys_page
->storeHash($tempHash, serialize($newTc), 'SHORT TC');
1358 $GLOBALS['TT']->pull();
1362 * Includes full TCA.
1363 * 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.
1364 * 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.
1365 * Global vars $TCA, $PAGES_TYPES, $LANG_GENERAL_LABELS can/will be affected.
1366 * The flag $this->TCAloaded will make sure that such an inclusion happens only once since; If $this->TCAloaded is set, nothing is included.
1368 * @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())
1370 * @see getCompressedTCarray()
1372 function includeTCA($TCAloaded=1) {
1373 global $TCA, $PAGES_TYPES, $LANG_GENERAL_LABELS, $TBE_MODULES;
1374 if (!$this->TCAloaded
) {
1376 include (TYPO3_tables_script ? PATH_typo3conf
.TYPO3_tables_script
: PATH_t3lib
.'stddb/tables.php');
1377 // Extension additions
1378 if ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE']) {
1379 include(PATH_typo3conf
.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php');
1381 include(PATH_t3lib
.'stddb/load_ext_tables.php');
1384 if (TYPO3_extTableDef_script
) {
1385 include (PATH_typo3conf
.TYPO3_extTableDef_script
);
1387 $this->TCAloaded
= $TCAloaded;
1392 * Setting the language key that'll be used by the current page.
1393 * 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.
1398 function settingLanguage() {
1399 $this->sys_language_uid
= intval($this->config
['config']['sys_language_uid']);
1400 $olRec = $this->sys_page
->getPageOverlay($this->id
,$this->sys_language_uid
);
1402 if (!count($olRec)) {
1403 $this->sys_language_uid
=0;
1405 $this->page
= $this->sys_page
->getPageOverlay($this->page
,$this->sys_language_uid
);
1407 $this->sys_page
->sys_language_uid
= $this->sys_language_uid
;
1409 // Updating content of the two rootLines IF the language key is set!
1410 if ($this->sys_language_uid
&& is_array($this->tmpl
->rootLine
)) {
1411 reset($this->tmpl
->rootLine
);
1412 while(list($rLk)=each($this->tmpl
->rootLine
)) {
1413 $this->tmpl
->rootLine
[$rLk] = $this->sys_page
->getPageOverlay($this->tmpl
->rootLine
[$rLk]);
1416 if ($this->sys_language_uid
&& is_array($this->rootLine
)) {
1417 reset($this->rootLine
);
1418 while(list($rLk)=each($this->rootLine
)) {
1419 $this->rootLine
[$rLk] = $this->sys_page
->getPageOverlay($this->rootLine
[$rLk]);
1423 // Finding the ISO code:
1424 if (t3lib_extMgm
::isLoaded('static_info_tables') && $this->sys_language_uid
) {
1425 $sys_language_row = $this->sys_page
->getRawRecord('sys_language',$this->sys_language_uid
,'static_lang_isocode');
1426 if (is_array($sys_language_row) && $sys_language_row['static_lang_isocode']) {
1427 $stLrow = $this->sys_page
->getRawRecord('static_languages',$sys_language_row['static_lang_isocode'],'lg_iso_2');
1428 $this->sys_language_isocode
=$stLrow['lg_iso_2'];
1434 * Checks if any email-submissions or submission via the fe_tce
1436 * @return string 'email' if a formmail has been send, 'fe_tce' if front-end data submission (like forums, guestbooks) is send. '' if none.
1438 function checkDataSubmission() {
1439 global $HTTP_POST_VARS;
1441 if ($HTTP_POST_VARS['formtype_db'] ||
$HTTP_POST_VARS['formtype_mail']) {
1442 $refInfo=parse_url(t3lib_div
::getIndpEnv('HTTP_REFERER'));
1443 if (t3lib_div
::getIndpEnv('TYPO3_HOST_ONLY')==$refInfo['host'] ||
$this->TYPO3_CONF_VARS
['SYS']['doNotCheckReferer']) {
1444 if ($this->locDataCheck($HTTP_POST_VARS['locationData'])) {
1446 if ($HTTP_POST_VARS['formtype_mail']) {
1448 } elseif ($HTTP_POST_VARS['formtype_db'] && is_array($HTTP_POST_VARS['data'])) {
1451 $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": Return value: '.$ret,0);
1454 } else $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": HTTP_HOST and REFERER HOST did not match when processing submitted formdata!',3);
1459 * Processes submitted user data (obsolete "Frontend TCE")
1463 * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=342&cHash=fdf55adb3b
1466 $fe_tce = t3lib_div
::makeInstance('tslib_feTCE');
1467 $fe_tce->start(t3lib_div
::_POST('data'),$this->config
['FEData.']);
1468 $fe_tce->includeScripts();
1472 * Checks if a formmail submission can be sent as email
1474 * @param string The input from $GLOBALS['HTTP_POST_VARS']['locationData']
1477 * @see checkDataSubmission()
1479 function locDataCheck($locationData) {
1480 $locData = explode(':',$locationData);
1481 if (!$locData[1] ||
$this->sys_page
->checkRecord($locData[1],$locData[2],1)) {
1482 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.
1484 } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: The page pointed to by location data ('.$locationData.') was not accessible.',2);
1485 } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: Location data ('.$locationData.') record pointed to was not accessible.',2);
1489 * Sends the emails from the formmail content object.
1493 * @see checkDataSubmission()
1495 function sendFormmail() {
1496 $formmail = t3lib_div
::makeInstance('t3lib_formmail');
1498 $EMAIL_VARS = t3lib_div
::_POST();
1499 unset($EMAIL_VARS['locationData']);
1500 unset($EMAIL_VARS['formtype_mail']);
1502 $formmail->start($EMAIL_VARS);
1503 $formmail->sendtheMail();
1504 $GLOBALS['TT']->setTSlogMessage('"Formmail" invoked, sending mail to '.$EMAIL_VARS['recipient'],0);
1508 * Checks if jumpurl is set.
1509 * This function also takes care of jumpurl utilized by the Direct Mail module (ext: direct_mail) which may set an integer value for jumpurl which refers to a link in a certain mail-record, mid
1513 function checkJumpUrl() {
1516 $mid = t3lib_div
::_GP('mid'); // mail id, if direct mail link
1517 $rid = t3lib_div
::_GP('rid'); // recipient id, if direct mail link
1518 if ((strcmp($this->jumpurl
,'') && ((t3lib_div
::getIndpEnv('HTTP_REFERER') ||
$this->TYPO3_CONF_VARS
['SYS']['doNotCheckReferer']) ||
$mid)) ||
($this->jumpurl
= $this->sys_page
->getExtURL($this->page
,$this->config
['config']['disablePageExternalUrl']))) {
1519 if ($mid && is_array($TCA['sys_dmail'])) { // Yes, it's OK if the link comes from a direct mail. AND sys_dmail module has installed the table, sys_dmail (and therefore we expect sys_dmail_maillog as well!)
1520 $temp_recip=explode('_',$rid);
1522 if (t3lib_div
::testInt($this->jumpurl
)) {
1523 $temp_res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('mailContent', 'sys_dmail', 'uid='.intval($mid));
1524 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($temp_res)) {
1525 $temp_unpackedMail = unserialize($row['mailContent']);
1526 $url_id=$this->jumpurl
;
1527 if ($this->jumpurl
>=0) {
1528 $responseType=1; // Link (number)
1529 $this->jumpurl
= $temp_unpackedMail['html']['hrefs'][$url_id]['absRef'];
1531 $responseType=2; // Link (number, plaintext)
1532 $this->jumpurl
= $temp_unpackedMail['plain']['link_ids'][abs($url_id)];
1534 switch($temp_recip[0]) {
1536 $theTable = 'tt_address';
1539 $theTable = 'fe_users';
1546 $recipRow = $this->sys_page
->getRawRecord($theTable,$temp_recip[1]);
1547 if (is_array($recipRow)) {
1548 // debug($recipRow);
1549 $authCode = t3lib_div
::stdAuthCode($recipRow['uid']);
1550 $rowFieldsArray = explode(',', 'uid,name,title,email,phone,www,address,company,city,zip,country,fax,firstname');
1551 reset($rowFieldsArray);
1552 while(list(,$substField)=each($rowFieldsArray)) {
1553 $this->jumpurl
= str_replace('###USER_'.$substField.'###', $recipRow[$substField], $this->jumpurl
);
1555 $this->jumpurl
= str_replace('###SYS_TABLE_NAME###', $tableNameChar, $this->jumpurl
); // Put in the tablename of the userinformation
1556 $this->jumpurl
= str_replace('###SYS_MAIL_ID###', $mid, $this->jumpurl
); // Put in the uid of the mail-record
1557 $this->jumpurl
= str_replace('###SYS_AUTHCODE###', $authCode, $this->jumpurl
);
1559 // debug($this->jumpurl);
1564 $GLOBALS['TYPO3_DB']->sql_free_result($temp_res);
1566 if (!$this->jumpurl
) die('Error: No further link. Please report error to the mail sender.');
1568 $responseType=-1; // received (url, dmailerping)
1570 if ($responseType!=0) {
1571 $insertFields = array(
1572 'mid' => intval($mid),
1573 'rtbl' => $temp_recip[0],
1574 'rid' => intval($temp_recip[1]),
1576 'url' => $this->jumpurl
,
1577 'response_type' => intval($responseType),
1578 'url_id' => intval($url_id)
1581 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_dmail_maillog', $insertFields);
1585 unset($this->jumpurl
);
1590 * Sends a header 'Location' to jumpurl, if jumpurl is set.
1591 * Will exit if a location header is sent (for instance if JumpUrl was triggered)
1595 function jumpUrl() {
1596 if ($this->jumpurl
) {
1597 if (t3lib_div
::_GP('juSecure')) {
1600 t3lib_div
::_GP('locationData'),
1601 $this->TYPO3_CONF_VARS
['SYS']['encryptionKey']
1603 $calcJuHash=t3lib_div
::shortMD5(serialize($hArr));
1604 $locationData = t3lib_div
::_GP('locationData');
1605 $juHash = t3lib_div
::_GP('juHash');
1606 if ($juHash == $calcJuHash) {
1607 if ($this->locDataCheck($locationData)) {
1608 $this->jumpurl
= rawurldecode($this->jumpurl
); // 211002 - goes with cObj->filelink() rawurlencode() of filenames so spaces can be allowed.
1609 if (@is_file
($this->jumpurl
)) {
1610 $mimeType = t3lib_div
::_GP('mimeType');
1611 $mimeType = $mimeType ?
$mimeType : 'application/octet-stream';
1612 Header('Content-Type: '.$mimeType);
1613 Header('Content-Disposition: attachment; filename='.basename($this->jumpurl
));
1614 readfile($this->jumpurl
);
1616 } else die('jumpurl Secure: "'.$this->jumpurl
.'" was not a valid file!');
1617 } else die('jumpurl Secure: locationData, '.$locationData.', was not accessible.');
1618 } else die('jumpurl Secure: Calculated juHash, '.$calcJuHash.', did not match the submitted juHash.');
1620 $TSConf = $this->getPagesTSconfig();
1621 if ($TSConf['TSFE.']['jumpUrl_transferSession']) {
1622 $uParts = parse_url($this->jumpurl
);
1623 $params = '&FE_SESSION_KEY='.rawurlencode($this->fe_user
->id
.'-'.md5($this->fe_user
->id
.'/'.$this->TYPO3_CONF_VARS
['SYS']['encryptionKey']));
1624 $this->jumpurl
.=($uParts['query']?
'':'?').$params; // Add the session parameter ...
1626 Header('Location: '.$this->jumpurl
);
1633 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
1638 function setUrlIdToken() {
1639 if ($this->config
['config']['ftu']) {
1640 $this->getMethodUrlIdToken
= $this->TYPO3_CONF_VARS
['FE']['get_url_id_token'];
1642 $this->getMethodUrlIdToken
= '';
1669 /********************************************
1671 * Page generation; cache handling
1673 *******************************************/
1676 * Returns true if the page should be generated
1677 * That is if jumpurl is not set and the cacheContentFlag is not set.
1681 function isGeneratePage() {
1682 return (!$this->cacheContentFlag
&& !$this->jumpurl
);
1686 * Temp cache content
1687 * 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.
1691 function tempPageCacheContent() {
1692 $this->tempContent
=0;
1693 if (!$this->no_cache
) {
1698 <title>'.htmlspecialchars($this->tmpl
->printTitle($this->page
['title'])).'</title>
1699 <meta http-equiv=Refresh Content="3; Url='.htmlspecialchars(t3lib_div
::getIndpEnv('REQUEST_URI')).'" />
1701 <body bgcolor="white">
1702 <font size="1" face="VERDANA,ARIAL,HELVETICA" color="#cccccc">
1703 <div align="center">
1704 <b>Page is being generated.</b><br />
1705 If this message does not disappear within '.$seconds.' seconds, please reload.
1710 $temp_content = $this->config
['config']['message_page_is_being_generated'] ?
$this->config
['config']['message_page_is_being_generated'] : $stdMsg;
1712 $this->setPageCacheContent($temp_content,'',$GLOBALS['EXEC_TIME']+
$seconds);
1713 $this->tempContent
=1; // This flag shows that temporary content is put in the cache
1718 * Set cache content to $this->content
1722 function realPageCacheContent() {
1723 $cache_timeout = $this->page
['cache_timeout'] ?
$this->page
['cache_timeout'] : ($this->cacheTimeOutDefault ?
$this->cacheTimeOutDefault
: 60*60*24); // seconds until a cached page is too old
1724 $timeOutTime = $GLOBALS['EXEC_TIME']+
$cache_timeout;
1725 if ($this->config
['config']['cache_clearAtMidnight']) {
1726 $midnightTime = mktime (0,0,0,date('m',$timeOutTime),date('d',$timeOutTime),date('Y',$timeOutTime));
1727 if ($midnightTime > time()) { // If the midnight time of the expire-day is greater than the current time, we may set the timeOutTime to the new midnighttime.
1728 $timeOutTime=$midnightTime;
1731 $this->config
['hash_base'] = $this->hash_base
;
1732 $this->setPageCacheContent($this->content
,$this->config
,$timeOutTime);
1736 * Sets cache content; Inserts the content string into the cache_pages table.
1738 * @param string The content to store in the HTML field of the cache table
1739 * @param mixed The additional cache_data array, fx. $this->config
1740 * @param integer Timestamp
1742 * @see realPageCacheContent(), tempPageCacheContent()
1744 function setPageCacheContent($c,$d,$t) {
1745 $this->clearPageCacheContent();
1747 $insertFields = array(
1748 'hash' => $this->newHash
,
1749 'page_id' => $this->id
,
1751 'cache_data' => serialize($d),
1755 if ($this->page_cache_reg1
) {
1756 $insertFields['reg1'] = intval($this->page_cache_reg1
);
1759 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_pages', $insertFields);
1763 * Clears cache content (for $this->newHash)
1767 function clearPageCacheContent() {
1768 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'hash="'.$GLOBALS['TYPO3_DB']->quoteStr($this->newHash
, 'cache_pages').'"');
1772 * Clears cache content for a list of page ids
1774 * @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)
1777 function clearPageCacheContent_pidList($pidList) {
1778 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($pidList).')');
1782 * Sets sys last changed
1783 * 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.
1786 * @see tslib_cObj::lastChanged()
1788 function setSysLastChanged() {
1789 if ($this->page
['SYS_LASTCHANGED'] < intval($this->register
['SYS_LASTCHANGED'])) {
1790 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($this->id
), array('SYS_LASTCHANGED' => intval($this->register
['SYS_LASTCHANGED'])));
1813 /********************************************
1815 * Page generation; rendering and inclusion
1817 *******************************************/
1820 * Does some processing BEFORE the pagegen script is included.
1824 function generatePage_preProcessing() {
1826 // 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!
1827 $this->newHash
= $this->getHash();
1829 // 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.
1830 $this->tempPageCacheContent();
1833 if ($this->config
['config']['locale_all']) {
1834 # Change by Rene Fritz, 22/10 2002
1835 # there`s the problem that PHP parses float values in scripts wrong if the locale LC_NUMERIC is set to something with a komma as decimal point
1836 # this does not work in php 4.2.3
1837 #setlocale('LC_ALL',$this->config['config']['locale_all']);
1838 #setlocale('LC_NUMERIC','en_US');
1840 # so we set all except LC_NUMERIC
1841 setlocale(LC_COLLATE
,$this->config
['config']['locale_all']);
1842 setlocale(LC_CTYPE
,$this->config
['config']['locale_all']);
1843 setlocale(LC_MONETARY
,$this->config
['config']['locale_all']);
1844 setlocale(LC_TIME
,$this->config
['config']['locale_all']);
1847 // Setting cache_timeout_default. May be overridden by PHP include scritps.
1848 $this->cacheTimeOutDefault
= intval($this->config
['config']['cache_period']);
1850 // page is generated
1851 $this->no_cacheBeforePageGen
= $this->no_cache
;
1855 * Determines to include custom or pagegen.php script
1856 * returns script-filename if a TypoScript (config) script is defined and should be include instead of pagegen.php
1858 * @return string The relative filepath of "config.pageGenScript" if found and allowed
1860 function generatePage_whichScript() {
1861 if (!$this->TYPO3_CONF_VARS
['FE']['noPHPscriptInclude'] && $this->config
['config']['pageGenScript']) {
1862 return $this->tmpl
->getFileName($this->config
['config']['pageGenScript']);
1867 * Does some processing AFTER the pagegen script is included.
1868 * This includes calling tidy (if configured), XHTML cleaning (if configured), caching the page, indexing the page (if configured) and setting sysLastChanged
1872 function generatePage_postProcessing() {
1873 // 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.
1874 if ($this->no_cacheBeforePageGen
) $this->set_no_cache();
1876 // Tidy up the code, if flag...
1877 if ($this->TYPO3_CONF_VARS
['FE']['tidy_option'] == 'all') {
1878 $GLOBALS['TT']->push('Tidy, all','');
1879 $this->content
= $this->tidyHTML($this->content
);
1880 $GLOBALS['TT']->pull();
1883 // XHTML-clean the code, if flag set
1884 if ($this->doXHTML_cleaning() == 'all') {
1885 $GLOBALS['TT']->push('XHTML clean, all','');
1886 $XHTML_clean = t3lib_div
::makeInstance('t3lib_parsehtml');
1887 $this->content
= $XHTML_clean->XHTML_clean($this->content
);
1888 $GLOBALS['TT']->pull();
1891 // Fix local anchors in links, if flag set
1892 if ($this->doLocalAnchorFix() == 'all') {
1893 $GLOBALS['TT']->push('Local anchor fix, all','');
1894 $this->prefixLocalAnchorsWithScript();
1895 $GLOBALS['TT']->pull();
1899 if (!$this->no_cache
) {
1900 // Tidy up the code, if flag...
1901 if ($this->TYPO3_CONF_VARS
['FE']['tidy_option'] == 'cached') {
1902 $GLOBALS['TT']->push('Tidy, cached','');
1903 $this->content
= $this->tidyHTML($this->content
);
1904 $GLOBALS['TT']->pull();
1906 // XHTML-clean the code, if flag set
1907 if ($this->doXHTML_cleaning() == 'cached') {
1908 $GLOBALS['TT']->push('XHTML clean, cached','');
1909 $XHTML_clean = t3lib_div
::makeInstance('t3lib_parsehtml');
1910 $this->content
= $XHTML_clean->XHTML_clean($this->content
);
1911 $GLOBALS['TT']->pull();
1913 // Fix local anchors in links, if flag set
1914 if ($this->doLocalAnchorFix() == 'cached') {
1915 $GLOBALS['TT']->push('Local anchor fix, cached','');
1916 $this->prefixLocalAnchorsWithScript();
1917 $GLOBALS['TT']->pull();
1920 $this->realPageCacheContent();
1921 } 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)
1922 $this->clearPageCacheContent();
1925 if ($this->isSearchIndexPage()) {
1926 $GLOBALS['TT']->push('Index page','');
1927 $indexer = t3lib_div
::makeInstance('tx_indexedsearch_indexer');
1928 $indexer->init($this->content
,$this->config
['config'],$this->id
,$this->type
,$this->gr_list
,$this->cHash_array
,$this->register
['SYS_LASTCHANGED'],$this->config
['rootLine']);
1929 $indexer->indexTypo3PageContent();
1930 $GLOBALS['TT']->pull();
1931 } elseif ($this->config
['config']['index_enable'] && $this->no_cache
) {
1932 $GLOBALS['TT']->push('Index page','');
1933 $GLOBALS['TT']->setTSlogMessage('Index page? No, page was set to "no_cache" and so cannot be indexed.');
1934 $GLOBALS['TT']->pull();
1936 $this->setSysLastChanged();
1940 * Processes the INTinclude-scripts
1944 function INTincScript() {
1945 $GLOBALS['TT']->push('Split content');
1946 $INTiS_splitC = explode('<!--INT_SCRIPT.',$this->content
); // Splits content with the key.
1948 $GLOBALS['TT']->setTSlogMessage('Parts: '.count($INTiS_splitC));
1949 $GLOBALS['TT']->pull();
1951 // Depreciated stuff:
1952 $this->additionalHeaderData
= is_array($this->config
['INTincScript_ext']['additionalHeaderData']) ?
$this->config
['INTincScript_ext']['additionalHeaderData'] : array();
1953 $this->additionalJavaScript
= $this->config
['INTincScript_ext']['additionalJavaScript'];
1954 $this->additionalCSS
= $this->config
['INTincScript_ext']['additionalCSS'];
1955 $this->JSCode
= $this->additionalHeaderData
['JSCode'];
1956 $this->JSImgCode
= $this->additionalHeaderData
['JSImgCode'];
1957 $this->divSection
='';
1959 $INTiS_config = $GLOBALS['TSFE']->config
['INTincScript'];
1960 reset($INTiS_splitC);
1961 while(list($INTiS_c,$INTiS_cPart)=each($INTiS_splitC)) {
1962 if (substr($INTiS_cPart,32,3)=='-->') { // If the split had a comment-end after 32 characters it's probably a split-string
1963 $GLOBALS['TT']->push('Include '.$INTiS_config[$INTiS_key]['file'],'');
1964 $INTiS_key = 'INT_SCRIPT.'.substr($INTiS_cPart,0,32);
1966 if (is_array($INTiS_config[$INTiS_key])) {
1967 $INTiS_cObj = unserialize($INTiS_config[$INTiS_key]['cObj']);
1968 $INTiS_cObj->INT_include
=1;
1969 switch($INTiS_config[$INTiS_key]['type']) {
1971 $incContent=$INTiS_cObj->PHP_SCRIPT($INTiS_config[$INTiS_key]['conf']);
1974 $incContent=$INTiS_cObj->COBJ_ARRAY($INTiS_config[$INTiS_key]['conf']);
1977 $incContent=$INTiS_cObj->USER($INTiS_config[$INTiS_key]['conf']);
1981 $this->content
.= $incContent;
1982 $this->content
.= substr($INTiS_cPart,35);
1983 $GLOBALS['TT']->pull($incContent);
1985 $this->content
.= ($c?
'<!--INT_SCRIPT.':'').$INTiS_cPart;
1988 $GLOBALS['TT']->push('Substitute header section');
1989 $this->INTincScript_loadJSCode();
1990 $this->content
= str_replace('<!--HD_'.$this->config
['INTincScript_ext']['divKey'].'-->', implode($this->additionalHeaderData
,chr(10)), $this->content
);
1991 $this->content
= str_replace('<!--TDS_'.$this->config
['INTincScript_ext']['divKey'].'-->', $this->divSection
, $this->content
);
1992 $this->setAbsRefPrefix();
1993 $GLOBALS['TT']->pull();
1997 * Loads the JavaScript code for INTincScript
2002 function INTincScript_loadJSCode() {
2003 if ($this->JSImgCode
) { // If any images added, then add them to the javascript section
2004 $this->additionalHeaderData
['JSImgCode']='
2005 <script type="text/javascript">
2008 if (version == "n3") {
2009 '.trim($this->JSImgCode
).'
2015 if ($this->JSCode ||
count($this->additionalJavaScript
)) { // Add javascript
2016 $this->additionalHeaderData
['JSCode']='
2017 <script type="text/javascript">
2020 '.implode($this->additionalJavaScript
,chr(10)).'
2021 '.trim($this->JSCode
).'
2026 if (count($this->additionalCSS
)) { // Add javascript
2027 $this->additionalHeaderData
['_CSS']='
2028 <style type="text/css">
2031 '.implode($this->additionalCSS
,chr(10)).'
2039 * Determines if there are any INTincScripts to include
2041 * @return boolean Returns true if scripts are found (and not jumpurl)
2043 function isINTincScript() {
2044 return (is_array($this->config
['INTincScript']) && !$this->jumpurl
);
2048 * Returns true if page should be indexed.
2052 function isSearchIndexPage() {
2053 return t3lib_extMgm
::isLoaded('indexed_search') && $this->config
['config']['index_enable'] && !$this->no_cache
;
2057 * Returns the mode of XHTML cleaning
2059 * @return string Keyword: "all", "cached" or "output"
2061 function doXHTML_cleaning() {
2062 return $this->config
['config']['xhtml_cleaning'];
2066 * Returns the mode of Local Anchor prefixing
2068 * @return string Keyword: "all", "cached" or "output"
2070 function doLocalAnchorFix() {
2071 return $this->config
['config']['prefixLocalAnchors'];
2089 /********************************************
2091 * Finished off; outputting, storing session data, statistics...
2093 *******************************************/
2096 * Determines if content should be outputted.
2097 * Outputting content is done only if jumpurl is NOT set.
2099 * @return boolean Returns true if $this->jumpurl is not set.
2101 function isOutputting() {
2102 return (!$this->jumpurl
);
2106 * Processes the output before it's actually outputted. Sends headers also.
2107 * This includes substituting the USERNAME comment, getMethodUrlIdToken, sending additional headers (as defined in the TypoScript "config.additionalheaders" object), tidy'ing content, XHTML cleaning content (if configured)
2108 * Works on $this->content
2112 function processOutput() {
2113 // Substitutes username mark with the username
2114 if ($this->fe_user
->user
['uid']) {
2115 $token = trim($this->config
['config']['USERNAME_substToken']);
2116 $this->content
= str_replace($token ?
$token : '<!--###USERNAME###-->',$this->fe_user
->user
['username'],$this->content
);
2118 // Substitutes get_URL_ID in case of GET-fallback
2119 if ($this->getMethodUrlIdToken
) {
2120 $this->content
= str_replace($this->getMethodUrlIdToken
, $this->fe_user
->get_URL_ID
, $this->content
);
2123 // Set header for charset-encoding if set. Added by RL 17.10.03
2124 if ($this->config
['config']['metaCharset']) {
2125 $headLine = 'Content-Type:text/html;charset='.trim ($this->config
['config']['metaCharset']);
2129 // Set headers, if any
2130 if ($this->config
['config']['additionalHeaders']) {
2131 $headerArray = explode('|', $this->config
['config']['additionalHeaders']);
2132 while(list(,$headLine)=each($headerArray)) {
2133 $headLine = trim($headLine);
2138 // Tidy up the code, if flag...
2139 if ($this->TYPO3_CONF_VARS
['FE']['tidy_option'] == 'output') {
2140 $GLOBALS['TT']->push('Tidy, output','');
2141 $this->content
= $this->tidyHTML($this->content
);
2142 $GLOBALS['TT']->pull();
2144 // XHTML-clean the code, if flag set
2145 if ($this->doXHTML_cleaning() == 'output') {
2146 $GLOBALS['TT']->push('XHTML clean, output','');
2147 $XHTML_clean = t3lib_div
::makeInstance('t3lib_parsehtml');
2148 $this->content
= $XHTML_clean->XHTML_clean($this->content
);
2149 $GLOBALS['TT']->pull();
2151 // Fix local anchors in links, if flag set
2152 if ($this->doLocalAnchorFix() == 'output') {
2153 $GLOBALS['TT']->push('Local anchor fix, output','');
2154 $this->prefixLocalAnchorsWithScript();
2155 $GLOBALS['TT']->pull();
2158 /* if ($this->beUserLogin && t3lib_div::_GP('ADMCMD_view')) { // This is a try to change target=_top to target=_self if pages are shown in the Web>View module...
2159 $this->content = str_replace('target="_top"','target="_self"',$this->content);
2160 $this->content = str_replace('target=_top','target="_self"',$this->content);
2165 * Determines if any EXTincScripts should be included
2167 * @return boolean True, if external php scripts should be included (set by PHP_SCRIPT_EXT cObjects)
2168 * @see tslib_cObj::PHP_SCRIPT
2170 function isEXTincScript() {
2171 return is_array($this->config
['EXTincScript']);
2175 * Stores session data for the front end user
2179 function storeSessionData() {
2180 $this->fe_user
->storeSessionData();
2184 * Sets the parsetime of the page.
2189 function setParseTime() {
2190 // Compensates for the time consumed with Back end user initialization.
2191 $this->scriptParseTime
= $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_end'])
2192 - $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_start'])
2193 - ($GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'])-$GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_start']));
2197 * Saves hit statistics
2201 function statistics() {
2202 if ($this->config
['config']['stat'] &&
2203 (!strcmp('',$this->config
['config']['stat_typeNumList']) || t3lib_div
::inList(str_replace(' ','',$this->config
['config']['stat_typeNumList']), $this->type
)) &&
2204 (!$this->config
['config']['stat_excludeBEuserHits'] ||
!$this->beUserLogin
) &&
2205 (!$this->config
['config']['stat_excludeIPList'] ||
!t3lib_div
::inList(str_replace(' ','',$this->config
['config']['stat_excludeIPList']), t3lib_div
::getIndpEnv('REMOTE_ADDR')))) {
2206 $GLOBALS['TT']->push('Stat');
2207 if (t3lib_extMgm
::isLoaded('sys_stat') && $this->config
['config']['stat_mysql']) {
2210 $sword = t3lib_div
::_GP('sword');
2212 $jumpurl_msg = 'sword:'.$sword;
2213 } elseif ($this->jumpurl
) {
2214 $jumpurl_msg = 'jumpurl:'.$this->jumpurl
;
2219 // Flags: bits: 0 = BE_user, 1=Cached page?
2221 if ($this->beUserLogin
) {$flags|
=1;}
2222 if ($this->cacheContentFlag
) {$flags|
=2;}
2225 $refUrl = t3lib_div
::getIndpEnv('HTTP_REFERER');
2226 $thisUrl = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR');
2227 if (t3lib_div
::isFirstPartOfStr($refUrl,$thisUrl)) {
2231 $insertFields = array(
2232 'page_id' => intval($this->id
), // id
2233 'page_type' => intval($this->type
), // type
2234 'jumpurl' => $jumpurl_msg, // jumpurl message
2235 'feuser_id' => $this->fe_user
->user
['uid'], // fe_user id, integer
2236 'cookie' => $this->fe_user
->id
, // cookie as set or retrieve. If people has cookies disabled this will vary all the time...
2237 'sureCookie' => hexdec(substr($this->fe_user
->cookieId
,0,8)), // This is the cookie value IF the cookie WAS actually set. However the first hit where the cookie is set will thus NOT be logged here. So this lets you select for a session of at least two clicks...
2238 'rl0' => $this->config
['rootLine'][0]['uid'], // RootLevel 0 uid
2239 'rl1' => $this->config
['rootLine'][1]['uid'], // RootLevel 1 uid
2240 'client_browser' => $GLOBALS['CLIENT']['BROWSER'], // Client browser (net, msie, opera)
2241 'client_version' => $GLOBALS['CLIENT']['VERSION'], // Client version (double value)
2242 'client_os' => $GLOBALS['CLIENT']['SYSTEM'], // Client Operating system (win, mac, unix)
2243 'parsetime' => intval($this->scriptParseTime
), // Parsetime for the page.
2244 'flags' => $flags, // Flags: Is be user logged in? Is page cached?
2245 'IP' => t3lib_div
::getIndpEnv('REMOTE_ADDR'), // Remote IP address
2246 'host' => t3lib_div
::getIndpEnv('REMOTE_HOST'), // Remote Host Address
2247 'referer' => $refUrl, // Referer URL
2248 'browser' => t3lib_div
::getIndpEnv('HTTP_USER_AGENT'), // User Agent Info.
2249 'tstamp' => $GLOBALS['EXEC_TIME'] // Time stamp
2252 $GLOBALS['TT']->push('Store SQL');
2253 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_stat', $insertFields);
2254 $GLOBALS['TT']->pull();
2258 if ($this->config
['config']['stat_apache'] && $this->config
['stat_vars']['pageName']) {
2259 if (@is_file
($this->config
['stat_vars']['logFile']) && TYPO3_OS
!='WIN') {
2260 $LogLine = ((t3lib_div
::getIndpEnv('REMOTE_HOST') && !$this->config
['config']['stat_apache_noHost']) ? t3lib_div
::getIndpEnv('REMOTE_HOST') : t3lib_div
::getIndpEnv('REMOTE_ADDR')).' - - '.Date('[d/M/Y:H:i:s +0000]',$GLOBALS['EXEC_TIME']).' "GET '.$this->config
['stat_vars']['pageName'].' HTTP/1.1" 200 '.strlen($this->content
);
2261 if (!$this->config
['config']['stat_apache_notExtended']) {
2262 $LogLine.= ' "'.t3lib_div
::getIndpEnv('HTTP_REFERER').'" "'.t3lib_div
::getIndpEnv('HTTP_USER_AGENT').'"';
2265 switch($GLOBALS['TYPO3_CONF_VARS']['FE']['logfile_write']) {
2267 $GLOBALS['TT']->push('Write to log file (fputs)');
2268 $logfilehandle = fopen(PATH_site
.$this->config
['stat_vars']['logFile'], 'a');
2269 fputs($logfilehandle, $LogLine."\n");
2270 @fclose
($logfilehandle);
2271 $GLOBALS['TT']->pull();
2274 $GLOBALS['TT']->push('Write to log file (echo)');
2275 $execCmd = 'echo "'.addslashes($LogLine).'" >> '.PATH_site
.$this->config
['stat_vars']['logFile'];
2277 $GLOBALS['TT']->pull();
2281 $GLOBALS['TT']->setTSlogMessage('Writing to logfile: OK',0);
2283 $GLOBALS['TT']->setTSlogMessage('Writing to logfile: Error - logFile did not exist or OS is Windows!',3);
2286 $GLOBALS['TT']->pull();
2291 * Outputs preview info.
2295 function previewInfo() {
2296 if ($this->fePreview
) {
2299 <div align="center">
2300 <table border="3" bordercolor="black" cellpadding="2" bgcolor="red">
2302 <td> <font face="Verdana" size="1"><b>PREVIEW!</b></font> </td>
2306 $temp_content = $this->config
['config']['message_preview'] ?
$this->config
['config']['message_preview'] : $stdMsg;
2312 * Returns a link to the login screen with redirect to the front-end
2314 * @return string HTML, a tag for a link to the backend.
2316 function beLoginLinkIPList() {
2317 if ($this->config
['config']['beLoginLinkIPList']) {
2318 if (t3lib_div
::cmpIP(t3lib_div
::getIndpEnv('REMOTE_ADDR'), $this->config
['config']['beLoginLinkIPList'])) {
2319 $label = !$this->beUserLogin ?
$this->config
['config']['beLoginLinkIPList_login'] : $this->config
['config']['beLoginLinkIPList_logout'];
2321 if (!$this->beUserLogin
) {
2322 $link = '<a href="'.htmlspecialchars(TYPO3_mainDir
.'index.php?redirect_url='.rawurlencode(t3lib_div
::getIndpEnv("REQUEST_URI"))).'">'.$label.'</a>';
2324 $link = '<a href="'.htmlspecialchars(TYPO3_mainDir
.'index.php?L=OUT&redirect_url='.rawurlencode(t3lib_div
::getIndpEnv("REQUEST_URI"))).'">'.$label.'</a>';
2353 /********************************************
2355 * Various internal API functions
2357 *******************************************/
2361 * Make simulation filename (without the ".html" ending, only body of filename)
2363 * @param string The page title to use
2364 * @param mixed The page id (integer) or alias (string)
2365 * @param integer The type number
2366 * @param string Query-parameters to encode (will be done only if caching is enabled and TypoScript configured for it. I don't know it this makes much sense in fact...)
2367 * @param boolean The "no_cache" status of the link.
2368 * @return string The body of the filename.
2369 * @see getSimulFileName(), t3lib_tstemplate::linkData(), tslib_frameset::frameParams()
2371 function makeSimulFileName($inTitle,$page,$type,$addParams='',$no_cache='') {
2372 $titleChars = intval($this->config
['config']['simulateStaticDocuments_addTitle']);
2375 $out = t3lib_div
::convUmlauts($inTitle);
2376 $out= ereg_replace('[^[:alnum:]_-]','_',trim(substr($out,0,$titleChars)));
2377 $out= ereg_replace('_*$','',$out);
2378 $out= ereg_replace('^_*','',$out);
2379 if ($out) $out.='.';
2382 if (strcmp($addParams,'') && !$no_cache) {
2383 switch ((string)$this->config
['config']['simulateStaticDocuments_pEnc']) {
2385 $md5=substr(md5($addParams),0,10);
2388 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($md5, 'cache_md5params').'"');
2389 if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
2390 $insertFields = array(
2394 'params' => $addParams
2397 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
2401 $enc='+B6'.str_replace('=','_',str_replace('/','-',base64_encode($addParams)));
2405 // Setting page and type number:
2406 $url = $out.$page.$enc;
2407 $url.= ($type ||
$out ||
!$this->config
['config']['simulateStaticDocuments_noTypeIfNoTitle']) ?
'.'.$type : '';
2412 * Processes a query-string with GET-parameters and returns two strings, one with the parameters that CAN be encoded and one array with those which can't be encoded (encoded by the M5 or B6 methods)
2414 * @param string Query string to analyse
2415 * @return array Two num keys returned, first is the parameters that MAY be encoded, second is the non-encodable parameters.
2416 * @see makeSimulFileName(), t3lib_tstemplate::linkData()
2418 function simulateStaticDocuments_pEnc_onlyP_proc($linkVars) {
2420 if (strcmp($linkVars,'')) {
2421 $p = explode('&',$linkVars);
2422 sort($p); // This sorts the parameters - and may not be needed and further it will generate new MD5 hashes in many cases. Maybe not so smart. Hmm?
2424 foreach($p as $k => $v) {
2426 list($pName) = explode('=',$v,2);
2427 if (!$this->pEncAllowedParamNames
[$pName]) {
2431 } else unset($p[$k]);
2434 $linkVars = count($p) ?
'&'.implode('&',$p) : '';
2435 $remainLinkVars = count($rem) ?
'&'.implode('&',$rem) : '';
2437 return array($linkVars, $remainLinkVars);
2441 * Returns the simulated static file name (*.html) for the current page (using the page record in $this->page)
2443 * @return string The filename (without path)
2444 * @see makeSimulFileName(), publish.php
2446 function getSimulFileName() {
2448 $url.=$this->makeSimulFileName($this->page
['title'], $this->page
['alias']?
$this->page
['alias']:$this->id
, $this->type
).'.html';
2453 * Encryption of email addresses for <A>-tags See the spam protection setup in TS 'config.'
2455 * @param string Input string to en/decode: "mailto:blabla@bla.com"
2456 * @param boolean If set, the process is reversed, effectively decoding, not encoding.
2457 * @return string encoded/decoded version of $string
2459 function encryptEmail($string,$back=0) {
2461 for ($a=0;$a<strlen($string);$a++
) {
2462 $charValue = ord(substr($string,$a,1));
2463 $charValue+
=intval($GLOBALS['TSFE']->spamProtectEmailAddresses
)*($back?
-1:1);
2464 $out.=chr($charValue);
2470 * Checks if a PHPfile may be included.
2472 * @param string Relative path to php file
2473 * @return boolean Returns true if $GLOBALS['TYPO3_CONF_VARS']['FE']['noPHPscriptInclude'] is not set OR if the file requested for inclusion is found in one of the allowed paths.
2474 * @see tslib_cObj::PHP_SCRIPT(), tslib_feTCE::includeScripts(), tslib_menu::includeMakeMenu()
2476 function checkFileInclude($incFile) {
2477 return !$GLOBALS['TYPO3_CONF_VARS']['FE']['noPHPscriptInclude']
2478 ||
substr($incFile,0,14)=='media/scripts/'
2479 ||
substr($incFile,0,4+
strlen(TYPO3_mainDir
))==TYPO3_mainDir
.'ext/'
2480 ||
substr($incFile,0,7+
strlen(TYPO3_mainDir
))==TYPO3_mainDir
.'sysext/'
2481 ||
substr($incFile,0,14)=='typo3conf/ext/';
2485 * Creates an instance of tslib_cObj in $this->cObj
2486 * This instance is used to start the rendering of the TypoScript template structure
2491 function newCObj() {
2492 $this->cObj
=t3lib_div
::makeInstance('tslib_cObj');
2493 $this->cObj
->start($this->page
,'pages');
2497 * Substitute the path's to files in the media/ folder like icons used in static_template of TypoScript
2498 * Works on $this->content
2502 * @see pagegen.php, INTincScript()
2504 function setAbsRefPrefix() {
2505 if ($this->absRefPrefix
) {
2506 $this->content
= str_replace('"media/', '"'.$this->absRefPrefix
.'media/', $this->content
);
2507 $this->content
= str_replace('"fileadmin/', '"'.$this->absRefPrefix
.'fileadmin/', $this->content
);
2512 * Prints error msg/header.
2513 * Echoes out the HTML content
2515 * @param string Message string
2516 * @param string Header string
2518 * @see t3lib_timeTrack::debug_typo3PrintError()
2520 function printError($label,$header='Error!') {
2521 t3lib_timeTrack
::debug_typo3PrintError($header,$label,0);
2525 * Updates the tstamp field of a cache_md5params record to the current time.
2527 * @param string The hash string identifying the cache_md5params record for which to update the "tstamp" field to the current time.
2531 function updateMD5paramsRecord($hash) {
2532 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('cache_md5params', 'md5hash="'.$GLOBALS['TYPO3_DB']->quoteStr($hash, 'cache_md5params').'"', array('tstamp' => time()));
2536 * Pass the content through tidy - a little program that cleans up HTML-code
2537 * Requires $this->TYPO3_CONF_VARS['FE']['tidy'] to be true and $this->TYPO3_CONF_VARS['FE']['tidy_path'] to contain the filename/path of tidy including clean-up arguments for tidy. See default value in TYPO3_CONF_VARS in t3lib/config_default.php
2539 * @param string The page content to clean up. Will be written to a temporary file which "tidy" is then asked to clean up. File content is read back and returned.
2540 * @return string Returns the
2542 function tidyHTML($content) {
2543 if ($this->TYPO3_CONF_VARS
['FE']['tidy'] && $this->TYPO3_CONF_VARS
['FE']['tidy_path']) {
2544 $oldContent = $content;
2545 $fname = t3lib_div
::tempnam('Typo3_Tidydoc_'); // Create temporary name
2546 @unlink
($fname); // Delete if exists, just to be safe.
2547 $fp = fopen ($fname,'wb'); // Open for writing
2548 fputs ($fp, $content); // Put $content
2549 @fclose
($fp); // Close
2551 exec ($this->TYPO3_CONF_VARS
['FE']['tidy_path'].' '.$fname, $output); // run the $content through 'tidy', which formats the HTML to nice code.
2552 @unlink
($fname); // Delete the tempfile again
2553 $content = implode($output,chr(10));
2554 if (!trim($content)) {
2555 $content = $oldContent; // Restore old content due empty return value.
2556 $GLOBALS['TT']->setTSlogMessage('"tidy" returned an empty value!',2);
2558 $GLOBALS['TT']->setTSlogMessage('"tidy" content lenght: '.strlen($content),0);
2564 * Substitutes all occurencies of <a href="#"... in $this->content with <a href="[path-to-url]#"...
2566 * @return void Works directly on $this->content
2568 function prefixLocalAnchorsWithScript() {
2569 $scriptPath = substr(t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
2570 $this->content
= eregi_replace('(<(a|area)[[:space:]]+href=")(#[^"]*")','\1'.htmlspecialchars($scriptPath).'\3',$this->content
);
2600 /********************************************
2602 * Various external API functions - for use in plugins etc.
2604 *******************************************/
2608 * Traverses the ->rootLine and returns an array with the first occurrance of storage pid and siteroot pid
2610 * @return array Array with keys '_STORAGE_PID' and '_SITEROOT' set to the first occurances found.
2612 function getStorageSiterootPids() {
2614 reset($this->rootLine
);
2615 while(list(,$rC)=each($this->rootLine
)) {
2616 if (!$res['_STORAGE_PID']) $res['_STORAGE_PID']=intval($rC['storage_pid']);
2617 if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?
intval($rC['uid']):0;
2623 * Returns the pages TSconfig array based on the currect ->rootLine
2627 function getPagesTSconfig() {
2628 if (!is_array($this->pagesTSconfig
)) {
2629 reset($this->rootLine
);
2630 $TSdataArray = array();
2631 $TSdataArray[]=$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig']; // Setting default configuration:
2632 while(list($k,$v)=each($this->rootLine
)) {
2633 $TSdataArray[]=$v['TSconfig'];
2635 // Parsing the user TS (or getting from cache)
2636 $TSdataArray = t3lib_TSparser
::checkIncludeLines_array($TSdataArray);
2637 $userTS = implode($TSdataArray,chr(10).'[GLOBAL]'.chr(10));
2638 $hash = md5('pageTS:'.$userTS);
2639 $cachedContent = $this->sys_page
->getHash($hash,0);
2640 if (isset($cachedContent)) {
2641 $this->pagesTSconfig
= unserialize($cachedContent);
2643 $parseObj = t3lib_div
::makeInstance('t3lib_TSparser');
2644 $parseObj->parse($userTS);
2645 $this->pagesTSconfig
= $parseObj->setup
;
2646 $this->sys_page
->storeHash($hash,serialize($this->pagesTSconfig
),'PAGES_TSconfig');
2649 return $this->pagesTSconfig
;
2653 * Sets JavaScript code in the additionalJavaScript array
2655 * @param string $key is the key in the array, for num-key let the value be empty. Note reserved keys 'openPic' and 'mouseOver'
2656 * @param string $content is the content if you want any
2658 * @see tslib_gmenu::writeMenu(), tslib_cObj::imageLinkWrap()
2660 function setJS($key,$content='') {
2664 $this->additionalJavaScript
[$key]=
2665 ' // JS function for mouse-over
2666 function over(name,imgObj) { //
2667 if (version == "n3" && document[name]) {document[name].src = eval(name+"_h.src");}
2668 else if (imgObj) {imgObj.src = eval(name+"_h.src");}
2670 // JS function for mouse-out
2671 function out(name,imgObj) { //
2672 if (version == "n3" && document[name]) {document[name].src = eval(name+"_n.src");}
2673 else if (imgObj) {imgObj.src = eval(name+"_n.src");}
2677 $this->additionalJavaScript
[$key]=
2678 ' function openPic(url,winName,winParams) { //
2679 var theWindow = window.open(url,winName,winParams);
2680 if (theWindow) {theWindow.focus();}
2684 $this->additionalJavaScript
[$key]=$content;
2691 * Sets CSS data in the additionalCSS array
2693 * @param string $key is the key in the array, for num-key let the value be empty
2694 * @param string $content is the content if you want any
2696 * @see setJS(), tslib_pibase::pi_setClassStyle()
2698 function setCSS($key,$content) {
2702 $this->additionalCSS
[$key]=$content;
2709 * Seeds the random number engine.
2713 function make_seed() {
2714 list($usec, $sec) = explode(' ', microtime());
2715 $seedV = (float)$sec +
((float)$usec * 100000);
2720 * Returns a unique md5 hash.
2721 * There is no special magic in this, the only point is that you don't have to call md5(uniqid()) which is slow and by this you are sure to get a unique string each time in a little faster way.
2723 * @param string Some string to include in what is hashed. Not significant at all.
2724 * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
2726 function uniqueHash($str='') {
2727 return md5($this->uniqueString
.'_'.$str.$this->uniqueCounter++
);
2731 * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
2735 function set_no_cache() {
2736 $this->no_cache
= 1;
2740 * Sets the cache-timeout in seconds
2742 * @param integer cache-timeout in seconds
2745 function set_cache_timeout_default($seconds) {
2746 $this->cacheTimeOutDefault
= intval($seconds);
2750 * Substitute function for the PHP mail() function.
2751 * It will encode the email with the setting of TS 'config.notification_email_encoding' (base64 or none)
2752 * It will also find all links to http:// in the text and substitute with a shorter link using the redirect feature which stores the long link in the database. Depends on configuration in TS 'config.notification_email_urlmode'
2754 * @param string recipient email address (or list of)
2755 * @param string The subject
2756 * @param string The message
2757 * @param string The headers (string with lines)
2759 * @see t3lib_div::plainMailEncoded()
2761 function plainMailEncoded($email,$subject,$message,$headers='') {
2762 $urlmode=$this->config
['config']['notification_email_urlmode']; // '76', 'all', ''
2765 $message=t3lib_div
::substUrlsInPlainText($message,$urlmode);
2768 t3lib_div
::plainMailEncoded(
2773 $this->config
['config']['notification_email_encoding'],
2774 $this->config
['config']['notification_email_charset']?
$this->config
['config']['notification_email_charset']:'ISO-8859-1'
2779 * Split Label function for front-end applications.
2781 * @param string Key string. Accepts the "LLL:" prefix.
2782 * @return string Label value, if any.
2784 function sL($input) {
2785 if (!$this->lang
) $this->initLLvars();
2787 if (strcmp(substr($input,0,4),'LLL:')) {
2788 $t = explode('|',$input);
2789 return $t[$this->langSplitIndex
] ?
$t[$this->langSplitIndex
] : $t[0];
2791 if (!isset($this->LL_labels_cache
[$this->lang
][$input])) { // If cached label
2792 $restStr = trim(substr($input,4));
2794 if (!strcmp(substr($restStr,0,4),'EXT:')) {
2795 $restStr = trim(substr($restStr,4));
2798 $parts = explode(':',$restStr);
2799 $parts[0]=$extPrfx.$parts[0];
2800 if (!isset($this->LL_files_cache
[$parts[0]])) { // Getting data if not cached
2801 $this->LL_files_cache
[$parts[0]] = $this->readLLfile($parts[0]);
2803 $this->LL_labels_cache
[$this->lang
][$input] = $this->csConv($this->getLLL($parts[1],$this->LL_files_cache
[$parts[0]]));
2805 return $this->LL_labels_cache
[$this->lang
][$input];
2810 * Converts the charset of the input string if applicable.
2811 * The "from" charset is determined by the TYPO3 system charset for the current language key ($this->lang)
2812 * The "to" charset is determined by the currently used charset for the page which is "iso-8859-1" by default or set by $GLOBALS['TSFE']->config['config']['metaCharset']
2813 * Only if there is a difference between the two charsets will a conversion be made
2814 * The conversion is done real-time - no caching for performance at this point!
2816 * @param string String to convert charset for
2817 * @param string Optional "from" charset.
2818 * @return string Output string, converted if needed.
2819 * @see initLLvars(), t3lib_cs
2821 function csConv($str,$from='') {
2822 if (!$this->lang
) $this->initLLvars();
2825 $output = $this->csConvObj
->conv($str,$this->csConvObj
->parse_charset($from),$this->siteCharset
,1);
2826 return $output ?
$output : $str;
2827 } elseif (is_array($this->convCharsetToFrom
)) {
2828 return $this->csConvObj
->conv($str,$this->convCharsetToFrom
['from'],$this->convCharsetToFrom
['to'],1);
2835 * Read locallang files - for frontend applications
2837 * @param string Reference to a relative filename to include.
2838 * @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
2840 function readLLfile($fileRef) {
2841 $file = t3lib_div
::getFileAbsFileName($fileRef);
2842 if (@is_file
($file)) {
2845 return is_array($LOCAL_LANG)?
$LOCAL_LANG:array();
2849 * Returns 'locallang' label - may need initializing by initLLvars
2851 * @param string Local_lang key for which to return label (language is determined by $this->lang)
2852 * @param array The locallang array in which to search
2853 * @return string Label value of $index key.
2855 function getLLL($index,$LOCAL_LANG) {
2856 if (strcmp($LOCAL_LANG[$this->lang
][$index],'')) {
2857 return $LOCAL_LANG[$this->lang
][$index];
2859 return $LOCAL_LANG['default'][$index];
2864 * Initializing the getLL variables needed.
2865 * Sets $this->langSplitIndex based on $this->config['config']['language']
2869 function initLLvars() {
2870 $this->lang
= $this->config
['config']['language'] ?
$this->config
['config']['language'] : 'default';
2872 $ls = explode('|',TYPO3_languages
);
2873 while(list($i,$v)=each($ls)) {
2874 if ($v==$this->lang
) {$this->langSplitIndex
=$i; break;}
2877 // Setting charsets:
2878 $this->siteCharset
= $this->csConvObj
->parse_charset($GLOBALS['TSFE']->config
['config']['metaCharset'] ?
$GLOBALS['TSFE']->config
['config']['metaCharset'] : $GLOBALS['TSFE']->defaultCharSet
);
2879 $this->labelsCharset
= $this->csConvObj
->parse_charset($this->csConvObj
->charSetArray
[$this->lang
] ?
$this->csConvObj
->charSetArray
[$this->lang
] : 'iso-8859-1');
2880 if ($this->siteCharset
!= $this->labelsCharset
) {
2881 $this->convCharsetToFrom
=array(
2882 'from' => $this->labelsCharset
,
2883 'to' => $this->siteCharset
2891 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['tslib/class.tslib_fe.php']) {
2892 include_once($TYPO3_CONF_VARS[TYPO3_MODE
]['XCLASS']['tslib/class.tslib_fe.php']);