PageRenderTime 69ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/typo3/sysext/cms/tslib/class.tslib_fe.php

https://bitbucket.org/linxpinx/mercurial
PHP | 4842 lines | 2699 code | 633 blank | 1510 comment | 608 complexity | ead83ebf7bf2a0da8f2109371dd3e7a8 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Unlicense, LGPL-2.1, Apache-2.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
  6. * All rights reserved
  7. *
  8. * This script is part of the TYPO3 project. The TYPO3 project is
  9. * free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * The GNU General Public License can be found at
  15. * http://www.gnu.org/copyleft/gpl.html.
  16. * A copy is found in the textfile GPL.txt and important notices to the license
  17. * from the author is found in LICENSE.txt distributed with these scripts.
  18. *
  19. *
  20. * This script is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * This copyright notice MUST APPEAR in all copies of the script!
  26. ***************************************************************/
  27. /**
  28. * Class for the built TypoScript based Front End
  29. *
  30. * This class has a lot of functions and internal variable which are use from index_ts.php.
  31. * The class is instantiated as $GLOBALS['TSFE'] in index_ts.php.
  32. * The use of this class should be inspired by the order of function calls as found in index_ts.php.
  33. *
  34. * $Id: class.tslib_fe.php 8429 2010-07-28 09:19:00Z ohader $
  35. * Revised for TYPO3 3.6 June/2003 by Kasper Skaarhoj
  36. * XHTML compliant
  37. *
  38. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  39. */
  40. /**
  41. * [CLASS/FUNCTION INDEX of SCRIPT]
  42. *
  43. *
  44. *
  45. * 213: class tslib_fe
  46. * 382: function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='')
  47. * 415: function connectToMySQL()
  48. * 425: function connectToDB()
  49. * 470: function sendRedirect()
  50. *
  51. * SECTION: Initializing, resolving page id
  52. * 508: function initFEuser()
  53. * 558: function initUserGroups()
  54. * 593: function isUserOrGroupSet()
  55. * 618: function checkAlternativeIdMethods()
  56. * 670: function clear_preview()
  57. * 683: function determineId()
  58. * 817: function fetch_the_id()
  59. * 911: function getPageAndRootline()
  60. * 994: function getPageShortcut($SC,$mode,$thisUid,$itera=20,$pageLog=array())
  61. * 1044: function checkRootlineForIncludeSection()
  62. * 1081: function checkEnableFields($row,$bypassGroupCheck=FALSE)
  63. * 1097: function checkPageGroupAccess($row, $groupList=NULL)
  64. * 1116: function checkPagerecordForIncludeSection($row)
  65. * 1125: function checkIfLoginAllowedInBranch()
  66. * 1150: function getPageAccessFailureReasons()
  67. * 1182: function setIDfromArgV()
  68. * 1198: function getPageAndRootlineWithDomain($domainStartPage)
  69. * 1225: function setSysPageWhereClause()
  70. * 1237: function findDomainRecord($recursive=0)
  71. * 1257: function pageNotFoundAndExit($reason='', $header='')
  72. * 1272: function pageNotFoundHandler($code, $header='', $reason='')
  73. * 1316: function checkAndSetAlias()
  74. * 1335: function idPartsAnalyze($str)
  75. * 1360: function mergingWithGetVars($GET_VARS)
  76. * 1390: function ADMCMD_preview()
  77. * 1433: function ADMCMD_preview_postInit($previewConfig)
  78. *
  79. * SECTION: Template and caching related functions.
  80. * 1465: function makeCacheHash()
  81. * 1489: function reqCHash()
  82. * 1511: function cHashParams($addQueryParams)
  83. * 1520: function initTemplate()
  84. * 1532: function getFromCache()
  85. * 1578: function getFromCache_queryRow()
  86. * 1608: function headerNoCache()
  87. * 1637: function getHash()
  88. * 1657: function getConfigArray()
  89. *
  90. * SECTION: Further initialization and data processing
  91. * 1818: function getCompressedTCarray()
  92. * 1872: function includeTCA($TCAloaded=1)
  93. * 1899: function settingLanguage()
  94. * 1992: function settingLocale()
  95. * 2017: function checkDataSubmission()
  96. * 2050: function fe_tce()
  97. * 2064: function locDataCheck($locationData)
  98. * 2080: function sendFormmail()
  99. * 2131: function extractRecipientCopy($bodytext)
  100. * 2145: function setExternalJumpUrl()
  101. * 2156: function checkJumpUrlReferer()
  102. * 2171: function jumpUrl()
  103. * 2215: function setUrlIdToken()
  104. *
  105. * SECTION: Page generation; cache handling
  106. * 2258: function isGeneratePage()
  107. * 2268: function tempPageCacheContent()
  108. * 2325: function realPageCacheContent()
  109. * 2355: function setPageCacheContent($content,$data,$tstamp)
  110. * 2382: function clearPageCacheContent()
  111. * 2392: function clearPageCacheContent_pidList($pidList)
  112. * 2426: function setSysLastChanged()
  113. *
  114. * SECTION: Page generation; rendering and inclusion
  115. * 2462: function generatePage_preProcessing()
  116. * 2484: function generatePage_whichScript()
  117. * 2496: function generatePage_postProcessing()
  118. * 2588: function INTincScript()
  119. * 2648: function INTincScript_loadJSCode()
  120. * 2689: function isINTincScript()
  121. * 2698: function doXHTML_cleaning()
  122. * 2707: function doLocalAnchorFix()
  123. *
  124. * SECTION: Finished off; outputting, storing session data, statistics...
  125. * 2738: function isOutputting()
  126. * 2761: function processOutput()
  127. * 2834: function sendCacheHeaders()
  128. * 2902: function isStaticCacheble()
  129. * 2915: function contentStrReplace()
  130. * 2941: function isEXTincScript()
  131. * 2950: function storeSessionData()
  132. * 2960: function setParseTime()
  133. * 2972: function statistics()
  134. * 3066: function previewInfo()
  135. * 3101: function hook_eofe()
  136. * 3117: function beLoginLinkIPList()
  137. * 3138: function addTempContentHttpHeaders()
  138. *
  139. * SECTION: Various internal API functions
  140. * 3184: function makeSimulFileName($inTitle,$page,$type,$addParams='',$no_cache='')
  141. * 3231: function simulateStaticDocuments_pEnc_onlyP_proc($linkVars)
  142. * 3260: function getSimulFileName()
  143. * 3271: function setSimulReplacementChar()
  144. * 3291: function fileNameASCIIPrefix($inTitle,$titleChars,$mergeChar='.')
  145. * 3314: function encryptEmail($string,$back=0)
  146. * 3340: function codeString($string, $decode=FALSE)
  147. * 3366: function roundTripCryptString($string)
  148. * 3386: function checkFileInclude($incFile)
  149. * 3401: function newCObj()
  150. * 3414: function setAbsRefPrefix()
  151. * 3428: function baseUrlWrap($url)
  152. * 3447: function printError($label,$header='Error!')
  153. * 3458: function updateMD5paramsRecord($hash)
  154. * 3469: function tidyHTML($content)
  155. * 3495: function prefixLocalAnchorsWithScript()
  156. * 3505: function workspacePreviewInit()
  157. * 3521: function doWorkspacePreview()
  158. * 3531: function whichWorkspace($returnTitle = FALSE)
  159. *
  160. * SECTION: Various external API functions - for use in plugins etc.
  161. * 3589: function getStorageSiterootPids()
  162. * 3604: function getPagesTSconfig()
  163. * 3637: function setJS($key,$content='')
  164. * 3677: function setCSS($key,$content)
  165. * 3692: function make_seed()
  166. * 3705: function uniqueHash($str='')
  167. * 3714: function set_no_cache()
  168. * 3724: function set_cache_timeout_default($seconds)
  169. * 3740: function plainMailEncoded($email,$subject,$message,$headers='')
  170. *
  171. * SECTION: Localization and character set conversion
  172. * 3784: function sL($input)
  173. * 3813: function readLLfile($fileRef)
  174. * 3824: function getLLL($index,$LOCAL_LANG)
  175. * 3838: function initLLvars()
  176. * 3872: function csConv($str,$from='')
  177. * 3890: function convOutputCharset($content,$label='')
  178. * 3903: function convPOSTCharset()
  179. *
  180. * TOTAL FUNCTIONS: 116
  181. * (This index is automatically created/updated by the extension "extdeveval")
  182. *
  183. */
  184. /**
  185. * Main frontend class, instantiated in the index_ts.php script as the global object TSFE
  186. *
  187. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  188. * @package TYPO3
  189. * @subpackage tslib
  190. */
  191. class tslib_fe {
  192. // CURRENT PAGE:
  193. var $id=''; // The page id (int)
  194. var $type=''; // RO The type (int)
  195. var $idParts=array(); // Loaded with the id, exploded by ','
  196. var $cHash=''; // The submitted cHash
  197. var $no_cache=''; // Page will not be cached. Write only true. Never clear value (some other code might have reasons to set it true)
  198. var $rootLine=''; // The rootLine (all the way to tree root, not only the current site!) (array)
  199. var $page=''; // The pagerecord (array)
  200. 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.
  201. protected $originalShortcutPage = null; // gets set when we are processing a page of type shortcut in the early stages opf init.php when we do not know about languages yet, used later in init.php to determine the correct shortcut in case a translation changes the shortcut target (array)
  202. /**
  203. * sys_page-object, pagefunctions
  204. *
  205. * @var t3lib_pageSelect
  206. */
  207. var $sys_page='';
  208. var $jumpurl='';
  209. var $pageNotFound=0; // Is set to 1 if a pageNotFound handler could have been called.
  210. var $domainStartPage=0; // Domain start page
  211. var $pageAccessFailureHistory=array(); // Array containing a history of why a requested page was not accessible.
  212. var $MP='';
  213. var $RDCT='';
  214. 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...
  215. 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.
  216. // USER
  217. /**
  218. * The FE user
  219. *
  220. * @var tslib_feUserAuth
  221. */
  222. var $fe_user='';
  223. var $loginUser=''; // Global flag indicating that a front-end user is logged in. This is set only if a user really IS logged in. The group-list may show other groups (like added by IP filter or so) even though there is no user.
  224. var $gr_list=''; // (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default group, but other groups may be added by other means than a user being logged in though...
  225. var $beUserLogin=''; // Flag that indicates if a Backend user is logged in!
  226. var $workspacePreview=''; // Integer, that indicates which workspace is being previewed.
  227. var $loginAllowedInBranch = TRUE; // Shows whether logins are allowed in branch
  228. var $loginAllowedInBranch_mode = ''; // Shows specific mode (all or groups)
  229. var $ADMCMD_preview_BEUSER_uid = 0; // Integer, set to backend user ID to initialize when keyword-based preview is used.
  230. // PREVIEW
  231. 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
  232. var $showHiddenPage=''; // Flag indicating that hidden pages should be shown, selected and so on. This goes for almost all selection of pages!
  233. 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.
  234. var $simUserGroup='0'; // Value that contains the simulated usergroup if any
  235. // CONFIGURATION
  236. 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.
  237. var $config=''; // "CONFIG" object from TypoScript. Array generated based on the TypoScript configuration of the current page. Saved with the cached pages.
  238. var $TCAcachedExtras=array(); // Array of cached information from TCA. This is NOT TCA itself!
  239. // TEMPLATE / CACHE
  240. /**
  241. * The TypoScript template object. Used to parse the TypoScript template
  242. *
  243. * @var t3lib_TStemplate
  244. */
  245. var $tmpl='';
  246. var $cacheTimeOutDefault=''; // Is set to the time-to-live time of cached pages. If false, default is 60*60*24, which is 24 hours.
  247. var $cacheContentFlag = 0; // Set internally if cached content is fetched from the database
  248. var $cacheExpires=0; // Set to the expire time of cached content
  249. var $isClientCachable=FALSE; // Set if cache headers allowing caching are sent.
  250. 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.
  251. var $sPre=''; // toplevel - objArrayName, eg 'page'
  252. var $pSetup=''; // TypoScript configuration of the page-object pointed to by sPre. $this->tmpl->setup[$this->sPre.'.']
  253. 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
  254. 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
  255. 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.
  256. var $tempContent = FALSE; // This flag indicates if temporary content went into the cache during page-generation.
  257. var $forceTemplateParsing=''; // Boolean, passed to TypoScript template class and tells it to render the template forcibly
  258. var $cHash_array=array(); // The array which cHash_calc is based on, see ->makeCacheHash().
  259. var $hash_base=''; // Loaded with the serialized array that is used for generating a hashstring for the cache
  260. var $pagesTSconfig=''; // May be set to the pagesTSconfig
  261. // PAGE-GENERATION / cOBJ
  262. /*
  263. Eg. insert JS-functions in this array ($additionalHeaderData) to include them once. Use associative keys.
  264. Keys in use:
  265. JSFormValidate : <script type="text/javascript" src="'.$GLOBALS["TSFE"]->absRefPrefix.'t3lib/jsfunc.validateform.js"></script>
  266. JSincludeFormupdate : <script type="text/javascript" src="t3lib/jsfunc.updateform.js"></script>
  267. JSMenuCode, JSMenuCode_menu : JavaScript for the JavaScript menu
  268. JSCode : reserved
  269. JSImgCode : reserved
  270. */
  271. var $additionalHeaderData=array(); // used to accumulate additional HTML-code for the header-section, <head>...</head>. Insert either associative keys (like additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys (like additionalHeaderData[] = '...')
  272. var $additionalJavaScript=array(); // used to accumulate additional JavaScript-code. Works like additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
  273. var $additionalCSS=array(); // used to accumulate additional Style code. Works like additionalHeaderData.
  274. var $JSeventFuncCalls = array( // you can add JavaScript functions to each entry in these arrays. Please see how this is done in the GMENU_LAYERS script. The point is that many applications on a page can set handlers for onload, onmouseover and onmouseup
  275. 'onmousemove' => array(),
  276. 'onmouseup' => array(),
  277. 'onmousemove' => array(),
  278. 'onkeydown' => array(),
  279. 'onkeyup' => array(),
  280. 'onkeypress' => array(),
  281. 'onload' => array(),
  282. 'onunload' => array(),
  283. );
  284. /**
  285. * Adds JavaScript code
  286. *
  287. * @var string
  288. * @deprecated since TYPO3 3.5 - use additionalJavaScript instead.
  289. */
  290. var $JSCode='';
  291. var $JSImgCode=''; // Used to accumulate JavaScript loaded images (by menus)
  292. var $divSection=''; // Used to accumulate DHTML-layers.
  293. var $defaultBodyTag='<body>'; // Default bodytag, if nothing else is set. This can be overridden by applications like TemplaVoila.
  294. // RENDERING configuration, settings from TypoScript is loaded into these vars. See pagegen.php
  295. var $debug=''; // Debug flag, may output special debug html-code.
  296. var $intTarget=''; // Default internal target
  297. var $extTarget=''; // Default external target
  298. var $fileTarget=''; // Default file link target
  299. var $MP_defaults=array(); // Keys are page ids and values are default &MP (mount point) values to set when using the linking features...)
  300. var $spamProtectEmailAddresses=0; // If set, typolink() function encrypts email addresses. Is set in pagegen-class.
  301. var $absRefPrefix=''; // Absolute Reference prefix
  302. 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 '/'
  303. var $compensateFieldWidth=''; // Factor for form-field widths compensation
  304. var $lockFilePath=''; // Lock file path
  305. var $ATagParams=''; // <A>-tag parameters
  306. 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.
  307. var $sWordList=''; // Is set to the incoming array sword_list in case of a page-view jumped to from a search-result.
  308. 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.
  309. 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.
  310. 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.
  311. 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.
  312. 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)
  313. var $sys_language_mode=''; // Site language mode for content fall back.
  314. 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)
  315. 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...]
  316. 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")
  317. // RENDERING data
  318. var $applicationData=Array(); // 'Global' Storage for various applications. Keys should be 'tx_'.extKey for extensions.
  319. var $register=Array();
  320. var $registerStack=Array(); // Stack used for storing array and retrieving register arrays (see LOAD_REGISTER and CLEAR_REGISTER)
  321. var $cObjectDepthCounter = 50; // Checking that the function is not called eternally. This is done by interrupting at a depth of 50
  322. var $recordRegister = Array(); // used by cObj->RECORDS and cObj->CONTENT to ensure the a records is NOT rendered twice through it!
  323. 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
  324. var $accessKey =array(); // Used by class tslib_menu to keep track of access-keys.
  325. 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.
  326. 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
  327. 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()
  328. var $uniqueString='';
  329. var $indexedDocTitle=''; // This value will be used as the title for the page in the indexer (if indexing happens)
  330. var $altPageTitle=''; // Alternative page title (normally the title of the page record). Can be set from applications you make.
  331. /**
  332. * An array that holds parameter names (keys) of GET parameters which MAY be MD5/base64 encoded with simulate_static_documents method.
  333. * @var array
  334. * @deprecated since TYPO3 4.3, remove in TYPO3 4.5
  335. */
  336. var $pEncAllowedParamNames=array();
  337. var $baseUrl=''; // The base URL set for the page header.
  338. var $anchorPrefix=''; // The proper anchor prefix needed when using speaking urls. (only set if baseUrl is set)
  339. /**
  340. * Page content render object
  341. *
  342. * @var tslib_cObj
  343. */
  344. var $cObj ='';
  345. // CONTENT accumulation
  346. var $content=''; // All page content is accumulated in this variable. See pagegen.php
  347. // GENERAL
  348. var $clientInfo=''; // Set to the browser: net / msie if 4+ browsers
  349. var $scriptParseTime=0;
  350. var $TCAloaded = 0; // Set ONLY if the full TCA is loaded
  351. // Character set (charset) conversion object:
  352. /**
  353. * charset conversion class. May be used by any application.
  354. *
  355. * @var t3lib_cs
  356. */
  357. var $csConvObj;
  358. var $defaultCharSet = 'iso-8859-1'; // The default charset used in the frontend if nothing else is set.
  359. var $renderCharset=''; // Internal charset of the frontend during rendering: Defaults to "forceCharset" and if that is not set, to ->defaultCharSet
  360. 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.
  361. var $localeCharset=''; // Assumed charset of locale strings.
  362. // LANG:
  363. var $lang=''; // Set to the system language key (used on the site)
  364. var $langSplitIndex=0; // Set to the index number of the language key
  365. var $LL_labels_cache=array();
  366. var $LL_files_cache=array();
  367. /**
  368. * Locking object
  369. *
  370. * @var t3lib_lock
  371. */
  372. var $pagesection_lockObj; // Locking object for accessing "cache_pagesection"
  373. /**
  374. * Locking object
  375. *
  376. * @var t3lib_lock
  377. */
  378. var $pages_lockObj; // Locking object for accessing "cache_pages"
  379. /**
  380. * @var t3lib_PageRenderer
  381. */
  382. protected $pageRenderer;
  383. /**
  384. * the page cache object, use this to save pages to the cache and to
  385. * retrieve them again
  386. *
  387. * @var t3lib_cache_AbstractBackend
  388. */
  389. protected $pageCache;
  390. protected $pageCacheTags = array();
  391. /**
  392. * Class constructor
  393. * Takes a number of GET/POST input variable as arguments and stores them internally.
  394. * The processing of these variables goes on later in this class.
  395. * Also sets internal clientInfo array (browser information) and a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
  396. *
  397. * @param array The global $TYPO3_CONF_VARS array. Will be set internally in ->TYPO3_CONF_VARS
  398. * @param mixed The value of t3lib_div::_GP('id')
  399. * @param integer The value of t3lib_div::_GP('type')
  400. * @param boolean The value of t3lib_div::_GP('no_cache'), evaluated to 1/0
  401. * @param string The value of t3lib_div::_GP('cHash')
  402. * @param string The value of t3lib_div::_GP('jumpurl')
  403. * @param string The value of t3lib_div::_GP('MP')
  404. * @param string The value of t3lib_div::_GP('RDCT')
  405. * @return void
  406. * @see index_ts.php
  407. */
  408. function tslib_fe($TYPO3_CONF_VARS, $id, $type, $no_cache='', $cHash='', $jumpurl='',$MP='',$RDCT='') {
  409. // Setting some variables:
  410. $this->TYPO3_CONF_VARS = $TYPO3_CONF_VARS;
  411. $this->id = $id;
  412. $this->type = $type;
  413. if ($no_cache) {
  414. if ($this->TYPO3_CONF_VARS['FE']['disableNoCacheParameter']) {
  415. $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
  416. $GLOBALS['TT']->setTSlogMessage($warning,2);
  417. } else {
  418. $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "'.t3lib_div::getIndpEnv('TYPO3_REQUEST_URL').'"';
  419. $this->disableCache();
  420. }
  421. t3lib_div::sysLog($warning, 'cms', 2);
  422. }
  423. $this->cHash = $cHash;
  424. $this->jumpurl = $jumpurl;
  425. $this->MP = $this->TYPO3_CONF_VARS['FE']['enable_mount_pids'] ? (string)$MP : '';
  426. $this->RDCT = $RDCT;
  427. $this->clientInfo = t3lib_div::clientInfo();
  428. $this->uniqueString=md5(microtime());
  429. $this->csConvObj = t3lib_div::makeInstance('t3lib_cs');
  430. // Call post processing function for constructor:
  431. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'])) {
  432. $_params = array('pObj' => &$this);
  433. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] as $_funcRef) {
  434. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  435. }
  436. }
  437. if (TYPO3_UseCachingFramework) {
  438. $this->initCaches();
  439. }
  440. }
  441. /**
  442. * Connect to MySQL database
  443. * May exit after outputting an error message or some JavaScript redirecting to the install tool.
  444. *
  445. * @return void
  446. * @deprecated since TYPO3 3.8, this function will be removed in TYPO3 4.5, use connectToDB() instead!
  447. */
  448. function connectToMySQL() {
  449. t3lib_div::logDeprecatedFunction();
  450. $this->connectToDB();
  451. }
  452. /**
  453. * Connect to SQL database
  454. * May exit after outputting an error message or some JavaScript redirecting to the install tool.
  455. *
  456. * @return void
  457. */
  458. function connectToDB() {
  459. try {
  460. $link = $GLOBALS['TYPO3_DB']->sql_pconnect(TYPO3_db_host, TYPO3_db_username, TYPO3_db_password);
  461. } catch (RuntimeException $e) {
  462. if (TYPO3_db) {
  463. // Database is defined, this should normally not happen, user should be informed
  464. throw $e;
  465. }
  466. $link = FALSE;
  467. }
  468. if ($link !== FALSE) {
  469. if (!TYPO3_db) {
  470. $this->printError('No database selected','Database Error');
  471. // Redirects to the Install Tool:
  472. echo '<script type="text/javascript">
  473. /*<![CDATA[*/
  474. window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
  475. /*]]>*/
  476. </script>';
  477. exit;
  478. } elseif (!$GLOBALS['TYPO3_DB']->sql_select_db(TYPO3_db)) {
  479. if ($this->checkPageUnavailableHandler()) {
  480. $this->pageUnavailableAndExit('Cannot connect to the current database, "'.TYPO3_db.'"');
  481. } else {
  482. $message = 'Cannot connect to the current database, "'.TYPO3_db.'"';
  483. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  484. header('HTTP/1.0 503 Service Temporarily Unavailable');
  485. $this->printError($message, 'Database Error');
  486. exit;
  487. }
  488. }
  489. } else {
  490. if (!TYPO3_db) {
  491. // Redirects to the Install Tool:
  492. echo '<script type="text/javascript">
  493. /*<![CDATA[*/
  494. window.location.href = "'.TYPO3_mainDir.'install/index.php?mode=123&step=1&password=joh316";
  495. /*]]>*/
  496. </script>';
  497. exit;
  498. }
  499. if ($this->checkPageUnavailableHandler()) {
  500. $this->pageUnavailableAndExit('The current username, password or host was not accepted when the connection to the database was attempted to be established!');
  501. } else {
  502. $message = 'The current username, password or host was not accepted when the connection to the database was attempted to be established!';
  503. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  504. header('HTTP/1.0 503 Service Temporarily Unavailable');
  505. $this->printError($message, 'Database Error');
  506. exit;
  507. }
  508. }
  509. // Call post processing function for DB connection:
  510. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'])) {
  511. $_params = array('pObj' => &$this);
  512. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] as $_funcRef) {
  513. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  514. }
  515. }
  516. }
  517. /**
  518. * Looks up the value of $this->RDCT in the database and if it is found to be associated with a redirect URL then the redirection is carried out with a 'Location:' header
  519. * May exit after sending a location-header.
  520. *
  521. * @return void
  522. */
  523. function sendRedirect() {
  524. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->RDCT, 'cache_md5params'));
  525. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  526. $this->updateMD5paramsRecord($this->RDCT);
  527. header('Location: '.$row['params']);
  528. exit;
  529. }
  530. }
  531. /**
  532. * Gets instance of PageRenderer
  533. *
  534. * @return t3lib_PageRenderer
  535. */
  536. public function getPageRenderer() {
  537. if (!isset($this->pageRenderer)) {
  538. $this->pageRenderer = t3lib_div::makeInstance('t3lib_PageRenderer');
  539. $this->pageRenderer->setTemplateFile(PATH_tslib . 'templates/tslib_page_frontend.html');
  540. $this->pageRenderer->setBackPath(TYPO3_mainDir);
  541. }
  542. return $this->pageRenderer;
  543. }
  544. /********************************************
  545. *
  546. * Initializing, resolving page id
  547. *
  548. ********************************************/
  549. /**
  550. * Initializes the caching system.
  551. *
  552. * @return void
  553. */
  554. protected function initCaches() {
  555. if (TYPO3_UseCachingFramework) {
  556. $GLOBALS['TT']->push('Initializing the Caching System','');
  557. $GLOBALS['typo3CacheManager'] = t3lib_div::makeInstance('t3lib_cache_Manager');
  558. $GLOBALS['typo3CacheFactory'] = t3lib_div::makeInstance('t3lib_cache_Factory');
  559. $GLOBALS['typo3CacheFactory']->setCacheManager($GLOBALS['typo3CacheManager']);
  560. try {
  561. $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
  562. 'cache_pages'
  563. );
  564. } catch(t3lib_cache_exception_NoSuchCache $e) {
  565. t3lib_cache::initPageCache();
  566. $this->pageCache = $GLOBALS['typo3CacheManager']->getCache(
  567. 'cache_pages'
  568. );
  569. }
  570. t3lib_cache::initPageSectionCache();
  571. t3lib_cache::initContentHashCache();
  572. $GLOBALS['TT']->pull();
  573. }
  574. }
  575. /**
  576. * Initializes the front-end login user.
  577. *
  578. * @return void
  579. */
  580. function initFEuser() {
  581. $this->fe_user = t3lib_div::makeInstance('tslib_feUserAuth');
  582. $this->fe_user->lockIP = $this->TYPO3_CONF_VARS['FE']['lockIP'];
  583. $this->fe_user->lockHashKeyWords = $this->TYPO3_CONF_VARS['FE']['lockHashKeyWords'];
  584. $this->fe_user->checkPid = $this->TYPO3_CONF_VARS['FE']['checkFeUserPid'];
  585. $this->fe_user->lifetime = intval($this->TYPO3_CONF_VARS['FE']['lifetime']);
  586. $this->fe_user->checkPid_value = $GLOBALS['TYPO3_DB']->cleanIntList(t3lib_div::_GP('pid')); // List of pid's acceptable
  587. // Check if a session is transferred:
  588. if (t3lib_div::_GP('FE_SESSION_KEY')) {
  589. $fe_sParts = explode('-',t3lib_div::_GP('FE_SESSION_KEY'));
  590. if (!strcmp(md5($fe_sParts[0].'/'.$this->TYPO3_CONF_VARS['SYS']['encryptionKey']), $fe_sParts[1])) { // If the session key hash check is OK:
  591. $_COOKIE[$this->fe_user->name] = $fe_sParts[0];
  592. $this->fe_user->forceSetCookie = 1;
  593. }
  594. }
  595. if ($this->TYPO3_CONF_VARS['FE']['dontSetCookie']) {
  596. $this->fe_user->dontSetCookie=1;
  597. }
  598. $this->fe_user->start();
  599. $this->fe_user->unpack_uc('');
  600. $this->fe_user->fetchSessionData(); // Gets session data
  601. $recs = t3lib_div::_GP('recs');
  602. if (is_array($recs)) { // If any record registration is submitted, register the record.
  603. $this->fe_user->record_registration($recs, $this->TYPO3_CONF_VARS['FE']['maxSessionDataSize']);
  604. }
  605. // Call hook for possible manipulation of frontend user object
  606. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'])) {
  607. $_params = array('pObj' => &$this);
  608. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] as $_funcRef) {
  609. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  610. }
  611. }
  612. // For every 60 seconds the is_online timestamp is updated.
  613. if (is_array($this->fe_user->user) && $this->fe_user->user['uid'] && $this->fe_user->user['is_online']<($GLOBALS['EXEC_TIME']-60)) {
  614. $GLOBALS['TYPO3_DB']->exec_UPDATEquery('fe_users', 'uid='.intval($this->fe_user->user['uid']), array('is_online' => $GLOBALS['EXEC_TIME']));
  615. }
  616. }
  617. /**
  618. * Initializes the front-end user groups.
  619. * Sets ->loginUser and ->gr_list based on front-end user status.
  620. *
  621. * @return void
  622. */
  623. function initUserGroups() {
  624. $this->fe_user->showHiddenRecords = $this->showHiddenRecords; // This affects the hidden-flag selecting the fe_groups for the user!
  625. $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!)
  626. if (is_array($this->fe_user->user) && count($this->fe_user->groupData['uid'])) {
  627. $this->loginUser=1; // global flag!
  628. $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!
  629. $gr_array = $this->fe_user->groupData['uid'];
  630. } else {
  631. $this->loginUser=0;
  632. $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!
  633. if ($this->loginAllowedInBranch) {
  634. $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.
  635. } else {
  636. $gr_array = array(); // Set to blank since we will NOT risk any groups being set when no logins are allowed!
  637. }
  638. }
  639. // Clean up.
  640. $gr_array = array_unique($gr_array); // Make unique...
  641. sort($gr_array); // sort
  642. if (count($gr_array) && !$this->loginAllowedInBranch_mode) {
  643. $this->gr_list.=','.implode(',',$gr_array);
  644. }
  645. if ($this->fe_user->writeDevLog) t3lib_div::devLog('Valid usergroups for TSFE: '.$this->gr_list, 'tslib_fe');
  646. }
  647. /**
  648. * Checking if a user is logged in or a group constellation different from "0,-1"
  649. *
  650. * @return boolean TRUE if either a login user is found (array fe_user->user) OR if the gr_list is set to something else than '0,-1' (could be done even without a user being logged in!)
  651. */
  652. function isUserOrGroupSet() {
  653. return is_array($this->fe_user->user) || $this->gr_list!=='0,-1';
  654. }
  655. /**
  656. * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
  657. *
  658. * Two options:
  659. * 1) Use PATH_INFO (also Apache) to extract id and type from that var. Does not require any special modules compiled with apache. (less typical)
  660. * 2) Using hook which enables features like those provided from "simulatestatic" or "realurl" extension (AKA "Speaking URLs")
  661. *
  662. * @return void
  663. * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&cHash=4ad9d7acb4
  664. */
  665. function checkAlternativeIdMethods() {
  666. $this->siteScript = t3lib_div::getIndpEnv('TYPO3_SITE_SCRIPT');
  667. // Call post processing function for custom URL methods.
  668. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'])) {
  669. $_params = array('pObj' => &$this);
  670. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] as $_funcRef) {
  671. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  672. }
  673. }
  674. }
  675. /**
  676. * Clears the preview-flags, sets sim_exec_time to current time.
  677. * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME'] in t3lib/config_default.inc. Alter it by adding or subtracting seconds.
  678. *
  679. * @return void
  680. */
  681. function clear_preview() {
  682. $this->showHiddenPage = 0;
  683. $this->showHiddenRecords = 0;
  684. $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
  685. $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
  686. $this->fePreview = 0;
  687. }
  688. /**
  689. * Determines the id and evaluates any preview settings
  690. * Basically this function is about determining whether a backend user is logged in, if he has read access to the page and if he's previewing the page. That all determines which id to show and how to initialize the id.
  691. *
  692. * @return void
  693. */
  694. function determineId() {
  695. // Getting ARG-v values if some
  696. $this->setIDfromArgV();
  697. // If there is a Backend login we are going to check for any preview settings:
  698. $GLOBALS['TT']->push('beUserLogin','');
  699. if ($this->beUserLogin || $this->doWorkspacePreview()) {
  700. // Backend user preview features:
  701. if ($this->beUserLogin && ($GLOBALS['BE_USER']->adminPanel instanceof tslib_AdminPanel)) {
  702. $this->fePreview = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview') ? true : false;
  703. // If admin panel preview is enabled...
  704. if ($this->fePreview) {
  705. $fe_user_OLD_USERGROUP = $this->fe_user->user['usergroup'];
  706. $this->showHiddenPage = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
  707. $this->showHiddenRecords = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
  708. // simulate date
  709. $simTime = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
  710. if ($simTime) {
  711. $GLOBALS['SIM_EXEC_TIME'] = $simTime;
  712. $GLOBALS['SIM_ACCESS_TIME'] = $simTime - ($simTime % 60);
  713. }
  714. // simulate user
  715. $simUserGroup = $GLOBALS['BE_USER']->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
  716. $this->simUserGroup = $simUserGroup;
  717. if ($simUserGroup) $this->fe_user->user['usergroup']=$simUserGroup;
  718. if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
  719. $this->fePreview=0;
  720. }
  721. }
  722. }
  723. if ($this->id) {
  724. // Now it's investigated if the raw page-id points to a hidden page and if so, the flag is set.
  725. // This does not require the preview flag to be set in the admin panel
  726. $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...
  727. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('uid', 'pages', $idQ . ' AND hidden!=0 AND deleted=0');
  728. if ($count) {
  729. $this->fePreview = 1; // The preview flag is set only if the current page turns out to actually be hidden!
  730. $this->showHiddenPage = 1;
  731. }
  732. // For Live workspace: Check root line for proper connection to tree root (done because of possible preview of page / branch versions)
  733. if (!$this->fePreview && $this->whichWorkspace()===0) {
  734. // Initialize the page-select functions to check rootline:
  735. $temp_sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
  736. $temp_sys_page->init($this->showHiddenPage);
  737. // If root line contained NO records and ->error_getRootLine_failPid tells us that it was because of a pid=-1 (indicating a "version" record)...:
  738. if (!count($temp_sys_page->getRootLine($this->id,$this->MP)) && $temp_sys_page->error_getRootLine_failPid==-1) {
  739. // Setting versioningPreview flag and try again:
  740. $temp_sys_page->versioningPreview = TRUE;
  741. if (count($temp_sys_page->getRootLine($this->id,$this->MP))) {
  742. // 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.
  743. $this->fePreview = 1;
  744. }
  745. }
  746. }
  747. }
  748. // The preview flag will be set if a backend user is in an offline workspace
  749. if (($GLOBALS['BE_USER']->user['workspace_preview'] || t3lib_div::_GP('ADMCMD_view') || $this->doWorkspacePreview()) && ($this->whichWorkspace()===-1 || $this->whichWorkspace()>0)) {
  750. $this->fePreview = 2; // Will show special preview message.
  751. }
  752. // If the front-end is showing a preview, caching MUST be disabled.
  753. if ($this->fePreview) {
  754. $this->disableCache();
  755. }
  756. }
  757. $GLOBALS['TT']->pull();
  758. // Now, get the id, validate access etc:
  759. $this->fetch_the_id();
  760. // Check if backend user has read access to this page. If not, recalculate the id.
  761. if ($this->beUserLogin && $this->fePreview) {
  762. if (!$GLOBALS['BE_USER']->doesUserHaveAccess($this->page,1)) {
  763. // Resetting
  764. $this->clear_preview();
  765. $this->fe_user->user['usergroup'] = $fe_user_OLD_USERGROUP;
  766. // Fetching the id again, now with the preview settings reset.
  767. $this->fetch_the_id();
  768. }
  769. }
  770. // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
  771. $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
  772. if (!$this->loginAllowedInBranch) { // Logins are not allowed:
  773. if ($this->isUserOrGroupSet()) { // Only if there is a login will we run this...
  774. if ($this->loginAllowedInBranch_mode=='all') {
  775. // Clear out user and group:
  776. unset($this->fe_user->user);
  777. $this->gr_list = '0,-1';
  778. } else {
  779. $this->gr_list = '0,-2';
  780. }
  781. // Fetching the id again, now with the preview settings reset.
  782. $this->fetch_the_id();
  783. }
  784. }
  785. // Final cleaning.
  786. $this->id = $this->contentPid = intval($this->id); // Make sure it's an integer
  787. $this->type = intval($this->type); // Make sure it's an integer
  788. // Look for alternative content PID if page is under version preview:
  789. if ($this->fePreview) {
  790. 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:
  791. // 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!
  792. $this->contentPid = $this->page['_ORIG_uid'];
  793. }
  794. }
  795. // Call post processing function for id determination:
  796. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'])) {
  797. $_params = array('pObj' => &$this);
  798. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] as $_funcRef) {
  799. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  800. }
  801. }
  802. }
  803. /**
  804. * Get The Page ID
  805. * This gets the id of the page, checks if the page is in the domain and if the page is accessible
  806. * Sets variables such as $this->sys_page, $this->loginUser, $this->gr_list, $this->id, $this->type, $this->domainStartPage, $this->idParts
  807. *
  808. * @return void
  809. * @access private
  810. */
  811. function fetch_the_id() {
  812. $GLOBALS['TT']->push('fetch_the_id initialize/','');
  813. // Initialize the page-select functions.
  814. $this->sys_page = t3lib_div::makeInstance('t3lib_pageSelect');
  815. $this->sys_page->versioningPreview = ($this->fePreview===2 || intval($this->workspacePreview) || t3lib_div::_GP('ADMCMD_view')) ? TRUE : FALSE;
  816. $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
  817. $this->sys_page->init($this->showHiddenPage);
  818. // Set the valid usergroups for FE
  819. $this->initUserGroups();
  820. // Sets sys_page where-clause
  821. $this->setSysPageWhereClause();
  822. // Splitting $this->id by a period (.). First part is 'id' and second part - if exists - will overrule the &type param if given
  823. $pParts = explode('.',$this->id);
  824. $this->id = $pParts[0]; // Set it.
  825. if (isset($pParts[1])) {$this->type=$pParts[1];}
  826. // Splitting $this->id by a comma (,). First part is 'id' and other parts are just stored for use in scripts.
  827. $this->idParts = explode(',',$this->id);
  828. // Splitting by a '+' sign - used for base64/md5 methods of parameter encryption for simulate static documents.
  829. list($pgID,$SSD_p)=explode('+',$this->idParts[0],2);
  830. if ($SSD_p) { $this->idPartsAnalyze($SSD_p); }
  831. $this->id = $pgID; // Set id
  832. // If $this->id is a string, it's an alias
  833. $this->checkAndSetAlias();
  834. // The id and type is set to the integer-value - just to be sure...
  835. $this->id = intval($this->id);
  836. $this->type = intval($this->type);
  837. $GLOBALS['TT']->pull();
  838. // We find the first page belonging to the current domain
  839. $GLOBALS['TT']->push('fetch_the_id domain/','');
  840. $this->domainStartPage = $this->findDomainRecord($this->TYPO3_CONF_VARS['SYS']['recursiveDomainSearch']); // the page_id of the current domain
  841. if (!$this->id) {
  842. if ($this->domainStartPage) {
  843. $this->id = $this->domainStartPage; // If the id was not previously set, set it to the id of the domain.
  844. } else {
  845. $theFirstPage = $this->sys_page->getFirstWebPage($this->id); // Find the first 'visible' page in that domain
  846. if ($theFirstPage) {
  847. $this->id = $theFirstPage['uid'];
  848. } else {
  849. if ($this->checkPageUnavailableHandler()) {
  850. $this->pageUnavailableAndExit('No pages are found on the rootlevel!');
  851. } else {
  852. $message = 'No pages are found on the rootlevel!';
  853. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  854. header('HTTP/1.0 503 Service Temporarily Unavailable');
  855. $this->printError($message);
  856. exit;
  857. }
  858. }
  859. }
  860. }
  861. $GLOBALS['TT']->pull();
  862. $GLOBALS['TT']->push('fetch_the_id rootLine/','');
  863. $requestedId = $this->id; // We store the originally requested id
  864. $this->getPageAndRootlineWithDomain($this->domainStartPage);
  865. $GLOBALS['TT']->pull();
  866. if ($this->pageNotFound && $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
  867. $pNotFoundMsg = array(
  868. 1 => 'ID was not an accessible page',
  869. 2 => 'Subsection was found and not accessible',
  870. 3 => 'ID was outside the domain',
  871. 4 => 'The requested page alias does not exist'
  872. );
  873. $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound]);
  874. }
  875. // set no_cache if set
  876. if ($this->page['no_cache']) {
  877. $this->set_no_cache();
  878. }
  879. // Init SYS_LASTCHANGED
  880. $this->register['SYS_LASTCHANGED'] = intval($this->page['tstamp']);
  881. if ($this->register['SYS_LASTCHANGED'] < intval($this->page['SYS_LASTCHANGED'])) {
  882. $this->register['SYS_LASTCHANGED'] = intval($this->page['SYS_LASTCHANGED']);
  883. }
  884. }
  885. /**
  886. * Gets the page and rootline arrays based on the id, $this->id
  887. *
  888. * If the id does not correspond to a proper page, the 'previous' valid page in the rootline is found
  889. * If the page is a shortcut (doktype=4), the ->id is loaded with that id
  890. *
  891. * Whether or not the ->id is changed to the shortcut id or the previous id in rootline (eg if a page is hidden), the ->page-array and ->rootline is found and must also be valid.
  892. *
  893. * Sets or manipulates internal variables such as: $this->id, $this->page, $this->rootLine, $this->MP, $this->pageNotFound
  894. *
  895. * @return void
  896. * @access private
  897. */
  898. function getPageAndRootline() {
  899. $this->page = $this->sys_page->getPage($this->id);
  900. if (!count($this->page)) {
  901. // If no page, we try to find the page before in the rootLine.
  902. $this->pageNotFound=1; // Page is 'not found' in case the id itself was not an accessible page. code 1
  903. $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
  904. if (count($this->rootLine)) {
  905. $c=count($this->rootLine)-1;
  906. while($c>0) {
  907. // Add to page access failure history:
  908. $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
  909. // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
  910. $c--;
  911. $this->id = $this->rootLine[$c]['uid'];
  912. $this->page = $this->sys_page->getPage($this->id);
  913. if (count($this->page)) { break; }
  914. }
  915. }
  916. // If still no page...
  917. if (!count($this->page)) {
  918. if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
  919. $this->pageNotFoundAndExit('The requested page does not exist!');
  920. } else {
  921. $message = 'The requested page does not exist!';
  922. header('HTTP/1.0 404 Page Not Found');
  923. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  924. $this->printError($message);
  925. exit;
  926. }
  927. }
  928. }
  929. // Spacer is not accessible in frontend
  930. if ($this->page['doktype'] == 199) {
  931. if ($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling']) {
  932. $this->pageNotFoundAndExit('The requested page does not exist!');
  933. } else {
  934. $message = 'The requested page does not exist!';
  935. header('HTTP/1.0 404 Page Not Found');
  936. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  937. $this->printError($message);
  938. exit;
  939. }
  940. }
  941. // Is the ID a link to another page??
  942. if ($this->page['doktype']==4) {
  943. $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.
  944. // saving the page so that we can check later - when we know
  945. // about languages - whether we took the correct shortcut or
  946. // whether a translation of the page overwrites the shortcut
  947. // target and we need to follow the new target
  948. $this->originalShortcutPage = $this->page;
  949. $this->page = $this->getPageShortcut($this->page['shortcut'],$this->page['shortcut_mode'],$this->page['uid']);
  950. $this->id = $this->page['uid'];
  951. }
  952. // Gets the rootLine
  953. $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
  954. // If not rootline we're off...
  955. if (!count($this->rootLine)) {
  956. $ws = $this->whichWorkspace();
  957. if ($this->sys_page->error_getRootLine_failPid==-1 && $ws) {
  958. $this->sys_page->versioningPreview = TRUE;
  959. $this->versioningWorkspaceId = $ws;
  960. $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
  961. }
  962. if (!count($this->rootLine)) {
  963. if ($this->checkPageUnavailableHandler()) {
  964. $this->pageUnavailableAndExit('The requested page didn\'t have a proper connection to the tree-root!');
  965. } else {
  966. $message = 'The requested page didn\'t have a proper connection to the tree-root! <br /><br />('.$this->sys_page->error_getRootLine.')';
  967. header('HTTP/1.0 503 Service Temporarily Unavailable');
  968. t3lib_div::sysLog(str_replace('<br /><br />','',$message), 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  969. $this->printError($message);
  970. exit;
  971. }
  972. }
  973. $this->fePreview = 1;
  974. }
  975. // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
  976. if ($this->checkRootlineForIncludeSection()) {
  977. if (!count($this->rootLine)) {
  978. if ($this->checkPageUnavailableHandler()) {
  979. $this->pageUnavailableAndExit('The requested page was not accessible!');
  980. } else {
  981. $message = 'The requested page was not accessible!';
  982. header('HTTP/1.0 503 Service Temporarily Unavailable');
  983. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  984. $this->printError($message);
  985. exit;
  986. }
  987. } else {
  988. $el = reset($this->rootLine);
  989. $this->id = $el['uid'];
  990. $this->page = $this->sys_page->getPage($this->id);
  991. $this->rootLine = $this->sys_page->getRootLine($this->id,$this->MP);
  992. }
  993. }
  994. }
  995. /**
  996. * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
  997. *
  998. * @param integer The value of the "shortcut" field from the pages record
  999. * @param integer The shortcut mode: 1 and 2 will select either first subpage or random subpage; the default is the page pointed to by $SC
  1000. * @param integer The current page UID of the page which is a shortcut
  1001. * @param integer Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
  1002. * @param array An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
  1003. * @return mixed Returns the page record of the page that the shortcut pointed to.
  1004. * @access private
  1005. * @see getPageAndRootline()
  1006. */
  1007. function getPageShortcut($SC,$mode,$thisUid,$itera=20,$pageLog=array()) {
  1008. $idArray = t3lib_div::intExplode(',',$SC);
  1009. // Find $page record depending on shortcut mode:
  1010. switch($mode) {
  1011. case 1:
  1012. case 2:
  1013. $pageArray = $this->sys_page->getMenu($idArray[0]?$idArray[0]:$thisUid,'*','sorting','AND pages.doktype<199 AND pages.doktype!=6');
  1014. $pO = 0;
  1015. if ($mode==2 && count($pageArray)) { // random
  1016. $randval = intval(rand(0,count($pageArray)-1));
  1017. $pO = $randval;
  1018. }
  1019. $c = 0;
  1020. foreach ($pageArray as $pV) {
  1021. if ($c==$pO) {
  1022. $page = $pV;
  1023. break;
  1024. }
  1025. $c++;
  1026. }
  1027. break;
  1028. default:
  1029. $page = $this->sys_page->getPage($idArray[0]);
  1030. break;
  1031. }
  1032. // Check if short cut page was a shortcut itself, if so look up recursively:
  1033. if ($page['doktype']==4) {
  1034. if (!in_array($page['uid'],$pageLog) && $itera>0) {
  1035. $pageLog[] = $page['uid'];
  1036. $page = $this->getPageShortcut($page['shortcut'],$page['shortcut_mode'],$page['uid'],$itera-1,$pageLog);
  1037. } else {
  1038. $pageLog[] = $page['uid'];
  1039. $message = 'Page shortcuts were looping in uids '.implode(',',$pageLog).'...!';
  1040. header('HTTP/1.0 500 Internal Server Error');
  1041. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  1042. $this->printError($message);
  1043. exit;
  1044. }
  1045. }
  1046. // Return resulting page:
  1047. return $page;
  1048. }
  1049. /**
  1050. * Checks the current rootline for defined sections.
  1051. *
  1052. * @return boolean
  1053. * @access private
  1054. */
  1055. function checkRootlineForIncludeSection() {
  1056. $c=count($this->rootLine);
  1057. $removeTheRestFlag=0;
  1058. for ($a=0;$a<$c;$a++) {
  1059. if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
  1060. // Add to page access failure history:
  1061. $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
  1062. $removeTheRestFlag=1;
  1063. }
  1064. if ($this->rootLine[$a]['doktype']==6) {
  1065. if ($this->beUserLogin) { // If there is a backend user logged in, check if he has read access to the page:
  1066. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'uid='.intval($this->id).' AND '.$GLOBALS['BE_USER']->getPagePermsClause(1)); // versionOL()?
  1067. list($isPage) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
  1068. 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...
  1069. } else { // Dont go here, if there is no backend user logged in.
  1070. $removeTheRestFlag=1;
  1071. }
  1072. }
  1073. if ($removeTheRestFlag) {
  1074. $this->pageNotFound=2; // Page is 'not found' in case a subsection was found and not accessible, code 2
  1075. unset($this->rootLine[$a]);
  1076. }
  1077. }
  1078. return $removeTheRestFlag;
  1079. }
  1080. /**
  1081. * Checks page record for enableFields
  1082. * Returns true if enableFields does not disable the page record.
  1083. * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
  1084. *
  1085. * @param array The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
  1086. * @param boolean Bypass group-check
  1087. * @return boolean True, if record is viewable.
  1088. * @see tslib_cObj::getTreeList(), checkPagerecordForIncludeSection()
  1089. */
  1090. function checkEnableFields($row,$bypassGroupCheck=FALSE) {
  1091. if ((!$row['hidden'] || $this->showHiddenPage)
  1092. && $row['starttime']<=$GLOBALS['SIM_ACCESS_TIME']
  1093. && ($row['endtime']==0 || $row['endtime']>$GLOBALS['SIM_ACCESS_TIME'])
  1094. && ($bypassGroupCheck || $this->checkPageGroupAccess($row))
  1095. ) { return TRUE; }
  1096. }
  1097. /**
  1098. * Check group access against a page record
  1099. *
  1100. * @param array The page record to evaluate (needs field: fe_group)
  1101. * @param mixed List of group id's (comma list or array). Default is $this->gr_list
  1102. * @return boolean True, if group access is granted.
  1103. * @access private
  1104. */
  1105. function checkPageGroupAccess($row, $groupList=NULL) {
  1106. if(is_null($groupList)) {
  1107. $groupList = $this->gr_list;
  1108. }
  1109. if(!is_array($groupList)) {
  1110. $groupList = explode(',', $groupList);
  1111. }
  1112. $pageGroupList = explode(',', $row['fe_group'] ? $row['fe_group'] : 0);
  1113. return count(array_intersect($groupList, $pageGroupList)) > 0;
  1114. }
  1115. /**
  1116. * Checks page record for include section
  1117. *
  1118. * @param array The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
  1119. * @return boolean Returns true if either extendToSubpages is not checked or if the enableFields does not disable the page record.
  1120. * @access private
  1121. * @see checkEnableFields(), tslib_cObj::getTreeList(), checkRootlineForIncludeSection()
  1122. */
  1123. function checkPagerecordForIncludeSection($row) {
  1124. return (!$row['extendToSubpages'] || $this->checkEnableFields($row)) ? 1 : 0;
  1125. }
  1126. /**
  1127. * Checks if logins are allowed in the current branch of the page tree. Traverses the full root line and returns TRUE if logins are OK, otherwise false (and then the login user must be unset!)
  1128. *
  1129. * @return boolean returns TRUE if logins are OK, otherwise false (and then the login user must be unset!)
  1130. */
  1131. function checkIfLoginAllowedInBranch() {
  1132. // Initialize:
  1133. $c = count($this->rootLine);
  1134. $disable = FALSE;
  1135. // Traverse root line from root and outwards:
  1136. for ($a=0; $a<$c; $a++) {
  1137. // If a value is set for login state:
  1138. if ($this->rootLine[$a]['fe_login_mode'] > 0) {
  1139. // Determine state from value:
  1140. if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
  1141. $disable = TRUE;
  1142. $this->loginAllowedInBranch_mode = 'all';
  1143. } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
  1144. $disable = TRUE;
  1145. $this->loginAllowedInBranch_mode = 'groups';
  1146. } else {
  1147. $disable = FALSE;
  1148. }
  1149. }
  1150. }
  1151. return !$disable;
  1152. }
  1153. /**
  1154. * Analysing $this->pageAccessFailureHistory into a summary array telling which features disabled display and on which pages and conditions. That data can be used inside a page-not-found handler
  1155. *
  1156. * @return array Summary of why page access was not allowed.
  1157. */
  1158. function getPageAccessFailureReasons() {
  1159. $output = array();
  1160. $combinedRecords = array_merge(
  1161. 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!
  1162. is_array($this->pageAccessFailureHistory['sub_section']) ? $this->pageAccessFailureHistory['sub_section'] : array()
  1163. );
  1164. if (count($combinedRecords)) {
  1165. foreach($combinedRecords as $k => $pagerec) {
  1166. // 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
  1167. // 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!
  1168. if (!$k || $pagerec['extendToSubpages']) {
  1169. if ($pagerec['hidden']) $output['hidden'][$pagerec['uid']] = TRUE;
  1170. if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
  1171. if ($pagerec['endtime']!=0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
  1172. if (!$this->checkPageGroupAccess($pagerec)) $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
  1173. }
  1174. }
  1175. }
  1176. return $output;
  1177. }
  1178. /**
  1179. * This checks if there are ARGV-parameters in the QUERY_STRING and if so, those are used for the id
  1180. * $this->id must be 'false' in order for any processing to happen in here
  1181. * If an id/alias value is extracted from the QUERY_STRING it is set in $this->id
  1182. *
  1183. * @return void
  1184. * @access private
  1185. */
  1186. function setIDfromArgV() {
  1187. if (!$this->id) {
  1188. list($theAlias) = explode('&',t3lib_div::getIndpEnv('QUERY_STRING'));
  1189. $theAlias = trim($theAlias);
  1190. $this->id = ($theAlias != '' && strpos($theAlias, '=') === false) ? $theAlias : 0;
  1191. }
  1192. }
  1193. /**
  1194. * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
  1195. * If not inside domain, then default to first page in domain.
  1196. *
  1197. * @param integer Page uid of the page where the found domain record is (pid of the domain record)
  1198. * @return void
  1199. * @access private
  1200. */
  1201. function getPageAndRootlineWithDomain($domainStartPage) {
  1202. $this->getPageAndRootline();
  1203. // 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.
  1204. if ($domainStartPage && is_array($this->rootLine)) {
  1205. $idFound = 0;
  1206. foreach ($this->rootLine as $key => $val) {
  1207. if ($val['uid']==$domainStartPage) {
  1208. $idFound=1;
  1209. break;
  1210. }
  1211. }
  1212. if (!$idFound) {
  1213. $this->pageNotFound=3; // Page is 'not found' in case the id was outside the domain, code 3
  1214. $this->id = $domainStartPage;
  1215. $this->getPageAndRootline(); //re-get the page and rootline if the id was not found.
  1216. }
  1217. }
  1218. }
  1219. /**
  1220. * Sets sys_page where-clause
  1221. *
  1222. * @return void
  1223. * @access private
  1224. */
  1225. function setSysPageWhereClause() {
  1226. $this->sys_page->where_hid_del.=' AND pages.doktype<200';
  1227. $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
  1228. }
  1229. /**
  1230. * Looking up a domain record based on HTTP_HOST
  1231. *
  1232. * @param boolean If set, it looks "recursively" meaning that a domain like "123.456.typo3.com" would find a domain record like "typo3.com" if "123.456.typo3.com" or "456.typo3.com" did not exist.
  1233. * @return integer Returns the page id of the page where the domain record was found.
  1234. * @access private
  1235. */
  1236. function findDomainRecord($recursive=0) {
  1237. if ($recursive) {
  1238. $host = explode('.',t3lib_div::getIndpEnv('HTTP_HOST'));
  1239. while(count($host)) {
  1240. $pageUid = $this->sys_page->getDomainStartPage(implode('.',$host),t3lib_div::getIndpEnv('SCRIPT_NAME'),t3lib_div::getIndpEnv('REQUEST_URI'));
  1241. if ($pageUid) return $pageUid; else array_shift($host);
  1242. }
  1243. return $pageUid;
  1244. } else {
  1245. return $this->sys_page->getDomainStartPage(t3lib_div::getIndpEnv('HTTP_HOST'),t3lib_div::getIndpEnv('SCRIPT_NAME'),t3lib_div::getIndpEnv('REQUEST_URI'));
  1246. }
  1247. }
  1248. /**
  1249. * Page unavailable handler for use in frontend plugins from extensions.
  1250. *
  1251. * @param string Reason text
  1252. * @param string HTTP header to send
  1253. * @return void Function exits.
  1254. */
  1255. function pageUnavailableAndExit($reason='', $header='') {
  1256. $header = $header ? $header : $this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling_statheader'];
  1257. $this->pageUnavailableHandler($this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling'], $header, $reason);
  1258. exit;
  1259. }
  1260. /**
  1261. * Page-not-found handler for use in frontend plugins from extensions.
  1262. *
  1263. * @param string Reason text
  1264. * @param string HTTP header to send
  1265. * @return void Function exits.
  1266. */
  1267. function pageNotFoundAndExit($reason='', $header='') {
  1268. $header = $header ? $header : $this->TYPO3_CONF_VARS['FE']['pageNotFound_handling_statheader'];
  1269. $this->pageNotFoundHandler($this->TYPO3_CONF_VARS['FE']['pageNotFound_handling'], $header, $reason);
  1270. exit;
  1271. }
  1272. /**
  1273. * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
  1274. * and devIPMask must not match the current visitor's IP address.
  1275. *
  1276. * @return boolean True/false whether the pageUnavailable_handler should be used.
  1277. */
  1278. function checkPageUnavailableHandler() {
  1279. if ($this->TYPO3_CONF_VARS['FE']['pageUnavailable_handling'] &&
  1280. !t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $this->TYPO3_CONF_VARS['SYS']['devIPmask'])) {
  1281. $checkPageUnavailableHandler = TRUE;
  1282. } else {
  1283. $checkPageUnavailableHandler = FALSE;
  1284. }
  1285. return $checkPageUnavailableHandler;
  1286. }
  1287. /**
  1288. * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
  1289. *
  1290. * @param mixed Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
  1291. * @param string If set, this is passed directly to the PHP function, header()
  1292. * @param string If set, error messages will also mention this as the reason for the page-not-found.
  1293. * @return void (The function exits!)
  1294. */
  1295. function pageUnavailableHandler($code, $header, $reason) {
  1296. $this->pageErrorHandler($code, $header, $reason);
  1297. }
  1298. /**
  1299. * Page not found handler. Acts a wrapper for the pageErrorHandler method.
  1300. *
  1301. * @param mixed Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
  1302. * @param string If set, this is passed directly to the PHP function, header()
  1303. * @param string If set, error messages will also mention this as the reason for the page-not-found.
  1304. * @return void (The function exits!)
  1305. */
  1306. function pageNotFoundHandler($code, $header='', $reason='') {
  1307. $this->pageErrorHandler($code, $header, $reason);
  1308. }
  1309. /**
  1310. * Generic error page handler.
  1311. * Exits.
  1312. *
  1313. * @param mixed Which type of handling; If a true PHP-boolean or TRUE then a ->printError message is outputted. If integer an error message with that number is shown. Otherwise the $code value is expected to be a "Location:" header value.
  1314. * @param string If set, this is passed directly to the PHP function, header()
  1315. * @param string If set, error messages will also mention this as the reason for the page-not-found.
  1316. * @return void (The function exits!)
  1317. */
  1318. function pageErrorHandler($code, $header='', $reason='') {
  1319. // Issue header in any case:
  1320. if ($header) {
  1321. $headerArr = preg_split('/\r|\n/',$header,-1,PREG_SPLIT_NO_EMPTY);
  1322. foreach ($headerArr as $header) {
  1323. header ($header);
  1324. }
  1325. }
  1326. // Create response:
  1327. if (gettype($code)=='boolean' || !strcmp($code,1)) { // Simply boolean; Just shows TYPO3 error page with reason:
  1328. $this->printError('The page did not exist or was inaccessible.'.($reason ? ' Reason: '.htmlspecialchars($reason) : ''));
  1329. } elseif (t3lib_div::isFirstPartOfStr($code,'USER_FUNCTION:')) {
  1330. $funcRef = trim(substr($code,14));
  1331. $params = array(
  1332. 'currentUrl' => t3lib_div::getIndpEnv('REQUEST_URI'),
  1333. 'reasonText' => $reason,
  1334. 'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
  1335. );
  1336. echo t3lib_div::callUserFunction($funcRef,$params,$this);
  1337. } elseif (t3lib_div::isFirstPartOfStr($code,'READFILE:')) {
  1338. $readFile = t3lib_div::getFileAbsFileName(trim(substr($code,9)));
  1339. if (@is_file($readFile)) {
  1340. $fileContent = t3lib_div::getUrl($readFile);
  1341. $fileContent = str_replace('###CURRENT_URL###', t3lib_div::getIndpEnv('REQUEST_URI'), $fileContent);
  1342. $fileContent = str_replace('###REASON###', htmlspecialchars($reason), $fileContent);
  1343. echo $fileContent;
  1344. } else {
  1345. $this->printError('Configuration Error: 404 page "'.$readFile.'" could not be found.');
  1346. }
  1347. } elseif (t3lib_div::isFirstPartOfStr($code,'REDIRECT:')) {
  1348. t3lib_utility_Http::redirect(substr($code, 9));
  1349. } elseif (strlen($code)) {
  1350. // Check if URL is relative
  1351. $url_parts = parse_url($code);
  1352. if ($url_parts['host'] == '') {
  1353. $url_parts['host'] = t3lib_div::getIndpEnv('HTTP_HOST');
  1354. $code = t3lib_div::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
  1355. $checkBaseTag = false;
  1356. } else {
  1357. $checkBaseTag = true;
  1358. }
  1359. // Check recursion
  1360. if ($code == t3lib_div::getIndpEnv('TYPO3_REQUEST_URL')) {
  1361. if ($reason == '') {
  1362. $reason = 'Page cannot be found.';
  1363. }
  1364. $reason.= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
  1365. $this->printError('Reason: '.nl2br(htmlspecialchars($reason)));
  1366. exit();
  1367. }
  1368. // Prepare headers
  1369. $headerArr = array(
  1370. 'User-agent: ' . t3lib_div::getIndpEnv('HTTP_USER_AGENT'),
  1371. 'Referer: ' . t3lib_div::getIndpEnv('TYPO3_REQUEST_URL')
  1372. );
  1373. $res = t3lib_div::getURL($code, 1, $headerArr);
  1374. // Header and content are separated by an empty line
  1375. list($header, $content) = explode(CRLF . CRLF, $res, 2);
  1376. $content.= CRLF;
  1377. if (false === $res) {
  1378. // Last chance -- redirect
  1379. t3lib_utility_Http::redirect($code);
  1380. } else {
  1381. $forwardHeaders = array( // Forward these response headers to the client
  1382. 'Content-Type:',
  1383. );
  1384. $headerArr = preg_split('/\r|\n/',$header,-1,PREG_SPLIT_NO_EMPTY);
  1385. foreach ($headerArr as $header) {
  1386. foreach ($forwardHeaders as $h) {
  1387. if (preg_match('/^'.$h.'/', $header)) {
  1388. header ($header);
  1389. }
  1390. }
  1391. }
  1392. // Put <base> if necesary
  1393. if ($checkBaseTag) {
  1394. // If content already has <base> tag, we do not need to do anything
  1395. if (false === stristr($content, '<base ')) {
  1396. // Generate href for base tag
  1397. $base = $url_parts['scheme'] . '://';
  1398. if ($url_parts['user'] != '') {
  1399. $base.= $url_parts['user'];
  1400. if ($url_parts['pass'] != '') {
  1401. $base.= ':' . $url_parts['pass'];
  1402. }
  1403. $base.= '@';
  1404. }
  1405. $base.= $url_parts['host'];
  1406. // Add path portion skipping possible file name
  1407. $base.= preg_replace('/(.*\/)[^\/]*/', '${1}', $url_parts['path']);
  1408. // Put it into content (generate also <head> if necessary)
  1409. $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
  1410. if (stristr($content, '<head>')) {
  1411. $content = preg_replace('/(<head>)/i', '\1' . $replacement, $content);
  1412. } else {
  1413. $content = preg_replace('/(<html[^>]*>)/i', '\1<head>' . $replacement . '</head>', $content);
  1414. }
  1415. }
  1416. }
  1417. echo $content; // Output the content
  1418. }
  1419. } else {
  1420. $this->printError($reason ? 'Reason: '.htmlspecialchars($reason) : 'Page cannot be found.');
  1421. }
  1422. exit();
  1423. }
  1424. /**
  1425. * Fetches the integer page id for a page alias.
  1426. * Looks if ->id is not an integer and if so it will search for a page alias and if found the page uid of that page is stored in $this->id
  1427. *
  1428. * @return void
  1429. * @access private
  1430. */
  1431. function checkAndSetAlias() {
  1432. if ($this->id && !t3lib_div::testInt($this->id)) {
  1433. $aid = $this->sys_page->getPageIdFromAlias($this->id);
  1434. if ($aid) {
  1435. $this->id = $aid;
  1436. } else {
  1437. $this->pageNotFound = 4;
  1438. }
  1439. }
  1440. }
  1441. /**
  1442. * Analyzes the second part of a id-string (after the "+"), looking for B6 or M5 encoding and if found it will resolve it and restore the variables in global $_GET
  1443. * If values for ->cHash, ->no_cache, ->jumpurl and ->MP is found, they are also loaded into the internal vars of this class.
  1444. *
  1445. * @param string String to analyze
  1446. * @return void
  1447. * @access private
  1448. * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  1449. * @todo Deprecated but still used in the Core!
  1450. */
  1451. function idPartsAnalyze($str) {
  1452. $GET_VARS = '';
  1453. switch(substr($str,0,2)) {
  1454. case 'B6':
  1455. $addParams = base64_decode(str_replace('_','=',str_replace('-','/',substr($str,2))));
  1456. parse_str($addParams,$GET_VARS);
  1457. break;
  1458. case 'M5':
  1459. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('params', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr(substr($str,2), 'cache_md5params'));
  1460. $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
  1461. $this->updateMD5paramsRecord(substr($str,2));
  1462. parse_str($row['params'],$GET_VARS);
  1463. break;
  1464. }
  1465. $this->mergingWithGetVars($GET_VARS);
  1466. }
  1467. /**
  1468. * Merging values into the global $_GET
  1469. *
  1470. * @param array Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
  1471. * @return void
  1472. */
  1473. function mergingWithGetVars($GET_VARS) {
  1474. if (is_array($GET_VARS)) {
  1475. $realGet = t3lib_div::_GET(); // Getting $_GET var, unescaped.
  1476. if (!is_array($realGet)) $realGet = array();
  1477. // Merge new values on top:
  1478. $realGet = t3lib_div::array_merge_recursive_overrule($realGet,$GET_VARS);
  1479. // Write values back to $_GET:
  1480. t3lib_div::_GETset($realGet);
  1481. // Setting these specifically (like in the init-function):
  1482. if (isset($GET_VARS['type'])) $this->type = intval($GET_VARS['type']);
  1483. if (isset($GET_VARS['cHash'])) $this->cHash = $GET_VARS['cHash'];
  1484. if (isset($GET_VARS['jumpurl'])) $this->jumpurl = $GET_VARS['jumpurl'];
  1485. if (isset($GET_VARS['MP'])) $this->MP = $this->TYPO3_CONF_VARS['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
  1486. if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) $this->set_no_cache();
  1487. }
  1488. }
  1489. /**
  1490. * Looking for a ADMCMD_prev code, looks it up if found and returns configuration data.
  1491. * Background: From the backend a request to the frontend to show a page, possibly with workspace preview can be "recorded" and associated with a keyword. When the frontend is requested with this keyword the associated request parameters are restored from the database AND the backend user is loaded - only for that request.
  1492. * The main point is that a special URL valid for a limited time, eg. http://localhost/typo3site/index.php?ADMCMD_prev=035d9bf938bd23cb657735f68a8cedbf will open up for a preview that doesn't require login. Thus it's useful for sending in an email to someone without backend account.
  1493. * This can also be used to generate previews of hidden pages, start/endtimes, usergroups and those other settings from the Admin Panel - just not implemented yet.
  1494. *
  1495. * @return array Preview configuration array from sys_preview record.
  1496. * @see t3lib_BEfunc::compilePreviewKeyword()
  1497. */
  1498. function ADMCMD_preview(){
  1499. $inputCode = t3lib_div::_GP('ADMCMD_prev');
  1500. // If no inputcode and a cookie is set, load input code from cookie:
  1501. if (!$inputCode && $_COOKIE['ADMCMD_prev']) {
  1502. $inputCode = $_COOKIE['ADMCMD_prev'];
  1503. }
  1504. // If inputcode now, look up the settings:
  1505. if ($inputCode) {
  1506. if ($inputCode=='LOGOUT') { // "log out":
  1507. SetCookie('ADMCMD_prev', '', 0, t3lib_div::getIndpEnv('TYPO3_SITE_PATH'));
  1508. if ($this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate']) {
  1509. if (@is_file(PATH_site.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate'])) {
  1510. $message = t3lib_div::getUrl(PATH_site.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate']);
  1511. } else {
  1512. $message = '<strong>ERROR!</strong><br>Template File "'.$this->TYPO3_CONF_VARS['FE']['workspacePreviewLogoutTemplate'].'" configured with $TYPO3_CONF_VARS["FE"]["workspacePreviewLogoutTemplate"] not found. Please contact webmaster about this problem.';
  1513. }
  1514. } else {
  1515. $message = 'You logged out from Workspace preview mode. Click this link to <a href="%1$s">go back to the website</a>';
  1516. }
  1517. $returnUrl = t3lib_div::sanitizeLocalUrl(t3lib_div::_GET('returnUrl'));
  1518. die(sprintf($message,
  1519. htmlspecialchars(preg_replace('/\&?ADMCMD_prev=[[:alnum:]]+/', '', $returnUrl))
  1520. ));
  1521. }
  1522. // Look for keyword configuration record:
  1523. list($previewData) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
  1524. '*',
  1525. 'sys_preview',
  1526. 'keyword='.$GLOBALS['TYPO3_DB']->fullQuoteStr($inputCode, 'sys_preview').
  1527. ' AND endtime>' . $GLOBALS['EXEC_TIME']
  1528. );
  1529. // Get: Backend login status, Frontend login status
  1530. // - Make sure to remove fe/be cookies (temporarily); BE already done in ADMCMD_preview_postInit()
  1531. if (is_array($previewData)) {
  1532. if (!count(t3lib_div::_POST())) {
  1533. // Unserialize configuration:
  1534. $previewConfig = unserialize($previewData['config']);
  1535. if ($previewConfig['fullWorkspace']) { // For full workspace preview we only ADD a get variable to set the preview of the workspace - so all other Get vars are accepted. Hope this is not a security problem. Still posting is not allowed and even if a backend user get initialized it shouldn't lead to situations where users can use those credentials.
  1536. // Set the workspace preview value:
  1537. t3lib_div::_GETset($previewConfig['fullWorkspace'],'ADMCMD_previewWS');
  1538. // If ADMCMD_prev is set the $inputCode value cannot come from a cookie and we set that cookie here. Next time it will be found from the cookie if ADMCMD_prev is not set again...
  1539. if (t3lib_div::_GP('ADMCMD_prev')) {
  1540. SetCookie('ADMCMD_prev', t3lib_div::_GP('ADMCMD_prev'), 0, t3lib_div::getIndpEnv('TYPO3_SITE_PATH')); // Lifetime is 1 hour, does it matter much? Requires the user to click the link from their email again if it expires.
  1541. }
  1542. return $previewConfig;
  1543. } elseif (t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.$inputCode === t3lib_div::getIndpEnv('TYPO3_REQUEST_URL')) {
  1544. // Set GET variables:
  1545. $GET_VARS = '';
  1546. parse_str($previewConfig['getVars'], $GET_VARS);
  1547. t3lib_div::_GETset($GET_VARS);
  1548. // Return preview keyword configuration:
  1549. return $previewConfig;
  1550. } else die(htmlspecialchars('Request URL did not match "'.t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev='.$inputCode.'"')); // This check is to prevent people from setting additional GET vars via realurl or other URL path based ways of passing parameters.
  1551. } else die('POST requests are incompatible with keyword preview.');
  1552. } else die('ADMCMD command could not be executed! (No keyword configuration found)');
  1553. }
  1554. }
  1555. /**
  1556. * Configuration after initialization of TSFE object.
  1557. * Basically this unsets the BE cookie if any and forces the BE user set according to the preview configuration.
  1558. *
  1559. * @param array Preview configuration, see ADMCMD_preview()
  1560. * @return void
  1561. * @see ADMCMD_preview(), index_ts.php
  1562. */
  1563. function ADMCMD_preview_postInit($previewConfig){
  1564. if (is_array($previewConfig)) {
  1565. // Clear cookies:
  1566. unset($_COOKIE['be_typo_user']);
  1567. $this->ADMCMD_preview_BEUSER_uid = $previewConfig['BEUSER_uid'];
  1568. } else die('Error in preview configuration.');
  1569. }
  1570. /********************************************
  1571. *
  1572. * Template and caching related functions.
  1573. *
  1574. *******************************************/
  1575. /**
  1576. * Calculates a hash string based on additional parameters in the url. This is used to cache pages with more parameters than just id and type
  1577. *
  1578. * @return void
  1579. * @see reqCHash()
  1580. */
  1581. function makeCacheHash() {
  1582. // No need to test anything if caching was already disabled.
  1583. if ($this->no_cache && !$this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
  1584. return;
  1585. }
  1586. $GET = t3lib_div::_GET();
  1587. if ($this->cHash && is_array($GET)) {
  1588. $this->cHash_array = t3lib_div::cHashParams(t3lib_div::implodeArrayForUrl('',$GET));
  1589. $cHash_calc = t3lib_div::calculateCHash($this->cHash_array);
  1590. if ($cHash_calc!=$this->cHash) {
  1591. if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
  1592. $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
  1593. } else {
  1594. $this->set_no_cache();
  1595. $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);
  1596. }
  1597. }
  1598. }
  1599. }
  1600. /**
  1601. * Will disable caching if the cHash value was not set.
  1602. * This function should be called to check the _existence_ of "&cHash" whenever a plugin generating cachable output is using extra GET variables. If there _is_ a cHash value the validation of it automatically takes place in makeCacheHash() (see above)
  1603. *
  1604. * @return void
  1605. * @see makeCacheHash(), tslib_pibase::pi_cHashCheck()
  1606. */
  1607. function reqCHash() {
  1608. if (!$this->cHash) {
  1609. if ($this->TYPO3_CONF_VARS['FE']['pageNotFoundOnCHashError']) {
  1610. if ($this->tempContent) { $this->clearPageCacheContent(); }
  1611. $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
  1612. } else {
  1613. $this->set_no_cache();
  1614. $GLOBALS['TT']->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled',2);
  1615. }
  1616. }
  1617. }
  1618. /**
  1619. * Splits the input query-parameters into an array with certain parameters filtered out.
  1620. * Used to create the cHash value
  1621. *
  1622. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  1623. * @return array Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc) and WITH a variable, encryptionKey, specific for this server/installation
  1624. * @access private
  1625. * @see makeCacheHash(), tslib_cObj::typoLink()
  1626. * @obsolete
  1627. */
  1628. function cHashParams($addQueryParams) {
  1629. return t3lib_div::cHashParams($addQueryParams);
  1630. }
  1631. /**
  1632. * Initialize the TypoScript template parser
  1633. *
  1634. * @return void
  1635. */
  1636. function initTemplate() {
  1637. $this->tmpl = t3lib_div::makeInstance('t3lib_TStemplate');
  1638. $this->tmpl->init();
  1639. $this->tmpl->tt_track= $this->beUserLogin ? 1 : 0;
  1640. }
  1641. /**
  1642. * See if page is in cache and get it if so
  1643. * Stores the page content in $this->content if something is found.
  1644. *
  1645. * @return void
  1646. */
  1647. function getFromCache() {
  1648. if (!$this->no_cache) {
  1649. $cc = $this->tmpl->getCurrentPageData();
  1650. if (!is_array($cc)) {
  1651. $key = $this->id.'::'.$this->MP;
  1652. $isLocked = $this->acquirePageGenerationLock($this->pagesection_lockObj, $key); // Returns true if the lock is active now
  1653. if (!$isLocked) {
  1654. // Lock is no longer active, the data in "cache_pagesection" is now ready
  1655. $cc = $this->tmpl->getCurrentPageData();
  1656. if (is_array($cc)) {
  1657. $this->releasePageGenerationLock($this->pagesection_lockObj); // Release the lock
  1658. }
  1659. }
  1660. }
  1661. if (is_array($cc)) {
  1662. // BE CAREFUL 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.
  1663. // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
  1664. $cc = $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.
  1665. ksort($cc);
  1666. $this->all = $cc;
  1667. }
  1668. unset($cc);
  1669. }
  1670. $this->content = ''; // clearing the content-variable, which will hold the pagecontent
  1671. unset($this->config); // Unsetting the lowlevel config
  1672. $this->cacheContentFlag = 0;
  1673. // Look for page in cache only if caching is not disabled and if a shift-reload is not sent to the server.
  1674. if (!$this->no_cache && !$this->headerNoCache()) {
  1675. $lockHash = $this->getLockHash();
  1676. if ($this->all) {
  1677. $this->newHash = $this->getHash();
  1678. $GLOBALS['TT']->push('Cache Row','');
  1679. $row = $this->getFromCache_queryRow();
  1680. if (!is_array($row)) {
  1681. $isLocked = $this->acquirePageGenerationLock($this->pages_lockObj, $lockHash);
  1682. if (!$isLocked) {
  1683. // Lock is no longer active, the data in "cache_pages" is now ready
  1684. $row = $this->getFromCache_queryRow();
  1685. if (is_array($row)) {
  1686. $this->releasePageGenerationLock($this->pages_lockObj); // Release the lock
  1687. }
  1688. }
  1689. }
  1690. if (is_array($row)) {
  1691. // Release this lock
  1692. $this->releasePageGenerationLock($this->pages_lockObj);
  1693. // Call hook when a page is retrieved from cache:
  1694. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'])) {
  1695. $_params = array('pObj' => &$this, 'cache_pages_row' => &$row);
  1696. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] as $_funcRef) {
  1697. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  1698. }
  1699. }
  1700. $this->config = (array)unserialize($row['cache_data']); // Fetches the lowlevel config stored with the cached data
  1701. $this->content = (TYPO3_UseCachingFramework ? $row['content'] : $row['HTML']); // Getting the content
  1702. $this->tempContent = $row['temp_content']; // Flag for temp content
  1703. $this->cacheContentFlag = 1; // Setting flag, so we know, that some cached content has been loaded
  1704. $this->cacheExpires = $row['expires'];
  1705. if ($this->TYPO3_CONF_VARS['FE']['debug'] || (isset($this->config['config']['debug']) && $this->config['config']['debug'])) {
  1706. $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
  1707. $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
  1708. $this->content.= LF.'<!-- Cached page generated '.date($dateFormat.' '.$timeFormat, $row['tstamp']).'. Expires '.Date($dateFormat.' '.$timeFormat, $row['expires']).' -->';
  1709. }
  1710. }
  1711. $GLOBALS['TT']->pull();
  1712. } else {
  1713. $this->acquirePageGenerationLock($this->pages_lockObj, $lockHash);
  1714. }
  1715. }
  1716. }
  1717. /**
  1718. * Returning the cached version of page with hash = newHash
  1719. *
  1720. * @return array Cached row, if any. Otherwise void.
  1721. */
  1722. function getFromCache_queryRow() {
  1723. if (TYPO3_UseCachingFramework) {
  1724. $GLOBALS['TT']->push('Cache Query', '');
  1725. $row = $this->pageCache->get($this->newHash);
  1726. $GLOBALS['TT']->pull();
  1727. } else {
  1728. $GLOBALS['TT']->push('Cache Query','');
  1729. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
  1730. 'S.*',
  1731. 'cache_pages S,pages P',
  1732. 'S.hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages').'
  1733. AND S.page_id=P.uid
  1734. AND S.expires > '.intval($GLOBALS['ACCESS_TIME']).'
  1735. AND P.deleted=0
  1736. AND P.hidden=0
  1737. AND P.starttime<='.intval($GLOBALS['ACCESS_TIME']).'
  1738. AND (P.endtime=0 OR P.endtime>'.intval($GLOBALS['ACCESS_TIME']).')'
  1739. );
  1740. $GLOBALS['TT']->pull();
  1741. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  1742. $this->pageCachePostProcess($row,'get');
  1743. }
  1744. $GLOBALS['TYPO3_DB']->sql_free_result($res);
  1745. }
  1746. return $row;
  1747. }
  1748. /**
  1749. * Detecting if shift-reload has been clicked
  1750. * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
  1751. * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
  1752. *
  1753. * @return boolean If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
  1754. */
  1755. function headerNoCache() {
  1756. $disableAcquireCacheData = FALSE;
  1757. if ($this->beUserLogin) {
  1758. if (strtolower($_SERVER['HTTP_CACHE_CONTROL'])==='no-cache' || strtolower($_SERVER['HTTP_PRAGMA'])==='no-cache') {
  1759. $disableAcquireCacheData = TRUE;
  1760. }
  1761. }
  1762. // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
  1763. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'])) {
  1764. $_params = array('pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData);
  1765. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] as $_funcRef) {
  1766. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  1767. }
  1768. }
  1769. return $disableAcquireCacheData;
  1770. }
  1771. /**
  1772. * Calculates the cache-hash
  1773. * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
  1774. * Used to get and later store the cached data.
  1775. *
  1776. * @return string MD5 hash of $this->hash_base which is a serialized version of there variables.
  1777. * @access private
  1778. * @see getFromCache(), getLockHash()
  1779. */
  1780. function getHash() {
  1781. $this->hash_base = serialize(
  1782. array(
  1783. 'all' => $this->all,
  1784. 'id' => intval($this->id),
  1785. 'type' => intval($this->type),
  1786. 'gr_list' => (string)$this->gr_list,
  1787. 'MP' => (string)$this->MP,
  1788. 'cHash' => $this->cHash_array,
  1789. 'domainStartPage' => $this->domainStartPage,
  1790. )
  1791. );
  1792. return md5($this->hash_base);
  1793. }
  1794. /**
  1795. * Calculates the lock-hash
  1796. * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
  1797. *
  1798. * @return string MD5 hash
  1799. * @access private
  1800. * @see getFromCache(), getHash()
  1801. */
  1802. function getLockHash() {
  1803. $lockHash = serialize(
  1804. array(
  1805. 'id' => intval($this->id),
  1806. 'type' => intval($this->type),
  1807. 'gr_list' => (string)$this->gr_list,
  1808. 'MP' => (string)$this->MP,
  1809. 'cHash' => $this->cHash_array,
  1810. 'domainStartPage' => $this->domainStartPage,
  1811. )
  1812. );
  1813. return md5($lockHash);
  1814. }
  1815. /**
  1816. * Checks if config-array exists already but if not, gets it
  1817. *
  1818. * @return void
  1819. */
  1820. function getConfigArray() {
  1821. $setStatPageName = false;
  1822. 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
  1823. $GLOBALS['TT']->push('Parse template','');
  1824. // Force parsing, if set?:
  1825. $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
  1826. // Start parsing the TS template. Might return cached version.
  1827. $this->tmpl->start($this->rootLine);
  1828. $GLOBALS['TT']->pull();
  1829. if ($this->tmpl->loaded) {
  1830. $GLOBALS['TT']->push('Setting the config-array','');
  1831. // t3lib_div::print_array($this->tmpl->setup);
  1832. $this->sPre = $this->tmpl->setup['types.'][$this->type]; // toplevel - objArrayName
  1833. $this->pSetup = $this->tmpl->setup[$this->sPre.'.'];
  1834. if (!is_array($this->pSetup)) {
  1835. if ($this->checkPageUnavailableHandler()) {
  1836. $this->pageUnavailableAndExit('The page is not configured! [type= '.$this->type.']['.$this->sPre.']');
  1837. } else {
  1838. $message = 'The page is not configured! [type= '.$this->type.']['.$this->sPre.']';
  1839. header('HTTP/1.0 503 Service Temporarily Unavailable');
  1840. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  1841. $this->printError($message);
  1842. exit;
  1843. }
  1844. } else {
  1845. $this->config['config'] = array();
  1846. // Filling the config-array, first with the main "config." part
  1847. if (is_array($this->tmpl->setup['config.'])) {
  1848. $this->config['config'] = $this->tmpl->setup['config.'];
  1849. }
  1850. // override it with the page/type-specific "config."
  1851. if (is_array($this->pSetup['config.'])) {
  1852. $this->config['config'] = t3lib_div::array_merge_recursive_overrule($this->config['config'], $this->pSetup['config.']);
  1853. }
  1854. if ($this->config['config']['typolinkEnableLinksAcrossDomains']) {
  1855. $this->config['config']['typolinkCheckRootline'] = true;
  1856. }
  1857. // Set default values for removeDefaultJS, inlineStyle2TempFile and minifyJS so CSS and JS are externalized/minified if compatversion is higher than 4.0
  1858. if (t3lib_div::compat_version('4.0')) {
  1859. if (!isset($this->config['config']['removeDefaultJS'])) {
  1860. $this->config['config']['removeDefaultJS'] = 'external';
  1861. }
  1862. if (!isset($this->config['config']['inlineStyle2TempFile'])) {
  1863. $this->config['config']['inlineStyle2TempFile'] = 1;
  1864. }
  1865. if (!isset($this->config['config']['minifyJS'])) {
  1866. $this->config['config']['minifyJS'] = 1;
  1867. }
  1868. }
  1869. // Processing for the config_array:
  1870. $this->config['rootLine'] = $this->tmpl->rootLine;
  1871. $this->config['mainScript'] = trim($this->config['config']['mainScript']) ? trim($this->config['config']['mainScript']) : 'index.php';
  1872. // Initialize statistics handling: Check filename and permissions
  1873. $setStatPageName = $this->statistics_init();
  1874. $this->config['FEData'] = $this->tmpl->setup['FEData'];
  1875. $this->config['FEData.'] = $this->tmpl->setup['FEData.'];
  1876. // class for render Header and Footer parts
  1877. $template = '';
  1878. if ($this->pSetup['pageHeaderFooterTemplateFile']) {
  1879. $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
  1880. if ($file) {
  1881. $this->setTemplateFile($file);
  1882. }
  1883. }
  1884. }
  1885. $GLOBALS['TT']->pull();
  1886. } else {
  1887. if ($this->checkPageUnavailableHandler()) {
  1888. $this->pageUnavailableAndExit('No TypoScript template found!');
  1889. } else {
  1890. $message = 'No TypoScript template found!';
  1891. header('HTTP/1.0 503 Service Temporarily Unavailable');
  1892. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  1893. $this->printError($message);
  1894. exit;
  1895. }
  1896. }
  1897. }
  1898. // Initialize charset settings etc.
  1899. $this->initLLvars();
  1900. // We want nice names, so we need to handle the charset
  1901. if ($setStatPageName) {
  1902. $this->statistics_init_pagename();
  1903. }
  1904. // No cache
  1905. if ($this->config['config']['no_cache']) { $this->set_no_cache(); } // Set $this->no_cache true if the config.no_cache value is set!
  1906. // merge GET with defaultGetVars
  1907. if (!empty($this->config['config']['defaultGetVars.'])) {
  1908. $modifiedGetVars = t3lib_div::array_merge_recursive_overrule(
  1909. t3lib_div::removeDotsFromTS($this->config['config']['defaultGetVars.']),
  1910. t3lib_div::_GET()
  1911. );
  1912. t3lib_div::_GETset($modifiedGetVars);
  1913. }
  1914. // Hook for postProcessing the configuration array
  1915. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'])) {
  1916. $params = array('config' => &$this->config['config']);
  1917. foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] as $funcRef) {
  1918. t3lib_div::callUserFunction($funcRef, $params, $this);
  1919. }
  1920. }
  1921. }
  1922. /********************************************
  1923. *
  1924. * Further initialization and data processing
  1925. * (jumpurl/submission of forms)
  1926. *
  1927. *******************************************/
  1928. /**
  1929. * Get the compressed $TCA array for use in the front-end
  1930. * A compressed $TCA array holds only the ctrl- and feInterface-part for each table. But the column-definitions are omitted in order to save some memory and be more efficient.
  1931. * Operates on the global variable, $TCA
  1932. *
  1933. * @return void
  1934. * @see includeTCA()
  1935. */
  1936. function getCompressedTCarray() {
  1937. global $TCA;
  1938. $GLOBALS['TT']->push('Get Compressed TC array');
  1939. if (!$this->TCAloaded) {
  1940. // Create hash string for storage / retrieval of cached content:
  1941. $tempHash = md5('tables.php:'.
  1942. filemtime(TYPO3_extTableDef_script ? PATH_typo3conf.TYPO3_extTableDef_script : PATH_t3lib.'stddb/tables.php').
  1943. (TYPO3_extTableDef_script?filemtime(PATH_typo3conf.TYPO3_extTableDef_script):'').
  1944. ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'] ? filemtime(PATH_typo3conf.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php') : '')
  1945. );
  1946. if ($this->TYPO3_CONF_VARS['EXT']['extCache'] != 0) {
  1947. // Try to fetch if cache is enabled
  1948. list($TCA, $this->TCAcachedExtras) = unserialize($this->sys_page->getHash($tempHash));
  1949. }
  1950. // If no result, create it:
  1951. if (!is_array($TCA)) {
  1952. $this->includeTCA(0);
  1953. $newTc = Array();
  1954. $this->TCAcachedExtras = array(); // Collects other information
  1955. foreach($TCA as $key => $val) {
  1956. $newTc[$key]['ctrl'] = $val['ctrl'];
  1957. $newTc[$key]['feInterface'] = $val['feInterface'];
  1958. // Collect information about localization exclusion of fields:
  1959. t3lib_div::loadTCA($key);
  1960. if (is_array($TCA[$key]['columns'])) {
  1961. $this->TCAcachedExtras[$key]['l10n_mode'] = array();
  1962. foreach($TCA[$key]['columns'] as $fN => $fV) {
  1963. if ($fV['l10n_mode']) {
  1964. $this->TCAcachedExtras[$key]['l10n_mode'][$fN] = $fV['l10n_mode'];
  1965. }
  1966. }
  1967. }
  1968. }
  1969. $TCA = $newTc;
  1970. // Store it in cache if cache is enabled
  1971. if ($this->TYPO3_CONF_VARS['EXT']['extCache'] != 0) {
  1972. $this->sys_page->storeHash($tempHash, serialize(array($newTc,$this->TCAcachedExtras)), 'SHORT_TC');
  1973. }
  1974. }
  1975. }
  1976. $GLOBALS['TT']->pull();
  1977. }
  1978. /**
  1979. * Includes TCA definitions from loaded extensions (ext_table.php files).
  1980. * Normally in the frontend only a part of the global $TCA array is loaded,
  1981. * namely the "ctrl" part. Thus it doesn't take up too much memory. To load
  1982. * full TCA for the table, use t3lib_div::loadTCA($tableName) after calling
  1983. * this function.
  1984. *
  1985. * @param boolean Probably, keep hands of this value. Just don't set it. (This may affect the first-ever time this function is called since if you set it to zero/false any subsequent call will still trigger the inclusion; In other words, this value will be set in $this->TCAloaded after inclusion and therefore if its false, another inclusion will be possible on the next call. See ->getCompressedTCarray())
  1986. * @return void
  1987. * @see getCompressedTCarray()
  1988. */
  1989. function includeTCA($TCAloaded=1) {
  1990. global $TCA, $PAGES_TYPES, $LANG_GENERAL_LABELS, $TBE_MODULES;
  1991. if (!$this->TCAloaded) {
  1992. $TCA = Array();
  1993. include (TYPO3_tables_script ? PATH_typo3conf.TYPO3_tables_script : PATH_t3lib.'stddb/tables.php');
  1994. // Extension additions
  1995. if ($GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE']) {
  1996. include(PATH_typo3conf.$GLOBALS['TYPO3_LOADED_EXT']['_CACHEFILE'].'_ext_tables.php');
  1997. } else {
  1998. include(PATH_t3lib.'stddb/load_ext_tables.php');
  1999. }
  2000. // ext-script
  2001. if (TYPO3_extTableDef_script) {
  2002. include (PATH_typo3conf.TYPO3_extTableDef_script);
  2003. }
  2004. $this->TCAloaded = $TCAloaded;
  2005. }
  2006. }
  2007. /**
  2008. * Setting the language key that will be used by the current page.
  2009. * In this function it should be checked, 1) that this language exists, 2) that a page_overlay_record exists, .. and if not the default language, 0 (zero), should be set.
  2010. *
  2011. * @return void
  2012. * @access private
  2013. */
  2014. function settingLanguage() {
  2015. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'])) {
  2016. $_params = array();
  2017. foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] as $_funcRef) {
  2018. t3lib_div::callUserFunction($_funcRef, $_params, $this);
  2019. }
  2020. }
  2021. // Get values from TypoScript:
  2022. $this->sys_language_uid = $this->sys_language_content = intval($this->config['config']['sys_language_uid']);
  2023. list($this->sys_language_mode,$sys_language_content) = t3lib_div::trimExplode(';', $this->config['config']['sys_language_mode']);
  2024. $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
  2025. // If sys_language_uid is set to another language than default:
  2026. if ($this->sys_language_uid>0) {
  2027. // check whether a shortcut is overwritten by a translated page
  2028. // we can only do this now, as this is the place where we get
  2029. // to know about translations
  2030. $this->checkTranslatedShortcut();
  2031. // Request the overlay record for the sys_language_uid:
  2032. $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
  2033. if (!count($olRec)) {
  2034. // If no OL record exists and a foreign language is asked for...
  2035. if ($this->sys_language_uid) {
  2036. // If requested translation is not available:
  2037. if (t3lib_div::hideIfNotTranslated($this->page['l18n_cfg'])) {
  2038. $this->pageNotFoundAndExit('Page is not available in the requested language.');
  2039. } else {
  2040. switch((string)$this->sys_language_mode) {
  2041. case 'strict':
  2042. $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
  2043. break;
  2044. case 'content_fallback':
  2045. $fallBackOrder = t3lib_div::intExplode(',', $sys_language_content);
  2046. foreach($fallBackOrder as $orderValue) {
  2047. if (!strcmp($orderValue,'0') || count($this->sys_page->getPageOverlay($this->id, $orderValue))) {
  2048. $this->sys_language_content = $orderValue; // Setting content uid (but leaving the sys_language_uid)
  2049. break;
  2050. }
  2051. }
  2052. break;
  2053. case 'ignore':
  2054. $this->sys_language_content = $this->sys_language_uid;
  2055. break;
  2056. default:
  2057. // Default is that everything defaults to the default language...
  2058. $this->sys_language_uid = $this->sys_language_content = 0;
  2059. break;
  2060. }
  2061. }
  2062. }
  2063. } else {
  2064. // Setting sys_language if an overlay record was found (which it is only if a language is used)
  2065. $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
  2066. }
  2067. }
  2068. // Setting sys_language_uid inside sys-page:
  2069. $this->sys_page->sys_language_uid = $this->sys_language_uid;
  2070. // If default translation is not available:
  2071. if ((!$this->sys_language_uid || !$this->sys_language_content) && $this->page['l18n_cfg']&1) {
  2072. $message = 'Page is not available in default language.';
  2073. t3lib_div::sysLog($message, 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  2074. $this->pageNotFoundAndExit($message);
  2075. }
  2076. // Updating content of the two rootLines IF the language key is set!
  2077. if ($this->sys_language_uid && is_array($this->tmpl->rootLine)) {
  2078. foreach ($this->tmpl->rootLine as $rLk => $value) {
  2079. $this->tmpl->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->tmpl->rootLine[$rLk]);
  2080. }
  2081. }
  2082. if ($this->sys_language_uid && is_array($this->rootLine)) {
  2083. foreach ($this->rootLine as $rLk => $value) {
  2084. $this->rootLine[$rLk] = $this->sys_page->getPageOverlay($this->rootLine[$rLk]);
  2085. }
  2086. }
  2087. // Finding the ISO code:
  2088. 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"
  2089. $sys_language_row = $this->sys_page->getRawRecord('sys_language',$this->sys_language_content,'static_lang_isocode');
  2090. if (is_array($sys_language_row) && $sys_language_row['static_lang_isocode']) {
  2091. $stLrow = $this->sys_page->getRawRecord('static_languages',$sys_language_row['static_lang_isocode'],'lg_iso_2');
  2092. $this->sys_language_isocode = $stLrow['lg_iso_2'];
  2093. }
  2094. }
  2095. // Setting softMergeIfNotBlank:
  2096. $table_fields = t3lib_div::trimExplode(',', $this->config['config']['sys_language_softMergeIfNotBlank'],1);
  2097. foreach($table_fields as $TF) {
  2098. list($tN,$fN) = explode(':',$TF);
  2099. $this->TCAcachedExtras[$tN]['l10n_mode'][$fN] = 'mergeIfNotBlank';
  2100. }
  2101. // Setting softExclude:
  2102. $table_fields = t3lib_div::trimExplode(',', $this->config['config']['sys_language_softExclude'],1);
  2103. foreach($table_fields as $TF) {
  2104. list($tN,$fN) = explode(':',$TF);
  2105. $this->TCAcachedExtras[$tN]['l10n_mode'][$fN] = 'exclude';
  2106. }
  2107. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'])) {
  2108. $_params = array();
  2109. foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] as $_funcRef) {
  2110. t3lib_div::callUserFunction($_funcRef, $_params, $this);
  2111. }
  2112. }
  2113. }
  2114. /**
  2115. * Setting locale for frontend rendering
  2116. *
  2117. * @return void
  2118. */
  2119. function settingLocale() {
  2120. // Setting locale
  2121. if ($this->config['config']['locale_all']) {
  2122. # Change by Rene Fritz, 22/10 2002
  2123. # 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
  2124. # this does not work in php 4.2.3
  2125. #setlocale('LC_ALL',$this->config['config']['locale_all']);
  2126. #setlocale('LC_NUMERIC','en_US');
  2127. # so we set all except LC_NUMERIC
  2128. $locale = setlocale(LC_COLLATE, $this->config['config']['locale_all']);
  2129. if ($locale) {
  2130. setlocale(LC_CTYPE, $this->config['config']['locale_all']);
  2131. setlocale(LC_MONETARY, $this->config['config']['locale_all']);
  2132. setlocale(LC_TIME, $this->config['config']['locale_all']);
  2133. $this->localeCharset = $this->csConvObj->get_locale_charset($this->config['config']['locale_all']);
  2134. } else {
  2135. $GLOBALS['TT']->setTSlogMessage('Locale "'.htmlspecialchars($this->config['config']['locale_all']).'" not found.', 3);
  2136. }
  2137. }
  2138. }
  2139. /**
  2140. * checks whether a translated shortcut page has a different shortcut
  2141. * target than the original language page.
  2142. * If that is the case, things get corrected to follow that alternative
  2143. * shortcut
  2144. *
  2145. * @return void
  2146. * @author Ingo Renner <ingo@typo3.org>
  2147. */
  2148. protected function checkTranslatedShortcut() {
  2149. if (!is_null($this->originalShortcutPage)) {
  2150. $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
  2151. if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
  2152. // the translation of the original shortcut page has a different shortcut target!
  2153. // set the correct page and id
  2154. $shortcut = $this->getPageShortcut(
  2155. $originalShortcutPageOverlay['shortcut'],
  2156. $originalShortcutPageOverlay['shortcut_mode'],
  2157. $originalShortcutPageOverlay['uid']
  2158. );
  2159. $this->id = $this->contentPid = $shortcut['uid'];
  2160. $this->page = $this->sys_page->getPage($this->id);
  2161. // fix various effects on things like menus f.e.
  2162. $this->fetch_the_id();
  2163. $this->tmpl->rootLine = array_reverse($this->rootLine);
  2164. }
  2165. }
  2166. }
  2167. /**
  2168. * Checks if any email-submissions or submission via the fe_tce
  2169. *
  2170. * @return string "email" if a formmail has been sent, "fe_tce" if front-end data submission (like forums, guestbooks) is sent. "" if none.
  2171. */
  2172. function checkDataSubmission() {
  2173. $ret = '';
  2174. $formtype_db = isset($_POST['formtype_db']) || isset($_POST['formtype_db_x']);
  2175. $formtype_mail = isset($_POST['formtype_mail']) || isset($_POST['formtype_mail_x']);
  2176. if ($formtype_db || $formtype_mail) {
  2177. $refInfo = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
  2178. if (t3lib_div::getIndpEnv('TYPO3_HOST_ONLY')==$refInfo['host'] || $this->TYPO3_CONF_VARS['SYS']['doNotCheckReferer']) {
  2179. if ($this->locDataCheck($_POST['locationData'])) {
  2180. if ($formtype_mail) {
  2181. $ret = 'email';
  2182. } elseif ($formtype_db && is_array($_POST['data'])) {
  2183. $ret = 'fe_tce';
  2184. }
  2185. $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": Return value: '.$ret,0);
  2186. return $ret;
  2187. }
  2188. } else $GLOBALS['TT']->setTSlogMessage('"Check Data Submission": HTTP_HOST and REFERER HOST did not match when processing submitted formdata!',3);
  2189. }
  2190. // Hook for processing data submission to extensions:
  2191. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'])) {
  2192. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] as $_classRef) {
  2193. $_procObj = t3lib_div::getUserObj($_classRef);
  2194. $_procObj->checkDataSubmission($this);
  2195. }
  2196. }
  2197. return $ret;
  2198. }
  2199. /**
  2200. * Processes submitted user data (obsolete "Frontend TCE")
  2201. *
  2202. * @return void
  2203. * @see tslib_feTCE
  2204. * @link http://typo3.org/doc.0.html?&tx_extrepmgm_pi1[extUid]=270&tx_extrepmgm_pi1[tocEl]=342&cHash=fdf55adb3b
  2205. */
  2206. function fe_tce() {
  2207. $fe_tce = t3lib_div::makeInstance('tslib_feTCE');
  2208. $fe_tce->start(t3lib_div::_POST('data'),$this->config['FEData.']);
  2209. $fe_tce->includeScripts();
  2210. }
  2211. /**
  2212. * Checks if a formmail submission can be sent as email
  2213. *
  2214. * @param string The input from $_POST['locationData']
  2215. * @return void
  2216. * @access private
  2217. * @see checkDataSubmission()
  2218. */
  2219. function locDataCheck($locationData) {
  2220. $locData = explode(':',$locationData);
  2221. if (!$locData[1] || $this->sys_page->checkRecord($locData[1],$locData[2],1)) {
  2222. 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.
  2223. return 1;
  2224. } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: The page pointed to by location data ('.$locationData.') was not accessible.',2);
  2225. } else $GLOBALS['TT']->setTSlogMessage('LocationData Error: Location data ('.$locationData.') record pointed to was not accessible.',2);
  2226. }
  2227. /**
  2228. * Sends the emails from the formmail content object.
  2229. *
  2230. * @return void
  2231. * @access private
  2232. * @see checkDataSubmission()
  2233. */
  2234. function sendFormmail() {
  2235. $formmail = t3lib_div::makeInstance('t3lib_formmail');
  2236. $EMAIL_VARS = t3lib_div::_POST();
  2237. $locationData = $EMAIL_VARS['locationData'];
  2238. unset($EMAIL_VARS['locationData']);
  2239. unset($EMAIL_VARS['formtype_mail'], $EMAIL_VARS['formtype_mail_x'], $EMAIL_VARS['formtype_mail_y']);
  2240. $integrityCheck = $this->TYPO3_CONF_VARS['FE']['strictFormmail'];
  2241. if (!$this->TYPO3_CONF_VARS['FE']['secureFormmail']) {
  2242. // Check recipient field:
  2243. $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.
  2244. foreach ($encodedFields as $fieldKey) {
  2245. if (strlen($EMAIL_VARS[$fieldKey])) {
  2246. if ($res = $this->codeString($EMAIL_VARS[$fieldKey], TRUE)) { // Decode...
  2247. $EMAIL_VARS[$fieldKey] = $res; // Set value if OK
  2248. } elseif ($integrityCheck) { // Otherwise abort:
  2249. $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);
  2250. return false;
  2251. } else {
  2252. $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);
  2253. }
  2254. }
  2255. }
  2256. } else {
  2257. $locData = explode(':',$locationData);
  2258. $record = $this->sys_page->checkRecord($locData[1],$locData[2],1);
  2259. $EMAIL_VARS['recipient'] = $record['subheader'];
  2260. $EMAIL_VARS['recipient_copy'] = $this->extractRecipientCopy($record['bodytext']);
  2261. }
  2262. // Hook for preprocessing of the content for formmails:
  2263. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass'])) {
  2264. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sendFormmail-PreProcClass'] as $_classRef) {
  2265. $_procObj = t3lib_div::getUserObj($_classRef);
  2266. $EMAIL_VARS = $_procObj->sendFormmail_preProcessVariables($EMAIL_VARS,$this);
  2267. }
  2268. }
  2269. $formmail->start($EMAIL_VARS);
  2270. $formmail->sendtheMail();
  2271. $GLOBALS['TT']->setTSlogMessage('"Formmail" invoked, sending mail to '.$EMAIL_VARS['recipient'],0);
  2272. }
  2273. /**
  2274. * Extracts the value of recipient copy field from a formmail CE bodytext
  2275. *
  2276. * @param string $bodytext The content of the related bodytext field
  2277. * @return string The value of the recipient_copy field, or an empty string
  2278. */
  2279. function extractRecipientCopy($bodytext) {
  2280. $recipient_copy = '';
  2281. $fdef = array();
  2282. //|recipient_copy=hidden|karsten@localhost.localdomain
  2283. preg_match('/^[\s]*\|[\s]*recipient_copy[\s]*=[\s]*hidden[\s]*\|(.*)$/m', $bodytext, $fdef);
  2284. $recipient_copy = (!empty($fdef[1])) ? $fdef[1] : '';
  2285. return $recipient_copy;
  2286. }
  2287. /**
  2288. * Sets the jumpurl for page type "External URL"
  2289. *
  2290. * @return void
  2291. */
  2292. function setExternalJumpUrl() {
  2293. if ($extUrl = $this->sys_page->getExtURL($this->page, $this->config['config']['disablePageExternalUrl'])) {
  2294. $this->jumpurl = $extUrl;
  2295. }
  2296. }
  2297. /**
  2298. * Check the jumpUrl referer if required
  2299. *
  2300. * @return void
  2301. */
  2302. function checkJumpUrlReferer() {
  2303. if (strlen($this->jumpurl) && !$this->TYPO3_CONF_VARS['SYS']['doNotCheckReferer']) {
  2304. $referer = parse_url(t3lib_div::getIndpEnv('HTTP_REFERER'));
  2305. if (isset($referer['host']) && !($referer['host'] == t3lib_div::getIndpEnv('TYPO3_HOST_ONLY'))) {
  2306. unset($this->jumpurl);
  2307. }
  2308. }
  2309. }
  2310. /**
  2311. * Sends a header "Location" to jumpUrl, if jumpurl is set.
  2312. * Will exit if a location header is sent (for instance if jumpUrl was triggered)
  2313. *
  2314. * "jumpUrl" is a concept where external links are redirected from the index_ts.php script, which first logs the URL.
  2315. * This feature is only interesting if config.sys_stat is used.
  2316. *
  2317. * @return void
  2318. */
  2319. function jumpUrl() {
  2320. if ($this->jumpurl) {
  2321. if (t3lib_div::_GP('juSecure')) {
  2322. $locationData = t3lib_div::_GP('locationData');
  2323. $mimeType = t3lib_div::_GP('mimeType');
  2324. $hArr = array(
  2325. $this->jumpurl,
  2326. t3lib_div::_GP('locationData'),
  2327. t3lib_div::_GP('mimeType'),
  2328. $this->TYPO3_CONF_VARS['SYS']['encryptionKey']
  2329. );
  2330. $calcJuHash=t3lib_div::shortMD5(serialize($hArr));
  2331. $juHash = t3lib_div::_GP('juHash');
  2332. if ($juHash == $calcJuHash) {
  2333. if ($this->locDataCheck($locationData)) {
  2334. $this->jumpurl = rawurldecode($this->jumpurl); // 211002 - goes with cObj->filelink() rawurlencode() of filenames so spaces can be allowed.
  2335. // Deny access to files that match TYPO3_CONF_VARS[SYS][fileDenyPattern] and whose parent directory is typo3conf/ (there could be a backup file in typo3conf/ which does not match against the fileDenyPattern)
  2336. if (t3lib_div::verifyFilenameAgainstDenyPattern($this->jumpurl) && basename(dirname($this->jumpurl)) !== 'typo3conf') {
  2337. if (@is_file($this->jumpurl)) {
  2338. $mimeType = $mimeType ? $mimeType : 'application/octet-stream';
  2339. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  2340. header('Content-Type: '.$mimeType);
  2341. header('Content-Disposition: attachment; filename='.basename($this->jumpurl));
  2342. readfile($this->jumpurl);
  2343. exit;
  2344. } else die('jumpurl Secure: "'.$this->jumpurl.'" was not a valid file!');
  2345. } else die('jumpurl Secure: The requested file type was not allowed to be accessed through jumpUrl (fileDenyPattern)!');
  2346. } else die('jumpurl Secure: locationData, '.$locationData.', was not accessible.');
  2347. } else die('jumpurl Secure: Calculated juHash did not match the submitted juHash.');
  2348. } else {
  2349. $TSConf = $this->getPagesTSconfig();
  2350. if ($TSConf['TSFE.']['jumpUrl_transferSession']) {
  2351. $uParts = parse_url($this->jumpurl);
  2352. $params = '&FE_SESSION_KEY='.rawurlencode($this->fe_user->id.'-'.md5($this->fe_user->id.'/'.$this->TYPO3_CONF_VARS['SYS']['encryptionKey']));
  2353. $this->jumpurl.= ($uParts['query']?'':'?').$params; // Add the session parameter ...
  2354. }
  2355. if ($TSConf['TSFE.']['jumpURL_HTTPStatusCode']) {
  2356. switch (intval($TSConf['TSFE.']['jumpURL_HTTPStatusCode'])){
  2357. case 301:
  2358. $statusCode = t3lib_utility_Http::HTTP_STATUS_301;
  2359. break;
  2360. case 302:
  2361. $statusCode = t3lib_utility_Http::HTTP_STATUS_302;
  2362. break;
  2363. case 307:
  2364. $statusCode = t3lib_utility_Http::HTTP_STATUS_307;
  2365. break;
  2366. case 303:
  2367. default:
  2368. $statusCode = t3lib_utility_Http::HTTP_STATUS_303;
  2369. break;
  2370. }
  2371. }
  2372. t3lib_utility_Http::redirect($this->jumpurl, $statusCode);
  2373. }
  2374. }
  2375. }
  2376. /**
  2377. * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
  2378. * This feature allows sessions to use a GET-parameter instead of a cookie.
  2379. *
  2380. * @return void
  2381. * @access private
  2382. */
  2383. function setUrlIdToken() {
  2384. if ($this->config['config']['ftu']) {
  2385. $this->getMethodUrlIdToken = $this->TYPO3_CONF_VARS['FE']['get_url_id_token'];
  2386. } else {
  2387. $this->getMethodUrlIdToken = '';
  2388. }
  2389. }
  2390. /********************************************
  2391. *
  2392. * Page generation; cache handling
  2393. *
  2394. *******************************************/
  2395. /**
  2396. * Returns true if the page should be generated
  2397. * That is if jumpurl is not set and the cacheContentFlag is not set.
  2398. *
  2399. * @return boolean
  2400. */
  2401. function isGeneratePage() {
  2402. return (!$this->cacheContentFlag && !$this->jumpurl);
  2403. }
  2404. /**
  2405. * Temp cache content
  2406. * 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.
  2407. *
  2408. * @return void
  2409. */
  2410. function tempPageCacheContent() {
  2411. $this->tempContent = false;
  2412. if (!$this->no_cache) {
  2413. $seconds = 30;
  2414. $title = htmlspecialchars($this->tmpl->printTitle($this->page['title']));
  2415. $request_uri = htmlspecialchars(t3lib_div::getIndpEnv('REQUEST_URI'));
  2416. $stdMsg = '
  2417. <strong>Page is being generated.</strong><br />
  2418. If this message does not disappear within '.$seconds.' seconds, please reload.';
  2419. $message = $this->config['config']['message_page_is_being_generated'];
  2420. if (strcmp('', $message)) {
  2421. $message = $this->csConvObj->utf8_encode($message,$this->renderCharset); // This page is always encoded as UTF-8
  2422. $message = str_replace('###TITLE###', $title, $message);
  2423. $message = str_replace('###REQUEST_URI###', $request_uri, $message);
  2424. } else $message = $stdMsg;
  2425. $temp_content = '<?xml version="1.0" encoding="UTF-8"?>
  2426. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  2427. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2428. <html xmlns="http://www.w3.org/1999/xhtml">
  2429. <head>
  2430. <title>'.$title.'</title>
  2431. <meta http-equiv="refresh" content="10" />
  2432. </head>
  2433. <body style="background-color:white; font-family:Verdana,Arial,Helvetica,sans-serif; color:#cccccc; text-align:center;">'.
  2434. $message.'
  2435. </body>
  2436. </html>';
  2437. // Fix 'nice errors' feature in modern browsers
  2438. $padSuffix = '<!--pad-->'; // prevent any trims
  2439. $padSize = 768 - strlen($padSuffix) - strlen($temp_content);
  2440. if ($padSize > 0) {
  2441. $temp_content = str_pad($temp_content, $padSize, LF) . $padSuffix;
  2442. }
  2443. if (!$this->headerNoCache() && $cachedRow = $this->getFromCache_queryRow()) {
  2444. // 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.
  2445. // This is either the "Page is being generated" screen or it can be the final result.
  2446. // In any case we should not begin another rendering process also, so we silently disable caching and render the page ourselves and thats it.
  2447. // 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...
  2448. $this->set_no_cache();
  2449. } else {
  2450. $this->tempContent = TRUE; // This flag shows that temporary content is put in the cache
  2451. $this->setPageCacheContent($temp_content, $this->config, $GLOBALS['EXEC_TIME']+$seconds);
  2452. }
  2453. }
  2454. }
  2455. /**
  2456. * Set cache content to $this->content
  2457. *
  2458. * @return void
  2459. */
  2460. function realPageCacheContent() {
  2461. $cache_timeout = $this->get_cache_timeout(); // seconds until a cached page is too old
  2462. $timeOutTime = $GLOBALS['EXEC_TIME']+$cache_timeout;
  2463. if ($this->config['config']['cache_clearAtMidnight']) {
  2464. $midnightTime = mktime (0,0,0,date('m',$timeOutTime),date('d',$timeOutTime),date('Y',$timeOutTime));
  2465. 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.
  2466. $timeOutTime = $midnightTime;
  2467. }
  2468. }
  2469. $this->tempContent = false;
  2470. $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
  2471. // Hook for cache post processing (eg. writing static files!)
  2472. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'])) {
  2473. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] as $_classRef) {
  2474. $_procObj = t3lib_div::getUserObj($_classRef);
  2475. $_procObj->insertPageIncache($this,$timeOutTime);
  2476. }
  2477. }
  2478. }
  2479. /**
  2480. * Sets cache content; Inserts the content string into the cache_pages cache.
  2481. *
  2482. * @param string The content to store in the HTML field of the cache table
  2483. * @param mixed The additional cache_data array, fx. $this->config
  2484. * @param integer Expiration timestamp
  2485. * @return void
  2486. * @see realPageCacheContent(), tempPageCacheContent()
  2487. */
  2488. function setPageCacheContent($content, $data, $expirationTstamp) {
  2489. if (TYPO3_UseCachingFramework) {
  2490. $cacheData = array(
  2491. 'identifier' => $this->newHash,
  2492. 'page_id' => $this->id,
  2493. 'content' => $content,
  2494. 'temp_content' => $this->tempContent,
  2495. 'cache_data' => serialize($data),
  2496. 'expires' => $expirationTstamp,
  2497. 'tstamp' => $GLOBALS['EXEC_TIME']
  2498. );
  2499. $this->cacheExpires = $expirationTstamp;
  2500. $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
  2501. if ($this->page_cache_reg1) {
  2502. $reg1 = intval($this->page_cache_reg1);
  2503. $cacheData['reg1'] = $reg1;
  2504. $this->pageCacheTags[] = 'reg1_' . $reg1;
  2505. }
  2506. $this->pageCache->set(
  2507. $this->newHash,
  2508. $cacheData,
  2509. $this->pageCacheTags,
  2510. $expirationTstamp - $GLOBALS['EXEC_TIME']
  2511. );
  2512. } else {
  2513. $this->clearPageCacheContent();
  2514. $insertFields = array(
  2515. 'hash' => $this->newHash,
  2516. 'page_id' => $this->id,
  2517. 'HTML' => $content,
  2518. 'temp_content' => $this->tempContent,
  2519. 'cache_data' => serialize($data),
  2520. 'expires' => $expirationTstamp,
  2521. 'tstamp' => $GLOBALS['EXEC_TIME']
  2522. );
  2523. $this->cacheExpires = $expirationTstamp;
  2524. if ($this->page_cache_reg1) {
  2525. $insertFields['reg1'] = intval($this->page_cache_reg1);
  2526. }
  2527. $this->pageCachePostProcess($insertFields,'set');
  2528. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_pages', $insertFields);
  2529. }
  2530. }
  2531. /**
  2532. * Clears cache content (for $this->newHash)
  2533. *
  2534. * @return void
  2535. */
  2536. function clearPageCacheContent() {
  2537. if (TYPO3_UseCachingFramework) {
  2538. $this->pageCache->remove($this->newHash);
  2539. } else {
  2540. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($this->newHash, 'cache_pages'));
  2541. }
  2542. }
  2543. /**
  2544. * Post processing page cache rows for both get and set.
  2545. *
  2546. * @param array Input "cache_pages" row, passed by reference!
  2547. * @param string Type of operation, either "get" or "set"
  2548. * @return void
  2549. */
  2550. function pageCachePostProcess(&$row,$type) {
  2551. if ($this->TYPO3_CONF_VARS['FE']['pageCacheToExternalFiles']) {
  2552. $cacheFileName = PATH_site.'typo3temp/cache_pages/'.$row['hash']{0}.$row['hash']{1}.'/'.$row['hash'].'.html';
  2553. switch((string)$type) {
  2554. case 'get':
  2555. $row['HTML'] = @is_file($cacheFileName) ? t3lib_div::getUrl($cacheFileName) : '<!-- CACHING ERROR, sorry -->';
  2556. break;
  2557. case 'set':
  2558. t3lib_div::writeFileToTypo3tempDir($cacheFileName, $row['HTML']);
  2559. $row['HTML'] = '';
  2560. break;
  2561. }
  2562. }
  2563. }
  2564. /**
  2565. * Clears cache content for a list of page ids
  2566. *
  2567. * @param string A list of INTEGER numbers which points to page uids for which to clear entries in the cache_pages cache (page content cache)
  2568. * @return void
  2569. */
  2570. function clearPageCacheContent_pidList($pidList) {
  2571. if (TYPO3_UseCachingFramework) {
  2572. $pageIds = t3lib_div::trimExplode(',', $pidList);
  2573. foreach ($pageIds as $pageId) {
  2574. $this->pageCache->flushByTag('pageId_' . (int) $pageId);
  2575. }
  2576. } else {
  2577. $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages', 'page_id IN ('.$GLOBALS['TYPO3_DB']->cleanIntList($pidList).')');
  2578. }
  2579. }
  2580. /**
  2581. * Sets sys last changed
  2582. * Setting the SYS_LASTCHANGED value in the pagerecord: This value will thus be set to the highest tstamp of records rendered on the page. This includes all records with no regard to hidden records, userprotection and so on.
  2583. *
  2584. * @return void
  2585. * @see tslib_cObj::lastChanged()
  2586. */
  2587. function setSysLastChanged() {
  2588. if ($this->page['SYS_LASTCHANGED'] < intval($this->register['SYS_LASTCHANGED'])) {
  2589. $GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($this->id), array('SYS_LASTCHANGED' => intval($this->register['SYS_LASTCHANGED'])));
  2590. }
  2591. }
  2592. /**
  2593. * Lock the page generation process
  2594. * The lock is used to queue page requests until this page is successfully stored in the cache.
  2595. *
  2596. * @param t3lib_lock Reference to a locking object
  2597. * @param string String to identify the lock in the system
  2598. * @return boolean Returns true if the lock could be obtained, false otherwise (= process had to wait for existing lock to be released)
  2599. * @see releasePageGenerationLock()
  2600. */
  2601. function acquirePageGenerationLock(&$lockObj, $key) {
  2602. if ($this->no_cache || $this->headerNoCache()) {
  2603. t3lib_div::sysLog('Locking: Page is not cached, no locking required', 'cms', t3lib_div::SYSLOG_SEVERITY_INFO);
  2604. return true; // No locking is needed if caching is disabled
  2605. }
  2606. try {
  2607. if (!is_object($lockObj)) {
  2608. $lockObj = t3lib_div::makeInstance('t3lib_lock', $key, $this->TYPO3_CONF_VARS['SYS']['lockingMode']);
  2609. }
  2610. $success = false;
  2611. if (strlen($key)) {
  2612. // true = Page could get locked without blocking
  2613. // false = Page could get locked but process was blocked before
  2614. $success = $lockObj->acquire();
  2615. if ($lockObj->getLockStatus()) {
  2616. $lockObj->sysLog('Acquired lock');
  2617. }
  2618. }
  2619. } catch (Exception $e) {
  2620. t3lib_div::sysLog('Locking: Failed to acquire lock: '.$e->getMessage(), 'cms', t3lib_div::SYSLOG_SEVERITY_ERROR);
  2621. $success = false; // If locking fails, return with false and continue without locking
  2622. }
  2623. return $success;
  2624. }
  2625. /**
  2626. * Release the page generation lock
  2627. *
  2628. * @param t3lib_lock Reference to a locking object
  2629. * @return boolean Returns true on success, false otherwise
  2630. * @see acquirePageGenerationLock()
  2631. */
  2632. function releasePageGenerationLock(&$lockObj) {
  2633. $success = false;
  2634. // If lock object is set and was acquired (may also happen if no_cache was enabled during runtime), release it:
  2635. if (is_object($lockObj) && $lockObj instanceof t3lib_lock && $lockObj->getLockStatus()) {
  2636. $success = $lockObj->release();
  2637. $lockObj->sysLog('Released lock');
  2638. $lockObj = null;
  2639. // Otherwise, if caching is disabled, no locking is required:
  2640. } elseif ($this->no_cache || $this->headerNoCache()) {
  2641. $success = true;
  2642. }
  2643. return $success;
  2644. }
  2645. /**
  2646. * adds tags to this page's cache entry, you can then f.e. remove cache
  2647. * entries by tag
  2648. *
  2649. * @param array an array of tag
  2650. * @return void
  2651. */
  2652. public function addCacheTags(array $tags) {
  2653. $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
  2654. }
  2655. /********************************************
  2656. *
  2657. * Page generation; rendering and inclusion
  2658. *
  2659. *******************************************/
  2660. /**
  2661. * Does some processing BEFORE the pagegen script is included.
  2662. *
  2663. * @return void
  2664. */
  2665. function generatePage_preProcessing() {
  2666. $this->newHash = $this->getHash(); // Same codeline as in getFromCache(). But $this->all has been changed by t3lib_TStemplate::start() in the meantime, so this must be called again!
  2667. $this->config['hash_base'] = $this->hash_base; // For cache management informational purposes.
  2668. if (!is_object($this->pages_lockObj) || $this->pages_lockObj->getLockStatus()==false) {
  2669. // 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.
  2670. $this->tempPageCacheContent();
  2671. }
  2672. // Setting cache_timeout_default. May be overridden by PHP include scritps.
  2673. $this->cacheTimeOutDefault = intval($this->config['config']['cache_period']);
  2674. // page is generated
  2675. $this->no_cacheBeforePageGen = $this->no_cache;
  2676. }
  2677. /**
  2678. * Determines to include custom or pagegen.php script
  2679. * returns script-filename if a TypoScript (config) script is defined and should be include instead of pagegen.php
  2680. *
  2681. * @return string The relative filepath of "config.pageGenScript" if found and allowed
  2682. */
  2683. function generatePage_whichScript() {
  2684. if (!$this->TYPO3_CONF_VARS['FE']['noPHPscriptInclude'] && $this->config['config']['pageGenScript']) {
  2685. return $this->tmpl->getFileName($this->config['config']['pageGenScript']);
  2686. }
  2687. }
  2688. /**
  2689. * Does some processing AFTER the pagegen script is included.
  2690. * This includes calling tidy (if configured), XHTML cleaning (if configured), caching the page, indexing the page (if configured) and setting sysLastChanged
  2691. *
  2692. * @return void
  2693. */
  2694. function generatePage_postProcessing() {
  2695. // 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.
  2696. if ($this->no_cacheBeforePageGen) $this->set_no_cache();
  2697. // Tidy up the code, if flag...
  2698. if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'all') {
  2699. $GLOBALS['TT']->push('Tidy, all','');
  2700. $this->content = $this->tidyHTML($this->content);
  2701. $GLOBALS['TT']->pull();
  2702. }
  2703. // XHTML-clean the code, if flag set
  2704. if ($this->doXHTML_cleaning() == 'all') {
  2705. $GLOBALS['TT']->push('XHTML clean, all','');
  2706. $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
  2707. $this->content = $XHTML_clean->XHTML_clean($this->content);
  2708. $GLOBALS['TT']->pull();
  2709. }
  2710. // Fix local anchors in links, if flag set
  2711. if ($this->doLocalAnchorFix() == 'all') {
  2712. $GLOBALS['TT']->push('Local anchor fix, all','');
  2713. $this->prefixLocalAnchorsWithScript();
  2714. $GLOBALS['TT']->pull();
  2715. }
  2716. // Hook for post-processing of page content cached/non-cached:
  2717. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'])) {
  2718. $_params = array('pObj' => &$this);
  2719. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] as $_funcRef) {
  2720. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  2721. }
  2722. }
  2723. // Processing if caching is enabled:
  2724. if (!$this->no_cache) {
  2725. // Tidy up the code, if flag...
  2726. if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'cached') {
  2727. $GLOBALS['TT']->push('Tidy, cached','');
  2728. $this->content = $this->tidyHTML($this->content);
  2729. $GLOBALS['TT']->pull();
  2730. }
  2731. // XHTML-clean the code, if flag set
  2732. if ($this->doXHTML_cleaning() == 'cached') {
  2733. $GLOBALS['TT']->push('XHTML clean, cached','');
  2734. $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
  2735. $this->content = $XHTML_clean->XHTML_clean($this->content);
  2736. $GLOBALS['TT']->pull();
  2737. }
  2738. // Fix local anchors in links, if flag set
  2739. if ($this->doLocalAnchorFix() == 'cached') {
  2740. $GLOBALS['TT']->push('Local anchor fix, cached','');
  2741. $this->prefixLocalAnchorsWithScript();
  2742. $GLOBALS['TT']->pull();
  2743. }
  2744. // Hook for post-processing of page content before being cached:
  2745. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'])) {
  2746. $_params = array('pObj' => &$this);
  2747. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] as $_funcRef) {
  2748. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  2749. }
  2750. }
  2751. }
  2752. // 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!
  2753. $this->content = $this->convOutputCharset($this->content,'mainpage');
  2754. // Hook for indexing pages
  2755. if (is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'])) {
  2756. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'] as $_classRef) {
  2757. $_procObj = t3lib_div::getUserObj($_classRef);
  2758. $_procObj->hook_indexContent($this);
  2759. }
  2760. }
  2761. // Storing for cache:
  2762. if (!$this->no_cache) {
  2763. $this->realPageCacheContent();
  2764. } elseif ($this->tempContent) { // If there happens to be temporary content in the cache and the cache was not cleared due to new content, put it in... ($this->no_cache=0)
  2765. $this->clearPageCacheContent();
  2766. $this->tempContent = false;
  2767. }
  2768. // Release open locks
  2769. $this->releasePageGenerationLock($this->pagesection_lockObj);
  2770. $this->releasePageGenerationLock($this->pages_lockObj);
  2771. // Sets sys-last-change:
  2772. $this->setSysLastChanged();
  2773. }
  2774. /**
  2775. * Processes the INTinclude-scripts
  2776. *
  2777. * @return void
  2778. */
  2779. function INTincScript() {
  2780. // Deprecated stuff:
  2781. $this->additionalHeaderData = is_array($this->config['INTincScript_ext']['additionalHeaderData']) ? $this->config['INTincScript_ext']['additionalHeaderData'] : array();
  2782. $this->additionalJavaScript = $this->config['INTincScript_ext']['additionalJavaScript'];
  2783. $this->additionalCSS = $this->config['INTincScript_ext']['additionalCSS'];
  2784. $this->JSCode = $this->additionalHeaderData['JSCode'];
  2785. $this->JSImgCode = $this->additionalHeaderData['JSImgCode'];
  2786. $this->divSection='';
  2787. do {
  2788. $INTiS_config = $this->config['INTincScript'];
  2789. $this->INTincScript_includeLibs($INTiS_config);
  2790. $this->INTincScript_process($INTiS_config);
  2791. // Check if there were new items added to INTincScript during the previous execution:
  2792. $INTiS_config = array_diff_assoc($this->config['INTincScript'], $INTiS_config);
  2793. $reprocess = (count($INTiS_config) ? true : false);
  2794. } while($reprocess);
  2795. $GLOBALS['TT']->push('Substitute header section');
  2796. $this->INTincScript_loadJSCode();
  2797. $this->content = str_replace('<!--HD_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset(implode(LF,$this->additionalHeaderData),'HD'), $this->content);
  2798. $this->content = str_replace('<!--TDS_'.$this->config['INTincScript_ext']['divKey'].'-->', $this->convOutputCharset($this->divSection,'TDS'), $this->content);
  2799. $this->setAbsRefPrefix();
  2800. $GLOBALS['TT']->pull();
  2801. }
  2802. /**
  2803. * Include libraries for uncached objects.
  2804. *
  2805. * @param array $INTiS_config: $GLOBALS['TSFE']->config['INTincScript'] or part of it
  2806. * @return void
  2807. * @see INTincScript()
  2808. */
  2809. protected function INTincScript_includeLibs($INTiS_config) {
  2810. foreach($INTiS_config as $INTiS_cPart) {
  2811. if (isset($INTiS_cPart['conf']['includeLibs']) && $INTiS_cPart['conf']['includeLibs']) {
  2812. $INTiS_resourceList = t3lib_div::trimExplode(',', $INTiS_cPart['conf']['includeLibs'], true);
  2813. $this->includeLibraries($INTiS_resourceList);
  2814. }
  2815. }
  2816. }
  2817. /**
  2818. * Processes the INTinclude-scripts and substitue in content.
  2819. *
  2820. * @param array $INTiS_config: $GLOBALS['TSFE']->config['INTincScript'] or part of it
  2821. * @return void
  2822. * @see INTincScript()
  2823. */
  2824. protected function INTincScript_process($INTiS_config) {
  2825. $GLOBALS['TT']->push('Split content');
  2826. $INTiS_splitC = explode('<!--INT_SCRIPT.',$this->content); // Splits content with the key.
  2827. $this->content = '';
  2828. $GLOBALS['TT']->setTSlogMessage('Parts: '.count($INTiS_splitC));
  2829. $GLOBALS['TT']->pull();
  2830. foreach($INTiS_splitC as $INTiS_c => $INTiS_cPart) {
  2831. if (substr($INTiS_cPart,32,3)=='-->') { // If the split had a comment-end after 32 characters it's probably a split-string
  2832. $INTiS_key = 'INT_SCRIPT.'.substr($INTiS_cPart,0,32);
  2833. $GLOBALS['TT']->push('Include '.$INTiS_config[$INTiS_key]['file'],'');
  2834. $incContent='';
  2835. if (is_array($INTiS_config[$INTiS_key])) {
  2836. $INTiS_cObj = unserialize($INTiS_config[$INTiS_key]['cObj']);
  2837. /* @var $INTiS_cObj tslib_cObj */
  2838. $INTiS_cObj->INT_include=1;
  2839. switch($INTiS_config[$INTiS_key]['type']) {
  2840. case 'SCRIPT':
  2841. $incContent = $INTiS_cObj->PHP_SCRIPT($INTiS_config[$INTiS_key]['conf']);
  2842. break;
  2843. case 'COA':
  2844. $incContent = $INTiS_cObj->COBJ_ARRAY($INTiS_config[$INTiS_key]['conf']);
  2845. break;
  2846. case 'FUNC':
  2847. $incContent = $INTiS_cObj->USER($INTiS_config[$INTiS_key]['conf']);
  2848. break;
  2849. case 'POSTUSERFUNC':
  2850. $incContent = $INTiS_cObj->callUserFunction($INTiS_config[$INTiS_key]['postUserFunc'], $INTiS_config[$INTiS_key]['conf'], $INTiS_config[$INTiS_key]['content']);
  2851. break;
  2852. }
  2853. }
  2854. $this->content.= $this->convOutputCharset($incContent,'INC-'.$INTiS_c);
  2855. $this->content.= substr($INTiS_cPart,35);
  2856. $GLOBALS['TT']->pull($incContent);
  2857. } else {
  2858. $this->content.= ($INTiS_c?'<!--INT_SCRIPT.':'').$INTiS_cPart;
  2859. }
  2860. }
  2861. }
  2862. /**
  2863. * Loads the JavaScript code for INTincScript
  2864. *
  2865. * @return void
  2866. * @access private
  2867. */
  2868. function INTincScript_loadJSCode() {
  2869. if ($this->JSImgCode) { // If any images added, then add them to the javascript section
  2870. $this->additionalHeaderData['JSImgCode']='
  2871. <script type="text/javascript">
  2872. /*<![CDATA[*/
  2873. <!--
  2874. if (version == "n3") {
  2875. '.trim($this->JSImgCode).'
  2876. }
  2877. // -->
  2878. /*]]>*/
  2879. </script>';
  2880. }
  2881. if ($this->JSCode || count($this->additionalJavaScript)) { // Add javascript
  2882. $this->additionalHeaderData['JSCode']='
  2883. <script type="text/javascript">
  2884. /*<![CDATA[*/
  2885. <!--
  2886. '.implode(LF,$this->additionalJavaScript).'
  2887. '.trim($this->JSCode).'
  2888. // -->
  2889. /*]]>*/
  2890. </script>';
  2891. }
  2892. if (count($this->additionalCSS)) { // Add javascript
  2893. $this->additionalHeaderData['_CSS']='
  2894. <style type="text/css">
  2895. /*<![CDATA[*/
  2896. <!--
  2897. '.implode(LF,$this->additionalCSS).'
  2898. // -->
  2899. /*]]>*/
  2900. </style>';
  2901. }
  2902. }
  2903. /**
  2904. * Determines if there are any INTincScripts to include
  2905. *
  2906. * @return boolean Returns true if scripts are found (and not jumpurl)
  2907. */
  2908. function isINTincScript() {
  2909. return (is_array($this->config['INTincScript']) && !$this->jumpurl);
  2910. }
  2911. /**
  2912. * Returns the mode of XHTML cleaning
  2913. *
  2914. * @return string Keyword: "all", "cached" or "output"
  2915. */
  2916. function doXHTML_cleaning() {
  2917. return $this->config['config']['xhtml_cleaning'];
  2918. }
  2919. /**
  2920. * Returns the mode of Local Anchor prefixing
  2921. *
  2922. * @return string Keyword: "all", "cached" or "output"
  2923. */
  2924. function doLocalAnchorFix() {
  2925. return (isset($this->config['config']['prefixLocalAnchors'])) ? $this->config['config']['prefixLocalAnchors'] : NULL;
  2926. }
  2927. /********************************************
  2928. *
  2929. * Finished off; outputting, storing session data, statistics...
  2930. *
  2931. *******************************************/
  2932. /**
  2933. * Determines if content should be outputted.
  2934. * Outputting content is done only if jumpUrl is NOT set.
  2935. *
  2936. * @return boolean Returns true if $this->jumpurl is not set.
  2937. */
  2938. function isOutputting() {
  2939. // Initialize by status of jumpUrl:
  2940. $enableOutput = (!$this->jumpurl);
  2941. // Call hook for possible disabling of output:
  2942. if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])
  2943. && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'])) {
  2944. $_params = array('pObj' => &$this, 'enableOutput' => &$enableOutput);
  2945. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'] as $_funcRef) {
  2946. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  2947. }
  2948. }
  2949. return $enableOutput;
  2950. }
  2951. /**
  2952. * Process the output before it's actually outputted. Sends headers also.
  2953. * This includes substituting the "username" comment, sending additional headers (as defined in the TypoScript "config.additionalheaders" object), tidy'ing content, XHTML cleaning content (if configured)
  2954. * Works on $this->content.
  2955. *
  2956. * @return void
  2957. */
  2958. function processOutput() {
  2959. // Set header for charset-encoding unless disabled
  2960. if (empty($this->config['config']['disableCharsetHeader'])) {
  2961. $headLine = 'Content-Type: text/html; charset='.trim($this->metaCharset);
  2962. header($headLine);
  2963. }
  2964. // Set cache related headers to client (used to enable proxy / client caching!)
  2965. if (!empty($this->config['config']['sendCacheHeaders'])) {
  2966. $this->sendCacheHeaders();
  2967. }
  2968. // Set headers, if any
  2969. if (!empty($this->config['config']['additionalHeaders'])) {
  2970. $headerArray = explode('|', $this->config['config']['additionalHeaders']);
  2971. foreach ($headerArray as $headLine) {
  2972. $headLine = trim($headLine);
  2973. header($headLine);
  2974. }
  2975. }
  2976. // Send appropriate status code in case of temporary content
  2977. if ($this->tempContent) {
  2978. $this->addTempContentHttpHeaders();
  2979. }
  2980. // Make substitution of eg. username/uid in content only if cache-headers for client/proxy caching is NOT sent!
  2981. if (!$this->isClientCachable) {
  2982. $this->contentStrReplace();
  2983. }
  2984. // Tidy up the code, if flag...
  2985. if ($this->TYPO3_CONF_VARS['FE']['tidy_option'] == 'output') {
  2986. $GLOBALS['TT']->push('Tidy, output','');
  2987. $this->content = $this->tidyHTML($this->content);
  2988. $GLOBALS['TT']->pull();
  2989. }
  2990. // XHTML-clean the code, if flag set
  2991. if ($this->doXHTML_cleaning() == 'output') {
  2992. $GLOBALS['TT']->push('XHTML clean, output','');
  2993. $XHTML_clean = t3lib_div::makeInstance('t3lib_parsehtml');
  2994. $this->content = $XHTML_clean->XHTML_clean($this->content);
  2995. $GLOBALS['TT']->pull();
  2996. }
  2997. // Fix local anchors in links, if flag set
  2998. if ($this->doLocalAnchorFix() == 'output') {
  2999. $GLOBALS['TT']->push('Local anchor fix, output','');
  3000. $this->prefixLocalAnchorsWithScript();
  3001. $GLOBALS['TT']->pull();
  3002. }
  3003. // Hook for post-processing of page content before output:
  3004. if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'])) {
  3005. $_params = array('pObj' => &$this);
  3006. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] as $_funcRef) {
  3007. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  3008. }
  3009. }
  3010. // Send content-lenght header.
  3011. // 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...) or if debug mode is turned on, we disable it!
  3012. if (!empty($this->config['config']['enableContentLengthHeader']) &&
  3013. !$this->isEXTincScript() &&
  3014. !$this->beUserLogin &&
  3015. !$this->TYPO3_CONF_VARS['FE']['debug'] &&
  3016. !$this->config['config']['debug'] &&
  3017. !$this->doWorkspacePreview()
  3018. ) {
  3019. header('Content-Length: '.strlen($this->content));
  3020. }
  3021. }
  3022. /**
  3023. * Send cache headers good for client/reverse proxy caching
  3024. * This function should not be called if the page content is temporary (like for "Page is being generated..." message, but in that case it is ok because the config-variables are not yet available and so will not allow to send cache headers)
  3025. *
  3026. * @return void
  3027. * @co-author Ole Tange, Forbrugernes Hus, Denmark
  3028. */
  3029. function sendCacheHeaders() {
  3030. // Getting status whether we can send cache control headers for proxy caching:
  3031. $doCache = $this->isStaticCacheble();
  3032. // 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...
  3033. $loginsDeniedCfg = (empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch));
  3034. // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
  3035. if ($doCache
  3036. && !$this->beUserLogin
  3037. && !$this->doWorkspacePreview()
  3038. && $loginsDeniedCfg) {
  3039. // Build headers:
  3040. $headers = array(
  3041. 'Last-Modified: '.gmdate('D, d M Y H:i:s T', $this->register['SYS_LASTCHANGED']),
  3042. 'Expires: '.gmdate('D, d M Y H:i:s T', $this->cacheExpires),
  3043. 'ETag: "' . md5($this->content) . '"',
  3044. 'Cache-Control: max-age='.($this->cacheExpires - $GLOBALS['EXEC_TIME']), // no-cache
  3045. 'Pragma: public',
  3046. );
  3047. $this->isClientCachable = TRUE;
  3048. } else {
  3049. // Build headers:
  3050. $headers = array(
  3051. #'Last-Modified: '.gmdate('D, d M Y H:i:s T', $this->register['SYS_LASTCHANGED']),
  3052. #'ETag: '.md5($this->content),
  3053. #'Cache-Control: no-cache',
  3054. #'Pragma: no-cache',
  3055. 'Cache-Control: private', // Changed to this according to Ole Tange, FI.dk
  3056. );
  3057. $this->isClientCachable = FALSE;
  3058. // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
  3059. if ($this->beUserLogin) {
  3060. if ($doCache) {
  3061. $GLOBALS['TT']->setTSlogMessage('Cache-headers with max-age "'.($this->cacheExpires - $GLOBALS['EXEC_TIME']).'" would have been sent');
  3062. } else {
  3063. $reasonMsg = '';
  3064. $reasonMsg.= !$this->no_cache ? '' : 'Caching disabled (no_cache). ';
  3065. $reasonMsg.= !$this->isINTincScript() ? '' : '*_INT object(s) on page. ';
  3066. $reasonMsg.= !$this->isEXTincScript() ? '' : '*_EXT object(s) on page. ';
  3067. $reasonMsg.= !is_array($this->fe_user->user) ? '' : 'Frontend user logged in. ';
  3068. $GLOBALS['TT']->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "'.$reasonMsg.'"',1);
  3069. }
  3070. }
  3071. }
  3072. // Send headers:
  3073. foreach($headers as $hL) {
  3074. header($hL);
  3075. }
  3076. }
  3077. /**
  3078. * Reporting status whether we can send cache control headers for proxy caching or publishing to static files
  3079. *
  3080. * Rules are:
  3081. * no_cache cannot be set: If it is, the page might contain dynamic content and should never be cached.
  3082. * There can be no USER_INT objects on the page ("isINTincScript()" / "isEXTincScript()") because they implicitly indicate dynamic content
  3083. * There can be no logged in user because user sessions are based on a cookie and thereby does not offer client caching a chance to know if the user is logged in. Actually, there will be a reverse problem here; If a page will somehow change when a user is logged in he may not see it correctly if the non-login version sent a cache-header! So do NOT use cache headers in page sections where user logins change the page content. (unless using such as realurl to apply a prefix in case of login sections)
  3084. *
  3085. * @return boolean
  3086. */
  3087. function isStaticCacheble() {
  3088. $doCache = !$this->no_cache
  3089. && !$this->isINTincScript()
  3090. && !$this->isEXTincScript()
  3091. && !$this->isUserOrGroupSet();
  3092. return $doCache;
  3093. }
  3094. /**
  3095. * Substitute various tokens in content. This should happen only if the content is not cached by proxies or client browsers.
  3096. *
  3097. * @return void
  3098. */
  3099. function contentStrReplace() {
  3100. $search = array();
  3101. $replace = array();
  3102. // Substitutes username mark with the username
  3103. if ($this->fe_user->user['uid']) {
  3104. // User name:
  3105. $token = (isset($this->config['config']['USERNAME_substToken'])) ? trim($this->config['config']['USERNAME_substToken']) : '';
  3106. $search[] = ($token ? $token : '<!--###USERNAME###-->');
  3107. $replace[] = $this->fe_user->user['username'];
  3108. // User uid (if configured):
  3109. $token = (isset($this->config['config']['USERUID_substToken'])) ? trim($this->config['config']['USERUID_substToken']) : '';
  3110. if ($token) {
  3111. $search[] = $token;
  3112. $replace[] = $this->fe_user->user['uid'];
  3113. }
  3114. }
  3115. // Substitutes get_URL_ID in case of GET-fallback
  3116. if ($this->getMethodUrlIdToken) {
  3117. $search[] = $this->getMethodUrlIdToken;
  3118. $replace[] = $this->fe_user->get_URL_ID;
  3119. }
  3120. // Hook for supplying custom search/replace data
  3121. if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-contentStrReplace'])) {
  3122. $contentStrReplaceHooks = &$this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-contentStrReplace'];
  3123. if (is_array($contentStrReplaceHooks)) {
  3124. $_params = array(
  3125. 'search' => &$search,
  3126. 'replace' => &$replace,
  3127. );
  3128. foreach ($contentStrReplaceHooks as $_funcRef) {
  3129. t3lib_div::callUserFunction($_funcRef, $_params, $this);
  3130. }
  3131. }
  3132. }
  3133. if (count($search)) {
  3134. $this->content = str_replace($search, $replace, $this->content);
  3135. }
  3136. }
  3137. /**
  3138. * Determines if any EXTincScripts should be included
  3139. *
  3140. * @return boolean True, if external php scripts should be included (set by PHP_SCRIPT_EXT cObjects)
  3141. * @see tslib_cObj::PHP_SCRIPT
  3142. */
  3143. function isEXTincScript() {
  3144. return (isset($this->config['EXTincScript']) && is_array($this->config['EXTincScript']));
  3145. }
  3146. /**
  3147. * Stores session data for the front end user
  3148. *
  3149. * @return void
  3150. */
  3151. function storeSessionData() {
  3152. $this->fe_user->storeSessionData();
  3153. }
  3154. /**
  3155. * Sets the parsetime of the page.
  3156. *
  3157. * @return void
  3158. * @access private
  3159. */
  3160. function setParseTime() {
  3161. // Compensates for the time consumed with Back end user initialization.
  3162. $microtime_start = (isset($GLOBALS['TYPO3_MISC']['microtime_start'])) ? $GLOBALS['TYPO3_MISC']['microtime_start'] : NULL;
  3163. $microtime_end = (isset($GLOBALS['TYPO3_MISC']['microtime_end'])) ? $GLOBALS['TYPO3_MISC']['microtime_end'] : NULL;
  3164. $microtime_BE_USER_start = (isset($GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'])) ? $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] : NULL;
  3165. $microtime_BE_USER_end = (isset($GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'])) ? $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] : NULL;
  3166. $this->scriptParseTime = $GLOBALS['TT']->getMilliseconds($microtime_end) - $GLOBALS['TT']->getMilliseconds($microtime_start)
  3167. - ($GLOBALS['TT']->getMilliseconds($microtime_BE_USER_end) - $GLOBALS['TT']->getMilliseconds($microtime_BE_USER_start));
  3168. }
  3169. /**
  3170. * Initialize file-based statistics handling: Check filename and permissions, and create the logfile if it does not exist yet.
  3171. * This function should be called with care because it might overwrite existing settings otherwise.
  3172. *
  3173. * @return boolean True if statistics are enabled (will require some more processing after charset handling is initialized)
  3174. * @access private
  3175. */
  3176. protected function statistics_init() {
  3177. $setStatPageName = false;
  3178. $theLogFile = $this->TYPO3_CONF_VARS['FE']['logfile_dir'].strftime($this->config['config']['stat_apache_logfile']);
  3179. // Add PATH_site left to $theLogFile if the path is not absolute yet
  3180. if (!t3lib_div::isAbsPath($theLogFile)) {
  3181. $theLogFile = PATH_site.$theLogFile;
  3182. }
  3183. if ($this->config['config']['stat_apache'] && $this->config['config']['stat_apache_logfile'] && !strstr($this->config['config']['stat_apache_logfile'],'/')) {
  3184. if (t3lib_div::isAllowedAbsPath($theLogFile)) {
  3185. if (!@is_file($theLogFile)) {
  3186. touch($theLogFile); // Try to create the logfile
  3187. t3lib_div::fixPermissions($theLogFile);
  3188. }
  3189. if (@is_file($theLogFile) && @is_writable($theLogFile)) {
  3190. $this->config['stat_vars']['logFile'] = $theLogFile;
  3191. $setStatPageName = true; // Set page name later on
  3192. } else {
  3193. $GLOBALS['TT']->setTSlogMessage('Could not set logfile path. Check filepath and permissions.',3);
  3194. }
  3195. }
  3196. }
  3197. return $setStatPageName;
  3198. }
  3199. /**
  3200. * Set the pagename for the logfile entry
  3201. *
  3202. * @return void
  3203. * @access private
  3204. */
  3205. protected function statistics_init_pagename() {
  3206. if (preg_match('/utf-?8/i', $this->config['config']['stat_apache_niceTitle'])) { // Make life easier and accept variants for utf-8
  3207. $this->config['config']['stat_apache_niceTitle'] = 'utf-8';
  3208. }
  3209. if ($this->config['config']['stat_apache_niceTitle'] == 'utf-8') {
  3210. $shortTitle = $this->csConvObj->utf8_encode($this->page['title'],$this->renderCharset);
  3211. } elseif ($this->config['config']['stat_apache_niceTitle']) {
  3212. $shortTitle = $this->csConvObj->specCharsToASCII($this->renderCharset,$this->page['title']);
  3213. } else {
  3214. $shortTitle = $this->page['title'];
  3215. }
  3216. $len = t3lib_div::intInRange($this->config['config']['stat_apache_pageLen'],1,100,30);
  3217. if ($this->config['config']['stat_apache_niceTitle'] == 'utf-8') {
  3218. $shortTitle = rawurlencode($this->csConvObj->substr('utf-8',$shortTitle,0,$len));
  3219. } else {
  3220. $shortTitle = substr(preg_replace('/[^.[:alnum:]_-]/','_',$shortTitle),0,$len);
  3221. }
  3222. $pageName = $this->config['config']['stat_apache_pagenames'] ? $this->config['config']['stat_apache_pagenames'] : '[path][title]--[uid].html';
  3223. $pageName = str_replace('[title]', $shortTitle ,$pageName);
  3224. $pageName = str_replace('[uid]',$this->page['uid'],$pageName);
  3225. $pageName = str_replace('[alias]',$this->page['alias'],$pageName);
  3226. $pageName = str_replace('[type]',$this->type,$pageName);
  3227. $pageName = str_replace('[request_uri]',t3lib_div::getIndpEnv('REQUEST_URI'),$pageName);
  3228. $temp = $this->config['rootLine'];
  3229. if ($temp) { // rootLine does not exist if this function is called at early stage (e.g. if DB connection failed)
  3230. array_pop($temp);
  3231. if ($this->config['config']['stat_apache_noRoot']) {
  3232. array_shift($temp);
  3233. }
  3234. $len = t3lib_div::intInRange($this->config['config']['stat_titleLen'],1,100,20);
  3235. if ($this->config['config']['stat_apache_niceTitle'] == 'utf-8') {
  3236. $path = '';
  3237. $c = count($temp);
  3238. for ($i=0; $i<$c; $i++) {
  3239. if ($temp[$i]['uid']) {
  3240. $p = $this->csConvObj->crop('utf-8',$this->csConvObj->utf8_encode($temp[$i]['title'],$this->renderCharset),$len,"\xE2\x80\xA6"); // U+2026; HORIZONTAL ELLIPSIS
  3241. $path.= '/' . rawurlencode($p);
  3242. }
  3243. }
  3244. } elseif ($this->config['config']['stat_apache_niceTitle']) {
  3245. $path = $this->csConvObj->specCharsToASCII($this->renderCharset,$this->sys_page->getPathFromRootline($temp,$len));
  3246. } else {
  3247. $path = $this->sys_page->getPathFromRootline($temp,$len);
  3248. }
  3249. } else {
  3250. $path = ''; // If rootLine is missing, we just drop the path...
  3251. }
  3252. if ($this->config['config']['stat_apache_niceTitle'] == 'utf-8') {
  3253. $this->config['stat_vars']['pageName'] = str_replace('[path]', $path.'/', $pageName);
  3254. } else {
  3255. $this->config['stat_vars']['pageName'] = str_replace('[path]', preg_replace('/[^.[:alnum:]\/_-]/','_',$path.'/'), $pageName);
  3256. }
  3257. }
  3258. /**
  3259. * Saves hit statistics
  3260. *
  3261. * @return void
  3262. */
  3263. function statistics() {
  3264. if (!empty($this->config['config']['stat']) &&
  3265. (!strcmp('',$this->config['config']['stat_typeNumList']) || t3lib_div::inList(str_replace(' ','',$this->config['config']['stat_typeNumList']), $this->type)) &&
  3266. (empty($this->config['config']['stat_excludeBEuserHits']) || !$this->beUserLogin) &&
  3267. (empty($this->config['config']['stat_excludeIPList']) || !t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'),str_replace(' ','',$this->config['config']['stat_excludeIPList'])))) {
  3268. $GLOBALS['TT']->push('Stat');
  3269. if (t3lib_extMgm::isLoaded('sys_stat') && !empty($this->config['config']['stat_mysql'])) {
  3270. // Jumpurl:
  3271. $sword = t3lib_div::_GP('sword');
  3272. if ($sword) {
  3273. $jumpurl_msg = 'sword:'.$sword;
  3274. } elseif ($this->jumpurl) {
  3275. $jumpurl_msg = 'jumpurl:'.$this->jumpurl;
  3276. } else {
  3277. $jumpurl_msg = '';
  3278. }
  3279. // Flags: bits: 0 = BE_user, 1=Cached page?
  3280. $flags=0;
  3281. if ($this->beUserLogin) {$flags|=1;}
  3282. if ($this->cacheContentFlag) {$flags|=2;}
  3283. // Ref url:
  3284. $refUrl = t3lib_div::getIndpEnv('HTTP_REFERER');
  3285. $thisUrl = t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR');
  3286. if (t3lib_div::isFirstPartOfStr($refUrl,$thisUrl)) {
  3287. $refUrl='[LOCAL]';
  3288. }
  3289. $insertFields = array(
  3290. 'page_id' => intval($this->id), // id
  3291. 'page_type' => intval($this->type), // type
  3292. 'jumpurl' => $jumpurl_msg, // jumpurl message
  3293. 'feuser_id' => $this->fe_user->user['uid'], // fe_user id, integer
  3294. 'cookie' => $this->fe_user->id, // cookie as set or retrieve. If people has cookies disabled this will vary all the time...
  3295. '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...
  3296. 'rl0' => $this->config['rootLine'][0]['uid'], // RootLevel 0 uid
  3297. 'rl1' => $this->config['rootLine'][1]['uid'], // RootLevel 1 uid
  3298. 'client_browser' => $GLOBALS['CLIENT']['BROWSER'], // Client browser (net, msie, opera)
  3299. 'client_version' => $GLOBALS['CLIENT']['VERSION'], // Client version (double value)
  3300. 'client_os' => $GLOBALS['CLIENT']['SYSTEM'], // Client Operating system (win, mac, unix)
  3301. 'parsetime' => intval($this->scriptParseTime), // Parsetime for the page.
  3302. 'flags' => $flags, // Flags: Is be user logged in? Is page cached?
  3303. 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'), // Remote IP address
  3304. 'host' => t3lib_div::getIndpEnv('REMOTE_HOST'), // Remote Host Address
  3305. 'referer' => $refUrl, // Referer URL
  3306. 'browser' => t3lib_div::getIndpEnv('HTTP_USER_AGENT'), // User Agent Info.
  3307. 'tstamp' => $GLOBALS['EXEC_TIME'] // Time stamp
  3308. );
  3309. // Hook for preprocessing the list of fields to insert into sys_stat:
  3310. if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass'])) {
  3311. foreach ($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['sys_stat-PreProcClass'] as $_classRef) {
  3312. $_procObj = t3lib_div::getUserObj($_classRef);
  3313. $insertFields = $_procObj->sysstat_preProcessFields($insertFields,$this);
  3314. }
  3315. }
  3316. $GLOBALS['TT']->push('Store SQL');
  3317. $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_stat', $insertFields);
  3318. $GLOBALS['TT']->pull();
  3319. }
  3320. // Apache:
  3321. if (!empty($this->config['config']['stat_apache']) && !empty($this->config['stat_vars']['pageName'])) {
  3322. if (@is_file($this->config['stat_vars']['logFile'])) {
  3323. // Build a log line (format is derived from the NCSA extended/combined log format)
  3324. // Log part 1: Remote hostname / address
  3325. $LogLine = (t3lib_div::getIndpEnv('REMOTE_HOST') && empty($this->config['config']['stat_apache_noHost'])) ? t3lib_div::getIndpEnv('REMOTE_HOST') : t3lib_div::getIndpEnv('REMOTE_ADDR');
  3326. // Log part 2: Fake the remote logname
  3327. $LogLine.= ' -';
  3328. // Log part 3: Remote username
  3329. $LogLine.= ' '.($this->loginUser ? $this->fe_user->user['username'] : '-');
  3330. // Log part 4: Time
  3331. $LogLine.= ' '.date('[d/M/Y:H:i:s +0000]',$GLOBALS['EXEC_TIME']);
  3332. // Log part 5: First line of request (the request filename)
  3333. $LogLine.= ' "GET '.$this->config['stat_vars']['pageName'].' HTTP/1.1"';
  3334. // Log part 6: Status and content length (ignores special content like admin panel!)
  3335. $LogLine.= ' 200 '.strlen($this->content);
  3336. if (empty($this->config['config']['stat_apache_notExtended'])) {
  3337. $referer = t3lib_div::getIndpEnv('HTTP_REFERER');
  3338. $LogLine.= ' "'.($referer ? $referer : '-').'" "'.t3lib_div::getIndpEnv('HTTP_USER_AGENT').'"';
  3339. }
  3340. $GLOBALS['TT']->push('Write to log file (fputs)');
  3341. $logfilehandle = fopen($this->config['stat_vars']['logFile'], 'a');
  3342. fputs($logfilehandle, $LogLine.LF);
  3343. @fclose($logfilehandle);
  3344. $GLOBALS['TT']->pull();
  3345. $GLOBALS['TT']->setTSlogMessage('Writing to logfile: OK',0);
  3346. } else {
  3347. $GLOBALS['TT']->setTSlogMessage('Writing to logfile: Error - logFile did not exist!',3);
  3348. }
  3349. }
  3350. $GLOBALS['TT']->pull();
  3351. }
  3352. }
  3353. /**
  3354. * Outputs preview info.
  3355. *
  3356. * @return void
  3357. */
  3358. function previewInfo() {
  3359. if ($this->fePreview) {
  3360. if ($this->fePreview === 2) {
  3361. $onclickForStoppingPreview = 'document.location="'.t3lib_div::getIndpEnv('TYPO3_SITE_URL').'index.php?ADMCMD_prev=LOGOUT&returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')).'";return false;';
  3362. $text = 'Preview of workspace "'.$this->whichWorkspace(TRUE).'" ('.$this->whichWorkspace().')';
  3363. $html = $this->doWorkspacePreview() ? '<br/><input name="_" type="submit" value="Stop preview" onclick="'.htmlspecialchars($onclickForStoppingPreview).'" />' : '';
  3364. } else {
  3365. $text = 'PREVIEW!';
  3366. $html = '';
  3367. }
  3368. $stdMsg = '<div id="typo3-previewInfo" style="position: absolute; top: 20px; right: 20px; border: 2px solid #000; padding: 5px 5px; background: #f00; font: 1em Verdana; color: #000; font-weight: bold; z-index: 10001">'.htmlspecialchars($text).$html.'</div>';
  3369. if ($this->fePreview === 2) {
  3370. $temp_content = $this->config['config']['message_preview_workspace'] ?
  3371. @sprintf($this->config['config']['message_preview_workspace'], $this->whichWorkspace(TRUE),$this->whichWorkspace()) :
  3372. $stdMsg;
  3373. } else {
  3374. $temp_content = $this->config['config']['message_preview'] ? $this->config['config']['message_preview'] : $stdMsg;
  3375. }
  3376. echo $temp_content;
  3377. }
  3378. }
  3379. /**
  3380. * End-Of-Frontend hook
  3381. *
  3382. * @return void
  3383. */
  3384. function hook_eofe() {
  3385. // Call hook for end-of-frontend processing:
  3386. if (isset($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe']) && is_array($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'])) {
  3387. $_params = array('pObj' => &$this);
  3388. foreach($this->TYPO3_CONF_VARS['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'] as $_funcRef) {
  3389. t3lib_div::callUserFunction($_funcRef,$_params,$this);
  3390. }
  3391. }
  3392. }
  3393. /**
  3394. * Returns a link to the BE login screen with redirect to the front-end
  3395. *
  3396. * @return string HTML, a tag for a link to the backend.
  3397. */
  3398. function beLoginLinkIPList() {
  3399. if (!empty($this->config['config']['beLoginLinkIPList'])) {
  3400. if (t3lib_div::cmpIP(t3lib_div::getIndpEnv('REMOTE_ADDR'), $this->config['config']['beLoginLinkIPList'])) {
  3401. $label = !$this->beUserLogin ? $this->config['config']['beLoginLinkIPList_login'] : $this->config['config']['beLoginLinkIPList_logout'];
  3402. if ($label) {
  3403. if (!$this->beUserLogin) {
  3404. $link = '<a href="'.htmlspecialchars(TYPO3_mainDir.'index.php?redirect_url='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))).'">'.$label.'</a>';
  3405. } else {
  3406. $link = '<a href="'.htmlspecialchars(TYPO3_mainDir.'index.php?L=OUT&redirect_url='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))).'">'.$label.'</a>';
  3407. }
  3408. return $link;
  3409. }
  3410. }
  3411. }
  3412. }
  3413. /**
  3414. * Sends HTTP headers for temporary content. These headers prevent search engines from caching temporary content and asks them to revisit this page again.
  3415. *
  3416. * @return void
  3417. */
  3418. function addTempContentHttpHeaders() {
  3419. header('HTTP/1.0 503 Service unavailable');
  3420. header('Retry-after: 3600');
  3421. header('Pragma: no-cache');
  3422. header('Cache-control: no-cache');
  3423. header('Expire: 0');
  3424. }
  3425. /********************************************
  3426. *
  3427. * Various internal API functions
  3428. *
  3429. *******************************************/
  3430. /**
  3431. * Make simulation filename (without the ".html" ending, only body of filename)
  3432. *
  3433. * @param string The page title to use
  3434. * @param mixed The page id (integer) or alias (string)
  3435. * @param integer The type number
  3436. * @param string Query-parameters to encode (will be done only if caching is enabled and TypoScript configured for it. I don't know it this makes much sense in fact...)
  3437. * @param boolean The "no_cache" status of the link.
  3438. * @return string The body of the filename.
  3439. * @see getSimulFileName(), t3lib_tstemplate::linkData(), tslib_frameset::frameParams()
  3440. * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  3441. * @todo Deprecated but still used in the Core!
  3442. */
  3443. function makeSimulFileName($inTitle, $page, $type, $addParams = '', $no_cache = false) {
  3444. if (t3lib_extMgm::isLoaded('simulatestatic')) {
  3445. $parameters = array(
  3446. 'inTitle' => $inTitle,
  3447. 'page' => $page,
  3448. 'type' => $type,
  3449. 'addParams' => $addParams,
  3450. 'no_cache' => $no_cache,
  3451. );
  3452. return t3lib_div::callUserFunction(
  3453. 'EXT:simulatestatic/class.tx_simulatestatic.php:&tx_simulatestatic->makeSimulatedFileNameCompat',
  3454. $parameters,
  3455. $this
  3456. );
  3457. } else {
  3458. return false;
  3459. }
  3460. }
  3461. /**
  3462. * Processes a query-string with GET-parameters and returns two strings, one with the parameters that CAN be encoded and one array with those which can't be encoded (encoded by the M5 or B6 methods)
  3463. *
  3464. * @param string Query string to analyse
  3465. * @return array Two num keys returned, first is the parameters that MAY be encoded, second is the non-encodable parameters.
  3466. * @see makeSimulFileName(), t3lib_tstemplate::linkData()
  3467. * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  3468. */
  3469. function simulateStaticDocuments_pEnc_onlyP_proc($linkVars) {
  3470. t3lib_div::logDeprecatedFunction();
  3471. if (t3lib_extMgm::isLoaded('simulatestatic')) {
  3472. return t3lib_div::callUserFunction(
  3473. 'EXT:simulatestatic/class.tx_simulatestatic.php:&tx_simulatestatic->processEncodedQueryString',
  3474. $linkVars,
  3475. $this
  3476. );
  3477. } else {
  3478. return false;
  3479. }
  3480. }
  3481. /**
  3482. * Returns the simulated static file name (*.html) for the current page (using the page record in $this->page)
  3483. *
  3484. * @return string The filename (without path)
  3485. * @see makeSimulFileName(), publish.php
  3486. * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  3487. * @todo Deprecated but still used in the Core!
  3488. */
  3489. function getSimulFileName() {
  3490. return $this->makeSimulFileName(
  3491. $this->page['title'],
  3492. ($this->page['alias'] ? $this->page['alias'] : $this->id),
  3493. $this->type
  3494. ) . '.html';
  3495. }
  3496. /**
  3497. * Checks and sets replacement character for simulateStaticDocuments. Default is underscore.
  3498. *
  3499. * @return void
  3500. * @deprecated since TYPO3 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  3501. */
  3502. function setSimulReplacementChar() {
  3503. t3lib_div::logDeprecatedFunction();
  3504. $replacement = $defChar = t3lib_div::compat_version('4.0') ? '-' : '_';
  3505. if (isset($this->config['config']['simulateStaticDocuments_replacementChar'])) {
  3506. $replacement = trim($this->config['config']['simulateStaticDocuments_replacementChar']);
  3507. if (urlencode($replacement) != $replacement) {
  3508. // Invalid character
  3509. $replacement = $defChar;
  3510. }
  3511. }
  3512. $this->config['config']['simulateStaticDocuments_replacementChar'] = $replacement;
  3513. }
  3514. /**
  3515. * Converts input string to an ASCII based file name prefix
  3516. *
  3517. * @param string String to base output on
  3518. * @param integer Number of characters in the string
  3519. * @param string Character to put in the end of string to merge it with the next value.
  3520. * @return string String
  3521. * @deprecated since TYPO3, 4.3, will be removed in TYPO3 4.5, please use the "simulatestatic" sysext directly
  3522. * @todo Deprecated but still used in the Core!
  3523. */
  3524. function fileNameASCIIPrefix($inTitle,$titleChars,$mergeChar='.') {
  3525. t3lib_div::logDeprecatedFunction();
  3526. $out = $this->csConvObj->specCharsToASCII($this->renderCharset, $inTitle);
  3527. // Get replacement character
  3528. $replacementChar = $this->config['config']['simulateStaticDocuments_replacementChar'];
  3529. $replacementChars = '_\-' . ($replacementChar != '_' && $replacementChar != '-' ? $replacementChar : '');
  3530. $out = preg_replace('/[^A-Za-z0-9_-]/', $replacementChar, trim(substr($out, 0, $titleChars)));
  3531. $out = preg_replace('/([' . $replacementChars . ']){2,}/', '\1', $out);
  3532. $out = preg_replace('/[' . $replacementChars . ']?$/', '', $out);
  3533. $out = preg_replace('/^[' . $replacementChars . ']?/', '', $out);
  3534. if (strlen($out)) {
  3535. $out.= $mergeChar;
  3536. }
  3537. return $out;
  3538. }
  3539. /**
  3540. * Encryption (or decryption) of a single character.
  3541. * Within the given range the character is shifted with the supplied offset.
  3542. *
  3543. * @param int Ordinal of input character
  3544. * @param int Start of range
  3545. * @param int End of range
  3546. * @param int Offset
  3547. * @return string encoded/decoded version of character
  3548. */
  3549. function encryptCharcode($n,$start,$end,$offset) {
  3550. $n = $n + $offset;
  3551. if ($offset > 0 && $n > $end) {
  3552. $n = $start + ($n - $end - 1);
  3553. } else if ($offset < 0 && $n < $start) {
  3554. $n = $end - ($start - $n - 1);
  3555. }
  3556. return chr($n);
  3557. }
  3558. /**
  3559. * Encryption of email addresses for <A>-tags See the spam protection setup in TS 'config.'
  3560. *
  3561. * @param string Input string to en/decode: "mailto:blabla@bla.com"
  3562. * @param boolean If set, the process is reversed, effectively decoding, not encoding.
  3563. * @return string encoded/decoded version of $string
  3564. */
  3565. function encryptEmail($string,$back=0) {
  3566. $out = '';
  3567. if ($this->spamProtectEmailAddresses === 'ascii') {
  3568. for ($a=0; $a<strlen($string); $a++) {
  3569. $out .= '&#'.ord(substr($string, $a, 1)).';';
  3570. }
  3571. } else {
  3572. // like str_rot13() but with a variable offset and a wider character range
  3573. $len = strlen($string);
  3574. $offset = intval($this->spamProtectEmailAddresses)*($back?-1:1);
  3575. for ($i=0; $i<$len; $i++) {
  3576. $charValue = ord($string{$i});
  3577. if ($charValue >= 0x2B && $charValue <= 0x3A) { // 0-9 . , - + / :
  3578. $out .= $this->encryptCharcode($charValue,0x2B,0x3A,$offset);
  3579. } elseif ($charValue >= 0x40 && $charValue <= 0x5A) { // A-Z @
  3580. $out .= $this->encryptCharcode($charValue,0x40,0x5A,$offset);
  3581. } else if ($charValue >= 0x61 && $charValue <= 0x7A) { // a-z
  3582. $out .= $this->encryptCharcode($charValue,0x61,0x7A,$offset);
  3583. } else {
  3584. $out .= $string{$i};
  3585. }
  3586. }
  3587. }
  3588. return $out;
  3589. }
  3590. /**
  3591. * En/decodes strings with lightweight encryption and a hash containing the server encryptionKey (salt)
  3592. * Can be used for authentication of information sent from server generated pages back to the server to establish that the server generated the page. (Like hidden fields with recipient mail addresses)
  3593. * Encryption is mainly to avoid spam-bots to pick up information.
  3594. *
  3595. * @param string Input string to en/decode
  3596. * @param boolean If set, string is decoded, not encoded.
  3597. * @return string encoded/decoded version of $string
  3598. */
  3599. function codeString($string, $decode=FALSE) {
  3600. if ($decode) {
  3601. list($md5Hash, $str) = explode(':',$string,2);
  3602. $newHash = substr(md5($this->TYPO3_CONF_VARS['SYS']['encryptionKey'].':'.$str),0,10);
  3603. if (!strcmp($md5Hash, $newHash)) {
  3604. $str = base64_decode($str);
  3605. $str = $this->roundTripCryptString($str);
  3606. return $str;
  3607. } else return FALSE; // Decoding check failed! Original string not produced by this server!
  3608. } else {
  3609. $str = $string;
  3610. $str = $this->roundTripCryptString($str);
  3611. $str = base64_encode($str);
  3612. $newHash = substr(md5($this->TYPO3_CONF_VARS['SYS']['encryptionKey'].':'.$str),0,10);
  3613. return $newHash.':'.$str;
  3614. }
  3615. }
  3616. /**
  3617. * Encrypts a strings by XOR'ing all characters with a key derived from the
  3618. * TYPO3 encryption key.
  3619. *
  3620. * Using XOR means that the string can be decrypted by simply calling the
  3621. * function again - just like rot-13 works (but in this case for ANY byte
  3622. * value).
  3623. *
  3624. * @param string $string string to crypt, may be empty
  3625. *
  3626. * @return string binary crypt string, will have the same length as $string
  3627. */
  3628. protected function roundTripCryptString($string) {
  3629. $out = '';
  3630. $cleartextLength = strlen($string);
  3631. $key = sha1($this->TYPO3_CONF_VARS['SYS']['encryptionKey']);
  3632. $keyLength = strlen($key);
  3633. for ($a = 0; $a < $cleartextLength; $a++) {
  3634. $xorVal = ord($key{($a % $keyLength)});
  3635. $out .= chr(ord($string{$a}) ^ $xorVal);
  3636. }
  3637. return $out;
  3638. }
  3639. /**
  3640. * Checks if a PHPfile may be included.
  3641. *
  3642. * @param string Relative path to php file
  3643. * @return boolean Returns true if $GLOBALS['TYPO3_CONF_VARS']['FE']['noPHPscriptInclude'] is not set OR if the file requested for inclusion is found in one of the allowed paths.
  3644. * @see tslib_cObj::PHP_SCRIPT(), tslib_feTCE::includeScripts(), tslib_menu::includeMakeMenu()
  3645. */
  3646. function checkFileInclude($incFile) {
  3647. return !$this->TYPO3_CONF_VARS['FE']['noPHPscriptInclude']
  3648. || substr($incFile,0,14)=='media/scripts/'
  3649. || substr($incFile,0,4+strlen(TYPO3_mainDir))==TYPO3_mainDir.'ext/'
  3650. || substr($incFile,0,7+strlen(TYPO3_mainDir))==TYPO3_mainDir.'sysext/'
  3651. || substr($incFile,0,14)=='typo3conf/ext/';
  3652. }
  3653. /**
  3654. * Creates an instance of tslib_cObj in $this->cObj
  3655. * This instance is used to start the rendering of the TypoScript template structure
  3656. *
  3657. * @return void
  3658. * @see pagegen.php
  3659. */
  3660. function newCObj() {
  3661. $this->cObj =t3lib_div::makeInstance('tslib_cObj');
  3662. $this->cObj->start($this->page,'pages');
  3663. }
  3664. /**
  3665. * Converts relative paths in the HTML source to absolute paths for fileadmin/, typo3conf/ext/ and media/ folders.
  3666. *
  3667. * @return void
  3668. * @access private
  3669. * @see pagegen.php, INTincScript()
  3670. */
  3671. function setAbsRefPrefix() {
  3672. if ($this->absRefPrefix) {
  3673. $this->content = str_replace('"media/', '"'.t3lib_extMgm::siteRelPath('cms').'tslib/media/', $this->content);
  3674. $this->content = str_replace('"typo3conf/ext/', '"'.$this->absRefPrefix.'typo3conf/ext/', $this->content);
  3675. $this->content = str_replace('"' . TYPO3_mainDir . 'contrib/', '"' . $this->absRefPrefix . TYPO3_mainDir . 'contrib/', $this->content);
  3676. $this->content = str_replace('"' . TYPO3_mainDir . 'ext/', '"' . $this->absRefPrefix . TYPO3_mainDir . 'ext/', $this->content);
  3677. $this->content = str_replace('"' . TYPO3_mainDir . 'sysext/' , '"' . $this->absRefPrefix . TYPO3_mainDir . 'sysext/', $this->content);
  3678. $this->content = str_replace('"'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '"'.$this->absRefPrefix.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], $this->content);
  3679. // Process additional directories
  3680. $directories = t3lib_div::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
  3681. foreach ($directories as $directory) {
  3682. $this->content = str_replace('"' . $directory, '"' . $this->absRefPrefix . $directory, $this->content);
  3683. }
  3684. }
  3685. }
  3686. /**
  3687. * Prefixing the input URL with ->baseUrl If ->baseUrl is set and the input url is not absolute in some way.
  3688. * Designed as a wrapper functions for use with all frontend links that are processed by JavaScript (for "realurl" compatibility!). So each time a URL goes into window.open, window.location.href or otherwise, wrap it with this function!
  3689. *
  3690. * @param string Input URL, relative or absolute
  3691. * @return string Processed input value.
  3692. */
  3693. function baseUrlWrap($url) {
  3694. if ($this->baseUrl) {
  3695. $urlParts = parse_url($url);
  3696. if (!strlen($urlParts['scheme']) && $url{0}!=='/') {
  3697. $url = $this->baseUrl.$url;
  3698. }
  3699. }
  3700. return $url;
  3701. }
  3702. /**
  3703. * Prints error msg/header.
  3704. * Echoes out the HTML content
  3705. *
  3706. * @param string Message string
  3707. * @param string Header string
  3708. * @return void
  3709. * @see t3lib_timeTrack::debug_typo3PrintError()
  3710. */
  3711. function printError($label,$header='Error!') {
  3712. t3lib_timeTrack::debug_typo3PrintError($header,$label,0,t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
  3713. }
  3714. /**
  3715. * Logs access to deprecated TypoScript objects and properties.
  3716. * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
  3717. *
  3718. * @param string Message string
  3719. * @return void
  3720. * @see t3lib_div::deprecationLog(), t3lib_timeTrack::setTSlogMessage()
  3721. */
  3722. function logDeprecatedTyposcript($msg) {
  3723. $GLOBALS['TT']->setTSlogMessage($msg . ' is deprecated.', 2);
  3724. t3lib_div::deprecationLog('TypoScript ' . $msg);
  3725. }
  3726. /**
  3727. * Updates the tstamp field of a cache_md5params record to the current time.
  3728. *
  3729. * @param string The hash string identifying the cache_md5params record for which to update the "tstamp" field to the current time.
  3730. * @return void
  3731. * @access private
  3732. */
  3733. function updateMD5paramsRecord($hash) {
  3734. $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
  3735. 'cache_md5params',
  3736. 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_md5params'), array('tstamp' => $GLOBALS['EXEC_TIME'])
  3737. );
  3738. }
  3739. /**
  3740. * Pass the content through tidy - a little program that cleans up HTML-code.
  3741. * Requires $this->TYPO3_CONF_VARS['FE']['tidy'] to be true and $this->TYPO3_CONF_VARS['FE']['tidy_path'] to contain the filename/path of tidy including clean-up arguments for tidy. See default value in TYPO3_CONF_VARS in t3lib/config_default.php
  3742. *
  3743. * @param string The page content to clean up. Will be written to a temporary file which "tidy" is then asked to clean up. File content is read back and returned.
  3744. * @return string Returns the
  3745. */
  3746. function tidyHTML($content) {
  3747. if ($this->TYPO3_CONF_VARS['FE']['tidy'] && $this->TYPO3_CONF_VARS['FE']['tidy_path']) {
  3748. $oldContent = $content;
  3749. $fname = t3lib_div::tempnam('typo3_tidydoc_'); // Create temporary name
  3750. @unlink ($fname); // Delete if exists, just to be safe.
  3751. $fp = fopen ($fname,'wb'); // Open for writing
  3752. fputs ($fp, $content); // Put $content
  3753. @fclose ($fp); // Close
  3754. exec ($this->TYPO3_CONF_VARS['FE']['tidy_path'].' '.$fname, $output); // run the $content through 'tidy', which formats the HTML to nice code.
  3755. @unlink ($fname); // Delete the tempfile again
  3756. $content = implode(LF,$output);
  3757. if (!trim($content)) {
  3758. $content = $oldContent; // Restore old content due empty return value.
  3759. $GLOBALS['TT']->setTSlogMessage('"tidy" returned an empty value!',2);
  3760. }
  3761. $GLOBALS['TT']->setTSlogMessage('"tidy" content lenght: '.strlen($content),0);
  3762. }
  3763. return $content;
  3764. }
  3765. /**
  3766. * Substitutes all occurencies of <a href="#"... in $this->content with <a href="[path-to-url]#"...
  3767. *
  3768. * @return void Works directly on $this->content
  3769. */
  3770. function prefixLocalAnchorsWithScript() {
  3771. $scriptPath = $GLOBALS['TSFE']->absRefPrefix . substr(t3lib_div::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
  3772. $originalContent = $this->content;
  3773. $this->content = preg_replace('/(<(?:a|area).*?href=")(#[^"]*")/i', '${1}' . htmlspecialchars($scriptPath) . '${2}', $originalContent);
  3774. // There was an error in the call to preg_replace, so keep the original content (behavior prior to PHP 5.2)
  3775. if (preg_last_error() > 0) {
  3776. t3lib_div::sysLog('preg_replace returned error-code: ' . preg_last_error().' in function prefixLocalAnchorsWithScript. Replacement not done!' , 'cms', 4);
  3777. $this->content = $originalContent;
  3778. }
  3779. }
  3780. /**
  3781. * Initialize workspace preview
  3782. *
  3783. * @return void
  3784. */
  3785. function workspacePreviewInit() {
  3786. $previewWS = t3lib_div::_GP('ADMCMD_previewWS');
  3787. if ($this->beUserLogin && is_object($GLOBALS['BE_USER']) && t3lib_div::testInt($previewWS)) {
  3788. if ($previewWS==0 || ($previewWS>=-1 && $GLOBALS['BE_USER']->checkWorkspace($previewWS))) { // Check Access to workspace. Live (0) is OK to preview for all.
  3789. $this->workspacePreview = intval($previewWS);
  3790. } else {
  3791. $this->workspacePreview = -99; // No preview, will default to "Live" at the moment
  3792. }
  3793. }
  3794. }
  3795. /**
  3796. * Returns true if workspace preview is enabled
  3797. *
  3798. * @return boolean Returns true if workspace preview is enabled
  3799. */
  3800. function doWorkspacePreview() {
  3801. return (string)$this->workspacePreview!=='';
  3802. }
  3803. /**
  3804. * Returns the name of the workspace
  3805. *
  3806. * @param boolean If set, returns title of current workspace being previewed
  3807. * @return mixed If $returnTitle is set, returns string (title), otherwise workspace integer for which workspace is being preview. False if none.
  3808. */
  3809. function whichWorkspace($returnTitle = FALSE) {
  3810. if ($this->doWorkspacePreview()) {
  3811. $ws = intval($this->workspacePreview);
  3812. } elseif ($this->beUserLogin) {
  3813. $ws = $GLOBALS['BE_USER']->workspace;
  3814. } else return FALSE;
  3815. if ($returnTitle) {
  3816. if ($ws===-1) {
  3817. return 'Default Draft Workspace';
  3818. } else {
  3819. $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('title', 'sys_workspace', 'uid='.intval($ws));
  3820. if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  3821. return $row['title'];
  3822. }
  3823. }
  3824. } else {
  3825. return $ws;
  3826. }
  3827. }
  3828. /**
  3829. * Includes a comma-separated list of library files by PHP function include_once.
  3830. *
  3831. * @param array $libraries: The libraries to be included.
  3832. * @return void
  3833. */
  3834. public function includeLibraries(array $libraries) {
  3835. global $TYPO3_CONF_VARS;
  3836. $GLOBALS['TT']->push('Include libraries');
  3837. $GLOBALS['TT']->setTSlogMessage('Files for inclusion: "' . implode(', ', $libraries) . '"');
  3838. foreach ($libraries as $library) {
  3839. $file = $GLOBALS['TSFE']->tmpl->getFileName($library);
  3840. if ($file) {
  3841. include_once('./' . $file);
  3842. } else {
  3843. $GLOBALS['TT']->setTSlogMessage('Include file "' . $file . '" did not exist!', 2);
  3844. }
  3845. }
  3846. $GLOBALS['TT']->pull();
  3847. }
  3848. /********************************************
  3849. *
  3850. * Various external API functions - for use in plugins etc.
  3851. *
  3852. *******************************************/
  3853. /**
  3854. * Traverses the ->rootLine and returns an array with the first occurrance of storage pid and siteroot pid
  3855. *
  3856. * @return array Array with keys '_STORAGE_PID' and '_SITEROOT' set to the first occurances found.
  3857. */
  3858. function getStorageSiterootPids() {
  3859. $res=array();
  3860. if(!is_array($this->rootLine)) {
  3861. return array();
  3862. }
  3863. foreach ($this->rootLine as $rC) {
  3864. if (!$res['_STORAGE_PID']) $res['_STORAGE_PID']=intval($rC['storage_pid']);
  3865. if (!$res['_SITEROOT']) $res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
  3866. }
  3867. return $res;
  3868. }
  3869. /**
  3870. * Returns the pages TSconfig array based on the currect ->rootLine
  3871. *
  3872. * @return array
  3873. */
  3874. function getPagesTSconfig() {
  3875. if (!is_array($this->pagesTSconfig)) {
  3876. $TSdataArray = array();
  3877. $TSdataArray[] = $this->TYPO3_CONF_VARS['BE']['defaultPageTSconfig']; // Setting default configuration:
  3878. foreach ($this->rootLine as $k => $v) {
  3879. $TSdataArray[]=$v['TSconfig'];
  3880. }
  3881. // Parsing the user TS (or getting from cache)
  3882. $TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
  3883. $userTS = implode(LF.'[GLOBAL]'.LF,$TSdataArray);
  3884. $hash = md5('pageTS:'.$userTS);
  3885. $cachedContent = $this->sys_page->getHash($hash);
  3886. if (isset($cachedContent)) {
  3887. $this->pagesTSconfig = unserialize($cachedContent);
  3888. } else {
  3889. $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
  3890. $parseObj->parse($userTS);
  3891. $this->pagesTSconfig = $parseObj->setup;
  3892. $this->sys_page->storeHash($hash,serialize($this->pagesTSconfig),'PAGES_TSconfig');
  3893. }
  3894. }
  3895. return $this->pagesTSconfig;
  3896. }
  3897. /**
  3898. * Sets JavaScript code in the additionalJavaScript array
  3899. *
  3900. * @param string $key is the key in the array, for num-key let the value be empty. Note reserved keys 'openPic' and 'mouseOver'
  3901. * @param string $content is the content if you want any
  3902. * @return void
  3903. * @see tslib_gmenu::writeMenu(), tslib_cObj::imageLinkWrap()
  3904. */
  3905. function setJS($key,$content='') {
  3906. if ($key) {
  3907. switch($key) {
  3908. case 'mouseOver':
  3909. $this->additionalJavaScript[$key]=
  3910. ' // JS function for mouse-over
  3911. function over(name,imgObj) { //
  3912. if (version == "n3" && document[name]) {document[name].src = eval(name+"_h.src");}
  3913. else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_h.src");}
  3914. else if (imgObj) {imgObj.src = eval(name+"_h.src");}
  3915. }
  3916. // JS function for mouse-out
  3917. function out(name,imgObj) { //
  3918. if (version == "n3" && document[name]) {document[name].src = eval(name+"_n.src");}
  3919. else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_n.src");}
  3920. else if (imgObj) {imgObj.src = eval(name+"_n.src");}
  3921. }';
  3922. break;
  3923. case 'openPic':
  3924. $this->additionalJavaScript[$key]=
  3925. ' function openPic(url,winName,winParams) { //
  3926. var theWindow = window.open(url,winName,winParams);
  3927. if (theWindow) {theWindow.focus();}
  3928. }';
  3929. break;
  3930. default:
  3931. $this->additionalJavaScript[$key]=$content;
  3932. break;
  3933. }
  3934. }
  3935. }
  3936. /**
  3937. * Sets CSS data in the additionalCSS array
  3938. *
  3939. * @param string $key is the key in the array, for num-key let the value be empty
  3940. * @param string $content is the content if you want any
  3941. * @return void
  3942. * @see setJS(), tslib_pibase::pi_setClassStyle()
  3943. */
  3944. function setCSS($key,$content) {
  3945. if ($key) {
  3946. switch($key) {
  3947. default:
  3948. $this->additionalCSS[$key]=$content;
  3949. break;
  3950. }
  3951. }
  3952. }
  3953. /**
  3954. * Seeds the random number engine.
  3955. *
  3956. * @return void
  3957. * @deprecated since TYPO3 4.3, this function will be removed in TYPO3 4.5, the random number generator is seeded automatically since PHP 4.2.0
  3958. */
  3959. function make_seed() {
  3960. t3lib_div::logDeprecatedFunction();
  3961. list($usec, $sec) = explode(' ', microtime());
  3962. $seedV = (float)$sec + ((float)$usec * 100000);
  3963. srand($seedV);
  3964. }
  3965. /**
  3966. * Returns a unique md5 hash.
  3967. * There is no special magic in this, the only point is that you don't have to call md5(uniqid()) which is slow and by this you are sure to get a unique string each time in a little faster way.
  3968. *
  3969. * @param string Some string to include in what is hashed. Not significant at all.
  3970. * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
  3971. */
  3972. function uniqueHash($str='') {
  3973. return md5($this->uniqueString.'_'.$str.$this->uniqueCounter++);
  3974. }
  3975. /**
  3976. * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
  3977. *
  3978. * @param string $reason: An optional reason to be written to the syslog.
  3979. * If not set, debug_backtrace() will be used to track down the call.
  3980. * @return void
  3981. */
  3982. function set_no_cache($reason = '') {
  3983. if (strlen($reason)) {
  3984. $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
  3985. } else {
  3986. $trace = debug_backtrace();
  3987. // This is a hack to work around ___FILE___ resolving symbolic links
  3988. $PATH_site_real = str_replace('t3lib','',realpath(PATH_site.'t3lib'));
  3989. $file = $trace[0]['file'];
  3990. if (substr($file,0,strlen($PATH_site_real))===$PATH_site_real) {
  3991. $file = str_replace($PATH_site_real,'',$file);
  3992. } else {
  3993. $file = str_replace(PATH_site,'',$file);
  3994. }
  3995. $line = $trace[0]['line'];
  3996. $trigger = $file.' on line '.$line;
  3997. $warning = '$TSFE->set_no_cache() was triggered by ' . $trigger.'.';
  3998. }
  3999. if ($this->TYPO3_CONF_VARS['FE']['disableNoCacheParameter']) {
  4000. $warning.= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
  4001. $GLOBALS['TT']->setTSlogMessage($warning,2);
  4002. } else {
  4003. $warning.= ' Caching is disabled!';
  4004. $this->disableCache();
  4005. }
  4006. t3lib_div::sysLog($warning, 'cms', 2);
  4007. }
  4008. /**
  4009. * Disables caching of the current page.
  4010. *
  4011. * @return void
  4012. * @internal
  4013. */
  4014. protected function disableCache() {
  4015. $this->no_cache = 1;
  4016. }
  4017. /**
  4018. * Sets the cache-timeout in seconds
  4019. *
  4020. * @param integer cache-timeout in seconds
  4021. * @return void
  4022. */
  4023. function set_cache_timeout_default($seconds) {
  4024. $this->cacheTimeOutDefault = intval($seconds);
  4025. }
  4026. /**
  4027. * Get the cache timeout for the current page.
  4028. *
  4029. * @return integer The cache timeout for the current page.
  4030. */
  4031. function get_cache_timeout() {
  4032. // Cache period was set for the page:
  4033. if ($this->page['cache_timeout']) {
  4034. $cacheTimeout = $this->page['cache_timeout'];
  4035. // Cache period was set for the whole site:
  4036. } elseif ($this->cacheTimeOutDefault) {
  4037. $cacheTimeout = $this->cacheTimeOutDefault;
  4038. // No cache period set at all, so we take one day (60*60*24 seconds = 86400 seconds):
  4039. } else {
  4040. $cacheTimeout = 86400;
  4041. }
  4042. return $cacheTimeout;
  4043. }
  4044. /**
  4045. * Substitute function for the PHP mail() function.
  4046. * It will encode the email with the setting of TS 'config.notification_email_encoding' (base64 or none)
  4047. * It will also find all links to http:// in the text and substitute with a shorter link using the redirect feature which stores the long link in the database. Depends on configuration in TS 'config.notification_email_urlmode'
  4048. *
  4049. * @param string recipient email address (or list of)
  4050. * @param string The subject
  4051. * @param string The message
  4052. * @param string The headers (string with lines)
  4053. * @return void
  4054. * @see t3lib_div::plainMailEncoded()
  4055. */
  4056. function plainMailEncoded($email,$subject,$message,$headers='') {
  4057. $urlmode = $this->config['config']['notification_email_urlmode']; // '76', 'all', ''
  4058. if ($urlmode) {
  4059. $message = t3lib_div::substUrlsInPlainText($message,$urlmode);
  4060. }
  4061. $encoding = $this->config['config']['notification_email_encoding'] ? $this->config['config']['notification_email_encoding'] : '';
  4062. $charset = $this->renderCharset;
  4063. $convCharset = FALSE; // do we need to convert mail data?
  4064. if ($this->config['config']['notification_email_charset']) { // Respect config.notification_email_charset if it was set
  4065. $charset = $this->csConvObj->parse_charset($this->config['config']['notification_email_charset']);
  4066. if ($charset != $this->renderCharset) {
  4067. $convCharset = TRUE;
  4068. }
  4069. } elseif ($this->metaCharset != $this->renderCharset) { // Use metaCharset for mail if different from renderCharset
  4070. $charset = $this->metaCharset;
  4071. $convCharset = TRUE;
  4072. }
  4073. if ($convCharset) {
  4074. $email = $this->csConvObj->conv($email,$this->renderCharset,$charset);
  4075. $subject = $this->csConvObj->conv($subject,$this->renderCharset,$charset);
  4076. $message = $this->csConvObj->conv($message,$this->renderCharset,$charset);
  4077. $headers = $this->csConvObj->conv($headers,$this->renderCharset,$charset);
  4078. }
  4079. t3lib_div::plainMailEncoded(
  4080. $email,
  4081. $subject,
  4082. $message,
  4083. $headers,
  4084. $encoding,
  4085. $charset
  4086. );
  4087. }
  4088. /*********************************************
  4089. *
  4090. * Localization and character set conversion
  4091. *
  4092. *********************************************/
  4093. /**
  4094. * Split Label function for front-end applications.
  4095. *
  4096. * @param string Key string. Accepts the "LLL:" prefix.
  4097. * @return string Label value, if any.
  4098. */
  4099. function sL($input) {
  4100. if (strcmp(substr($input,0,4),'LLL:')) {
  4101. $t = explode('|',$input);
  4102. return $t[$this->langSplitIndex] ? $t[$this->langSplitIndex] : $t[0];
  4103. } else {
  4104. if (!isset($this->LL_labels_cache[$this->lang][$input])) { // If cached label
  4105. $restStr = trim(substr($input,4));
  4106. $extPrfx='';
  4107. if (!strcmp(substr($restStr,0,4),'EXT:')) {
  4108. $restStr = trim(substr($restStr,4));
  4109. $extPrfx='EXT:';
  4110. }
  4111. $parts = explode(':',$restStr);
  4112. $parts[0] = $extPrfx.$parts[0];
  4113. if (!isset($this->LL_files_cache[$parts[0]])) { // Getting data if not cached
  4114. $this->LL_files_cache[$parts[0]] = $this->readLLfile($parts[0]);
  4115. }
  4116. $this->LL_labels_cache[$this->lang][$input] = $this->getLLL($parts[1],$this->LL_files_cache[$parts[0]]);
  4117. }
  4118. return $this->LL_labels_cache[$this->lang][$input];
  4119. }
  4120. }
  4121. /**
  4122. * Read locallang files - for frontend applications
  4123. *
  4124. * @param string Reference to a relative filename to include.
  4125. * @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
  4126. */
  4127. function readLLfile($fileRef) {
  4128. return t3lib_div::readLLfile($fileRef, $this->lang, $this->renderCharset);
  4129. }
  4130. /**
  4131. * Returns 'locallang' label - may need initializing by initLLvars
  4132. *
  4133. * @param string Local_lang key for which to return label (language is determined by $this->lang)
  4134. * @param array The locallang array in which to search
  4135. * @return string Label value of $index key.
  4136. */
  4137. function getLLL($index, &$LOCAL_LANG) {
  4138. if (strcmp($LOCAL_LANG[$this->lang][$index],'')) {
  4139. return $LOCAL_LANG[$this->lang][$index];
  4140. } else {
  4141. return $LOCAL_LANG['default'][$index];
  4142. }
  4143. }
  4144. /**
  4145. * Initializing the getLL variables needed.
  4146. * Sets $this->langSplitIndex based on $this->config['config']['language']
  4147. *
  4148. * @return void
  4149. */
  4150. function initLLvars() {
  4151. // Setting language key and split index:
  4152. $this->lang = $this->config['config']['language'] ? $this->config['config']['language'] : 'default';
  4153. $this->getPageRenderer()->setLanguage($this->lang);
  4154. $ls = explode('|',TYPO3_languages);
  4155. foreach ($ls as $i => $v) {
  4156. if ($v==$this->lang) {$this->langSplitIndex=$i; break;}
  4157. }
  4158. // Setting charsets:
  4159. $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.
  4160. $this->metaCharset = $this->csConvObj->parse_charset($this->config['config']['metaCharset'] ? $this->config['config']['metaCharset'] : $this->renderCharset); // Output charset of HTML page.
  4161. }
  4162. /**
  4163. * Converts the charset of the input string if applicable.
  4164. * The "to" charset is determined by the currently used charset for the page which is "iso-8859-1" by default or set by $GLOBALS['TSFE']->config['config']['renderCharset']
  4165. * Only if there is a difference between the two charsets will a conversion be made
  4166. * The conversion is done real-time - no caching for performance at this point!
  4167. *
  4168. * @param string String to convert charset for
  4169. * @param string Optional "from" charset.
  4170. * @return string Output string, converted if needed.
  4171. * @see t3lib_cs
  4172. */
  4173. function csConv($str,$from='') {
  4174. if ($from) {
  4175. $output = $this->csConvObj->conv($str,$this->csConvObj->parse_charset($from),$this->renderCharset,1);
  4176. return $output ? $output : $str;
  4177. } else {
  4178. return $str;
  4179. }
  4180. }
  4181. /**
  4182. * Converts input string from renderCharset to metaCharset IF the two charsets are different.
  4183. *
  4184. * @param string Content to be converted.
  4185. * @param string Label (just for fun, no function)
  4186. * @return string Converted content string.
  4187. */
  4188. function convOutputCharset($content,$label='') {
  4189. if ($this->renderCharset != $this->metaCharset) {
  4190. $content = $this->csConvObj->conv($content,$this->renderCharset,$this->metaCharset,TRUE);
  4191. }
  4192. return $content;
  4193. }
  4194. /**
  4195. * Converts the $_POST array from metaCharset (page HTML charset from input form) to renderCharset (internal processing) IF the two charsets are different.
  4196. *
  4197. * @return void
  4198. */
  4199. function convPOSTCharset() {
  4200. if ($this->renderCharset != $this->metaCharset && is_array($_POST) && count($_POST)) {
  4201. $this->csConvObj->convArray($_POST,$this->metaCharset,$this->renderCharset);
  4202. $GLOBALS['HTTP_POST_VARS'] = $_POST;
  4203. }
  4204. }
  4205. }
  4206. if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php']) {
  4207. include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['tslib/class.tslib_fe.php']);
  4208. }
  4209. ?>