"TYPO3 4.0.1: typo3_src-4.0.1/typo3/sysext/cms/tslib/class.tslib_fe.php Source File", "datetime" => "Sat Dec 2 19:22:28 2006", "date" => "2 Dec 2006", "doxygenversion" => "1.4.6", "projectname" => "TYPO3 4.0.1", "projectnumber" => "4.0.1" ); get_header($doxygen_vars); ?>

class.tslib_fe.php

00001 <?php
00002 /***************************************************************
00003 *  Copyright notice
00004 *
00005 *  (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@typo3.com)
00006 *  All rights reserved
00007 *
00008 *  This script is part of the TYPO3 project. The TYPO3 project is
00009 *  free software; you can redistribute it and/or modify
00010 *  it under the terms of the GNU General Public License as published by
00011 *  the Free Software Foundation; either version 2 of the License, or
00012 *  (at your option) any later version.
00013 *
00014 *  The GNU General Public License can be found at
00015 *  http://www.gnu.org/copyleft/gpl.html.
00016 *  A copy is found in the textfile GPL.txt and important notices to the license
00017 *  from the author is found in LICENSE.txt distributed with these scripts.
00018 *
00019 *
00020 *  This script is distributed in the hope that it will be useful,
00021 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023 *  GNU General Public License for more details.
00024 *
00025 *  This copyright notice MUST APPEAR in all copies of the script!
00026 ***************************************************************/
00213  class tslib_fe {
00214 
00215                 // CURRENT PAGE:
00216         var $id='';                                                     // The page id (int)
00217         var $type='';                                           // RO The type (int)
00218         var $idParts=array();                           // Loaded with the id, exploded by ','
00219         var $cHash='';                                          // The submitted cHash
00220         var $no_cache='';                                       // Page will not be cached. Write only true. Never clear value (some other code might have reasons to set it true)
00221         var $rootLine='';                                       // The rootLine (all the way to tree root, not only the current site!) (array)
00222         var $page='';                                           // The pagerecord (array)
00223         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.
00224         var $sys_page='';                                       // The object with pagefunctions (object)
00225         var $jumpurl='';
00226         var $pageNotFound=0;                            // Is set to 1 if a pageNotFound handler could have been called.
00227         var $domainStartPage=0;                         // Domain start page
00228         var $pageAccessFailureHistory=array();  // Array containing a history of why a requested page was not accessible.
00229         var $MP='';
00230         var $RDCT='';
00231         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...
00232         var $siteScript='';                                     // Contains the value of the current script path that activated the frontend. Typically "index.php" but by rewrite rules it could be something else! Used for Speaking Urls / Simulate Static Documents.
00233 
00234                 // USER
00235         var $fe_user='';                                        // The user (object)
00236         var $loginUser='';                                      // Global flag indicating that a front-end user is logged in. This is set only if a user really IS logged in. The group-list may show other groups (like added by IP filter or so) even though there is no user.
00237         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...
00238         var $beUserLogin='';                            // Flag that indicates if a Backend user is logged in!
00239         var $workspacePreview='';                       // Integer, that indicates which workspace is being previewed.
00240         var $loginAllowedInBranch = TRUE;       // Shows whether logins are allowed in branch
00241         var $ADMCMD_preview_BEUSER_uid = 0;     // Integer, set to backend user ID to initialize when keyword-based preview is used.
00242 
00243                 // PREVIEW
00244         var $fePreview='';                                      // Flag indication that preview is active. This is based on the login of a backend user and whether the backend user has read access to the current page. A value of 1 means ordinary preview, 2 means preview of a non-live workspace
00245         var $showHiddenPage='';                         // Flag indicating that hidden pages should be shown, selected and so on. This goes for almost all selection of pages!
00246         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.
00247         var $simUserGroup='0';                          // Value that contains the simulated usergroup if any
00248 
00249                 // CONFIGURATION
00250         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.
00251         var $config='';                                         // 'CONFIG' object from TypoScript. Array generated based on the TypoScript configuration of the current page. Saved with the cached pages.
00252         var $TCAcachedExtras=array();           // Array of cached information from TCA. This is NOT TCA itself!
00253 
00254                 // TEMPLATE / CACHE
00255         var $tmpl='';                                           // The TypoScript template object. Used to parse the TypoScript template
00256         var $cacheTimeOutDefault='';            // Is set to the time-to-live time of cached pages. If false, default is 60*60*24, which is 24 hours.
00257         var $cacheContentFlag='';                       // Set internally if cached content is fetched from the database
00258         var $cacheExpires=0;                            // Set to the expire time of cached content
00259         var $isClientCachable=FALSE;            // Set if cache headers allowing caching are sent.
00260         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.
00261         var $sPre='';                                           // toplevel - objArrayName, eg 'page'
00262         var $pSetup='';                                         // TypoScript configuration of the page-object pointed to by sPre. $this->tmpl->setup[$this->sPre.'.']
00263         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
00264         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
00265         var $no_CacheBeforePageGen='';          // This flag is set before inclusion of pagegen.php IF no_cache is set. If this flag is set after the inclusion of pagegen.php, no_cache is forced to be set. This is done in order to make sure that php-code from pagegen does not falsely clear the no_cache flag.
00266         var $tempContent = FALSE;                       // This flag indicates if temporary content went into the cache during page-generation.
00267         var $forceTemplateParsing='';                           // Boolean, passed to TypoScript template class and tells it to render the template forcibly
00268         var $cHash_array=array();                       // The array which cHash_calc is based on, see ->makeCacheHash().
00269         var $hash_base='';                                      // Loaded with the serialized array that is used for generating a hashstring for the cache
00270         var $pagesTSconfig='';                          // May be set to the pagesTSconfig
00271                 // PAGE-GENERATION / cOBJ
00272         /*
00273                 Eg. insert JS-functions in this array ($additionalHeaderData) to include them once. Use associative keys.
00274                 Keys in use:
00275                         JSFormValidate  :               <script type="text/javascript" src="'.$GLOBALS["TSFE"]->absRefPrefix.'t3lib/jsfunc.validateform.js"></script>
00276                         JSincludeFormupdate :   <script type="text/javascript" src="t3lib/jsfunc.updateform.js"></script>
00277                         JSMenuCode, JSMenuCode_menu :                   JavaScript for the JavaScript menu
00278                         JSCode : reserved
00279                         JSImgCode : reserved
00280         */
00281         var $defaultBodyTag='<body>';           // Default bodytag, if nothing else is set. This can be overridden by applications like TemplaVoila.
00282         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[] = '...')
00283         var $additionalJavaScript=array();      // used to accumulate additional JavaScript-code. Works like additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
00284         var $additionalCSS=array();                     // used to accumulate additional Style code. Works like additionalHeaderData.
00285         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
00286                 'onmousemove' => array(),
00287                 'onmouseup' => array(),
00288                 'onload' => array(),
00289         );
00290         var $JSCode='';                                         // Deprecated, use additionalJavaScript instead.
00291         var $JSImgCode='';                                      // Used to accumulate JavaScript loaded images (by menus)
00292         var $divSection='';                                     // Used to accumulate DHTML-layers.
00293 
00294                 // RENDERING configuration, settings from TypoScript is loaded into these vars. See pagegen.php
00295         var $debug='';                                          // Debug flag, may output special debug html-code.
00296         var $intTarget='';                                      // Default internal target
00297         var $extTarget='';                                      // Default external target
00298         var $MP_defaults=array();                       // Keys are page ids and values are default &MP (mount point) values to set when using the linking features...)
00299         var $spamProtectEmailAddresses=0;       // If set, typolink() function encrypts email addresses. Is set in pagegen-class.
00300         var $absRefPrefix='';                           // Absolute Reference prefix
00301         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 '/'
00302         var $compensateFieldWidth='';           // Factor for form-field widths compensation
00303         var $lockFilePath='';                           // Lock file path
00304         var $ATagParams='';                                     // <A>-tag parameters
00305         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.
00306         var $sWordList='';                                      // Is set to the incoming array sword_list in case of a page-view jumped to from a search-result.
00307         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.
00308         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.
00309         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.
00310         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.
00311         var $sys_language_uid=0;                        // Site language, 0 (zero) is default, int+ is uid pointing to a sys_language record. Should reflect which language menus, templates etc is displayed in (master language) - but not necessarily the content which could be falling back to default (see sys_language_content)
00312         var $sys_language_mode='';                      // Site language mode for content fall back.
00313         var $sys_language_content=0;            // Site content selection uid (can be different from sys_language_uid if content is to be selected from a fall-back language. Depends on sys_language_mode)
00314         var $sys_language_contentOL=0;          // Site content overlay flag; If set - and sys_language_content is > 0 - , records selected will try to look for a translation pointing to their uid. (If configured in [ctrl][languageField] / [ctrl][transOrigP...]
00315         var $sys_language_isocode = '';         // Is set to the iso code of the sys_language_content if that is properly defined by the sys_language record representing the sys_language_uid. (Requires the extension "static_info_tables")
00316 
00317                 // RENDERING data
00318         var $applicationData=Array();           //       'Global' Storage for various applications. Keys should be 'tx_'.extKey for extensions.
00319         var $register=Array();
00320         var $registerStack=Array();                     // Stack used for storing array and retrieving register arrays (see LOAD_REGISTER and CLEAR_REGISTER)
00321         var $cObjectDepthCounter = 50;          // Checking that the function is not called eternally. This is done by interrupting at a depth of 50
00322         var $recordRegister = Array();          // used by cObj->RECORDS and cObj->CONTENT to ensure the a records is NOT rendered twice through it!
00323         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
00324         var $accessKey =array();                        // Used by class tslib_menu to keep track of access-keys.
00325         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.
00326         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
00327         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()
00328         var $uniqueString='';
00329         var $indexedDocTitle='';                        // This value will be used as the title for the page in the indexer (if indexing happens)
00330         var $altPageTitle='';                           // Alternative page title (normally the title of the page record). Can be set from applications you make.
00331         var $pEncAllowedParamNames=array();     // An array that holds parameter names (keys) of GET parameters which MAY be MD5/base64 encoded with simulate_static_documents method.
00332         var $baseUrl='';                                        // The Base url set for the page header.
00333         var $anchorPrefix='';                           // The proper anchor prefix needed when using speaking urls. (only set if baseUrl is set)
00334 
00335                 // Page content render object
00336         var $cObj ='';                                          // is instantiated object of tslib_cObj
00337 
00338                 // CONTENT accumulation
00339         var $content='';                                        // All page content is accumulated in this variable. See pagegen.php
00340 
00341                 // GENERAL
00342         var $clientInfo='';                                     // Set to the browser: net / msie if 4+ browsers
00343         var $scriptParseTime=0;
00344         var $TCAloaded = 0;                                     // Set ONLY if the full TCA is loaded
00345 
00346                 // Character set (charset) conversion object:
00347         var $csConvObj;                                         // An instance of the "t3lib_cs" class. May be used by any application.
00348         var $defaultCharSet = 'iso-8859-1';     // The default charset used in the frontend if nothing else is set.
00349         var $renderCharset='';                          // Internal charset of the frontend during rendering: Defaults to "forceCharset" and if that is not set, to ->defaultCharSet
00350         var $metaCharset='';                            // Output charset of the websites content. This is the charset found in the header, meta tag etc. If different from $renderCharset a conversion happens before output to browser. Defaults to ->renderCharset if not set.
00351         var $localeCharset='';                          // Assumed charset of locale strings.
00352 
00353                 // LANG:
00354         var $lang='';                                           // Set to the system language key (used on the site)
00355         var $langSplitIndex=0;                          // Set to the index number of the language key
00356         var $labelsCharset='';                          // Charset of the labels from locallang (based on $this->lang)
00357         var $convCharsetToFrom='';                      // Set to the charsets to convert from/to IF there are any difference. Otherwise this stays a string
00358         var $LL_labels_cache=array();
00359         var $LL_files_cache=array();
00360 
00361 
00362 
00363 
00364 
00382         function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='')   {
00383 
00384                         // Setting some variables:
00385                 $this->TYPO3_CONF_VARS = $TYPO3_CONF_VARS;
00386                 $this->id = $id;
00387                 $this->type = $type;
00388                 $this->no_cache = $no_cache ? 1 : 0;
00389                 $this->cHash = $cHash;
00390                 $this->jumpurl = $jumpurl;
00391                 $this->MP = $this->TYPO3_CONF_VARS['FE']['enable_mount_pids'] ? (string)$MP : '';
00392                 $this->RDCT = $RDCT;
00393                 $this->clientInfo = t3lib_div::clientInfo();
00394                 $this->uniqueString=md5(microtime());
00395 
00396                 $this->csConvObj = t3lib_div::makeInstance('t3lib_cs');
00397 
00398                         // Call post processing function for constructor:
00399                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc']))    {
00400                         $_params = array('pObj' => &$this);
00401                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef)     {
00402                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
00403                         }
00404                 }
00405         }
00406 
00415         function connectToMySQL()       {
00416                 $this->connectToDB();
00417         }
00418 
00425         function connectToDB()  {
00426                 if ($GLOBALS['TYPO3_DB']->sql_pconnect(TYPO3_db_host, TYPO3_db_username, TYPO3_db_password))    {
00427                         if (!TYPO3_db)  {
00428                                 $this->printError('No database selected','Database Error');
00429                                         // Redirects to the Install Tool:
00430                                 echo '<script type="text/javascript">
00431                                                 /*<![CDATA[*/
00432                                         window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
00433                                                 /*]]>*/
00434                                         </script>';
00435                                 exit;
00436                         } elseif (!$GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db))       {
00437                                 $this->printError('Cannot connect to the current database, "'.TYPO3_db.'"','Database Error');
00438                                 exit;
00439                         }
00440                 } else {
00441                         if (!TYPO3_db)  {
00442                                         // Redirects to the Install Tool:
00443                                 echo '<script type="text/javascript">
00444                                                 /*<![CDATA[*/
00445                                         window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
00446                                                 /*]]>*/
00447                                         </script>';
00448                                 exit;
00449                         }
00450                         $this->printError('The current username, password or host was not accepted when the connection to the database was attempted to be established!','Database Error');
00451                         exit;
00452                 }
00453 
00454 
00455                         // Call post processing function for DB connection:
00456                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB']))  {
00457                         $_params = array('pObj' => &$this);
00458                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef)   {
00459                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
00460                         }
00461                 }
00462         }
00463 
00470         function sendRedirect() {
00471                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->RDCT, 'cache_md5params'));
00472                 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
00473                         $this->updateMD5paramsRecord($this->RDCT);
00474                         header('Location: '.$row['params']);
00475                         exit;
00476                 }
00477         }
00478 
00479 
00480 
00481 
00482 
00483 
00484 
00485 
00486 
00487 
00488 
00489 
00490 
00491 
00492 
00493 
00494 
00495 
00496         /********************************************
00497          *
00498          * Initializing, resolving page id
00499          *
00500          ********************************************/
00501 
00502 
00508         function initFEuser()   {
00509                 $this->fe_user = t3lib_div::makeInstance('tslib_feUserAuth');
00510 
00511                 $this->fe_user->lockIP = $this->TYPO3_CONF_VARS['FE']['lockIP'];
00512                 $this->fe_user->lockHashKeyWords = $this->TYPO3_CONF_VARS['FE']['lockHashKeyWords'];
00513                 $this->fe_user->checkPid = $this->TYPO3_CONF_VARS['FE']['checkFeUserPid'];
00514                 $this->fe_user->lifetime = intval($this->TYPO3_CONF_VARS['FE']['lifetime']);
00515                 $this->fe_user->checkPid_value = $GLOBALS['TYPO3_DB']->cleanIntList(t3lib_div::_GP('pid'));     // List of pid's acceptable
00516 
00517                         // Check if a session is transferred:
00518                 if (t3lib_div::_GP('FE_SESSION_KEY'))   {
00519                         $fe_sParts = explode('-',t3lib_div::_GP('FE_SESSION_KEY'));
00520                         if (!strcmp(md5($fe_sParts[0].'/'.$this->TYPO3_CONF_VARS['SYS']['encryptionKey']), $fe_sParts[1]))      {       // If the session key hash check is OK:
00521                                 $_COOKIE[$this->fe_user->name] = $fe_sParts[0];
00522                                 $this->fe_user->forceSetCookie = 1;
00523                         }
00524                 }
00525 
00526                 if ($this->TYPO3_CONF_VARS['FE']['dontSetCookie'])      {
00527                         $this->fe_user->dontSetCookie=1;
00528                 }
00529 
00530                 $this->fe_user->start();
00531                 $this->fe_user->unpack_uc('');
00532                 $this->fe_user->fetchSessionData();     // Gets session data
00533                 $recs = t3lib_div::_GP('recs');
00534                 if (is_array($recs))    {       // If any record registration is submitted, register the record.
00535                         $this->fe_user->record_registration($recs, $this->TYPO3_CONF_VARS['FE']['maxSessionDataSize']);
00536                 }
00537 
00538                         // Call hook for possible manipulation of frontend user object
00539                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser']))   {
00540                         $_params = array('pObj' => &$this);
00541                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef)    {
00542                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
00543                         }
00544                 }
00545 
00546                         // For every 60 seconds the is_online timestamp is updated.
00547                 if (is_array($this->fe_user->user) && $this->fe_user->user['uid'] && $this->fe_user->user['is_online']<($GLOBALS['EXEC_TIME']-60))      {
00548                         $GLOBALS['TYPO3_DB']->exec_UPDATEquery('fe_users', 'uid='.intval($this->fe_user->user['uid']), array('is_online' => $GLOBALS['EXEC_TIME']));
00549                 }
00550         }
00551 
00558         function initUserGroups() {
00559 
00560                 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;           // This affects the hidden-flag selecting the fe_groups for the user!
00561                 $this->fe_user->fetchGroupData();       // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
00562 
00563                 if (is_array($this->fe_user->user) && count($this->fe_user->groupData['uid']))  {
00564                         $this->loginUser=1;     // global flag!
00565                         $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!
00566                         $gr_array = $this->fe_user->groupData['uid'];
00567                 } else {
00568                         $this->loginUser=0;
00569                         $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!
00570 
00571                         if ($this->loginAllowedInBranch)        {
00572                                 $gr_array = $this->fe_user->groupData['uid'];   // For cases where logins are not banned from a branch usergroups can be set based on IP masks so we should add the usergroups uids.
00573                         } else {
00574                                 $gr_array = array();            // Set to blank since we will NOT risk any groups being set when no logins are allowed!
00575                         }
00576                 }
00577 
00578                         // Clean up.
00579                 $gr_array = array_unique($gr_array);    // Make unique...
00580                 sort($gr_array);        // sort
00581                 if (count($gr_array))   {
00582                         $this->gr_list.=','.implode(',',$gr_array);
00583                 }
00584 
00585                 if ($this->fe_user->writeDevLog)        t3lib_div::devLog('Valid usergroups for TSFE: '.$this->gr_list, 'tslib_fe');
00586         }
00587 
00593         function isUserOrGroupSet()     {
00594                 return is_array($this->fe_user->user) || $this->gr_list!=='0,-1';
00595         }
00596 
00618         function checkAlternativeIdMethods()    {
00619 
00620                 $this->siteScript = t3lib_div::getIndpEnv('TYPO3_SITE_SCRIPT');
00621 
00622                         // Resolving of "simulateStaticDocuments" URLs:
00623                 if ($this->siteScript && substr($this->siteScript,0,9)!='index.php')    {               // If there has been a redirect (basically; we arrived here otherwise than via "index.php" in the URL) this can happend either due to a CGI-script or because of reWrite rule. Earlier we used $_SERVER['REDIRECT_URL'] to check but
00624                         $uParts = parse_url($this->siteScript); // Parse the path:
00625                         $fI = t3lib_div::split_fileref($uParts['path']);
00626 
00627                         if (!$fI['path'] && $fI['file'] && substr($fI['file'],-5)=='.html')     {
00628                                 $parts = explode('.',$fI['file']);
00629                                 $pCount = count($parts);
00630                                 if ($pCount>2)  {
00631                                         $this->type = intval($parts[$pCount-2]);
00632                                         $this->id = $parts[$pCount-3];
00633                                 } else {
00634                                         $this->type = 0;
00635                                         $this->id = $parts[0];
00636                                 }
00637                         }
00638                 }
00639 
00640                         // If PATH_INFO
00641                 if (t3lib_div::getIndpEnv('PATH_INFO')) {               // If pathinfo contains stuff...
00642                         $parts=t3lib_div::trimExplode('/',t3lib_div::getIndpEnv('PATH_INFO'),1);
00643                         $parts[]='html';
00644                         $pCount = count($parts);
00645                         if ($pCount>2)  {
00646                                 $this->type = intval($parts[$pCount-2]);
00647                                 $this->id = $parts[$pCount-3];
00648                         } else {
00649                                 $this->type = 0;
00650                                 $this->id = $parts[0];
00651                         }
00652                         $this->absRefPrefix_force=1;
00653                 }
00654 
00655                         // Call post processing function for custom URL methods.
00656                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc']))   {
00657                         $_params = array('pObj' => &$this);
00658                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef)    {
00659                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
00660                         }
00661                 }
00662         }
00663 
00670         function clear_preview()        {
00671                 $this->showHiddenPage = 0;
00672                 $this->showHiddenRecords = 0;
00673                 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
00674                 $this->fePreview = 0;
00675         }
00676 
00683         function determineId()  {
00684 
00685                         // Getting ARG-v values if some
00686                 $this->setIDfromArgV();
00687 
00688                         // If there is a Backend login we are going to check for any preview settings:
00689                 $GLOBALS['TT']->push('beUserLogin','');
00690                 if ($this->beUserLogin || $this->doWorkspacePreview())  {
00691 
00692                                 // Backend user preview features:
00693                         if ($this->beUserLogin) {
00694                                 $this->fePreview = $GLOBALS['BE_USER']->extGetFeAdminValue('preview') ? 1 : 0;
00695 
00696                                         // If admin panel preview is enabled...
00697                                 if ($this->fePreview)   {
00698                                         $fe_user_OLD_USERGROUP = $this->fe_user->user['usergroup'];
00699 
00700                                         $this->showHiddenPage = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','showHiddenPages');
00701                                         $this->showHiddenRecords = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','showHiddenRecords');
00702                                                 // simulate date
00703                                         $simTime = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','simulateDate');
00704                                         if ($simTime)   $GLOBALS['SIM_EXEC_TIME']=$simTime;
00705                                                 // simulate user
00706                                         $simUserGroup = $GLOBALS['BE_USER']->extGetFeAdminValue('preview','simulateUserGroup');
00707                                         $this->simUserGroup = $simUserGroup;
00708                                         if ($simUserGroup)      $this->fe_user->user['usergroup']=$simUserGroup;
00709                                         if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
00710                                                 $this->fePreview=0;
00711                                         }
00712                                 }
00713                         }
00714 
00715                         if ($this->id)  {
00716 
00717                                         // Now it's investigated if the raw page-id points to a hidden page and if so, the flag is set.
00718                                         // This does not require the preview flag to be set in the admin panel
00719                                 $idQ = t3lib_div::testInt($this->id) ? 'uid='.intval($this->id) : 'alias='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, 'pages').' AND pid>=0';        // pid>=0 added for the sake of versioning...
00720                                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('hidden', 'pages', $idQ.' AND hidden!=0 AND deleted=0');
00721                                 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {
00722                                         $this->fePreview = 1;   // The preview flag is set only if the current page turns out to actually be hidden!
00723                                         $this->showHiddenPage = 1;
00724                                 }
00725 
00726                                         // For Live workspace: Check root line for proper connection to tree root (done because of possible preview of page / branch versions)
00727                                 if (!$this->fePreview && $this->whichWorkspace()===0)   {
00728 
00729                                                 // Initialize the page-select functions to check rootline:
00730                                         $temp_sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
00731                                         $temp_sys_page->init($this->showHiddenPage);
00732 
00733                                                 // If root line contained NO records and ->error_getRootLine_failPid tells us that it was because of a pid=-1 (indicating a "version" record)...:
00734                                         if (!count($temp_sys_page->getRootLine($this->id,$this->MP)) && $temp_sys_page->error_getRootLine_failPid==-1)  {
00735 
00736                                                         // Setting versioningPreview flag and try again:
00737                                                 $temp_sys_page->versioningPreview = TRUE;
00738                                                 if (count($temp_sys_page->getRootLine($this->id,$this->MP)))    {
00739                                                                 // Finally, we got a root line (meaning that it WAS due to versioning preview of a page somewhere) and we set the fePreview flag which in itself will allow sys_page class to display previews of versionized records.
00740                                                         $this->fePreview = 1;
00741                                                 }
00742                                         }
00743                                 }
00744                         }
00745 
00746                                 // The preview flag will be set if a backend user is in an offline workspace
00747                         if (($GLOBALS['BE_USER']->user['workspace_preview'] || t3lib_div::_GP('ADMCMD_view') || $this->doWorkspacePreview()) && ($this->whichWorkspace()===-1 || $this->whichWorkspace()>0))    {
00748                                 $this->fePreview = 2;   // Will show special preview message.
00749                         }
00750 
00751                                 // If the front-end is showing a preview, caching MUST be disabled.
00752                         if ($this->fePreview)   {
00753                                 $this->set_no_cache();
00754                         }
00755                 }
00756                 $GLOBALS['TT']->pull();
00757 
00758                         // Now, get the id, validate access etc:
00759                 $this->fetch_the_id();
00760 
00761                         // Check if backend user has read access to this page. If not, recalculate the id.
00762                 if ($this->beUserLogin && $this->fePreview)     {
00763                         if (!$GLOBALS['BE_USER']->doesUserHaveAccess($this->page,1))    {
00764 
00765                                         // Resetting
00766                                 $this->clear_preview();
00767                                 $this->fe_user->user['usergroup'] = $fe_user_OLD_USERGROUP;
00768 
00769                                         // Fetching the id again, now with the preview settings reset.
00770                                 $this->fetch_the_id();
00771                         }
00772                 }
00773 
00774                         // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
00775                 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
00776                 if (!$this->loginAllowedInBranch)       {       // Logins are not allowed:
00777                         if ($this->isUserOrGroupSet())  {       // Only if there is a login will we run this...
00778 
00779                                         // Clear out user and group:
00780                                 unset($this->fe_user->user);
00781                                 $this->gr_list = '0,-1';
00782 
00783                                         // Fetching the id again, now with the preview settings reset.
00784                                 $this->fetch_the_id();
00785                         }
00786                 }
00787 
00788                         // Final cleaning.
00789                 $this->id = $this->contentPid = intval($this->id);      // Make sure it's an integer
00790                 $this->type = intval($this->type);      // Make sure it's an integer
00791 
00792                         // Look for alternative content PID if page is under version preview:
00793                 if ($this->fePreview)   {
00794                         if ($this->page['_ORIG_pid']==-1 && $this->page['t3ver_swapmode']==0)   {       // Current page must have been an offline version and have swapmode set to 0:
00795                                         // Setting contentPid here for preview might not be completely correct to do. Strictly the "_ORIG_uid" value should be used for tables where "versioning_followPages" is set and for others not. However this is a working quick-fix to display content elements at least!
00796                                 $this->contentPid = $this->page['_ORIG_uid'];
00797                         }
00798                 }
00799 
00800                         // Call post processing function for id determination:
00801                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
00802                         $_params = array('pObj' => &$this);
00803                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef)  {
00804                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
00805                         }
00806                 }
00807         }
00808 
00817         function fetch_the_id() {
00818                 $GLOBALS['TT']->push('fetch_the_id initialize/','');
00819 
00820                         // Initialize the page-select functions.
00821                 $this->sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
00822                 $this->sys_page->versioningPreview = $this->fePreview ? TRUE : FALSE;
00823                 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
00824                 $this->sys_page->init($this->showHiddenPage);
00825 
00826                         // Set the valid usergroups for FE
00827                 $this->initUserGroups();
00828 
00829                         // Sets sys_page where-clause
00830                 $this->setSysPageWhereClause();
00831 
00832                         // Splitting $this->id by a period (.). First part is 'id' and second part - if exists - will overrule the &type param if given
00833                 $pParts = explode('.',$this->id);
00834                 $this->id = $pParts[0]; // Set it.
00835                 if (isset($pParts[1]))  {$this->type=$pParts[1];}
00836 
00837                         // Splitting $this->id by a comma (,). First part is 'id' and other parts are just stored for use in scripts.
00838                 $this->idParts = explode(',',$this->id);
00839 
00840                         // Splitting by a '+' sign - used for base64/md5 methods of parameter encryption for simulate static documents.
00841                 list($pgID,$SSD_p)=explode('+',$this->idParts[0],2);
00842                 if ($SSD_p)     {       $this->idPartsAnalyze($SSD_p);  }
00843                 $this->id = $pgID;      // Set id
00844 
00845                         // If $this->id is a string, it's an alias
00846                 $this->checkAndSetAlias();
00847 
00848                         // The id and type is set to the integer-value - just to be sure...
00849                 $this->id = intval($this->id);
00850                 $this->type = intval($this->type);
00851                 $GLOBALS['TT']->pull();
00852 
00853                         // We find the first page belonging to the current domain
00854                 $GLOBALS['TT']->push('fetch_the_id domain/','');
00855                 $this->domainStartPage = $this->findDomainRecord($this->TYPO3_CONF_VARS['SYS']['recursiveDomainSearch']);       // the page_id of the current domain
00856                 if (!$this->id) {
00857                         if ($this->domainStartPage)     {
00858                                 $this->id = $this->domainStartPage;     // If the id was not previously set, set it to the id of the domain.
00859                         } else {
00860                                 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);    // Find the first 'visible' page in that domain
00861                                 if ($theFirstPage)      {
00862                                         $this->id = $theFirstPage['uid'];
00863                                 } else {
00864                                         $this->printError('No pages are found on the rootlevel!');
00865                                         exit;
00866                                 }
00867                         }
00868                 }
00869                 $GLOBALS['TT']->pull();
00870 
00871                 $GLOBALS['TT']->push('fetch_the_id rootLine/','');
00872                 $requestedId = $this->id;               // We store the originally requested id
00873                 $this->getPageAndRootlineWithDomain($this->domainStartPage);
00874                 $GLOBALS['TT']->pull();
00875 
00876                 if ($this->pageNotFound && $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'])       {
00877                         $pNotFoundMsg = array(
00878                                 1 => 'ID was not an accessible page',
00879                                 2 => 'Subsection was found and not accessible',
00880                                 3 => 'ID was outside the domain',
00881                                 4 => 'The requested page alias does not exist'
00882                         );
00883                         $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound]);
00884                 }
00885 
00886                         // set no_cache if set
00887                 if ($this->page['no_cache'])    {
00888                         $this->set_no_cache();
00889                 }
00890 
00891                         // Init SYS_LASTCHANGED
00892                 $this->register['SYS_LASTCHANGED'] = intval($this->page['tstamp']);
00893                 if ($this->register['SYS_LASTCHANGED'] < intval($this->page['SYS_LASTCHANGED']))        {
00894                         $this->register['SYS_LASTCHANGED'] = intval($this->page['SYS_LASTCHANGED']);
00895                 }
00896         }
00897 
00911         function getPageAndRootline() {
00912                 $this->page = $this->sys_page->getPage($this->id);
00913                 if (!count($this->page))        {
00914                                 // If no page, we try to find the page before in the rootLine.
00915                         $this->pageNotFound=1;                  // Page is 'not found' in case the id itself was not an accessible page. code 1
00916                         $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
00917                         if (count($this->rootLine))     {
00918                                 $c=count($this->rootLine)-1;
00919                                 while($c>0)     {
00920 
00921                                                 // Add to page access failure history:
00922                                         $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
00923 
00924                                                 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
00925                                         $c--;
00926                                         $this->id = $this->rootLine[$c]['uid'];
00927                                         $this->page = $this->sys_page->getPage($this->id);
00928                                         if (count($this->page)){ break; }
00929                                 }
00930                         }
00931                                 // If still no page...
00932                         if (!count($this->page))        {
00933                                 if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'])      {
00934                                         $this->pageNotFoundAndExit('The requested page does not exist!');
00935                                 } else {
00936                                         $this->printError('The requested page does not exist!');
00937                                         exit;
00938                                 }
00939                         }
00940                 }
00941 
00942                 // spacer is not accessible in frontend
00943                 if ($this->page['doktype'] == 199)      {
00944                         if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'])      {
00945                                 $this->pageNotFoundAndExit('The requested page does not exist!');
00946                         } else {
00947                                 $this->printError('The requested page does not exist!');
00948                                 exit;
00949                         }
00950                 }
00951 
00952                         // Is the ID a link to another page??
00953                 if ($this->page['doktype']==4)  {
00954                         $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.
00955                         $this->page = $this->getPageShortcut($this->page['shortcut'],$this->page['shortcut_mode'],$this->page['uid']);
00956                         $this->id = $this->page['uid'];
00957                 }
00958 
00959                         // Gets the rootLine
00960                 $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
00961 
00962                         // If not rootline we're off...
00963                 if (!count($this->rootLine))    {
00964                         $this->printError('The requested page didn\'t have a proper connection to the tree-root! <br /><br />('.$this->sys_page->error_getRootLine.')');
00965                         exit;
00966                 }
00967 
00968                         // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
00969                 if ($this->checkRootlineForIncludeSection())    {
00970                         if (!count($this->rootLine))    {
00971                                 $this->printError('The requested page was not accessible!');
00972                                 exit;
00973                         } else {
00974                                 $el = reset($this->rootLine);
00975                                 $this->id = $el['uid'];
00976                                 $this->page = $this->sys_page->getPage($this->id);
00977                                 $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
00978                         }
00979                 }
00980         }
00981 
00994         function getPageShortcut($SC,$mode,$thisUid,$itera=20,$pageLog=array()) {
00995                 $idArray = t3lib_div::intExplode(',',$SC);
00996 
00997                         // Find $page record depending on shortcut mode:
00998                 switch($mode)   {
00999                         case 1:
01000                         case 2:
01001                                 $pageArray = $this->sys_page->getMenu($idArray[0]?$idArray[0]:$thisUid,'*','sorting','AND pages.doktype<199 AND pages.doktype!=6');
01002                                 $pO = 0;
01003                                 if ($mode==2 && count($pageArray))      {       // random
01004                                         $this->make_seed();
01005                                         $randval = intval(rand(0,count($pageArray)-1));
01006                                         $pO = $randval;
01007                                 }
01008                                 $c = 0;
01009                                 reset($pageArray);
01010                                 while(list(,$pV)=each($pageArray))      {
01011                                         if ($c==$pO)    {
01012                                                 $page = $pV;
01013                                                 break;
01014                                         }
01015                                         $c++;
01016                                 }
01017                         break;
01018                         default:
01019                                 $page = $this->sys_page->getPage($idArray[0]);
01020                         break;
01021                 }
01022 
01023                         // Check if short cut page was a shortcut itself, if so look up recursively:
01024                 if ($page['doktype']==4)        {
01025                         if (!in_array($page['uid'],$pageLog) && $itera>0)       {
01026                                 $pageLog[] = $page['uid'];
01027                                 $page = $this->getPageShortcut($page['shortcut'],$page['shortcut_mode'],$page['uid'],$itera-1,$pageLog);
01028                         } else {
01029                                 $pageLog[] = $page['uid'];
01030                                 $this->printError('Page shortcuts were looping in uids '.implode(',',$pageLog).'...!');
01031                                 exit;
01032                         }
01033                 }
01034                         // Return resulting page:
01035                 return $page;
01036         }
01037 
01044         function checkRootlineForIncludeSection()       {
01045                 $c=count($this->rootLine);
01046                 $removeTheRestFlag=0;
01047 
01048                 for ($a=0;$a<$c;$a++)   {
01049                         if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a]))      {
01050                                         // Add to page access failure history:
01051                                 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
01052                                 $removeTheRestFlag=1;
01053                         }
01054                         if ($this->rootLine[$a]['doktype']==6)  {
01055                                 if ($this->beUserLogin) {       // If there is a backend user logged in, check if he has read access to the page:
01056                                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($this->id).' AND '.$GLOBALS['BE_USER']->getPagePermsClause(1));     // versionOL()?
01057                                         list($isPage) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
01058                                         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...
01059                                 } else {        // Dont go here, if there is no backend user logged in.
01060                                         $removeTheRestFlag=1;
01061                                 }
01062                         }
01063                         if ($removeTheRestFlag) {
01064                                 $this->pageNotFound=2;                  // Page is 'not found' in case a subsection was found and not accessible, code 2
01065                                 unset($this->rootLine[$a]);
01066                         }
01067                 }
01068                 return $removeTheRestFlag;
01069         }
01070 
01081         function checkEnableFields($row,$bypassGroupCheck=FALSE)        {
01082                 if ((!$row['hidden'] || $this->showHiddenPage)
01083                         && $row['starttime']<=$GLOBALS['SIM_EXEC_TIME']
01084                         && ($row['endtime']==0 || $row['endtime']>$GLOBALS['SIM_EXEC_TIME'])
01085                         && ($bypassGroupCheck || $this->checkPageGroupAccess($row))
01086                 ) { return TRUE; }
01087         }
01088 
01097         function checkPageGroupAccess($row, $groupList=NULL) {
01098                 if(is_null($groupList)) {
01099                         $groupList = $this->gr_list;
01100                 }
01101                 if(!is_array($groupList)) {
01102                         $groupList = explode(',', $groupList);
01103                 }
01104                 $pageGroupList = explode(',', $row['fe_group'] ? $row['fe_group'] : 0);
01105                 return count(array_intersect($groupList, $pageGroupList)) > 0;
01106         }
01107 
01116         function checkPagerecordForIncludeSection($row) {
01117                 return (!$row['extendToSubpages'] || $this->checkEnableFields($row)) ? 1 : 0;
01118         }
01119 
01125         function checkIfLoginAllowedInBranch()  {
01126 
01127                         // Initialize:
01128                 $c = count($this->rootLine);
01129                 $disable = FALSE;
01130 
01131                         // Traverse root line from root and outwards:
01132                 for ($a=0; $a<$c; $a++) {
01133 
01134                                 // If a value is set for login state:
01135                         if ($this->rootLine[$a]['fe_login_mode'] > 0)   {
01136 
01137                                         // Determine state from value:
01138                                 $disable = (int)$this->rootLine[$a]['fe_login_mode'] === 1 ? TRUE : FALSE;
01139                         }
01140                 }
01141 
01142                 return !$disable;
01143         }
01144 
01150         function getPageAccessFailureReasons()  {
01151                 $output = array();
01152 
01153                 $combinedRecords = array_merge(
01154                         is_array($this->pageAccessFailureHistory['direct_access']) ? $this->pageAccessFailureHistory['direct_access'] : array(array('fe_group'=>0)),    // Adding fake first record for direct access if none, otherwise $k==0 below will be indicating a sub-section record to be first direct_access record which is of course false!
01155                         is_array($this->pageAccessFailureHistory['sub_section']) ? $this->pageAccessFailureHistory['sub_section'] : array()
01156                 );
01157 
01158                 if (count($combinedRecords))    {
01159                         foreach($combinedRecords as $k => $pagerec)     {
01160                                 // If $k=0 then it is the very first page the original ID was pointing at and that will get a full check of course
01161                                 // If $k>0 it is parent pages being tested. They are only significant for the access to the first page IF they had the extendToSubpages flag set, hence checked only then!
01162                                 if (!$k || $pagerec['extendToSubpages'])        {
01163                                         if ($pagerec['hidden']) $output['hidden'][$pagerec['uid']] = TRUE;
01164                                         if ($pagerec['starttime'] > $GLOBALS['SIM_EXEC_TIME'])  $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
01165                                         if ($pagerec['endtime']!=0 && $pagerec['endtime'] <= $GLOBALS['SIM_EXEC_TIME']) $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
01166                                         if (!$this->checkPageGroupAccess($pagerec))     $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
01167                                 }
01168                         }
01169                 }
01170 
01171                 return $output;
01172         }
01173 
01182         function setIDfromArgV()        {
01183                 if (!$this->id) {
01184                         list($theAlias) = explode('&',t3lib_div::getIndpEnv('QUERY_STRING'));
01185                         $theAlias = trim($theAlias);
01186                         $this->id = $theAlias ? $theAlias : 0;
01187                 }
01188         }
01189 
01198         function getPageAndRootlineWithDomain($domainStartPage) {
01199                 $this->getPageAndRootline();
01200 
01201                 // 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.
01202                 if ($domainStartPage && is_array($this->rootLine)) {
01203                         reset ($this->rootLine);
01204                         $idFound = 0;
01205                         while(list($key,$val)=each($this->rootLine)) {
01206                                 if ($val['uid']==$domainStartPage)      {
01207                                         $idFound=1;
01208                                         break;
01209                                 }
01210                         }
01211                         if (!$idFound)  {
01212                                 $this->pageNotFound=3;                  // Page is 'not found' in case the id was outside the domain, code 3
01213                                 $this->id = $domainStartPage;
01214                                 $this->getPageAndRootline();            //re-get the page and rootline if the id was not found.
01215                         }
01216                 }
01217         }
01218 
01225         function setSysPageWhereClause()        {
01226                 $this->sys_page->where_hid_del.=' AND pages.doktype<200';
01227                 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
01228         }
01229 
01237         function findDomainRecord($recursive=0) {
01238                 if ($recursive) {
01239                         $host = explode('.',t3lib_div::getIndpEnv('HTTP_HOST'));
01240                         while(count($host))     {
01241                                 $pageUid = $this->sys_page->getDomainStartPage(implode('.',$host),t3lib_div::getIndpEnv('SCRIPT_NAME'),t3lib_div::getIndpEnv('REQUEST_URI'));
01242                                 if ($pageUid)   return $pageUid; else array_shift($host);
01243                         }
01244                         return $pageUid;
01245                 } else {
01246                         return $this->sys_page->getDomainStartPage(t3lib_div::getIndpEnv('HTTP_HOST'),t3lib_div::getIndpEnv('SCRIPT_NAME'),t3lib_div::getIndpEnv('REQUEST_URI'));
01247                 }
01248         }
01249 
01257         function pageNotFoundAndExit($reason='', $header='')    {
01258                 $header = $header ? $header : $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling_statheader'];
01259                 $this->pageNotFoundHandler($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'], $header, $reason);
01260                 exit;
01261         }
01262 
01272         function pageNotFoundHandler($code, $header='', $reason='')     {
01273                         // Issue header in any case:
01274                 if ($header)    {header($header);}
01275 
01276                         // Create response:
01277                 if (gettype($code)=='boolean' || !strcmp($code,1))      {       // Simply boolean; Just shows TYPO3 error page with reason:
01278                         $this->printError('The page did not exist or was inaccessible.'.($reason ? ' Reason: '.htmlspecialchars($reason) : ''));
01279                 } elseif (t3lib_div::isFirstPartOfStr($code,'USER_FUNCTION:')) {
01280                         $funcRef = trim(substr($code,14));
01281                         $params = array(
01282                                 'currentUrl' => t3lib_div::getIndpEnv('REQUEST_URI'),
01283                                 'reasonText' => $reason,
01284                                 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
01285                         );
01286                         echo t3lib_div::callUserFunction($funcRef,$params,$this);
01287                 } elseif (t3lib_div::isFirstPartOfStr($code,'READFILE:')) {
01288                         $readFile = t3lib_div::getFileAbsFileName(trim(substr($code,9)));
01289                         if (@is_file($readFile))        {
01290                                 $fileContent = t3lib_div::getUrl($readFile);
01291                                 $fileContent = str_replace('###CURRENT_URL###', t3lib_div::getIndpEnv('REQUEST_URI'), $fileContent);
01292                                 $fileContent = str_replace('###REASON###', htmlspecialchars($reason), $fileContent);
01293                                 echo $fileContent;
01294                         } else {
01295                                 $this->printError('Configuration Error: 404 page "'.$readFile.'" could not be found.');
01296                         }
01297                 } elseif (strlen($code))        {
01298                                 // Check if URL is relative
01299                         $url_parts = parse_url($code);
01300                         if ($url_parts['host'] == '')   {
01301                                 $url_parts['host'] = t3lib_div::getIndpEnv('HTTP_HOST');
01302                                 $code = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
01303                                 $checkBaseTag = false;
01304                         } else {
01305                                 $checkBaseTag = true;
01306                         }
01307 
01308                                 // Check recursion
01309                         if ($code == t3lib_div::getIndpEnv('TYPO3_REQUEST_URL')) {
01310                                 if ($reason == '') {
01311                                         $reason = 'Page cannot be found.';
01312                                 }
01313                                 $reason.= chr(10) . chr(10) . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
01314                                 $this->printError('Reason: '.nl2br(htmlspecialchars($reason)));
01315                                 exit();
01316                         }
01317 
01318                                 // Prepare headers
01319                         $headers = array(
01320                                 'User-agent: ' . t3lib_div::getIndpEnv('HTTP_USER_AGENT'),
01321                                 'Referer: ' . t3lib_div::getIndpEnv('TYPO3_REQUEST_URL')
01322                         );
01323                         $content = t3lib_div::getURL($code, 0, $headers);
01324                         if (false === $content) {
01325                                         // Last chance -- redirect
01326                                 header('Location: '.t3lib_div::locationHeaderUrl($code));
01327                         } else {
01328                                         // Put <base> if necesary
01329                                 if ($checkBaseTag)      {
01330 
01331                                                 // If content already has <base> tag, we do not need to do anything
01332                                         if (false === stristr($content, '<base '))      {
01333 
01334                                                         // Generate href for base tag
01335                                                 $base = $url_parts['scheme'] . '://';
01336                                                 if ($url_parts['user'] != '')   {
01337                                                         $base.= $url_parts['user'];
01338                                                         if ($url_parts['pass'] != '')   {
01339                                                                 $base.= ':' . $url_parts['pass'];
01340                                                         }
01341                                                         $base.= '@';
01342                                                 }
01343                                                 $base.= $url_parts['host'];
01344 
01345                                                         // Add path portion skipping possible file name
01346                                                 $base.= preg_replace('/(.*\/)[^\/]*/', '\1', $url_parts['path']);
01347 
01348                                                         // Put it into content (generate also <head> if necessary)
01349                                                 $replacement = chr(10) . '<base href="' . htmlentities($base) . '" />' . chr(10);
01350                                                 if (stristr($content, '<head>'))        {
01351                                                         $content = preg_replace('/(<head>)/i', '\1' . $replacement, $content);
01352                                                 } else {
01353                                                         $content = preg_replace('/(<html[^>]*>)/i', '\1<head>' . $replacement . '</head>', $content);
01354                                                 }
01355                                         }
01356                                 }
01357                                 echo $content;  // Output the content
01358                         }
01359                 } else {
01360                         $this->printError($reason ? 'Reason: '.htmlspecialchars($reason) : 'Page cannot be found.');
01361                 }
01362                 exit();
01363         }
01364 
01372         function checkAndSetAlias()     {
01373                 if ($this->id && !t3lib_div::testInt($this->id))        {
01374                         $aid = $this->sys_page->getPageIdFromAlias($this->id);
01375                         if ($aid)       {
01376                                 $this->id = $aid;
01377                         } else {
01378                                 $this->pageNotFound = 4;
01379                         }
01380                 }
01381         }
01382 
01391         function idPartsAnalyze($str)   {
01392                 $GET_VARS = '';
01393                 switch(substr($str,0,2))        {
01394                         case 'B6':
01395                                 $addParams = base64_decode(str_replace('_','=',str_replace('-','/',substr($str,2))));
01396                                 parse_str($addParams,$GET_VARS);
01397                         break;
01398                         case 'M5':
01399                                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr(substr($str,2), 'cache_md5params'));
01400                                 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
01401 
01402                                 $this->updateMD5paramsRecord(substr($str,2));
01403                                 parse_str($row['params'],$GET_VARS);
01404                         break;
01405                 }
01406 
01407                 $this->mergingWithGetVars($GET_VARS);
01408         }
01409 
01416         function mergingWithGetVars($GET_VARS)  {
01417                 if (is_array($GET_VARS))        {
01418                         $realGet = t3lib_div::_GET();           // Getting $_GET var, unescaped.
01419                         if (!is_array($realGet))        $realGet = array();
01420 
01421                                 // Merge new values on top:
01422                         $realGet = t3lib_div::array_merge_recursive_overrule($realGet,$GET_VARS);
01423 
01424                                 // Write values back to $_GET:
01425                         t3lib_div::_GETset($realGet);
01426 
01427                                 // Setting these specifically (like in the init-function):
01428                         if (isset($GET_VARS['type']))           $this->type = intval($GET_VARS['type']);
01429                         if (isset($GET_VARS['cHash']))          $this->cHash = $GET_VARS['cHash'];
01430                         if (isset($GET_VARS['jumpurl']))        $this->jumpurl = $GET_VARS['jumpurl'];
01431                         if (isset($GET_VARS['MP']))                     $this->MP = $this->TYPO3_CONF_VARS['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
01432 
01433                         if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache'])      $this->set_no_cache();
01434                 }
01435         }
01436 
01446         function ADMCMD_preview(){
01447                 $inputCode = t3lib_div::_GP('ADMCMD_prev');
01448 
01449                 if ($inputCode) {
01450 
01451                                 // Look for keyword configuration record:
01452                         list($previewData) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
01453                                 '*',
01454                                 'sys_preview',
01455                                 'keyword='.$GLOBALS['TYPO3_DB']->fullQuoteStr($inputCode, 'sys_preview').
01456                                         ' AND endtime>'.time()
01457                         );
01458 
01459                                 // Get: Backend login status, Frontend login status
01460                                 // - Make sure to remove fe/be cookies (temporarily); BE already done in ADMCMD_preview_postInit()
01461                         if (is_array($previewData))     {
01462                                 if (!count(t3lib_div::_POST())) {
01463                                         if (t3lib_div::getIndpEnv('TYPO3_SITE_URL').'?ADMCMD_prev='.$inputCode === t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'))  {
01464 
01465                                                         // Unserialize configuration:
01466                                                 $previewConfig = unserialize($previewData['config']);
01467 
01468                                                         // Set GET variables:
01469                                                 $GET_VARS = '';
01470                                                 parse_str($previewConfig['getVars'], $GET_VARS);
01471                                                 t3lib_div::_GETset($GET_VARS);
01472 
01473                                                         // Return preview keyword configuration:
01474                                                 return $previewConfig;
01475                                         } else die(htmlspecialchars('Request URL did not match "'.t3lib_div::getIndpEnv('TYPO3_SITE_URL').'?ADMCMD_prev='.$inputCode.'"'));     // This check is to prevent people from setting additional GET vars via realurl or other URL path based ways of passing parameters.
01476                                 } else die('POST requests are incompatible with keyword preview.');
01477                         } else die('ADMCMD command could not be executed! (No keyword configuration found)');
01478                 }
01479         }
01480 
01489         function ADMCMD_preview_postInit($previewConfig){
01490                 if (is_array($previewConfig))   {
01491 
01492                                 // Clear cookies:
01493                         unset($_COOKIE['be_typo_user']);
01494                         $this->ADMCMD_preview_BEUSER_uid = $previewConfig['BEUSER_uid'];
01495 
01496                 } else die('Error in preview configuration.');
01497         }
01498 
01499 
01500 
01501 
01502 
01503 
01504 
01505 
01506 
01507 
01508 
01509         /********************************************
01510          *
01511          * Template and caching related functions.
01512          *
01513          *******************************************/
01514 
01521         function makeCacheHash()        {
01522                 $GET = t3lib_div::_GET();
01523                 if ($this->cHash && is_array($GET))     {
01524                         $this->cHash_array = t3lib_div::cHashParams(t3lib_div::implodeArrayForUrl('',$GET));
01525                         $cHash_calc = t3lib_div::shortMD5(serialize($this->cHash_array));
01526 
01527                         if ($cHash_calc!=$this->cHash)  {
01528                                 if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
01529                                         $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
01530                                 } else {
01531                                         $this->set_no_cache();
01532                                         $GLOBALS['TT']->setTSlogMessage('The incoming cHash "'.$this->cHash.'" and calculated cHash "'.$cHash_calc.'" did not match, so caching was disabled. The fieldlist used was "'.implode(',',array_keys($this->cHash_array)).'"',2);
01533                                 }
01534                         }
01535                 }
01536         }
01537 
01545         function reqCHash()     {
01546                 if (!$this->cHash)      {
01547                         if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
01548                                 if ($this->tempContent) { $this->clearPageCacheContent(); }
01549                                 $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
01550                         } else {
01551                                 $this->set_no_cache();
01552                                 $GLOBALS['TT']->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled ',2);
01553                         }
01554                 }
01555         }
01556 
01567         function cHashParams($addQueryParams) {
01568                 return t3lib_div::cHashParams($addQueryParams);
01569         }
01570 
01576         function initTemplate() {
01577                 $this->tmpl = t3lib_div::makeInstance('t3lib_TStemplate');
01578                 $this->tmpl->init();
01579                 $this->tmpl->tt_track= $this->beUserLogin ? 1 : 0;
01580         }
01581 
01588         function getFromCache() {
01589                 $this->tmpl->getCurrentPageData();
01590                 $cc = Array();
01591                 if (is_array($this->tmpl->currentPageData))     {
01592                                 // 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.
01593                                 // If this hash is not the same in here in this section and after page-generation the page will not be properly cached!
01594 
01595                         $cc['all'] = $this->tmpl->currentPageData['all'];
01596                         $cc['rowSum'] = $this->tmpl->currentPageData['rowSum'];
01597                         $cc['rootLine'] = $this->tmpl->currentPageData['rootLine'];             // This rootline is used with templates only (matching()-function)
01598                         $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.
01599                         ksort($this->all);
01600                 }
01601 
01602                 $this->content='';      // clearing the content-variable, which will hold the pagecontent
01603                 unset($this->config);   // Unsetting the lowlevel config
01604                 $this->cacheContentFlag = 0;
01605 
01606                         // Look for page in cache only if caching is not disabled and if a shift-reload is not sent to the server.
01607                 if ($this->all && !$this->no_cache && !$this->headerNoCache())  {
01608 
01609                         $this->newHash = $this->getHash();
01610 
01611                         $GLOBALS['TT']->push('Cache Row','');
01612                                 if ($row = $this->getFromCache_queryRow())      {
01613 
01614                                         $this->config = (array)unserialize($row['cache_data']);         // Fetches the lowlevel config stored with the cached data
01615                                         $this->content = $row['HTML'];  // Getting the content
01616                                         $this->tempContent = $row['temp_content'];      // Flag for temp content
01617                                         $this->cacheContentFlag = 1;    // Setting flag, so we know, that some cached content is gotten.
01618                                         $this->cacheExpires = $row['expires'];
01619 
01620                                         if ($this->TYPO3_CONF_VARS['FE']['debug'] || $this->config['config']['debug'])  {
01621                                                 $this->content.=chr(10).'<!-- Cached page generated '.Date('d/m Y H:i', $row['tstamp']).'. Expires '.Date('d/m Y H:i', $row['expires']).' -->';
01622                                         }
01623 
01624                                 }
01625                         $GLOBALS['TT']->pull();
01626                 }
01627         }
01628 
01634         function getFromCache_queryRow()        {
01635 
01636                 $GLOBALS['TT']->push('Cache Query','');
01637                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
01638                                 'S.*',
01639                                 'cache_pages S,pages P',
01640                                 'S.hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages').'
01641                                         AND S.page_id=P.uid
01642                                         AND S.expires > '.intval($GLOBALS['EXEC_TIME']).'
01643                                         AND P.deleted=0
01644                                         AND P.hidden=0
01645                                         AND P.starttime<='.intval($GLOBALS['EXEC_TIME']).'
01646                                         AND (P.endtime=0 OR P.endtime>'.intval($GLOBALS['EXEC_TIME']).')'
01647                         );
01648                 $GLOBALS['TT']->pull();
01649 
01650                 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
01651                         $this->pageCachePostProcess($row,'get');
01652                 }
01653                 $GLOBALS['TYPO3_DB']->sql_free_result($res);
01654                 return $row;
01655         }
01656 
01664         function headerNoCache()        {
01665                 $disableAcquireCacheData = FALSE;
01666 
01667                 if ($this->beUserLogin) {
01668                         if (strtolower($_SERVER['HTTP_CACHE_CONTROL'])==='no-cache' || strtolower($_SERVER['HTTP_PRAGMA'])==='no-cache')        {
01669                                 $disableAcquireCacheData = TRUE;
01670                         }
01671                 }
01672 
01673                         // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
01674                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache']))        {
01675                         $_params = array('pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData);
01676                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] as $_funcRef) {
01677                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
01678                         }
01679                 }
01680 
01681                 return $disableAcquireCacheData;
01682         }
01683 
01693         function getHash()      {
01694                 $this->hash_base = serialize(
01695                         array(
01696                                 'all' => $this->all,
01697                                 'id' => intval($this->id),
01698                                 'type' => intval($this->type),
01699                                 'gr_list' => (string)$this->gr_list,
01700                                 'MP' => (string)$this->MP,
01701                                 'cHash' => $this->cHash_array
01702                         )
01703                 );
01704 
01705                 return md5($this->hash_base);
01706         }
01707 
01713         function getConfigArray()       {
01714                 $setStatPageName = false;
01715 
01716                 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
01717                                 $GLOBALS['TT']->push('Parse template','');
01718 
01719                                 // Force parsing, if set?:
01720                         $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
01721 
01722                                 // Start parsing the TS template. Might return cached version.
01723                         $this->tmpl->start($this->rootLine);
01724                                 $GLOBALS['TT']->pull();
01725 
01726                         if ($this->tmpl->loaded)        {
01727                                 $GLOBALS['TT']->push('Setting the config-array','');
01728                         //      t3lib_div::print_array($this->tmpl->setup);
01729                                 $this->sPre = $this->tmpl->setup['types.'][$this->type];        // toplevel - objArrayName
01730                                 $this->pSetup = $this->tmpl->setup[$this->sPre.'.'];
01731 
01732                                 if (!is_array($this->pSetup))   {
01733                                         $this->printError('The page is not configured! [type= '.$this->type.']['.$this->sPre.']');
01734                                         exit;
01735                                 } else {
01736                                         $this->config['config']=Array();
01737 
01738                                                 // Filling the config-array.
01739                                         if (is_array($this->tmpl->setup['config.']))    {
01740                                                 $this->config['config'] = $this->tmpl->setup['config.'];
01741                                         }
01742                                         if (is_array($this->pSetup['config.'])) {
01743                                                 reset($this->pSetup['config.']);
01744                                                 while(list($theK,$theV)=each($this->pSetup['config.'])) {
01745                                                         $this->config['config'][$theK] = $theV;
01746                                                 }
01747                                         }
01748                                                 // if .simulateStaticDocuments was not present, the default value will rule.
01749                                         if (!isset($this->config['config']['simulateStaticDocuments'])) {
01750                                                 $this->config['config']['simulateStaticDocuments'] = trim($this->TYPO3_CONF_VARS['FE']['simulateStaticDocuments']);
01751                                         }
01752                                         if ($this->config['config']['simulateStaticDocuments']) {
01753                                                         // Set replacement char only if it is needed
01754                                                 $this->setSimulReplacementChar();
01755                                         }
01756 
01757                                                 // set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
01758                                         if (!isset($this->config['config']['removeDefaultJS']) && t3lib_div::compat_version('4.0'))     {
01759                                                 $this->config['config']['removeDefaultJS'] = 'external';
01760                                         }
01761                                         if (!isset($this->config['config']['inlineStyle2TempFile']) && t3lib_div::compat_version('4.0'))        {
01762                                                 $this->config['config']['inlineStyle2TempFile'] = 1;
01763                                         }
01764 
01765                                                         // Processing for the config_array:
01766                                         $this->config['rootLine'] = $this->tmpl->rootLine;
01767                                         $this->config['mainScript'] = trim($this->config['config']['mainScript']) ? trim($this->config['config']['mainScript']) : 'index.php';
01768 
01769                                                 // STAT:
01770                                         $theLogFile = $this->TYPO3_CONF_VARS['FE']['logfile_dir'].$this->config['config']['stat_apache_logfile'];
01771                                                 // Add PATH_site left to $theLogFile if the path is not absolute yet
01772                                         if (!t3lib_div::isAbsPath($theLogFile)) $theLogFile = PATH_site.$theLogFile;
01773 
01774                                         if ($this->config['config']['stat_apache'] && $this->config['config']['stat_apache_logfile'] && !strstr($this->config['config']['stat_apache_logfile'],'/'))    {
01775                                                 if (t3lib_div::isAllowedAbsPath($theLogFile))   {
01776                                                         if (!@is_file($theLogFile))     {
01777                                                                 touch($theLogFile);     // Try to create the logfile
01778                                                                 t3lib_div::fixPermissions($theLogFile);
01779                                                         }
01780 
01781                                                         if (@is_file($theLogFile) && @is_writable($theLogFile)) {
01782                                                                 $this->config['stat_vars']['logFile'] = $theLogFile;
01783                                                                 $setStatPageName = true;        // Set page name later on
01784                                                         } else {
01785                                                                 $GLOBALS['TT']->setTSlogMessage('Could not set logfile path. Check filepath and permissions.',3);
01786                                                         }
01787                                                 }
01788                                         }
01789 
01790                                         $this->config['FEData'] = $this->tmpl->setup['FEData'];
01791                                         $this->config['FEData.'] = $this->tmpl->setup['FEData.'];
01792                                 }
01793                                 $GLOBALS['TT']->pull();
01794                         } else {
01795                                 $this->printError('No template found!');
01796                                 exit;
01797                         }
01798                 }
01799 
01800                         // Initialize charset settings etc.
01801                 $this->initLLvars();
01802 
01803                         // We want nice names, so we need to know the charset
01804                 if ($setStatPageName)   {
01805                         if ($this->config['config']['stat_apache_niceTitle'])   {
01806                                 $shortTitle = $this->csConvObj->specCharsToASCII($this->renderCharset,$this->page['title']);
01807                         } else {
01808                                 $shortTitle = $this->page['title'];
01809                         }
01810                         $shortTitle = substr(preg_replace('/[^.[:alnum:]_-]/','_',$shortTitle),0,30);
01811                         $pageName = $this->config['config']['stat_apache_pagenames'] ? $this->config['config']['stat_apache_pagenames'] : '[path][title]--[uid].html';
01812                         $pageName = str_replace('[title]', $shortTitle ,$pageName);
01813                         $pageName = str_replace('[uid]',$this->page['uid'],$pageName);
01814                         $pageName = str_replace('[alias]',$this->page['alias'],$pageName);
01815                         $pageName = str_replace('[type]',$this->type,$pageName);
01816                         $temp = $this->config['rootLine'];
01817                         array_pop($temp);
01818                         if ($this->config['config']['stat_apache_noRoot'])      {
01819                                 array_shift($temp);
01820                         }
01821                         $len = t3lib_div::intInRange($this->config['config']['stat_titleLen'],1,100,20);
01822                         if ($this->config['config']['stat_apache_niceTitle'])   {
01823                                 $path = $this->csConvObj->specCharsToASCII($this->renderCharset,$this->sys_page->getPathFromRootline($temp,$len));
01824                         } else {
01825                                 $path = $this->sys_page->getPathFromRootline($temp,$len);
01826                         }
01827                         $this->config['stat_vars']['pageName'] = str_replace('[path]', preg_replace('/[^.[:alnum:]\/_-]/','_',$path.'/'), $pageName);
01828                 }
01829 
01830                         // No cache
01831                 if ($this->config['config']['no_cache'])        { $this->set_no_cache(); }              // Set $this->no_cache true if the config.no_cache value is set!
01832 
01833                         // Check PATH_INFO url
01834                 if ($this->absRefPrefix_force && strcmp($this->config['config']['simulateStaticDocuments'],'PATH_INFO'))        {
01835                         $redirectUrl = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php?id='.$this->id.'&type='.$this->type;
01836                         if ($this->config['config']['simulateStaticDocuments_dontRedirectPathInfoError'])       {
01837                                 $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');
01838                         } else {
01839                                 header('Location: '.t3lib_div::locationHeaderUrl($redirectUrl));
01840                         }
01841                         exit;
01842 //                      $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.
01843                 }
01844         }
01845 
01846 
01847 
01848 
01849 
01850 
01851 
01852 
01853 
01854 
01855 
01856 
01857 
01858 
01859         /********************************************
01860          *
01861          * Further initialization and data processing
01862          * (jumpurl/submission of forms)
01863          *
01864          *******************************************/
01865 
01874         function getCompressedTCarray() {
01875                 global $TCA;
01876 
01877                 $GLOBALS['TT']->push('Get Compressed TC array');
01878                 if (!$this->TCAloaded)  {
01879                                 // Create hash string for storage / retrieval of cached content:
01880                         $tempHash = md5('tables.php:'.
01881                                 filemtime(TYPO3_extTableDef_script ? PATH_typo3conf.TYPO3_extTableDef_script : PATH_t3lib.'stddb/tables.php').
01882                                 (TYPO3_extTableDef_script?filemtime(PATH_typo3conf.TYPO3_extTableDef_script):'').
01883                                 ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'] ? filemtime(PATH_typo3conf.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php') : '')
01884                         );
01885                                 // Try to fetch if:
01886                         list($TCA,$this->TCAcachedExtras) = unserialize($this->sys_page->getHash($tempHash, 0));
01887                                 // If no result, create it:
01888                         if (!is_array($TCA))    {
01889                                 $this->includeTCA(0);
01890                                 $newTc = Array();
01891                                 $this->TCAcachedExtras = array();       // Collects other information
01892 
01893                                 foreach($TCA as $key => $val)           {
01894                                         $newTc[$key]['ctrl'] = $val['ctrl'];
01895                                         $newTc[$key]['feInterface'] = $val['feInterface'];
01896 
01897                                                 // Collect information about localization exclusion of fields:
01898                                         t3lib_div::loadTCA($key);
01899                                         if (is_array($TCA[$key]['columns']))    {
01900                                                 $this->TCAcachedExtras[$key]['l10n_mode'] = array();
01901                                                 foreach($TCA[$key]['columns'] as $fN => $fV)    {
01902                                                         if ($fV['l10n_mode'])   {
01903                                                                 $this->TCAcachedExtras[$key]['l10n_mode'][$fN] = $fV['l10n_mode'];
01904                                                         }
01905                                                 }
01906                                         }
01907                                 }
01908 
01909                                         // Store it in cache:
01910                                 $TCA = $newTc;
01911                                 $this->sys_page->storeHash($tempHash, serialize(array($newTc,$this->TCAcachedExtras)), 'SHORT TC');
01912                         }
01913                 }
01914                 $GLOBALS['TT']->pull();
01915         }
01916 
01928         function includeTCA($TCAloaded=1)       {
01929                 global $TCA, $PAGES_TYPES, $LANG_GENERAL_LABELS, $TBE_MODULES;
01930                 if (!$this->TCAloaded)  {
01931                         $TCA = Array();
01932                         include (TYPO3_tables_script ? PATH_typo3conf.TYPO3_tables_script : PATH_t3lib.'stddb/tables.php');
01933                                 // Extension additions
01934                         if ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE']) {
01935                                 include(PATH_typo3conf.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php');
01936                         } else {
01937                                 include(PATH_t3lib.'stddb/load_ext_tables.php');
01938                         }
01939                                 // ext-script
01940                         if (TYPO3_extTableDef_script)   {
01941                                 include (PATH_typo3conf.TYPO3_extTableDef_script);
01942                         }
01943 
01944                         $this->TCAloaded = $TCAloaded;
01945                 }
01946         }
01947 
01955         function settingLanguage()      {
01956 
01957                         // Get values from TypoScript:
01958                 $this->sys_language_uid = $this->sys_language_content = intval($this->config['config']['sys_language_uid']);
01959                 list($this->sys_language_mode,$sys_language_content) = t3lib_div::trimExplode(';', $this->config['config']['sys_language_mode']);
01960                 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
01961 
01962                         // If sys_language_uid is set to another language than default:
01963                 if ($this->sys_language_uid>0)  {
01964                                 // Request the overlay record for the sys_language_uid:
01965                         $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
01966                         if (!count($olRec))     {
01967 
01968                                         // If no OL record exists and a foreign language is asked for...
01969                                 if ($this->sys_language_uid)    {
01970 
01971                                                 // If requested translation is not available:
01972                                         if (t3lib_div::hideIfNotTranslated($this->page['l18n_cfg']))    {
01973                                                 $this->pageNotFoundAndExit('Page is not available in the requested language.');
01974                                         } else {
01975                                                 switch((string)$this->sys_language_mode)        {
01976                                                         case 'strict':
01977                                                                 $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
01978                                                         break;
01979                                                         case 'content_fallback':
01980                                                                 $fallBackOrder = t3lib_div::intExplode(',', $sys_language_content);
01981                                                                 foreach($fallBackOrder as $orderValue)  {
01982                                                                         if (!strcmp($orderValue,'0') || count($this->sys_page->getPageOverlay($this->id, $orderValue))) {
01983                                                                                 $this->sys_language_content = $orderValue;      // Setting content uid (but leaving the sys_language_uid)
01984                                                                                 break;
01985                                                                         }
01986                                                                 }
01987                                                         break;
01988                                                         case 'ignore':
01989                                                                 $this->sys_language_content = $this->sys_language_uid;
01990                                                         break;
01991                                                         default:
01992                                                                         // Default is that everything defaults to the default language...
01993                                                                 $this->sys_language_uid = $this->sys_language_content = 0;
01994                                                         break;
01995                                                 }
01996                                         }
01997                                 }
01998                         } else {
01999                                         // Setting sys_language if an overlay record was found (which it is only if a language is used)
02000                                 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
02001                         }
02002                 }
02003 
02004                         // Setting sys_language_uid inside sys-page:
02005                 $this->sys_page->sys_language_uid = $this->sys_language_uid;
02006 
02007                         // If default translation is not available:
02008                 if ((!$this->sys_language_uid || !$this->sys_language_content) && $this->page['l18n_cfg']&1)    {
02009                         $this->pageNotFoundAndExit('Page is not available in default language.');
02010                 }
02011 
02012                         // Updating content of the two rootLines IF the language key is set!
02013                 if ($this->sys_language_uid && is_array($this->tmpl->rootLine)) {
02014                         reset($this->tmpl->rootLine);
02015                         while(list($rLk)=each($this->tmpl->rootLine))   {
02016                                 $this->tmpl->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->tmpl->rootLine[$rLk]);
02017                         }
02018                 }
02019                 if ($this->sys_language_uid && is_array($this->rootLine))       {
02020                         reset($this->rootLine);
02021                         while(list($rLk)=each($this->rootLine)) {
02022                                 $this->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->rootLine[$rLk]);
02023                         }
02024                 }
02025 
02026                         // Finding the ISO code:
02027                 if (t3lib_extMgm::isLoaded('static_info_tables') && $this->sys_language_content)        {       // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
02028                         $sys_language_row = $this->sys_page->getRawRecord('sys_language',$this->sys_language_content,'static_lang_isocode');
02029                         if (is_array($sys_language_row) && $sys_language_row['static_lang_isocode'])    {
02030                                 $stLrow = $this->sys_page->getRawRecord('static_languages',$sys_language_row['static_lang_isocode'],'lg_iso_2');
02031                                 $this->sys_language_isocode = $stLrow['lg_iso_2'];
02032                         }
02033                 }
02034 
02035                         // Setting softMergeIfNotBlank:
02036                 $table_fields = t3lib_div::trimExplode(',', $this->config['config']['sys_language_softMergeIfNotBlank'],1);
02037                 foreach($table_fields as $TF)   {
02038                         list($tN,$fN) = explode(':',$TF);
02039                         $this->TCAcachedExtras[$tN]['l10n_mode'][$fN] = 'mergeIfNotBlank';
02040                 }
02041         }
02042 
02048         function settingLocale()        {
02049 
02050                         // Setting locale
02051                 if ($this->config['config']['locale_all'])      {
02052                         # Change by Rene Fritz, 22/10 2002
02053                         # there's a problem that PHP parses float values in scripts wrong if the locale LC_NUMERIC is set to something with a comma as decimal point
02054                         # this does not work in php 4.2.3
02055                         #setlocale('LC_ALL',$this->config['config']['locale_all']);
02056                         #setlocale('LC_NUMERIC','en_US');
02057 
02058                         # so we set all except LC_NUMERIC
02059                         setlocale(LC_COLLATE,$this->config['config']['locale_all']);
02060                         setlocale(LC_CTYPE,$this->config['config']['locale_all']);
02061                         setlocale(LC_MONETARY,$this->config['config']['locale_all']);
02062                         setlocale(LC_TIME,$this->config['config']['locale_all']);
02063 
02064                         $this->localeCharset = $this->csConvObj->get_locale_charset($this->config['config']['locale_all']);
02065                 }
02066         }
02067 
02073         function checkDataSubmission()  {
02074                 $ret = '';
02075                 $formtype_db = isset($_POST['formtype_db']) || isset($_POST['formtype_db_x']);
02076                 $formtype_mail = isset($_POST['formtype_mail']) || isset($_POST['formtype_mail_x']);
02077                 if ($formtype_db || $formtype_mail)     {
02078                         $refInfo = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
02079                         if (t3lib_div::getIndpEnv('TYPO3_HOST_ONLY')==$refInfo['host'] || $this->TYPO3_CONF_VARS['SYS']['doNotCheckReferer'])   {
02080                                 if ($this->locDataCheck($_POST['locationData']))        {
02081                                         if ($formtype_mail)     {
02082                                                 $ret = 'email';
02083                                         } elseif ($formtype_db && is_array($_POST['data']))     {
02084                                                 $ret = 'fe_tce';
02085                                         }
02086                                         $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": Return value: '.$ret,0);
02087                                         return $ret;
02088                                 }
02089                         } else $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": HTTP_HOST and REFERER HOST did not match when processing submitted formdata!',3);
02090                 }
02091 
02092                         // Hook for processing data submission to extensions:
02093                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission']))  {
02094                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $_classRef)  {
02095                                 $_procObj = &t3lib_div::getUserObj($_classRef);
02096                                 $_procObj->checkDataSubmission($this);
02097                         }
02098                 }
02099                 return $ret;
02100         }
02101 
02109         function fe_tce()       {
02110                 $fe_tce = t3lib_div::makeInstance('tslib_feTCE');
02111                 $fe_tce->start(t3lib_div::_POST('data'),$this->config['FEData.']);
02112                 $fe_tce->includeScripts();
02113         }
02114 
02123         function locDataCheck($locationData)    {
02124                 $locData = explode(':',$locationData);
02125                 if (!$locData[1] ||  $this->sys_page->checkRecord($locData[1],$locData[2],1))   {
02126                         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.
02127                                 return 1;
02128                         } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: The page pointed to by location data ('.$locationData.') was not accessible.',2);
02129                 } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: Location data ('.$locationData.') record pointed to was not accessible.',2);
02130         }
02131 
02139         function sendFormmail() {
02140                 $formmail = t3lib_div::makeInstance('t3lib_formmail');
02141 
02142                 $EMAIL_VARS = t3lib_div::_POST();
02143                 $locationData = $EMAIL_VARS['locationData'];
02144                 unset($EMAIL_VARS['locationData']);
02145                 unset($EMAIL_VARS['formtype_mail'], $EMAIL_VARS['formtype_mail_x'], $EMAIL_VARS['formtype_mail_y']);
02146 
02147                 $integrityCheck = $this->TYPO3_CONF_VARS['FE']['strictFormmail'];
02148 
02149                 if(!$this->TYPO3_CONF_VARS['FE']['secureFormmail']) {
02150                                 // Check recipient field:
02151                         $encodedFields = explode(',','recipient,recipient_copy');       // These two fields are the ones which contain recipient addresses that can be misused to send mail from foreign servers.
02152                         foreach($encodedFields as $fieldKey)    {
02153                                 if (strlen($EMAIL_VARS[$fieldKey]))     {
02154                                         if ($res = $this->codeString($EMAIL_VARS[$fieldKey], TRUE))     {       // Decode...
02155                                                 $EMAIL_VARS[$fieldKey] = $res;  // Set value if OK
02156                                         } elseif ($integrityCheck)      {       // Otherwise abort:
02157                                                 $GLOBALS['TT']->setTSlogMessage('"Formmail" discovered a field ('.$fieldKey.') which could not be decoded to a valid string. Sending formmail aborted due to security reasons!',3);
02158                                                 return false;
02159                                         } else {
02160                                                 $GLOBALS['TT']->setTSlogMessage('"Formmail" discovered a field ('.$fieldKey.') which could not be decoded to a valid string. The security level accepts this, but you should consider a correct coding though!',2);
02161                                         }
02162                                 }
02163                         }
02164                 } else  {
02165                         $locData = explode(':',$locationData);
02166                         $record = $this->sys_page->checkRecord($locData[1],$locData[2],1);
02167                         $EMAIL_VARS['recipient'] = $record['subheader'];
02168                         $EMAIL_VARS['recipient_copy'] = $this->extractRecipientCopy($record['bodytext']);
02169                 }
02170 
02171                         // Hook for preprocessing of the content for formmails:
02172                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass']))    {
02173                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass'] as $_classRef)    {
02174                                 $_procObj = &t3lib_div::getUserObj($_classRef);
02175                                 $EMAIL_VARS = $_procObj->sendFormmail_preProcessVariables($EMAIL_VARS,$this);
02176                         }
02177                 }
02178 
02179                 $formmail->start($EMAIL_VARS);
02180                 $formmail->sendtheMail();
02181                 $GLOBALS['TT']->setTSlogMessage('"Formmail" invoked, sending mail to '.$EMAIL_VARS['recipient'],0);
02182         }
02183 
02190         function extractRecipientCopy($bodytext) {
02191                 $recipient_copy = '';
02192                 $fdef = array();
02193                 //|recipient_copy=hidden|karsten@localhost.localdomain
02194                 preg_match('/^[\s]*\|[\s]*recipient_copy[\s]*=[\s]*hidden[\s]*\|(.*)$/m', $bodytext, $fdef);
02195                 $recipient_copy = (!empty($fdef[1])) ? $fdef[1] : '';
02196                 return $recipient_copy;
02197         }
02198 
02204         function setExternalJumpUrl()   {
02205                 if ($extUrl = $this->sys_page->getExtURL($this->page, $this->config['config']['disablePageExternalUrl']))       {
02206                         $this->jumpurl = $extUrl;
02207                 }
02208         }
02209 
02215         function checkJumpUrlReferer()  {
02216                 if (strcmp($this->jumpurl,'') && !$this->TYPO3_CONF_VARS['SYS']['doNotCheckReferer']) {
02217                         $referer = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
02218                         if (isset($referer['host']) && !($referer['host'] == t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'))) {
02219                                 unset($this->jumpurl);
02220                         }
02221                 }
02222         }
02223 
02230         function jumpUrl()      {
02231                 if ($this->jumpurl)     {
02232                         if (t3lib_div::_GP('juSecure')) {
02233                                 $hArr = array(
02234                                         $this->jumpurl,
02235                                         t3lib_div::_GP('locationData'),
02236                                         $this->TYPO3_CONF_VARS['SYS']['encryptionKey']
02237                                 );
02238                                 $calcJuHash=t3lib_div::shortMD5(serialize($hArr));
02239                                 $locationData = t3lib_div::_GP('locationData');
02240                                 $juHash = t3lib_div::_GP('juHash');
02241                                 if ($juHash == $calcJuHash)     {
02242                                         if ($this->locDataCheck($locationData)) {
02243                                                 $this->jumpurl = rawurldecode($this->jumpurl);  // 211002 - goes with cObj->filelink() rawurlencode() of filenames so spaces can be allowed.
02244                                                 if (@is_file($this->jumpurl))   {
02245                                                         $mimeType = t3lib_div::_GP('mimeType');
02246                                                         $mimeType = $mimeType ? $mimeType : 'application/octet-stream';
02247                                                         Header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
02248                                                         Header('Content-Type: '.$mimeType);
02249                                                         Header('Content-Disposition: attachment; filename='.basename($this->jumpurl));
02250                                                         readfile($this->jumpurl);
02251                                                         exit;
02252                                                 } else die('jumpurl Secure: "'.$this->jumpurl.'" was not a valid file!');
02253                                         } else die('jumpurl Secure: locationData, '.$locationData.', was not accessible.');
02254                                 } else die('jumpurl Secure: Calculated juHash, '.$calcJuHash.', did not match the submitted juHash.');
02255                         } else {
02256                                 $TSConf = $this->getPagesTSconfig();
02257                                 if ($TSConf['TSFE.']['jumpUrl_transferSession'])        {
02258                                         $uParts = parse_url($this->jumpurl);
02259                                         $params = '&FE_SESSION_KEY='.rawurlencode($this->fe_user->id.'-'.md5($this->fe_user->id.'/'.$this->TYPO3_CONF_VARS['SYS']['encryptionKey']));
02260                                         $this->jumpurl.=($uParts['query']?'':'?').$params;      // Add the session parameter ...
02261                                 }
02262                                 Header('Location: '.$this->jumpurl);
02263                                 exit;
02264                         }
02265                 }
02266         }
02267 
02274         function setUrlIdToken()        {
02275                 if ($this->config['config']['ftu'])     {
02276                         $this->getMethodUrlIdToken = $this->TYPO3_CONF_VARS['FE']['get_url_id_token'];
02277                 } else {
02278                         $this->getMethodUrlIdToken = '';
02279                 }
02280         }
02281 
02282 
02283 
02284 
02285 
02286 
02287 
02288 
02289 
02290 
02291 
02292 
02293 
02294 
02295 
02296 
02297 
02298 
02299 
02300 
02301 
02302 
02303 
02304 
02305         /********************************************
02306          *
02307          * Page generation; cache handling
02308          *
02309          *******************************************/
02310 
02317         function isGeneratePage()       {
02318                 return (!$this->cacheContentFlag && !$this->jumpurl);
02319         }
02320 
02327         function tempPageCacheContent() {
02328                 $this->tempContent = false;
02329 
02330                 if (!$this->no_cache)   {
02331                         $seconds = 30;
02332                         $title = htmlspecialchars($this->tmpl->printTitle($this->page['title']));
02333                         $request_uri = htmlspecialchars(t3lib_div::getIndpEnv('REQUEST_URI'));
02334 
02335                         $stdMsg = '
02336                 <strong>Page is being generated.</strong><br />
02337                 If this message does not disappear within '.$seconds.' seconds, please reload.';
02338 
02339                         $message = $this->config['config']['message_page_is_being_generated'];
02340                         if (strcmp('', $message))       {
02341                                 $message = $this->csConvObj->utf8_encode($message,$this->renderCharset);        // This page is always encoded as UTF-8
02342                                 $message = str_replace('###TITLE###', $title, $message);
02343                                 $message = str_replace('###REQUEST_URI###', $request_uri, $message);
02344                         } else $message = $stdMsg;
02345 
02346                         $temp_content = '<?xml version="1.0" encoding="UTF-8"?>
02347 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
02348   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
02349 <html xmlns="http://www.w3.org/1999/xhtml">
02350         <head>
02351                 <title>'.$title.'</title>
02352                 <meta http-equiv="refresh" content="10" />
02353         </head>
02354         <body style="background-color:white; font-family:Verdana,Arial,Helvetica,sans-serif; color:#cccccc; text-align:center;">'.
02355                 $message.'
02356         </body>
02357 </html>';
02358 
02359                                 // Fix 'nice errors' feature in modern browsers
02360                         $padSuffix = '<!--pad-->';      // prevent any trims
02361                         $padSize = 768 - strlen($padSuffix) - strlen($temp_content);
02362                         if ($padSize > 0) {
02363                                 $temp_content = str_pad($temp_content, $padSize, "\n") . $padSuffix;
02364                         }
02365 
02366                         if (!$this->headerNoCache() && $cachedRow = $this->getFromCache_queryRow())     {
02367                                         // We are here because between checking for cached content earlier and now some other HTTP-process managed to store something in cache AND it was not due to a shift-reload by-pass.
02368                                         // This is either the "Page is being generated" screen or it can be the final result.
02369                                         // In any case we should not begin another rendering process also, so we silently disable caching and render the page ourselves and thats it.
02370                                         // Actually $cachedRow contains content that we could show instead of rendering. Maybe we should do that to gain more performance but then we should set all the stuff done in $this->getFromCache()... For now we stick to this...
02371                                 $this->set_no_cache();
02372                         } else {
02373                                 $this->tempContent = TRUE;              // This flag shows that temporary content is put in the cache
02374                                 $this->setPageCacheContent($temp_content, $this->config, $GLOBALS['EXEC_TIME']+$seconds);
02375                         }
02376                 }
02377         }
02378 
02384         function realPageCacheContent() {
02385                 $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
02386                 $timeOutTime = $GLOBALS['EXEC_TIME']+$cache_timeout;
02387                 if ($this->config['config']['cache_clearAtMidnight'])   {
02388                         $midnightTime = mktime (0,0,0,date('m',$timeOutTime),date('d',$timeOutTime),date('Y',$timeOutTime));
02389                         if ($midnightTime > $GLOBALS['EXEC_TIME'])      {               // If the midnight time of the expire-day is greater than the current time, we may set the timeOutTime to the new midnighttime.
02390                                 $timeOutTime = $midnightTime;
02391                         }
02392                 }
02393                 $this->tempContent = false;
02394                 $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
02395 
02396                         // Hook for cache post processing (eg. writing static files!)
02397                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache']))    {
02398                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] as $_classRef)    {
02399                                 $_procObj = &t3lib_div::getUserObj($_classRef);
02400                                 $_procObj->insertPageIncache($this,$timeOutTime);
02401                         }
02402                 }
02403         }
02404 
02414         function setPageCacheContent($content,$data,$tstamp)    {
02415                 $this->clearPageCacheContent();
02416                 $insertFields = array(
02417                         'hash' => $this->newHash,
02418                         'page_id' => $this->id,
02419                         'HTML' => $content,
02420                         'temp_content' => $this->tempContent,
02421                         'cache_data' => serialize($data),
02422                         'expires' => $tstamp,
02423                         'tstamp' => $GLOBALS['EXEC_TIME']
02424                 );
02425 
02426                 $this->cacheExpires = $tstamp;
02427 
02428                 if ($this->page_cache_reg1)     {
02429                         $insertFields['reg1'] = intval($this->page_cache_reg1);
02430                 }
02431                 $this->pageCachePostProcess($insertFields,'set');
02432 
02433                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_pages', $insertFields);
02434         }
02435 
02441         function clearPageCacheContent()        {
02442                 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages'));
02443         }
02444 
02451         function clearPageCacheContent_pidList($pidList)        {
02452                 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($pidList).')');
02453         }
02454 
02462         function pageCachePostProcess(&$row,$type)      {
02463 
02464                 if ($this->TYPO3_CONF_VARS['FE']['pageCacheToExternalFiles'])   {
02465                         $cacheFileName = PATH_site.'typo3temp/cache_pages/'.$row['hash']{0}.$row['hash']{1}.'/'.$row['hash'].'.html';
02466                         switch((string)$type)   {
02467                                 case 'get':
02468                                         $row['HTML'] = @is_file($cacheFileName) ? t3lib_div::getUrl($cacheFileName) : '<!-- CACHING ERROR, sorry -->';
02469                                 break;
02470                                 case 'set':
02471                                         t3lib_div::writeFileToTypo3tempDir($cacheFileName,$row['HTML']);
02472                                         $row['HTML'] = '';
02473                                 break;
02474                         }
02475                 }
02476         }
02477 
02485         function setSysLastChanged()    {
02486                 if ($this->page['SYS_LASTCHANGED'] < intval($this->register['SYS_LASTCHANGED']))        {
02487                         $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($this->id), array('SYS_LASTCHANGED' => intval($this->register['SYS_LASTCHANGED'])));
02488                 }
02489         }
02490 
02491 
02492 
02493 
02494 
02495 
02496 
02497 
02498 
02499 
02500 
02501 
02502 
02503 
02504 
02505 
02506 
02507 
02508 
02509 
02510         /********************************************
02511          *
02512          * Page generation; rendering and inclusion
02513          *
02514          *******************************************/
02515 
02521         function generatePage_preProcessing()   {
02522                 ksort($this->all);
02523                         // 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!
02524                 $this->newHash = $this->getHash();
02525                 $this->config['hash_base'] = $this->hash_base;  // For cache management informational purposes.
02526 
02527                         // 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.
02528                 $this->tempPageCacheContent();
02529 
02530                         // Setting cache_timeout_default. May be overridden by PHP include scritps.
02531                 $this->cacheTimeOutDefault = intval($this->config['config']['cache_period']);
02532 
02533                         // page is generated
02534                 $this->no_cacheBeforePageGen = $this->no_cache;
02535         }
02536 
02543         function generatePage_whichScript()     {
02544                 if (!$this->TYPO3_CONF_VARS['FE']['noPHPscriptInclude'] && $this->config['config']['pageGenScript'])    {
02545                         return $this->tmpl->getFileName($this->config['config']['pageGenScript']);
02546                 }
02547         }
02548 
02555         function generatePage_postProcessing()  {
02556                         // 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.
02557                 if ($this->no_cacheBeforePageGen) $this->set_no_cache();
02558 
02559                         // Tidy up the code, if flag...
02560                 if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'all')               {
02561                         $GLOBALS['TT']->push('Tidy, all','');
02562                                 $this->content = $this->tidyHTML($this->content);
02563                         $GLOBALS['TT']->pull();
02564                 }
02565 
02566                         // XHTML-clean the code, if flag set
02567                 if ($this->doXHTML_cleaning() == 'all')         {
02568                         $GLOBALS['TT']->push('XHTML clean, all','');
02569                                 $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
02570                                 $this->content = $XHTML_clean->XHTML_clean($this->content);
02571                         $GLOBALS['TT']->pull();
02572                 }
02573 
02574                         // Fix local anchors in links, if flag set
02575                 if ($this->doLocalAnchorFix() == 'all')         {
02576                         $GLOBALS['TT']->push('Local anchor fix, all','');
02577                                 $this->prefixLocalAnchorsWithScript();
02578                         $GLOBALS['TT']->pull();
02579                 }
02580 
02581                         // Hook for post-processing of page content cached/non-cached:
02582                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all']))  {
02583                         $_params = array('pObj' => &$this);
02584                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] as $_funcRef)   {
02585                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
02586                         }
02587                 }
02588 
02589                         // Processing if caching is enabled:
02590                 if (!$this->no_cache)   {
02591                                         // Tidy up the code, if flag...
02592                         if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'cached')            {
02593                                 $GLOBALS['TT']->push('Tidy, cached','');
02594                                         $this->content = $this->tidyHTML($this->content);
02595                                 $GLOBALS['TT']->pull();
02596                         }
02597                                 // XHTML-clean the code, if flag set
02598                         if ($this->doXHTML_cleaning() == 'cached')              {
02599                                 $GLOBALS['TT']->push('XHTML clean, cached','');
02600                                         $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
02601                                         $this->content = $XHTML_clean->XHTML_clean($this->content);
02602                                 $GLOBALS['TT']->pull();
02603                         }
02604                                 // Fix local anchors in links, if flag set
02605                         if ($this->doLocalAnchorFix() == 'cached')              {
02606                                 $GLOBALS['TT']->push('Local anchor fix, cached','');
02607                                         $this->prefixLocalAnchorsWithScript();
02608                                 $GLOBALS['TT']->pull();
02609                         }
02610 
02611                                 // Hook for post-processing of page content before being cached:
02612                         if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached']))       {
02613                                 $_params = array('pObj' => &$this);
02614                                 foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] as $_funcRef)        {
02615                                         t3lib_div::callUserFunction($_funcRef,$_params,$this);
02616                                 }
02617                         }
02618                 }
02619 
02620                         // Convert char-set for output: (should be BEFORE indexing of the content (changed 22/4 2005)), because otherwise indexed search might convert from the wrong charset! One thing is that the charset mentioned in the HTML header would be wrong since the output charset (metaCharset) has not been converted to from renderCharset. And indexed search will internally convert from metaCharset to renderCharset so the content MUST be in metaCharset already!
02621                 $this->content = $this->convOutputCharset($this->content,'mainpage');
02622 
02623                         // Hook for indexing pages
02624                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'])) {
02625                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'] as $_classRef) {
02626                                 $_procObj = &t3lib_div::getUserObj($_classRef);
02627                                 $_procObj->hook_indexContent($this);
02628                         }
02629                 }
02630 
02631                         // Storing for cache:
02632                 if (!$this->no_cache)   {
02633                         $this->realPageCacheContent();
02634                 } 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)
02635                         $this->clearPageCacheContent();
02636                         $this->tempContent = false;
02637                 }
02638 
02639                         // Sets sys-last-change:
02640                 $this->setSysLastChanged();
02641         }
02642 
02648         function INTincScript() {
02649                 $GLOBALS['TT']->push('Split content');
02650                 $INTiS_splitC = explode('<!--INT_SCRIPT.',$this->content);                      // Splits content with the key.
02651                 $this->content='';
02652                 $GLOBALS['TT']->setTSlogMessage('Parts: '.count($INTiS_splitC));
02653                 $GLOBALS['TT']->pull();
02654 
02655                         // Deprecated stuff:
02656                 $this->additionalHeaderData = is_array($this->config['INTincScript_ext']['additionalHeaderData']) ? $this->config['INTincScript_ext']['additionalHeaderData'] : array();
02657                 $this->additionalJavaScript = $this->config['INTincScript_ext']['additionalJavaScript'];
02658                 $this->additionalCSS = $this->config['INTincScript_ext']['additionalCSS'];
02659                 $this->JSCode = $this->additionalHeaderData['JSCode'];
02660                 $this->JSImgCode = $this->additionalHeaderData['JSImgCode'];
02661                 $this->divSection='';
02662 
02663                 $INTiS_config = $GLOBALS['TSFE']->config['INTincScript'];
02664                 foreach($INTiS_splitC as $INTiS_c => $INTiS_cPart)      {
02665                         if (substr($INTiS_cPart,32,3)=='-->')   {       // If the split had a comment-end after 32 characters it's probably a split-string
02666                                 $INTiS_key = 'INT_SCRIPT.'.substr($INTiS_cPart,0,32);
02667                                 $GLOBALS['TT']->push('Include '.$INTiS_config[$INTiS_key]['file'],'');
02668                                 $incContent='';
02669                                 if (is_array($INTiS_config[$INTiS_key]))        {
02670                                         $INTiS_cObj = unserialize($INTiS_config[$INTiS_key]['cObj']);
02671                                         $INTiS_cObj->INT_include=1;
02672                                         switch($INTiS_config[$INTiS_key]['type'])       {
02673                                                 case 'SCRIPT':
02674                                                         $incContent = $INTiS_cObj->PHP_SCRIPT($INTiS_config[$INTiS_key]['conf']);
02675                                                 break;
02676                                                 case 'COA':
02677                                                         $incContent = $INTiS_cObj->COBJ_ARRAY($INTiS_config[$INTiS_key]['conf']);
02678                                                 break;
02679                                                 case 'FUNC':
02680                                                         $incContent = $INTiS_cObj->USER($INTiS_config[$INTiS_key]['conf']);
02681                                                 break;
02682                                                 case 'POSTUSERFUNC':
02683                                                         $incContent = $INTiS_cObj->callUserFunction($INTiS_config[$INTiS_key]['postUserFunc'], $INTiS_config[$INTiS_key]['conf'], $INTiS_config[$INTiS_key]['content']);
02684                                                 break;
02685                                         }
02686                                 }
02687                                 $this->content.= $this->convOutputCharset($incContent,'INC-'.$INTiS_c);
02688                                 $this->content.= substr($INTiS_cPart,35);
02689                                 $GLOBALS['TT']->pull($incContent);
02690                         } else {
02691                                 $this->content.= ($INTiS_c?'<!--INT_SCRIPT.':'').$INTiS_cPart;
02692                         }
02693                 }
02694                 $GLOBALS['TT']->push('Substitute header section');
02695                 $this->INTincScript_loadJSCode();
02696                 $this->content = str_replace('<!--HD_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset(implode(chr(10),$this->additionalHeaderData),'HD'), $this->content);
02697                 $this->content = str_replace('<!--TDS_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset($this->divSection,'TDS'), $this->content);
02698                 $this->setAbsRefPrefix();
02699                 $GLOBALS['TT']->pull();
02700         }
02701 
02708         function INTincScript_loadJSCode()      {
02709                 if ($this->JSImgCode)   {       // If any images added, then add them to the javascript section
02710                         $this->additionalHeaderData['JSImgCode']='
02711 <script type="text/javascript">
02712         /*<![CDATA[*/
02713 <!--
02714 if (version == "n3") {
02715 '.trim($this->JSImgCode).'
02716 }
02717 // -->
02718         /*]]>*/
02719 </script>';
02720                 }
02721                 if ($this->JSCode || count($this->additionalJavaScript))        {       // Add javascript
02722                         $this->additionalHeaderData['JSCode']='
02723 <script type="text/javascript">
02724         /*<![CDATA[*/
02725 <!--
02726 '.implode(chr(10),$this->additionalJavaScript).'
02727 '.trim($this->JSCode).'
02728 // -->
02729         /*]]>*/
02730 </script>';
02731                 }
02732                 if (count($this->additionalCSS))        {       // Add javascript
02733                         $this->additionalHeaderData['_CSS']='
02734 <style type="text/css">
02735         /*<![CDATA[*/
02736 <!--
02737 '.implode(chr(10),$this->additionalCSS).'
02738 // -->
02739         /*]]>*/
02740 </style>';
02741                 }
02742         }
02743 
02749         function isINTincScript()       {
02750                 return  (is_array($this->config['INTincScript']) && !$this->jumpurl);
02751         }
02752 
02758         function doXHTML_cleaning()     {
02759                 return $this->config['config']['xhtml_cleaning'];
02760         }
02761 
02767         function doLocalAnchorFix()     {
02768                 return $this->config['config']['prefixLocalAnchors'];
02769         }
02770 
02771 
02772 
02773 
02774 
02775 
02776 
02777 
02778 
02779 
02780 
02781 
02782 
02783 
02784 
02785 
02786         /********************************************
02787          *
02788          * Finished off; outputting, storing session data, statistics...
02789          *
02790          *******************************************/
02791 
02798         function isOutputting() {
02799 
02800                         // Initialize by status of jumpUrl:
02801                 $enableOutput = (!$this->jumpurl);
02802 
02803                         // Call hook for possible disabling of output:
02804                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])) {
02805                         $_params = array('pObj' => &$this, 'enableOutput' => &$enableOutput);
02806                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'] as $_funcRef)  {
02807                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
02808                         }
02809                 }
02810 
02811                 return $enableOutput;
02812         }
02813 
02821         function processOutput()        {
02822 
02823                         // Set header for charset-encoding unless disabled
02824                 if (!$this->config['config']['disableCharsetHeader'])   {
02825                         $headLine = 'Content-Type:text/html;charset='.trim($this->metaCharset);
02826                         header($headLine);
02827                 }
02828 
02829                         // Set cache related headers to client (used to enable proxy / client caching!)
02830                 if ($this->config['config']['sendCacheHeaders'])        {
02831                         $this->sendCacheHeaders();
02832                 }
02833 
02834                         // Set headers, if any
02835                 if ($this->config['config']['additionalHeaders'])       {
02836                         $headerArray = explode('|', $this->config['config']['additionalHeaders']);
02837                         while(list(,$headLine)=each($headerArray))      {
02838                                 $headLine = trim($headLine);
02839                                 header($headLine);
02840                         }
02841                 }
02842 
02843                         // Send appropriate status code in case of temporary content
02844                 if ($this->tempContent) {
02845                         $this->addTempContentHttpHeaders();
02846                 }
02847 
02848                         // Make substitution of eg. username/uid in content only if cache-headers for client/proxy caching is NOT sent!
02849                 if (!$this->isClientCachable)   {
02850                         $this->contentStrReplace();
02851                 }
02852 
02853                                 // Tidy up the code, if flag...
02854                 if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'output')            {
02855                         $GLOBALS['TT']->push('Tidy, output','');
02856                                 $this->content = $this->tidyHTML($this->content);
02857                         $GLOBALS['TT']->pull();
02858                 }
02859                         // XHTML-clean the code, if flag set
02860                 if ($this->doXHTML_cleaning() == 'output')              {
02861                         $GLOBALS['TT']->push('XHTML clean, output','');
02862                                 $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
02863                                 $this->content = $XHTML_clean->XHTML_clean($this->content);
02864                         $GLOBALS['TT']->pull();
02865                 }
02866                         // Fix local anchors in links, if flag set
02867                 if ($this->doLocalAnchorFix() == 'output')              {
02868                         $GLOBALS['TT']->push('Local anchor fix, output','');
02869                                 $this->prefixLocalAnchorsWithScript();
02870                         $GLOBALS['TT']->pull();
02871                 }
02872 
02873                         // Hook for post-processing of page content before output:
02874                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output']))       {
02875                         $_params = array('pObj' => &$this);
02876                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] as $_funcRef)        {
02877                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
02878                         }
02879                 }
02880 
02881                         // Send content-lenght header. Notice that all HTML content outside the length of the content-length header will be cut off! Therefore content of unknown length from included PHP-scripts and if admin users are logged in (admin panel might show...) we disable it!
02882                 if ($this->config['config']['enableContentLengthHeader'] && !$this->isEXTincScript() && !$this->beUserLogin && !$this->doWorkspacePreview())    {
02883                         header('Content-Length: '.strlen($this->content));
02884                 }
02885         }
02886 
02894         function sendCacheHeaders()     {
02895 
02896                         // Getting status whether we can send cache control headers for proxy caching:
02897                 $doCache = $this->isStaticCacheble();
02898 
02899                         // This variable will be TRUE unless cache headers are configured to be sent ONLY if a branch does not allow logins and logins turns out to be allowed anyway...
02900                 $loginsDeniedCfg = !$this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch'] || !$this->loginAllowedInBranch;
02901 
02902                         // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
02903                 if ($doCache
02904                                 && !$this->beUserLogin
02905                                 && !$this->doWorkspacePreview()
02906                                 && $loginsDeniedCfg)    {
02907 
02908                                 // Build headers:
02909                         $headers = array(
02910                                 'Last-Modified: '.gmdate('D, d M Y H:i:s T', $this->register['SYS_LASTCHANGED']),
02911                                 'Expires: '.gmdate('D, d M Y H:i:s T', $this->cacheExpires),
02912                                 'ETag: '.md5($this->content),
02913                                 'Cache-Control: max-age='.($this->cacheExpires - $GLOBALS['EXEC_TIME']),                // no-cache
02914                                 'Pragma: public',
02915                         );
02916 
02917                         $this->isClientCachable = TRUE;
02918                 } else {
02919                                 // Build headers:
02920                         $headers = array(
02921                                 #'Last-Modified: '.gmdate('D, d M Y H:i:s T', $this->register['SYS_LASTCHANGED']),
02922                                 #'ETag: '.md5($this->content),
02923 
02924                                 #'Cache-Control: no-cache',
02925                                 #'Pragma: no-cache',
02926                                 'Cache-Control: private',               // Changed to this according to Ole Tange, FI.dk
02927                         );
02928 
02929                         $this->isClientCachable = FALSE;
02930 
02931                                 // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
02932                         if ($this->beUserLogin) {
02933                                 if ($doCache)   {
02934                                         $GLOBALS['TT']->setTSlogMessage('Cache-headers with max-age "'.($this->cacheExpires - $GLOBALS['EXEC_TIME']).'" would have been sent');
02935                                 } else {
02936                                         $reasonMsg = '';
02937                                         $reasonMsg.= !$this->no_cache ? '' : 'Caching disabled (no_cache). ';
02938                                         $reasonMsg.= !$this->isINTincScript() ? '' : '*_INT object(s) on page. ';
02939                                         $reasonMsg.= !$this->isEXTincScript() ? '' : '*_EXT object(s) on page. ';
02940                                         $reasonMsg.= !is_array($this->fe_user->user) ? '' : 'Frontend user logged in. ';
02941                                         $GLOBALS['TT']->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "'.$reasonMsg.'"',1);
02942                                 }
02943                         }
02944                 }
02945 
02946                         // Send headers:
02947                 foreach($headers as $hL)        {
02948                         header($hL);
02949                 }
02950         }
02951 
02962         function isStaticCacheble()     {
02963                 $doCache = !$this->no_cache
02964                                 && !$this->isINTincScript()
02965                                 && !$this->isEXTincScript()
02966                                 && !$this->isUserOrGroupSet();
02967                 return $doCache;
02968         }
02969 
02975         function contentStrReplace()    {
02976                         // Substitutes username mark with the username
02977                 if ($this->fe_user->user['uid'])        {
02978 
02979                                 // User name:
02980                         $token = trim($this->config['config']['USERNAME_substToken']);
02981                         $this->content = str_replace($token ? $token : '<!--###USERNAME###-->',$this->fe_user->user['username'],$this->content);
02982 
02983                                 // User uid (if configured):
02984                         $token = trim($this->config['config']['USERUID_substToken']);
02985                         if ($token)     {
02986                                 $this->content = str_replace($token, $this->fe_user->user['uid'], $this->content);
02987                         }
02988                 }
02989                         // Substitutes get_URL_ID in case of GET-fallback
02990                 if ($this->getMethodUrlIdToken) {
02991                         $this->content = str_replace($this->getMethodUrlIdToken, $this->fe_user->get_URL_ID, $this->content);
02992                 }
02993         }
02994 
03001         function isEXTincScript()       {
03002                 return is_array($this->config['EXTincScript']);
03003         }
03004 
03010         function storeSessionData()     {
03011                 $this->fe_user->storeSessionData();
03012         }
03013 
03020         function setParseTime() {
03021                         // Compensates for the time consumed with Back end user initialization.
03022                 $this->scriptParseTime = $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_end'])
03023                                                                 - $GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_start'])
03024                                                                 - ($GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'])-$GLOBALS['TT']->convertMicrotime($GLOBALS['TYPO3_MISC']['microtime_BE_USER_start']));
03025         }
03026 
03032         function statistics()   {
03033                 if ($this->config['config']['stat'] &&
03034                                 (!strcmp('',$this->config['config']['stat_typeNumList']) || t3lib_div::inList(str_replace(' ','',$this->config['config']['stat_typeNumList']), $this->type)) &&
03035                                 (!$this->config['config']['stat_excludeBEuserHits'] || !$this->beUserLogin) &&
03036                                 (!$this->config['config']['stat_excludeIPList'] || !t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'),str_replace(' ','',$this->config['config']['stat_excludeIPList'])))) {
03037 
03038                         $GLOBALS['TT']->push('Stat');
03039                                 if (t3lib_extMgm::isLoaded('sys_stat') && $this->config['config']['stat_mysql'])        {
03040 
03041                                                 // Jumpurl:
03042                                         $sword = t3lib_div::_GP('sword');
03043                                         if ($sword)     {
03044                                                 $jumpurl_msg = 'sword:'.$sword;
03045                                         } elseif ($this->jumpurl) {
03046                                                 $jumpurl_msg = 'jumpurl:'.$this->jumpurl;
03047                                         } else {
03048                                                 $jumpurl_msg = '';
03049                                         }
03050 
03051                                                 // Flags: bits: 0 = BE_user, 1=Cached page?
03052                                         $flags=0;
03053                                         if ($this->beUserLogin) {$flags|=1;}
03054                                         if ($this->cacheContentFlag) {$flags|=2;}
03055 
03056                                                 // Ref url:
03057                                         $refUrl = t3lib_div::getIndpEnv('HTTP_REFERER');
03058                                         $thisUrl = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
03059                                         if (t3lib_div::isFirstPartOfStr($refUrl,$thisUrl))      {
03060                                                 $refUrl='[LOCAL]';
03061                                         }
03062 
03063                                         $insertFields = array(
03064                                                 'page_id' => intval($this->id),                                                 // id
03065                                                 'page_type' => intval($this->type),                                             // type
03066                                                 'jumpurl' => $jumpurl_msg,                                                              // jumpurl message
03067                                                 'feuser_id' => $this->fe_user->user['uid'],                             // fe_user id, integer
03068                                                 'cookie' => $this->fe_user->id,                                                 // cookie as set or retrieve. If people has cookies disabled this will vary all the time...
03069                                                 '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...
03070                                                 'rl0' => $this->config['rootLine'][0]['uid'],                   // RootLevel 0 uid
03071                                                 'rl1' => $this->config['rootLine'][1]['uid'],                   // RootLevel 1 uid
03072                                                 'client_browser' => $GLOBALS['CLIENT']['BROWSER'],              // Client browser (net, msie, opera)
03073                                                 'client_version' => $GLOBALS['CLIENT']['VERSION'],              // Client version (double value)
03074                                                 'client_os' => $GLOBALS['CLIENT']['SYSTEM'],                    // Client Operating system (win, mac, unix)
03075                                                 'parsetime' => intval($this->scriptParseTime),                  // Parsetime for the page.
03076                                                 'flags' => $flags,                                                                              // Flags: Is be user logged in? Is page cached?
03077                                                 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),                   // Remote IP address
03078                                                 'host' => t3lib_div::getIndpEnv('REMOTE_HOST'),                 // Remote Host Address
03079                                                 'referer' => $refUrl,                                                                   // Referer URL
03080                                                 'browser' => t3lib_div::getIndpEnv('HTTP_USER_AGENT'),  // User Agent Info.
03081                                                 'tstamp' => $GLOBALS['EXEC_TIME']                                               // Time stamp
03082                                         );
03083 
03084                                                 // Hook for preprocessing the list of fields to insert into sys_stat:
03085                                         if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass']))    {
03086                                                 foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass'] as $_classRef)    {
03087                                                         $_procObj = &t3lib_div::getUserObj($_classRef);
03088                                                         $insertFields = $_procObj->sysstat_preProcessFields($insertFields,$this);
03089                                                 }
03090                                         }
03091 
03092 
03093                                         $GLOBALS['TT']->push('Store SQL');
03094                                         $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_stat', $insertFields);
03095                                         $GLOBALS['TT']->pull();
03096                                 }
03097 
03098                                         // Apache:
03099                                 if ($this->config['config']['stat_apache'] && $this->config['stat_vars']['pageName'])   {
03100                                         if (@is_file($this->config['stat_vars']['logFile']))    {
03101                                                 $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);
03102                                                 if (!$this->config['config']['stat_apache_notExtended'])        {
03103                                                         $LogLine.= ' "'.t3lib_div::getIndpEnv('HTTP_REFERER').'" "'.t3lib_div::getIndpEnv('HTTP_USER_AGENT').'"';
03104                                                 }
03105 
03106                                                 $GLOBALS['TT']->push('Write to log file (fputs)');
03107                                                         $logfilehandle = fopen($this->config['stat_vars']['logFile'], 'a');
03108                                                         fputs($logfilehandle, $LogLine.chr(10));
03109                                                         @fclose($logfilehandle);
03110                                                 $GLOBALS['TT']->pull();
03111 
03112                                                 $GLOBALS['TT']->setTSlogMessage('Writing to logfile: OK',0);
03113                                         } else {
03114                                                 $GLOBALS['TT']->setTSlogMessage('Writing to logfile: Error - logFile did not exist!',3);
03115                                         }
03116                                 }
03117                         $GLOBALS['TT']->pull();
03118                 }
03119         }
03120 
03126         function previewInfo()  {
03127                 if ($this->fePreview)   {
03128 
03129                                 if ($this->fePreview==2)        {
03130                                         $text = 'Preview of workspace "'.$this->whichWorkspace(TRUE).'" ('.$this->whichWorkspace().')';
03131                                 } else {
03132                                         $text = 'PREVIEW!';
03133                                 }
03134 
03135                                 $stdMsg = '
03136                                 <br />
03137                                 <div align="center">
03138                                         <table border="3" bordercolor="black" cellpadding="2" bgcolor="red">
03139                                                 <tr>
03140                                                         <td>&nbsp;&nbsp;<font face="Verdana" size="1"><b>'.htmlspecialchars($text).'</b></font>&nbsp;&nbsp;</td>
03141                                                 </tr>
03142                                         </table>
03143                                 </div>';
03144 
03145                                 if ($this->fePreview==2)        {
03146                                         $temp_content = $this->config['config']['message_preview_workspace'] ?
03147                                                 @sprintf($this->config['config']['message_preview_workspace'], $this->whichWorkspace(TRUE),$this->whichWorkspace()) :
03148                                                 $stdMsg;
03149                                 } else {
03150                                         $temp_content = $this->config['config']['message_preview'] ? $this->config['config']['message_preview'] : $stdMsg;
03151                                 }
03152                                 echo $temp_content;
03153                 }
03154         }
03155 
03161         function hook_eofe()    {
03162 
03163                         // Call hook for end-of-frontend processing:
03164                 if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe']))    {
03165                         $_params = array('pObj' => &$this);
03166                         foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'] as $_funcRef)     {
03167                                 t3lib_div::callUserFunction($_funcRef,$_params,$this);
03168                         }
03169                 }
03170         }
03171 
03177         function beLoginLinkIPList()    {
03178                 if ($this->config['config']['beLoginLinkIPList'])       {
03179                         if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $this->config['config']['beLoginLinkIPList']))       {
03180                                 $label = !$this->beUserLogin ? $this->config['config']['beLoginLinkIPList_login'] : $this->config['config']['beLoginLinkIPList_logout'];
03181                                 if ($label)     {
03182                                         if (!$this->beUserLogin)        {
03183                                                 $link = '<a href="'.htmlspecialchars(TYPO3_mainDir.'index.php?redirect_url='.rawurlencode(t3lib_div::getIndpEnv("REQUEST_URI"))).'">'.$label.'</a>';
03184                                         } else {
03185                                                 $link = '<a href="'.htmlspecialchars(TYPO3_mainDir.'index.php?L=OUT&redirect_url='.rawurlencode(t3lib_div::getIndpEnv("REQUEST_URI"))).'">'.$label.'</a>';
03186                                         }
03187                                         return $link;
03188                                 }
03189                         }
03190                 }
03191         }
03192 
03198         function addTempContentHttpHeaders() {
03199                 header('HTTP/1.0 503 Service unavailable');
03200                 header('Retry-after: 3600');
03201                 header('Pragma: no-cache');
03202                 header('Cache-control: no-cache');
03203                 header('Expire: 0');
03204         }
03205 
03206 
03207 
03208 
03209 
03210 
03211 
03212 
03213 
03214 
03215 
03216 
03217 
03218 
03219 
03220 
03221 
03222 
03223 
03224 
03225 
03226         /********************************************
03227          *
03228          * Various internal API functions
03229          *
03230          *******************************************/
03231 
03232 
03244         function makeSimulFileName($inTitle,$page,$type,$addParams='',$no_cache='')     {
03245                 $titleChars = intval($this->config['config']['simulateStaticDocuments_addTitle']);
03246                         // Default value is 30 but values > 1 will be override this
03247                 if($titleChars==1)      { $titleChars = 30; }
03248 
03249                 $out = '';
03250                 if ($titleChars)        {
03251                         $out = $this->fileNameASCIIPrefix($inTitle, $titleChars);
03252                 }
03253                 $enc = '';
03254 
03255                 if (strcmp($addParams,'') && !$no_cache)        {
03256                         switch ((string)$this->config['config']['simulateStaticDocuments_pEnc'])        {
03257                                 case 'md5':
03258                                         $md5 = substr(md5($addParams),0,10);
03259                                         $enc = '+M5'.$md5;
03260 
03261                                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
03262                                         if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))  {
03263                                                 $insertFields = array(
03264                                                         'md5hash' => $md5,
03265                                                         'tstamp' => time(),
03266                                                         'type' => 1,
03267                                                         'params' => $addParams
03268                                                 );
03269 
03270                                                 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
03271                                         }
03272                                 break;
03273                                 case 'base64':
03274                                         $enc = '+B6'.str_replace('=','_',str_replace('/','-',base64_encode($addParams)));
03275                                 break;
03276                         }
03277                 }
03278                         // Setting page and type number:
03279                 $url = $out.$page.$enc;
03280                 $url.= ($type || $out || !$this->config['config']['simulateStaticDocuments_noTypeIfNoTitle']) ? '.'.$type : '';
03281                 return $url;
03282         }
03283 
03291         function simulateStaticDocuments_pEnc_onlyP_proc($linkVars)     {
03292                 $remainLinkVars = '';
03293                 if (strcmp($linkVars,''))       {
03294                         $p = explode('&',$linkVars);
03295                         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?
03296                         $rem = array();
03297                         foreach($p as $k => $v) {
03298                                 if (strlen($v)) {
03299                                         list($pName) = explode('=',$v,2);
03300                                         $pName = rawurldecode($pName);
03301                                         if (!$this->pEncAllowedParamNames[$pName])      {
03302                                                 unset($p[$k]);
03303                                                 $rem[] = $v;
03304                                         }
03305                                 } else unset($p[$k]);
03306                         }
03307 
03308                         $linkVars = count($p) ? '&'.implode('&',$p) : '';
03309                         $remainLinkVars = count($rem) ? '&'.implode('&',$rem) : '';
03310                 }
03311                 return array($linkVars, $remainLinkVars);
03312         }
03313 
03320         function getSimulFileName()     {
03321                 $url='';
03322                 $url.=$this->makeSimulFileName($this->page['title'], $this->page['alias']?$this->page['alias']:$this->id, $this->type).'.html';
03323                 return $url;
03324         }
03325 
03331         function setSimulReplacementChar() {
03332                 $replacement = $defChar = t3lib_div::compat_version('4.0') ? '-' : '_';
03333                 if (isset($this->config['config']['simulateStaticDocuments_replacementChar'])) {
03334                         $replacement = trim($this->config['config']['simulateStaticDocuments_replacementChar']);
03335                         if (urlencode($replacement) != $replacement) {
03336                                         // Invalid character
03337                                 $replacement = $defChar;
03338                         }
03339                 }
03340                 $this->config['config']['simulateStaticDocuments_replacementChar'] = $replacement;
03341         }
03342 
03351         function fileNameASCIIPrefix($inTitle,$titleChars,$mergeChar='.')       {
03352                 $out = $this->csConvObj->specCharsToASCII($this->renderCharset, $inTitle);
03353                         // Get replacement character
03354                 $replacementChar = &$this->config['config']['simulateStaticDocuments_replacementChar'];
03355                 $replacementChars = '_\-' . ($replacementChar != '_' && $replacementChar != '-' ? $replacementChar : '');
03356                 $out = preg_replace('/[^A-Za-z0-9_-]/', $replacementChar, trim(substr($out, 0, $titleChars)));
03357                 $out = preg_replace('/([' . $replacementChars . ']){2,}/', '\1', $out);
03358                 $out = preg_replace('/[' . $replacementChars . ']?$/', '', $out);
03359                 $out = preg_replace('/^[' . $replacementChars . ']?/', '', $out);
03360                 if (strlen($out)) {
03361                         $out .= $mergeChar;
03362                 }
03363 
03364                 return $out;
03365         }
03366 
03377         function encryptCharcode($n,$start,$end,$offset)        {
03378                 $n = $n + $offset;
03379                 if ($offset > 0 && $n > $end)   {
03380                         $n = $start + ($n - $end - 1);
03381                 } else if ($offset < 0 && $n < $start)  {
03382                         $n = $end - ($start - $n - 1);
03383                 }
03384                 return chr($n);
03385         }
03386 
03394         function encryptEmail($string,$back=0)  {
03395                 $out = '';
03396 
03397                 if ($this->spamProtectEmailAddresses === 'ascii') {
03398                         for ($a=0; $a<strlen($string); $a++) {
03399                                 $out .= '&#'.ord(substr($string, $a, 1)).';';
03400                         }
03401                 } else  {
03402                                 // like str_rot13() but with a variable offset and a wider character range
03403                         $len = strlen($string);
03404                         $offset = intval($this->spamProtectEmailAddresses)*($back?-1:1);
03405                         for ($i=0; $i<$len; $i++)       {
03406                                 $charValue = ord($string{$i});
03407                                 if ($charValue >= 0x2B && $charValue <= 0x3A)   {       // 0-9 . , - + / :
03408                                         $out .= $this->encryptCharcode($charValue,0x2B,0x3A,$offset);
03409                                 } elseif ($charValue >= 0x40 && $charValue <= 0x5A)     {       // A-Z @
03410                                         $out .= $this->encryptCharcode($charValue,0x40,0x5A,$offset);
03411                                 } else if ($charValue >= 0x61 && $charValue <= 0x7A)    {       // a-z
03412                                         $out .= $this->encryptCharcode($charValue,0x61,0x7A,$offset);
03413                                 } else {
03414                                         $out .= $string{$i};
03415                                 }
03416                         }
03417                 }
03418                 return $out;
03419         }
03420 
03430         function codeString($string, $decode=FALSE)     {
03431 
03432                 if ($decode) {
03433                         list($md5Hash, $str) = explode(':',$string,2);
03434                         $newHash = substr(md5($this->TYPO3_CONF_VARS['SYS']['encryptionKey'].':'.$str),0,10);
03435                         if (!strcmp($md5Hash, $newHash))        {
03436                                 $str = base64_decode($str);
03437                                 $str = $this->roundTripCryptString($str);
03438                                 return $str;
03439                         } else return FALSE;    // Decoding check failed! Original string not produced by this server!
03440                 } else {
03441                         $str = $string;
03442                         $str = $this->roundTripCryptString($str);
03443                         $str = base64_encode($str);
03444                         $newHash = substr(md5($this->TYPO3_CONF_VARS['SYS']['encryptionKey'].':'.$str),0,10);
03445                         return $newHash.':'.$str;
03446                 }
03447         }
03448 
03456         function roundTripCryptString($string)  {
03457                 $out = '';
03458                 $strLen = strlen($string);
03459                 $cryptLen = strlen($this->TYPO3_CONF_VARS['SYS']['encryptionKey']);
03460 
03461                 for ($a=0; $a < $strLen; $a++)  {
03462                         $xorVal = $cryptLen>0 ? ord($this->TYPO3_CONF_VARS['SYS']['encryptionKey']{($a%$cryptLen)}) : 255;
03463                         $out.= chr(ord($string{$a}) ^ $xorVal);
03464                 }
03465 
03466                 return $out;
03467         }
03468 
03476         function checkFileInclude($incFile)     {
03477                 return !$this->TYPO3_CONF_VARS['FE']['noPHPscriptInclude']
03478                         || substr($incFile,0,14)=='media/scripts/'
03479                         || substr($incFile,0,4+strlen(TYPO3_mainDir))==TYPO3_mainDir.'ext/'
03480                         || substr($incFile,0,7+strlen(TYPO3_mainDir))==TYPO3_mainDir.'sysext/'
03481                         || substr($incFile,0,14)=='typo3conf/ext/';
03482         }
03483 
03491         function newCObj()      {
03492                 $this->cObj =t3lib_div::makeInstance('tslib_cObj');
03493                 $this->cObj->start($this->page,'pages');
03494         }
03495 
03504         function setAbsRefPrefix()      {
03505                 if ($this->absRefPrefix)        {
03506                         $this->content = str_replace('"media/', '"'.t3lib_extMgm::siteRelPath('cms').'tslib/media/', $this->content);
03507                         $this->content = str_replace('"fileadmin/', '"'.$this->absRefPrefix.'fileadmin/', $this->content);
03508                 }
03509         }
03510 
03518         function baseUrlWrap($url)      {
03519                 if ($this->baseUrl)     {
03520                         $urlParts = parse_url($url);
03521                         if (!strlen($urlParts['scheme']) && $url{0}!=='/')      {
03522                                 $url = $this->baseUrl.$url;
03523                         }
03524                 }
03525                 return $url;
03526         }
03527 
03537         function printError($label,$header='Error!')    {
03538                 t3lib_timeTrack::debug_typo3PrintError($header,$label,0,t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
03539         }
03540 
03548         function updateMD5paramsRecord($hash)   {
03549                 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_md5params'), array('tstamp' => time()));
03550         }
03551 
03559         function tidyHTML($content)             {
03560                 if ($this->TYPO3_CONF_VARS['FE']['tidy'] && $this->TYPO3_CONF_VARS['FE']['tidy_path'])  {
03561                         $oldContent = $content;
03562                         $fname = t3lib_div::tempnam('typo3_tidydoc_');          // Create temporary name
03563                         @unlink ($fname);       // Delete if exists, just to be safe.
03564                         $fp = fopen ($fname,'wb');      // Open for writing
03565                         fputs ($fp, $content);  // Put $content
03566                         @fclose ($fp);  // Close
03567 
03568                         exec ($this->TYPO3_CONF_VARS['FE']['tidy_path'].' '.$fname, $output);                   // run the $content through 'tidy', which formats the HTML to nice code.
03569                         @unlink ($fname);       // Delete the tempfile again
03570                         $content = implode(chr(10),$output);
03571                         if (!trim($content))    {
03572                                 $content = $oldContent; // Restore old content due empty return value.
03573                                 $GLOBALS['TT']->setTSlogMessage('"tidy" returned an empty value!',2);
03574                         }
03575                         $GLOBALS['TT']->setTSlogMessage('"tidy" content lenght: '.strlen($content),0);
03576                 }
03577                 return $content;
03578         }
03579 
03585         function prefixLocalAnchorsWithScript() {
03586                 $scriptPath = substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
03587                 $this->content = preg_replace('/(<(a|area).*?href=")(#[^"]*")/i','$1' . htmlspecialchars($scriptPath) . '$3',$this->content);
03588         }
03589 
03595         function workspacePreviewInit() {
03596                 $previewWS = t3lib_div::_GP('ADMCMD_previewWS');
03597                 if ($this->beUserLogin && is_object($GLOBALS['BE_USER']) && t3lib_div::testInt($previewWS))     {
03598                         if ($previewWS>=-1 && ($previewWS==0 || $GLOBALS['BE_USER']->checkWorkspace($previewWS)))       {       // Check Access to workspace. Live (0) is OK to preview for all.
03599                                 $this->workspacePreview = intval($previewWS);
03600                         } else {
03601                                 $this->workspacePreview = -99;  // No preview, will default to "Live" at the moment
03602                         }
03603                 }
03604         }
03605 
03611         function doWorkspacePreview()   {
03612                 return (string)$this->workspacePreview!=='';
03613         }
03614 
03621         function whichWorkspace($returnTitle = FALSE)   {
03622                 if ($this->doWorkspacePreview())        {
03623                         $ws = intval($this->workspacePreview);
03624                 } elseif ($this->beUserLogin) {
03625                         $ws = $GLOBALS['BE_USER']->workspace;
03626                 } else return FALSE;
03627 
03628                 if ($returnTitle)       {
03629                         if ($ws===-1)   {
03630                                 return 'Default Draft Workspace';
03631                         } else {
03632                                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('title', 'sys_workspace', 'uid='.intval($ws));
03633                                 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
03634                                         return $row['title'];
03635                                 }
03636                         }
03637                 } else {
03638                         return $ws;
03639                 }
03640         }
03641 
03642 
03643 
03644 
03645 
03646 
03647 
03648 
03649 
03650 
03651 
03652 
03653 
03654 
03655 
03656 
03657 
03658 
03659 
03660 
03661 
03662 
03663 
03664 
03665 
03666 
03667         /********************************************
03668          *
03669          * Various external API functions - for use in plugins etc.
03670          *
03671          *******************************************/
03672 
03673 
03679         function getStorageSiterootPids()       {
03680                 $res=array();
03681                 reset($this->rootLine);
03682                 while(list(,$rC)=each($this->rootLine)) {
03683                         if (!$res['_STORAGE_PID'])      $res['_STORAGE_PID']=intval($rC['storage_pid']);
03684                         if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
03685                 }
03686                 return $res;
03687         }
03688 
03694         function getPagesTSconfig()     {
03695                 if (!is_array($this->pagesTSconfig))    {
03696                         reset($this->rootLine);
03697                         $TSdataArray = array();
03698                         $TSdataArray[] = $this->TYPO3_CONF_VARS['BE']['defaultPageTSconfig'];   // Setting default configuration:
03699                         while(list($k,$v)=each($this->rootLine))        {
03700                                 $TSdataArray[]=$v['TSconfig'];
03701                         }
03702                                 // Parsing the user TS (or getting from cache)
03703                         $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
03704                         $userTS = implode(chr(10).'[GLOBAL]'.chr(10),$TSdataArray);
03705                         $hash = md5('pageTS:'.$userTS);
03706                         $cachedContent = $this->sys_page->getHash($hash,0);
03707                         if (isset($cachedContent))      {
03708                                 $this->pagesTSconfig = unserialize($cachedContent);
03709                         } else {
03710                                 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
03711                                 $parseObj->parse($userTS);
03712                                 $this->pagesTSconfig = $parseObj->setup;
03713                                 $this->sys_page->storeHash($hash,serialize($this->pagesTSconfig),'PAGES_TSconfig');
03714                         }
03715                 }
03716                 return $this->pagesTSconfig;
03717         }
03718 
03727         function setJS($key,$content='')        {
03728                 if ($key)       {
03729                         switch($key)    {
03730                                 case 'mouseOver':
03731                                         $this->additionalJavaScript[$key]=
03732 '               // JS function for mouse-over
03733         function over(name,imgObj)      {       //
03734                 if (version == "n3" && document[name]) {document[name].src = eval(name+"_h.src");}
03735                 else if (typeof(document.getElementById)=="function" && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_h.src");}
03736                 else if (imgObj)        {imgObj.src = eval(name+"_h.src");}
03737         }
03738                 // JS function for mouse-out
03739         function out(name,imgObj)       {       //
03740                 if (version == "n3" && document[name]) {document[name].src = eval(name+"_n.src");}
03741                 else if (typeof(document.getElementById)=="function" && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_n.src");}
03742                 else if (imgObj)        {imgObj.src = eval(name+"_n.src");}
03743         }';
03744                                 break;
03745                                 case 'openPic':
03746                                         $this->additionalJavaScript[$key]=
03747 '       function openPic(url,winName,winParams) {       //
03748                 var theWindow = window.open(url,winName,winParams);
03749                 if (theWindow)  {theWindow.focus();}
03750         }';
03751                                 break;
03752                                 default:
03753                                         $this->additionalJavaScript[$key]=$content;
03754                                 break;
03755                         }
03756                 }
03757         }
03758 
03767         function setCSS($key,$content)  {
03768                 if ($key)       {
03769                         switch($key)    {
03770                                 default:
03771                                         $this->additionalCSS[$key]=$content;
03772                                 break;
03773                         }
03774                 }
03775         }
03776 
03782         function make_seed() {
03783                 list($usec, $sec) = explode(' ', microtime());
03784                 $seedV = (float)$sec + ((float)$usec * 100000);
03785                 srand($seedV);
03786         }
03787 
03795         function uniqueHash($str='')    {
03796                 return md5($this->uniqueString.'_'.$str.$this->uniqueCounter++);
03797         }
03798 
03804         function set_no_cache() {
03805                 $this->no_cache = 1;
03806         }
03807 
03814         function set_cache_timeout_default($seconds)    {
03815                 $this->cacheTimeOutDefault = intval($seconds);
03816         }
03817 
03830         function plainMailEncoded($email,$subject,$message,$headers='') {
03831                 $urlmode=$this->config['config']['notification_email_urlmode']; // '76', 'all', ''
03832 
03833                 if ($urlmode)   {
03834                         $message=t3lib_div::substUrlsInPlainText($message,$urlmode);
03835                 }
03836 
03837                 $encoding = $this->config['config']['notification_email_encoding'] ? $this->config['config']['notification_email_encoding'] : 'quoted-printable';
03838                 $charset = $this->config['config']['notification_email_charset'] ? $this->config['config']['notification_email_charset'] : ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1');
03839 
03840                 t3lib_div::plainMailEncoded(
03841                         $email,
03842                         $subject,
03843                         $message,
03844                         $headers,
03845                         $encoding,
03846                         $charset
03847                 );
03848         }
03849 
03850 
03851 
03852 
03853 
03854 
03855 
03856 
03857 
03858 
03859 
03860 
03861 
03862         /*********************************************
03863          *
03864          * Localization and character set conversion
03865          *
03866          *********************************************/
03867 
03874         function sL($input)     {
03875                 if (strcmp(substr($input,0,4),'LLL:'))  {
03876                         $t = explode('|',$input);
03877                         return $t[$this->langSplitIndex] ? $t[$this->langSplitIndex] : $t[0];
03878                 } else {
03879                         if (!isset($this->LL_labels_cache[$this->lang][$input])) {      // If cached label
03880                                 $restStr = trim(substr($input,4));
03881                                 $extPrfx='';
03882                                 if (!strcmp(substr($restStr,0,4),'EXT:'))       {
03883                                         $restStr = trim(substr($restStr,4));
03884                                         $extPrfx='EXT:';
03885                                 }
03886                                 $parts = explode(':',$restStr);
03887                                 $parts[0]=$extPrfx.$parts[0];
03888                                 if (!isset($this->LL_files_cache[$parts[0]]))   {       // Getting data if not cached
03889                                         $this->LL_files_cache[$parts[0]] = $this->readLLfile($parts[0]);
03890                                 }
03891                                 $this->LL_labels_cache[$this->lang][$input] = $this->csConv($this->getLLL($parts[1],$this->LL_files_cache[$parts[0]]));
03892                         }
03893                         return $this->LL_labels_cache[$this->lang][$input];
03894                 }
03895         }
03896 
03903         function readLLfile($fileRef)   {
03904                 return t3lib_div::readLLfile($fileRef,$this->lang);
03905         }
03906 
03914         function getLLL($index,$LOCAL_LANG)     {
03915                 if (strcmp($LOCAL_LANG[$this->lang][$index],''))        {
03916                         return $LOCAL_LANG[$this->lang][$index];
03917                 } else {
03918                         return $LOCAL_LANG['default'][$index];
03919                 }
03920         }
03921 
03928         function initLLvars()   {
03929 
03930                         // Setting language key and split index:
03931                 $this->lang = $this->config['config']['language'] ? $this->config['config']['language'] : 'default';
03932 
03933                 $ls = explode('|',TYPO3_languages);
03934                 while(list($i,$v)=each($ls))    {
03935                         if ($v==$this->lang)    {$this->langSplitIndex=$i; break;}
03936                 }
03937 
03938                         // Setting charsets:
03939                 $this->renderCharset = $this->csConvObj->parse_charset($this->config['config']['renderCharset'] ? $this->config['config']['renderCharset'] : ($this->TYPO3_CONF_VARS['BE']['forceCharset'] ? $this->TYPO3_CONF_VARS['BE']['forceCharset'] : $this->defaultCharSet));    // Rendering charset of HTML page.
03940                 $this->metaCharset = $this->csConvObj->parse_charset($this->config['config']['metaCharset'] ? $this->config['config']['metaCharset'] : $this->renderCharset);   // Output charset of HTML page.
03941                 $this->labelsCharset = $this->csConvObj->parse_charset($this->csConvObj->charSetArray[$this->lang] ? $this->csConvObj->charSetArray[$this->lang] : 'iso-8859-1');
03942                 if ($this->renderCharset != $this->labelsCharset)       {
03943                         $this->convCharsetToFrom = array(
03944                                 'from' => $this->labelsCharset,
03945                                 'to' => $this->renderCharset
03946                         );
03947                 }
03948         }
03949 
03962         function csConv($str,$from='')  {
03963                 if ($from)      {
03964                         $output = $this->csConvObj->conv($str,$this->csConvObj->parse_charset($from),$this->renderCharset,1);
03965                         return $output ? $output : $str;
03966                 } elseif (is_array($this->convCharsetToFrom))   {
03967                         return $this->csConvObj->conv($str,$this->convCharsetToFrom['from'],$this->convCharsetToFrom['to'],1);
03968                 } else {
03969                         return $str;
03970                 }
03971         }
03972 
03980         function convOutputCharset($content,$label='')  {
03981                 if ($this->renderCharset != $this->metaCharset) {
03982                         $content = $this->csConvObj->conv($content,$this->renderCharset,$this->metaCharset,TRUE);
03983                 }
03984 
03985                 return $content;
03986         }
03987 
03993         function convPOSTCharset()      {
03994                 if ($this->renderCharset != $this->metaCharset && is_array($_POST) && count($_POST))    {
03995                         $this->csConvObj->convArray($_POST,$this->metaCharset,$this->renderCharset);
03996                         $GLOBALS['HTTP_POST_VARS'] = $_POST;
03997                 }
03998         }
03999 }
04000 
04001 
04002 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php'])        {
04003         include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php']);
04004 }
04005 ?>