PageRenderTime 93ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_div.php

https://github.com/foxsoft/typo3v4core
PHP | 6019 lines | 3363 code | 574 blank | 2082 comment | 760 complexity | a0fd2c77bbdfc297fd830fb0beca4713 MD5 | raw file
Possible License(s): 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. * Contains the reknown class "t3lib_div" with general purpose functions
  29. *
  30. * $Id$
  31. * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
  32. * XHTML compliant
  33. * Usage counts are based on search 22/2 2003 through whole source including tslib/
  34. *
  35. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  36. */
  37. /**
  38. * [CLASS/FUNCTION INDEX of SCRIPT]
  39. *
  40. *
  41. *
  42. * 232: class t3lib_div
  43. *
  44. * SECTION: GET/POST Variables
  45. * 262: function _GP($var)
  46. * 280: function _GET($var=NULL)
  47. * 297: function _POST($var=NULL)
  48. * 313: function _GETset($inputGet,$key='')
  49. * 336: function GPvar($var,$strip=0)
  50. * 353: function GParrayMerged($var)
  51. *
  52. * SECTION: IMAGE FUNCTIONS
  53. * 397: function gif_compress($theFile, $type)
  54. * 425: function png_to_gif_by_imagemagick($theFile)
  55. * 450: function read_png_gif($theFile,$output_png=0)
  56. *
  57. * SECTION: STRING FUNCTIONS
  58. * 499: function fixed_lgd($string,$origChars,$preStr='...')
  59. * 524: function fixed_lgd_pre($string,$chars)
  60. * 538: function fixed_lgd_cs($string,$chars)
  61. * 555: function breakTextForEmail($str,$implChar=LF,$charWidth=76)
  62. * 574: function breakLinesForEmail($str,$implChar=LF,$charWidth=76)
  63. * 610: function cmpIP($baseIP, $list)
  64. * 626: function cmpIPv4($baseIP, $list)
  65. * 668: function cmpIPv6($baseIP, $list)
  66. * 711: function IPv6Hex2Bin ($hex)
  67. * 726: function normalizeIPv6($address)
  68. * 782: function validIPv6($ip)
  69. * 805: function cmpFQDN($baseIP, $list)
  70. * 835: function inList($list,$item)
  71. * 847: function rmFromList($element,$list)
  72. * 863: function expandList($list)
  73. * 894: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
  74. * 910: function intval_positive($theInt)
  75. * 923: function int_from_ver($verNumberStr)
  76. * 934: function compat_version($verNumberStr)
  77. * 952: function md5int($str)
  78. * 965: function shortMD5($input, $len=10)
  79. * 978: function uniqueList($in_list, $secondParameter=NULL)
  80. * 992: function split_fileref($fileref)
  81. * 1030: function dirname($path)
  82. * 1046: function modifyHTMLColor($color,$R,$G,$B)
  83. * 1066: function modifyHTMLColorAll($color,$all)
  84. * 1077: function rm_endcomma($string)
  85. * 1090: function danish_strtoupper($string)
  86. * 1105: function convUmlauts($str)
  87. * 1118: function testInt($var)
  88. * 1130: function isFirstPartOfStr($str,$partStr)
  89. * 1146: function formatSize($sizeInBytes,$labels='')
  90. * 1181: function convertMicrotime($microtime)
  91. * 1195: function splitCalc($string,$operators)
  92. * 1217: function calcPriority($string)
  93. * 1258: function calcParenthesis($string)
  94. * 1284: function htmlspecialchars_decode($value)
  95. * 1299: function deHSCentities($str)
  96. * 1312: function slashJS($string,$extended=0,$char="'")
  97. * 1325: function rawUrlEncodeJS($str)
  98. * 1337: function rawUrlEncodeFP($str)
  99. * 1348: function validEmail($email)
  100. * 1363: function formatForTextarea($content)
  101. *
  102. * SECTION: ARRAY FUNCTIONS
  103. * 1394: function inArray($in_array,$item)
  104. * 1411: function intExplode($delim, $string)
  105. * 1430: function revExplode($delim, $string, $count=0)
  106. * 1450: function trimExplode($delim, $string, $onlyNonEmptyValues=0)
  107. * 1472: function uniqueArray($valueArray)
  108. * 1484: function removeArrayEntryByValue($array,$cmpValue)
  109. * 1513: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
  110. * 1538: function explodeUrl2Array($string,$multidim=FALSE)
  111. * 1564: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
  112. * 1587: function addSlashesOnArray(&$theArray)
  113. * 1611: function stripSlashesOnArray(&$theArray)
  114. * 1633: function slashArray($arr,$cmd)
  115. * 1650: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
  116. * 1683: function array_merge($arr1,$arr2)
  117. * 1696: function csvValues($row,$delim=',',$quote='"')
  118. *
  119. * SECTION: HTML/XML PROCESSING
  120. * 1738: function get_tag_attributes($tag)
  121. * 1775: function split_tag_attributes($tag)
  122. * 1809: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
  123. * 1836: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
  124. * 1851: function wrapJS($string, $linebreak=TRUE)
  125. * 1882: function xml2tree($string,$depth=999)
  126. * 1969: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())
  127. * 2088: function xml2array($string,$NSprefix='',$reportDocTag=FALSE)
  128. * 2198: function xmlRecompileFromStructValArray($vals)
  129. * 2242: function xmlGetHeaderAttribs($xmlData)
  130. *
  131. * SECTION: FILES FUNCTIONS
  132. * 2275: function getURL($url, $includeHeader=0)
  133. * 2342: function writeFile($file,$content)
  134. * 2367: function fixPermissions($file)
  135. * 2384: function writeFileToTypo3tempDir($filepath,$content)
  136. * 2427: function mkdir($theNewFolder)
  137. * 2446: function mkdir_deep($destination,$deepDir)
  138. * 2468: function get_dirs($path)
  139. * 2493: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
  140. * 2547: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
  141. * 2570: function removePrefixPathFromList($fileArr,$prefixToRemove)
  142. * 2586: function fixWindowsFilePath($theFile)
  143. * 2598: function resolveBackPath($pathStr)
  144. * 2626: function locationHeaderUrl($path)
  145. *
  146. * SECTION: DEBUG helper FUNCTIONS
  147. * 2666: function debug_ordvalue($string,$characters=100)
  148. * 2683: function view_array($array_in)
  149. * 2711: function print_array($array_in)
  150. * 2726: function debug($var="",$brOrHeader=0)
  151. * 2757: function debug_trail()
  152. * 2779: function debugRows($rows,$header='')
  153. *
  154. * SECTION: SYSTEM INFORMATION
  155. * 2857: function getThisUrl()
  156. * 2873: function linkThisScript($getParams=array())
  157. * 2897: function linkThisUrl($url,$getParams=array())
  158. * 2920: function getIndpEnv($getEnvName)
  159. * 3113: function milliseconds()
  160. * 3125: function clientInfo($useragent='')
  161. *
  162. * SECTION: TYPO3 SPECIFIC FUNCTIONS
  163. * 3212: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
  164. * 3248: function validPathStr($theFile)
  165. * 3259: function isAbsPath($path)
  166. * 3270: function isAllowedAbsPath($path)
  167. * 3287: function verifyFilenameAgainstDenyPattern($filename)
  168. * 3305: function upload_copy_move($source,$destination)
  169. * 3331: function upload_to_tempfile($uploadedFileName)
  170. * 3349: function unlink_tempfile($uploadedTempFileName)
  171. * 3365: function tempnam($filePrefix)
  172. * 3379: function stdAuthCode($uid_or_record,$fields='',$codeLength=8)
  173. * 3410: function cHashParams($addQueryParams)
  174. * 3433: function hideIfNotTranslated($l18n_cfg_fieldValue)
  175. * 3448: function readLLfile($fileRef,$langKey)
  176. * 3472: function readLLXMLfile($fileRef,$langKey)
  177. * 3589: function llXmlAutoFileName($fileRef,$language)
  178. * 3633: function loadTCA($table)
  179. * 3653: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
  180. * 3686: function resolveAllSheetsInDS($dataStructArray)
  181. * 3715: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
  182. * 3813: function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
  183. * 3871: function &makeInstance($className)
  184. * 3883: function makeInstanceClassName($className)
  185. * 3897: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
  186. * 3961: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='',$dontEncodeHeader=false)
  187. * 4031: function quoted_printable($string,$maxlen=76)
  188. * 4078: function encodeHeader($line,$enc='',$charset='ISO-8859-1')
  189. * 4121: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
  190. * 4155: function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
  191. * 4182: function freetypeDpiComp($font_size)
  192. * 4194: function initSysLog()
  193. * 4251: function sysLog($msg, $extKey, $severity=0)
  194. * 4334: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
  195. * 4355: function arrayToLogString($arr, $valueList=array(), $valueLength=20)
  196. * 4378: function imageMagickCommand($command, $parameters, $path='')
  197. * 4425: function unQuoteFilenames($parameters,$unQuote=FALSE)
  198. * 4459: function quoteJSvalue($value, $inScriptTags = false)
  199. *
  200. * TOTAL FUNCTIONS: 138
  201. * (This index is automatically created/updated by the extension "extdeveval")
  202. *
  203. */
  204. // a tabulator
  205. define('TAB', chr(9));
  206. // a linefeed
  207. define('LF', chr(10));
  208. // a carriage return
  209. define('CR', chr(13));
  210. // a CR-LF combination
  211. define('CRLF', CR . LF);
  212. /**
  213. * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
  214. * Most of the functions does not relate specifically to TYPO3
  215. * However a section of functions requires certain TYPO3 features available
  216. * See comments in the source.
  217. * You are encouraged to use this library in your own scripts!
  218. *
  219. * USE:
  220. * The class is intended to be used without creating an instance of it.
  221. * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
  222. * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
  223. *
  224. * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
  225. * @package TYPO3
  226. * @subpackage t3lib
  227. */
  228. final class t3lib_div {
  229. // Severity constants used by t3lib_div::sysLog()
  230. const SYSLOG_SEVERITY_INFO = 0;
  231. const SYSLOG_SEVERITY_NOTICE = 1;
  232. const SYSLOG_SEVERITY_WARNING = 2;
  233. const SYSLOG_SEVERITY_ERROR = 3;
  234. const SYSLOG_SEVERITY_FATAL = 4;
  235. /*************************
  236. *
  237. * GET/POST Variables
  238. *
  239. * Background:
  240. * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
  241. * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
  242. * But the clean solution is that quotes are never escaped and that is what the functions below offers.
  243. * Eventually TYPO3 should provide this in the global space as well.
  244. * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
  245. *
  246. *************************/
  247. /**
  248. * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
  249. * Strips slashes from all output, both strings and arrays.
  250. * This function substitutes t3lib_div::GPvar()
  251. * To enhancement security in your scripts, please consider using t3lib_div::_GET or t3lib_div::_POST if you already know by which method your data is arriving to the scripts!
  252. * Usage: 537
  253. *
  254. * @param string GET/POST var to return
  255. * @return mixed POST var named $var and if not set, the GET var of the same name.
  256. */
  257. public static function _GP($var) {
  258. if(empty($var)) return;
  259. $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
  260. if (isset($value)) {
  261. if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  262. }
  263. return $value;
  264. }
  265. /**
  266. * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
  267. *
  268. * @param string Key (variable name) from GET or POST vars
  269. * @return array Returns the GET vars merged recursively onto the POST vars.
  270. */
  271. public static function _GPmerged($parameter) {
  272. $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array();
  273. $getParameter = (isset($_GET[$parameter]) && is_array($_GET[$parameter])) ? $_GET[$parameter] : array();
  274. $mergedParameters = self::array_merge_recursive_overrule($getParameter, $postParameter);
  275. self::stripSlashesOnArray($mergedParameters);
  276. return $mergedParameters;
  277. }
  278. /**
  279. * Returns the global $_GET array (or value from) normalized to contain un-escaped values.
  280. * ALWAYS use this API function to acquire the GET variables!
  281. * Usage: 27
  282. *
  283. * @param string Optional pointer to value in GET array (basically name of GET var)
  284. * @return mixed If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself. In any case *slashes are stipped from the output!*
  285. * @see _POST(), _GP(), _GETset()
  286. */
  287. public static function _GET($var=NULL) {
  288. $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]);
  289. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  290. if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  291. }
  292. return $value;
  293. }
  294. /**
  295. * Returns the global $_POST array (or value from) normalized to contain un-escaped values.
  296. * ALWAYS use this API function to acquire the $_POST variables!
  297. * Usage: 41
  298. *
  299. * @param string Optional pointer to value in POST array (basically name of POST var)
  300. * @return mixed If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself. In any case *slashes are stipped from the output!*
  301. * @see _GET(), _GP()
  302. */
  303. public static function _POST($var=NULL) {
  304. $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]);
  305. if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
  306. if (is_array($value)) { self::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
  307. }
  308. return $value;
  309. }
  310. /**
  311. * Writes input value to $_GET.
  312. * Usage: 2
  313. *
  314. * @param mixed $inputGet
  315. * array or single value to write to $_GET. Values should NOT be
  316. * escaped at input time (but will be escaped before writing
  317. * according to TYPO3 standards).
  318. * @param string $key
  319. * alternative key; If set, this will not set the WHOLE GET array,
  320. * but only the key in it specified by this value!
  321. * You can specify to replace keys on deeper array levels by
  322. * separating the keys with a pipe.
  323. * Example: 'parentKey|childKey' will result in
  324. * array('parentKey' => array('childKey' => $inputGet))
  325. *
  326. * @return void
  327. */
  328. public static function _GETset($inputGet, $key = '') {
  329. // adds slashes since TYPO3 standard currently is that slashes
  330. // must be applied (regardless of magic_quotes setting)
  331. if (is_array($inputGet)) {
  332. self::addSlashesOnArray($inputGet);
  333. } else {
  334. $inputGet = addslashes($inputGet);
  335. }
  336. if ($key != '') {
  337. if (strpos($key, '|') !== FALSE) {
  338. $pieces = explode('|', $key);
  339. $newGet = array();
  340. $pointer =& $newGet;
  341. foreach ($pieces as $piece) {
  342. $pointer =& $pointer[$piece];
  343. }
  344. $pointer = $inputGet;
  345. $mergedGet = self::array_merge_recursive_overrule(
  346. $_GET, $newGet
  347. );
  348. $_GET = $mergedGet;
  349. $GLOBALS['HTTP_GET_VARS'] = $mergedGet;
  350. } else {
  351. $_GET[$key] = $inputGet;
  352. $GLOBALS['HTTP_GET_VARS'][$key] = $inputGet;
  353. }
  354. } elseif (is_array($inputGet)) {
  355. $_GET = $inputGet;
  356. $GLOBALS['HTTP_GET_VARS'] = $inputGet;
  357. }
  358. }
  359. /**
  360. * Returns the value of incoming data from globals variable $_POST or $_GET, with priority to $_POST (that is equalent to 'GP' order).
  361. * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
  362. * Usage: 2
  363. *
  364. * @param string GET/POST var to return
  365. * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
  366. * @return mixed POST var named $var and if not set, the GET var of the same name.
  367. * @deprecated since TYPO3 3.6 - Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
  368. * @see _GP()
  369. */
  370. public static function GPvar($var,$strip=0) {
  371. self::logDeprecatedFunction();
  372. if(empty($var)) return;
  373. $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var];
  374. if (isset($value) && is_string($value)) { $value = stripslashes($value); } // Originally check '&& get_magic_quotes_gpc() ' but the values of $_GET are always slashed regardless of get_magic_quotes_gpc() because HTTP_POST/GET_VARS are run through addSlashesOnArray in the very beginning of index_ts.php eg.
  375. if ($strip && isset($value) && is_array($value)) { self::stripSlashesOnArray($value); }
  376. return $value;
  377. }
  378. /**
  379. * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
  380. * Usage: 1
  381. *
  382. * @param string Key (variable name) from GET or POST vars
  383. * @return array Returns the GET vars merged recursively onto the POST vars.
  384. * @deprecated since TYPO3 3.7 - Use t3lib_div::_GPmerged instead
  385. * @see _GP()
  386. */
  387. public static function GParrayMerged($var) {
  388. self::logDeprecatedFunction();
  389. return self::_GPmerged($var);
  390. }
  391. /**
  392. * Wrapper for the RemoveXSS function.
  393. * Removes potential XSS code from an input string.
  394. *
  395. * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
  396. *
  397. * @param string Input string
  398. * @return string Input string with potential XSS code removed
  399. */
  400. public static function removeXSS($string) {
  401. require_once(PATH_typo3.'contrib/RemoveXSS/RemoveXSS.php');
  402. $string = RemoveXSS::process($string);
  403. return $string;
  404. }
  405. /*************************
  406. *
  407. * IMAGE FUNCTIONS
  408. *
  409. *************************/
  410. /**
  411. * Compressing a GIF file if not already LZW compressed.
  412. * This function is a workaround for the fact that ImageMagick and/or GD does not compress GIF-files to their minimun size (that is RLE or no compression used)
  413. *
  414. * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
  415. * GIF:
  416. * If $type is not set, the compression is done with ImageMagick (provided that $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] is pointing to the path of a lzw-enabled version of 'convert') else with GD (should be RLE-enabled!)
  417. * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
  418. * PNG:
  419. * No changes.
  420. *
  421. * $theFile is expected to be a valid GIF-file!
  422. * The function returns a code for the operation.
  423. * Usage: 9
  424. *
  425. * @param string Filepath
  426. * @param string See description of function
  427. * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
  428. */
  429. public static function gif_compress($theFile, $type) {
  430. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  431. $returnCode='';
  432. if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
  433. if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
  434. $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
  435. exec($cmd);
  436. $returnCode='IM';
  437. } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
  438. $tempImage = imageCreateFromGif($theFile);
  439. imageGif($tempImage, $theFile);
  440. imageDestroy($tempImage);
  441. $returnCode='GD';
  442. }
  443. }
  444. return $returnCode;
  445. }
  446. /**
  447. * Converts a png file to gif.
  448. * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
  449. * Usage: 5
  450. *
  451. * @param string $theFile the filename with path
  452. * @return string new filename
  453. */
  454. public static function png_to_gif_by_imagemagick($theFile) {
  455. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
  456. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
  457. && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
  458. && strtolower(substr($theFile,-4,4))=='.png'
  459. && @is_file($theFile)) { // IM
  460. $newFile = substr($theFile,0,-4).'.gif';
  461. $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
  462. exec($cmd);
  463. $theFile = $newFile;
  464. // unlink old file?? May be bad idea bacause TYPO3 would then recreate the file every time as TYPO3 thinks the file is not generated because it's missing!! So do not unlink $theFile here!!
  465. }
  466. return $theFile;
  467. }
  468. /**
  469. * Returns filename of the png/gif version of the input file (which can be png or gif).
  470. * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
  471. * Usage: 2
  472. *
  473. * @param string Filepath of image file
  474. * @param boolean If set, then input file is converted to PNG, otherwise to GIF
  475. * @return string If the new image file exists, it's filepath is returned
  476. */
  477. public static function read_png_gif($theFile,$output_png=0) {
  478. if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) {
  479. $ext = strtolower(substr($theFile,-4,4));
  480. if (
  481. ((string)$ext=='.png' && $output_png) ||
  482. ((string)$ext=='.gif' && !$output_png)
  483. ) {
  484. return $theFile;
  485. } else {
  486. $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif');
  487. $cmd = self::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
  488. exec($cmd);
  489. if (@is_file($newFile)) return $newFile;
  490. }
  491. }
  492. }
  493. /*************************
  494. *
  495. * STRING FUNCTIONS
  496. *
  497. *************************/
  498. /**
  499. * Truncates string.
  500. * Returns a new string of max. $chars length.
  501. * If the string is longer, it will be truncated and appended with '...'.
  502. * Usage: 39
  503. *
  504. * @param string string to truncate
  505. * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
  506. * @param string String to append to the output if it is truncated, default is '...'
  507. * @return string new string
  508. * @deprecated since TYPO3 4.1 - Works ONLY for single-byte charsets! Use t3lib_div::fixed_lgd_cs() instead
  509. * @see fixed_lgd_pre()
  510. */
  511. public static function fixed_lgd($string,$origChars,$preStr='...') {
  512. self::logDeprecatedFunction();
  513. $chars = abs($origChars);
  514. if ($chars >= 4) {
  515. if(strlen($string)>$chars) {
  516. return $origChars < 0 ?
  517. $preStr.trim(substr($string, -($chars-3))) :
  518. trim(substr($string, 0, $chars-3)).$preStr;
  519. }
  520. }
  521. return $string;
  522. }
  523. /**
  524. * Truncates string.
  525. * Returns a new string of max. $chars length.
  526. * If the string is longer, it will be truncated and prepended with '...'.
  527. * This works like fixed_lgd(), but is truncated in the start of the string instead of the end
  528. * Usage: 6
  529. *
  530. * @param string string to truncate
  531. * @param integer must be an integer of at least 4
  532. * @return string new string
  533. * @deprecated since TYPO3 4.1 - Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
  534. * @see fixed_lgd()
  535. */
  536. public static function fixed_lgd_pre($string,$chars) {
  537. self::logDeprecatedFunction();
  538. return strrev(self::fixed_lgd(strrev($string),$chars));
  539. }
  540. /**
  541. * Truncates a string with appended/prepended "..." and takes current character set into consideration.
  542. * Usage: 75
  543. *
  544. * @param string string to truncate
  545. * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
  546. * @param string appendix to the truncated string
  547. * @return string cropped string
  548. */
  549. public static function fixed_lgd_cs($string, $chars, $appendString='...') {
  550. if (is_object($GLOBALS['LANG'])) {
  551. return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet, $string, $chars, $appendString);
  552. } elseif (is_object($GLOBALS['TSFE'])) {
  553. $charSet = ($GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet);
  554. return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString);
  555. } else {
  556. // this case should not happen
  557. $csConvObj = self::makeInstance('t3lib_cs');
  558. return $csConvObj->crop('iso-8859-1', $string, $chars, $appendString);
  559. }
  560. }
  561. /**
  562. * Breaks up the text for emails
  563. * Usage: 1
  564. *
  565. * @param string The string to break up
  566. * @param string The string to implode the broken lines with (default/typically \n)
  567. * @param integer The line length
  568. * @deprecated since TYPO3 4.1 - Use PHP function wordwrap()
  569. * @return string
  570. */
  571. public static function breakTextForEmail($str,$implChar=LF,$charWidth=76) {
  572. self::logDeprecatedFunction();
  573. $lines = explode(LF,$str);
  574. $outArr=array();
  575. foreach ($lines as $lStr) {
  576. $outArr[] = self::breakLinesForEmail($lStr,$implChar,$charWidth);
  577. }
  578. return implode(LF,$outArr);
  579. }
  580. /**
  581. * Breaks up a single line of text for emails
  582. * Usage: 5
  583. *
  584. * @param string The string to break up
  585. * @param string The string to implode the broken lines with (default/typically \n)
  586. * @param integer The line length
  587. * @return string
  588. * @see breakTextForEmail()
  589. */
  590. public static function breakLinesForEmail($str,$implChar=LF,$charWidth=76) {
  591. $lines=array();
  592. $l=$charWidth;
  593. $p=0;
  594. while(strlen($str)>$p) {
  595. $substr=substr($str,$p,$l);
  596. if (strlen($substr)==$l) {
  597. $count = count(explode(' ',trim(strrev($substr))));
  598. if ($count>1) { // OK...
  599. $parts = explode(' ',strrev($substr),2);
  600. $theLine = strrev($parts[1]);
  601. } else {
  602. $afterParts = explode(' ',substr($str,$l+$p),2);
  603. $theLine = $substr.$afterParts[0];
  604. }
  605. if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
  606. } else {
  607. $theLine=$substr;
  608. }
  609. $lines[]=trim($theLine);
  610. $p+=strlen($theLine);
  611. if (!trim(substr($str,$p,$l))) break; // added...
  612. }
  613. return implode($implChar,$lines);
  614. }
  615. /**
  616. * Match IP number with list of numbers with wildcard
  617. * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
  618. * Usage: 10
  619. *
  620. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  621. * @param string $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE.
  622. * @return boolean True if an IP-mask from $list matches $baseIP
  623. */
  624. public static function cmpIP($baseIP, $list) {
  625. $list = trim($list);
  626. if ($list === '') {
  627. return false;
  628. } elseif ($list === '*') {
  629. return true;
  630. }
  631. if (strpos($baseIP, ':') !== false && self::validIPv6($baseIP)) {
  632. return self::cmpIPv6($baseIP, $list);
  633. } else {
  634. return self::cmpIPv4($baseIP, $list);
  635. }
  636. }
  637. /**
  638. * Match IPv4 number with list of numbers with wildcard
  639. *
  640. * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
  641. * @param string $list is a comma-list of IP-addresses to match with. *-wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.*.* equals 192.168)
  642. * @return boolean True if an IP-mask from $list matches $baseIP
  643. */
  644. public static function cmpIPv4($baseIP, $list) {
  645. $IPpartsReq = explode('.',$baseIP);
  646. if (count($IPpartsReq)==4) {
  647. $values = self::trimExplode(',',$list,1);
  648. foreach($values as $test) {
  649. list($test,$mask) = explode('/',$test);
  650. if(intval($mask)) {
  651. // "192.168.3.0/24"
  652. $lnet = ip2long($test);
  653. $lip = ip2long($baseIP);
  654. $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
  655. $firstpart = substr($binnet,0,$mask);
  656. $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
  657. $firstip = substr($binip,0,$mask);
  658. $yes = (strcmp($firstpart,$firstip)==0);
  659. } else {
  660. // "192.168.*.*"
  661. $IPparts = explode('.',$test);
  662. $yes = 1;
  663. foreach ($IPparts as $index => $val) {
  664. $val = trim($val);
  665. if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
  666. $yes=0;
  667. }
  668. }
  669. }
  670. if ($yes) return true;
  671. }
  672. }
  673. return false;
  674. }
  675. /**
  676. * Match IPv6 address with a list of IPv6 prefixes
  677. *
  678. * @param string $baseIP is the current remote IP address for instance
  679. * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
  680. * @return boolean True if an baseIP matches any prefix
  681. */
  682. public static function cmpIPv6($baseIP, $list) {
  683. $success = false; // Policy default: Deny connection
  684. $baseIP = self::normalizeIPv6($baseIP);
  685. $values = self::trimExplode(',',$list,1);
  686. foreach ($values as $test) {
  687. list($test,$mask) = explode('/',$test);
  688. if (self::validIPv6($test)) {
  689. $test = self::normalizeIPv6($test);
  690. if (intval($mask)) {
  691. switch ($mask) { // test on /48 /64
  692. case '48':
  693. $testBin = substr(self::IPv6Hex2Bin($test), 0, 48);
  694. $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 48);
  695. $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
  696. break;
  697. case '64':
  698. $testBin = substr(self::IPv6Hex2Bin($test), 0, 64);
  699. $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 64);
  700. $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
  701. break;
  702. default:
  703. $success = false;
  704. }
  705. } else {
  706. if (self::validIPv6($test)) { // test on full ip address 128 bits
  707. $testBin = self::IPv6Hex2Bin($test);
  708. $baseIPBin = self::IPv6Hex2Bin($baseIP);
  709. $success = strcmp($testBin, $baseIPBin)==0 ? true : false;
  710. }
  711. }
  712. }
  713. if ($success) return true;
  714. }
  715. return false;
  716. }
  717. /**
  718. * [Describe function...]
  719. *
  720. * @param [type] $hex: ...
  721. * @return [type] ...
  722. */
  723. public static function IPv6Hex2Bin ($hex) {
  724. $bin = '';
  725. $hex = str_replace(':', '', $hex); // Replace colon to nothing
  726. for ($i=0; $i<strlen($hex); $i=$i+2) {
  727. $bin.= chr(hexdec(substr($hex, $i, 2)));
  728. }
  729. return $bin;
  730. }
  731. /**
  732. * Normalize an IPv6 address to full length
  733. *
  734. * @param string Given IPv6 address
  735. * @return string Normalized address
  736. */
  737. public static function normalizeIPv6($address) {
  738. $normalizedAddress = '';
  739. $stageOneAddress = '';
  740. $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
  741. if (count($chunks)==2) {
  742. $chunksLeft = explode(':', $chunks[0]);
  743. $chunksRight = explode(':', $chunks[1]);
  744. $left = count($chunksLeft);
  745. $right = count($chunksRight);
  746. // Special case: leading zero-only blocks count to 1, should be 0
  747. if ($left==1 && strlen($chunksLeft[0])==0) $left=0;
  748. $hiddenBlocks = 8 - ($left + $right);
  749. $hiddenPart = '';
  750. while ($h<$hiddenBlocks) {
  751. $hiddenPart .= '0000:';
  752. $h++;
  753. }
  754. if ($left == 0) {
  755. $stageOneAddress = $hiddenPart . $chunks[1];
  756. } else {
  757. $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
  758. }
  759. } else $stageOneAddress = $address;
  760. // normalize the blocks:
  761. $blocks = explode(':', $stageOneAddress);
  762. $divCounter = 0;
  763. foreach ($blocks as $block) {
  764. $tmpBlock = '';
  765. $i = 0;
  766. $hiddenZeros = 4 - strlen($block);
  767. while ($i < $hiddenZeros) {
  768. $tmpBlock .= '0';
  769. $i++;
  770. }
  771. $normalizedAddress .= $tmpBlock . $block;
  772. if ($divCounter < 7) {
  773. $normalizedAddress .= ':';
  774. $divCounter++;
  775. }
  776. }
  777. return $normalizedAddress;
  778. }
  779. /**
  780. * Validate a given IP address.
  781. *
  782. * Possible format are IPv4 and IPv6.
  783. *
  784. * @param string IP address to be tested
  785. * @return boolean True if $ip is either of IPv4 or IPv6 format.
  786. */
  787. public static function validIP($ip) {
  788. return (filter_var($ip, FILTER_VALIDATE_IP) !== false);
  789. }
  790. /**
  791. * Validate a given IP address to the IPv4 address format.
  792. *
  793. * Example for possible format: 10.0.45.99
  794. *
  795. * @param string IP address to be tested
  796. * @return boolean True if $ip is of IPv4 format.
  797. */
  798. public static function validIPv4($ip) {
  799. return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false);
  800. }
  801. /**
  802. * Validate a given IP address to the IPv6 address format.
  803. *
  804. * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
  805. *
  806. * @param string IP address to be tested
  807. * @return boolean True if $ip is of IPv6 format.
  808. */
  809. public static function validIPv6($ip) {
  810. return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false);
  811. }
  812. /**
  813. * Match fully qualified domain name with list of strings with wildcard
  814. *
  815. * @param string The current remote IP address for instance, typ. REMOTE_ADDR
  816. * @param string A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
  817. * @return boolean True if a domain name mask from $list matches $baseIP
  818. */
  819. public static function cmpFQDN($baseIP, $list) {
  820. if (count(explode('.',$baseIP))==4) {
  821. $resolvedHostName = explode('.', gethostbyaddr($baseIP));
  822. $values = self::trimExplode(',',$list,1);
  823. foreach($values as $test) {
  824. $hostNameParts = explode('.',$test);
  825. $yes = 1;
  826. foreach($hostNameParts as $index => $val) {
  827. $val = trim($val);
  828. if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
  829. $yes=0;
  830. }
  831. }
  832. if ($yes) return true;
  833. }
  834. }
  835. return false;
  836. }
  837. /**
  838. * Checks if a given URL matches the host that currently handles this HTTP request.
  839. * Scheme, hostname and (optional) port of the given URL are compared.
  840. *
  841. * @param string $url: URL to compare with the TYPO3 request host
  842. * @return boolean Whether the URL matches the TYPO3 request host
  843. */
  844. public static function isOnCurrentHost($url) {
  845. return (stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0);
  846. }
  847. /**
  848. * Check for item in list
  849. * Check if an item exists in a comma-separated list of items.
  850. * Usage: 163
  851. *
  852. * @param string comma-separated list of items (string)
  853. * @param string item to check for
  854. * @return boolean true if $item is in $list
  855. */
  856. public static function inList($list, $item) {
  857. return (strpos(','.$list.',', ','.$item.',')!==false ? true : false);
  858. }
  859. /**
  860. * Removes an item from a comma-separated list of items.
  861. * Usage: 1
  862. *
  863. * @param string element to remove
  864. * @param string comma-separated list of items (string)
  865. * @return string new comma-separated list of items
  866. */
  867. public static function rmFromList($element,$list) {
  868. $items = explode(',',$list);
  869. foreach ($items as $k => $v) {
  870. if ($v==$element) {
  871. unset($items[$k]);
  872. }
  873. }
  874. return implode(',',$items);
  875. }
  876. /**
  877. * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
  878. * Ranges are limited to 1000 values per range.
  879. *
  880. * @param string comma-separated list of integers with ranges (string)
  881. * @return string new comma-separated list of items
  882. * @author Martin Kutschker <martin.kutschker@activesolution.at>
  883. */
  884. public static function expandList($list) {
  885. $items = explode(',',$list);
  886. $list = array();
  887. foreach ($items as $item) {
  888. $range = explode('-',$item);
  889. if (isset($range[1])) {
  890. $runAwayBrake = 1000;
  891. for ($n=$range[0]; $n<=$range[1]; $n++) {
  892. $list[] = $n;
  893. $runAwayBrake--;
  894. if ($runAwayBrake<=0) break;
  895. }
  896. } else {
  897. $list[] = $item;
  898. }
  899. }
  900. return implode(',',$list);
  901. }
  902. /**
  903. * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
  904. * Usage: 224
  905. *
  906. * @param integer Input value
  907. * @param integer Lower limit
  908. * @param integer Higher limit
  909. * @param integer Default value if input is false.
  910. * @return integer The input value forced into the boundaries of $min and $max
  911. */
  912. public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
  913. // Returns $theInt as an integer in the integerspace from $min to $max
  914. $theInt = intval($theInt);
  915. if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
  916. if ($theInt<$min){$theInt=$min;}
  917. if ($theInt>$max){$theInt=$max;}
  918. return $theInt;
  919. }
  920. /**
  921. * Returns the $integer if greater than zero, otherwise returns zero.
  922. * Usage: 1
  923. *
  924. * @param integer Integer string to process
  925. * @return integer
  926. */
  927. public static function intval_positive($theInt) {
  928. $theInt = intval($theInt);
  929. if ($theInt<0){$theInt=0;}
  930. return $theInt;
  931. }
  932. /**
  933. * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
  934. * Usage: 2
  935. *
  936. * @param string Version number on format x.x.x
  937. * @return integer Integer version of version number (where each part can count to 999)
  938. */
  939. public static function int_from_ver($verNumberStr) {
  940. $verParts = explode('.',$verNumberStr);
  941. return intval((int)$verParts[0].str_pad((int)$verParts[1],3,'0',STR_PAD_LEFT).str_pad((int)$verParts[2],3,'0',STR_PAD_LEFT));
  942. }
  943. /**
  944. * Returns true if the current TYPO3 version (or compatibility version) is compatible to the input version
  945. * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
  946. *
  947. * @param string Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
  948. * @return boolean Returns true if this setup is compatible with the provided version number
  949. * @todo Still needs a function to convert versions to branches
  950. */
  951. public static function compat_version($verNumberStr) {
  952. global $TYPO3_CONF_VARS;
  953. $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch;
  954. if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr)) {
  955. return FALSE;
  956. } else {
  957. return TRUE;
  958. }
  959. }
  960. /**
  961. * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
  962. * Usage: 5
  963. *
  964. * @param string String to md5-hash
  965. * @return integer Returns 28bit integer-hash
  966. */
  967. public static function md5int($str) {
  968. return hexdec(substr(md5($str),0,7));
  969. }
  970. /**
  971. * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
  972. *
  973. * Usage: 37
  974. *
  975. * @param string Input string to be md5-hashed
  976. * @param integer The string-length of the output
  977. * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
  978. */
  979. public static function shortMD5($input, $len=10) {
  980. return substr(md5($input),0,$len);
  981. }
  982. /**
  983. * Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
  984. *
  985. * @param string Input string to create HMAC from
  986. * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)
  987. */
  988. public static function hmac($input) {
  989. $hashAlgorithm = 'sha1';
  990. $hashBlocksize = 64;
  991. $hmac = '';
  992. if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) {
  993. $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']);
  994. } else {
  995. // outer padding
  996. $opad = str_repeat(chr(0x5C), $hashBlocksize);
  997. // innner padding
  998. $ipad = str_repeat(chr(0x36), $hashBlocksize);
  999. if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) {
  1000. // keys longer than blocksize are shorten
  1001. $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00));
  1002. } else {
  1003. // keys shorter than blocksize are zero-padded
  1004. $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00));
  1005. }
  1006. $hmac = call_user_func($hashAlgorithm, ($key^$opad) . pack('H*', call_user_func($hashAlgorithm, ($key^$ipad) . $input)));
  1007. }
  1008. return $hmac;
  1009. }
  1010. /**
  1011. * Takes comma-separated lists and arrays and removes all duplicates
  1012. * If a value in the list is trim(empty), the value is ignored.
  1013. * Usage: 16
  1014. *
  1015. * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
  1016. * @param mixed $secondParameter: Dummy field, which if set will show a warning!
  1017. * @return string Returns the list without any duplicates of values, space around values are trimmed
  1018. */
  1019. public static function uniqueList($in_list, $secondParameter=NULL) {
  1020. if (is_array($in_list)) {
  1021. throw new InvalidArgumentException(
  1022. 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!',
  1023. 1270853885
  1024. );
  1025. }
  1026. if (isset($secondParameter)) {
  1027. throw new InvalidArgumentException(
  1028. 'TYPO3 Fatal Error: t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one!',
  1029. 1270853886
  1030. );
  1031. }
  1032. return implode(',',array_unique(self::trimExplode(',',$in_list,1)));
  1033. }
  1034. /**
  1035. * Splits a reference to a file in 5 parts
  1036. * Usage: 43
  1037. *
  1038. * @param string Filename/filepath to be analysed
  1039. * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
  1040. */
  1041. public static function split_fileref($fileref) {
  1042. $reg = array();
  1043. if (preg_match('/(.*\/)(.*)$/', $fileref, $reg)) {
  1044. $info['path'] = $reg[1];
  1045. $info['file'] = $reg[2];
  1046. } else {
  1047. $info['path'] = '';
  1048. $info['file'] = $fileref;
  1049. }
  1050. $reg = '';
  1051. if (!is_dir($fileref) && preg_match('/(.*)\.([^\.]*$)/', $info['file'], $reg)) {
  1052. $info['filebody'] = $reg[1];
  1053. $info['fileext'] = strtolower($reg[2]);
  1054. $info['realFileext'] = $reg[2];
  1055. } else {
  1056. $info['filebody'] = $info['file'];
  1057. $info['fileext'] = '';
  1058. }
  1059. reset($info);
  1060. return $info;
  1061. }
  1062. /**
  1063. * Returns the directory part of a path without trailing slash
  1064. * If there is no dir-part, then an empty string is returned.
  1065. * Behaviour:
  1066. *
  1067. * '/dir1/dir2/script.php' => '/dir1/dir2'
  1068. * '/dir1/' => '/dir1'
  1069. * 'dir1/script.php' => 'dir1'
  1070. * 'd/script.php' => 'd'
  1071. * '/script.php' => ''
  1072. * '' => ''
  1073. * Usage: 5
  1074. *
  1075. * @param string Directory name / path
  1076. * @return string Processed input value. See function description.
  1077. */
  1078. public static function dirname($path) {
  1079. $p = self::revExplode('/',$path,2);
  1080. return count($p)==2 ? $p[0] : '';
  1081. }
  1082. /**
  1083. * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
  1084. * Usage: 11
  1085. *
  1086. * @param string A hexadecimal color code, #xxxxxx
  1087. * @param integer Offset value 0-255
  1088. * @param integer Offset value 0-255
  1089. * @param integer Offset value 0-255
  1090. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  1091. * @see modifyHTMLColorAll()
  1092. */
  1093. public static function modifyHTMLColor($color,$R,$G,$B) {
  1094. // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
  1095. $nR = self::intInRange(hexdec(substr($color,1,2))+$R,0,255);
  1096. $nG = self::intInRange(hexdec(substr($color,3,2))+$G,0,255);
  1097. $nB = self::intInRange(hexdec(substr($color,5,2))+$B,0,255);
  1098. return '#'.
  1099. substr('0'.dechex($nR),-2).
  1100. substr('0'.dechex($nG),-2).
  1101. substr('0'.dechex($nB),-2);
  1102. }
  1103. /**
  1104. * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
  1105. * Usage: 6
  1106. *
  1107. * @param string A hexadecimal color code, #xxxxxx
  1108. * @param integer Offset value 0-255 for all three channels.
  1109. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
  1110. * @see modifyHTMLColor()
  1111. */
  1112. public static function modifyHTMLColorAll($color,$all) {
  1113. return self::modifyHTMLColor($color,$all,$all,$all);
  1114. }
  1115. /**
  1116. * Removes comma (if present) in the end of string
  1117. * Usage: 2
  1118. *
  1119. * @param string String from which the comma in the end (if any) will be removed.
  1120. * @return string
  1121. */
  1122. public static function rm_endcomma($string) {
  1123. return rtrim($string, ',');
  1124. }
  1125. /**
  1126. * strtoupper which converts danish (and other characters) characters as well
  1127. * Usage: 0
  1128. *
  1129. * @param string String to process
  1130. * @return string
  1131. * @deprecated since TYPO3 3.5 - Use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
  1132. * @ignore
  1133. */
  1134. public static function danish_strtoupper($string) {
  1135. self::logDeprecatedFunction();
  1136. $value = strtoupper($string);
  1137. return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
  1138. }
  1139. /**
  1140. * Change umlaut characters to plain ASCII with normally two character target
  1141. * Only known characters will be converted, so don't expect a result for any character.
  1142. *
  1143. * ä => ae, Ö => Oe
  1144. *
  1145. * @param string String to convert.
  1146. * @deprecated since TYPO3 4.1 - Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
  1147. * @return string
  1148. */
  1149. public static function convUmlauts($str) {
  1150. self::logDeprecatedFunction();
  1151. $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
  1152. $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
  1153. return preg_replace($pat,$repl,$str);
  1154. }
  1155. /**
  1156. * Tests if the input is an integer.
  1157. * Usage: 77
  1158. *
  1159. * @param mixed Any input variable to test.
  1160. * @return boolean Returns true if string is an integer
  1161. */
  1162. public static function testInt($var) {
  1163. return !strcmp($var,intval($var));
  1164. }
  1165. /**
  1166. * Returns true if the first part of $str matches the string $partStr
  1167. * Usage: 59
  1168. *
  1169. * @param string Full string to check
  1170. * @param string Reference string which must be found as the "first part" of the full string
  1171. * @return boolean True if $partStr was found to be equal to the first part of $str
  1172. */
  1173. public static function isFirstPartOfStr($str,$partStr) {
  1174. // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
  1175. $psLen = strlen($partStr);
  1176. if ($psLen) {
  1177. return substr($str,0,$psLen)==(string)$partStr;
  1178. } else return false;
  1179. }
  1180. /**
  1181. * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
  1182. * Usage: 53
  1183. *
  1184. * @param integer Number of bytes to format.
  1185. * @param string Labels for bytes, kilo, mega and giga separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G" (which is the default value)
  1186. * @return string Formatted representation of the byte number, for output.
  1187. */
  1188. public static function formatSize($sizeInBytes,$labels='') {
  1189. // Set labels:
  1190. if (strlen($labels) == 0) {
  1191. $labels = ' | K| M| G';
  1192. } else {
  1193. $labels = str_replace('"','',$labels);
  1194. }
  1195. $labelArr = explode('|',$labels);
  1196. // Find size:
  1197. if ($sizeInBytes>900) {
  1198. if ($sizeInBytes>900000000) { // GB
  1199. $val = $sizeInBytes/(1024*1024*1024);
  1200. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3];
  1201. }
  1202. elseif ($sizeInBytes>900000) { // MB
  1203. $val = $sizeInBytes/(1024*1024);
  1204. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2];
  1205. } else { // KB
  1206. $val = $sizeInBytes/(1024);
  1207. return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1];
  1208. }
  1209. } else { // Bytes
  1210. return $sizeInBytes.$labelArr[0];
  1211. }
  1212. }
  1213. /**
  1214. * Returns microtime input to milliseconds
  1215. * Usage: 2
  1216. *
  1217. * @param string Microtime
  1218. * @return integer Microtime input string converted to an integer (milliseconds)
  1219. */
  1220. public static function convertMicrotime($microtime) {
  1221. $parts = explode(' ',$microtime);
  1222. return round(($parts[0]+$parts[1])*1000);
  1223. }
  1224. /**
  1225. * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
  1226. * Usage: 2
  1227. *
  1228. * @param string Input string, eg "123 + 456 / 789 - 4"
  1229. * @param string Operators to split by, typically "/+-*"
  1230. * @return array Array with operators and operands separated.
  1231. * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
  1232. */
  1233. public static function splitCalc($string,$operators) {
  1234. $res = Array();
  1235. $sign='+';
  1236. while($string) {
  1237. $valueLen=strcspn($string,$operators);
  1238. $value=substr($string,0,$valueLen);
  1239. $res[] = Array($sign,trim($value));
  1240. $sign=substr($string,$valueLen,1);
  1241. $string=substr($string,$valueLen+1);
  1242. }
  1243. reset($res);
  1244. return $res;
  1245. }
  1246. /**
  1247. * Calculates the input by +,-,*,/,%,^ with priority to + and -
  1248. * Usage: 1
  1249. *
  1250. * @param string Input string, eg "123 + 456 / 789 - 4"
  1251. * @return integer Calculated value. Or error string.
  1252. * @see calcParenthesis()
  1253. */
  1254. public static function calcPriority($string) {
  1255. $string=preg_replace('/[[:space:]]*/','',$string); // removing all whitespace
  1256. $string='+'.$string; // Ensuring an operator for the first entrance
  1257. $qm='\*\/\+-^%';
  1258. $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
  1259. // split the expression here:
  1260. $reg = array();
  1261. preg_match_all('/'.$regex.'/',$string,$reg);
  1262. reset($reg[2]);
  1263. $number=0;
  1264. $Msign='+';
  1265. $err='';
  1266. $buffer=doubleval(current($reg[2]));
  1267. next($reg[2]); // Advance pointer
  1268. while(list($k,$v)=each($reg[2])) {
  1269. $v=doubleval($v);
  1270. $sign = $reg[1][$k];
  1271. if ($sign=='+' || $sign=='-') {
  1272. $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
  1273. $Msign = $sign;
  1274. $buffer=$v;
  1275. } else {
  1276. if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
  1277. if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';}
  1278. if ($sign=='*') {$buffer*=$v;}
  1279. if ($sign=='^') {$buffer=pow($buffer,$v);}
  1280. }
  1281. }
  1282. $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer;
  1283. return $err ? 'ERROR: '.$err : $number;
  1284. }
  1285. /**
  1286. * Calculates the input with parenthesis levels
  1287. * Usage: 2
  1288. *
  1289. * @param string Input string, eg "(123 + 456) / 789 - 4"
  1290. * @return integer Calculated value. Or error string.
  1291. * @see calcPriority(), tslib_cObj::stdWrap()
  1292. */
  1293. public static function calcParenthesis($string) {
  1294. $securC=100;
  1295. do {
  1296. $valueLenO=strcspn($string,'(');
  1297. $valueLenC=strcspn($string,')');
  1298. if ($valueLenC==strlen($string) || $valueLenC < $valueLenO) {
  1299. $value = self::calcPriority(substr($string,0,$valueLenC));
  1300. $string = $value.substr($string,$valueLenC+1);
  1301. return $string;
  1302. } else {
  1303. $string = substr($string,0,$valueLenO).self::calcParenthesis(substr($string,$valueLenO+1));
  1304. }
  1305. // Security:
  1306. $securC--;
  1307. if ($securC<=0) break;
  1308. } while($valueLenO<strlen($string));
  1309. return $string;
  1310. }
  1311. /**
  1312. * Inverse version of htmlspecialchars()
  1313. * Usage: 4
  1314. *
  1315. * @param string Value where &gt;, &lt;, &quot; and &amp; should be converted to regular chars.
  1316. * @return string Converted result.
  1317. */
  1318. public static function htmlspecialchars_decode($value) {
  1319. $value = str_replace('&gt;','>',$value);
  1320. $value = str_replace('&lt;','<',$value);
  1321. $value = str_replace('&quot;','"',$value);
  1322. $value = str_replace('&amp;','&',$value);
  1323. return $value;
  1324. }
  1325. /**
  1326. * Re-converts HTML entities if they have been converted by htmlspecialchars()
  1327. * Usage: 10
  1328. *
  1329. * @param string String which contains eg. "&amp;amp;" which should stay "&amp;". Or "&amp;#1234;" to "&#1234;". Or "&amp;#x1b;" to "&#x1b;"
  1330. * @return string Converted result.
  1331. */
  1332. public static function deHSCentities($str) {
  1333. return preg_replace('/&amp;([#[:alnum:]]*;)/','&\1',$str);
  1334. }
  1335. /**
  1336. * This function is used to escape any ' -characters when transferring text to JavaScript!
  1337. * Usage: 3
  1338. *
  1339. * @param string String to escape
  1340. * @param boolean If set, also backslashes are escaped.
  1341. * @param string The character to escape, default is ' (single-quote)
  1342. * @return string Processed input string
  1343. */
  1344. public static function slashJS($string,$extended=0,$char="'") {
  1345. if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
  1346. return str_replace ($char, "\\".$char, $string);
  1347. }
  1348. /**
  1349. * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
  1350. * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
  1351. * Usage: 4
  1352. *
  1353. * @param string String to raw-url-encode with spaces preserved
  1354. * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
  1355. */
  1356. public static function rawUrlEncodeJS($str) {
  1357. return str_replace('%20',' ',rawurlencode($str));
  1358. }
  1359. /**
  1360. * rawurlencode which preserves "/" chars
  1361. * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
  1362. * Usage: 5
  1363. *
  1364. * @param string Input string
  1365. * @return string Output string
  1366. */
  1367. public static function rawUrlEncodeFP($str) {
  1368. return str_replace('%2F','/',rawurlencode($str));
  1369. }
  1370. /**
  1371. * Checking syntax of input email address
  1372. * Usage: 5
  1373. *
  1374. * @param string Input string to evaluate
  1375. * @return boolean Returns true if the $email address (input string) is valid
  1376. */
  1377. public static function validEmail($email) {
  1378. return (filter_var($email, FILTER_VALIDATE_EMAIL) !== false);
  1379. }
  1380. /**
  1381. * Checks if current e-mail sending method does not accept recipient/sender name
  1382. * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
  1383. * program are known not to process such input correctly and they cause SMTP
  1384. * errors. This function will return true if current mail sending method has
  1385. * problem with recipient name in recipient/sender argument for mail().
  1386. *
  1387. * TODO: 4.3 should have additional configuration variable, which is combined
  1388. * by || with the rest in this function.
  1389. *
  1390. * @return boolean true if mail() does not accept recipient name
  1391. */
  1392. public static function isBrokenEmailEnvironment() {
  1393. return TYPO3_OS == 'WIN' || (false !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
  1394. }
  1395. /**
  1396. * Changes from/to arguments for mail() function to work in any environment.
  1397. *
  1398. * @param string $address Address to adjust
  1399. * @return string Adjusted address
  1400. * @see t3lib_::isBrokenEmailEnvironment()
  1401. */
  1402. public static function normalizeMailAddress($address) {
  1403. if (self::isBrokenEmailEnvironment() && false !== ($pos1 = strrpos($address, '<'))) {
  1404. $pos2 = strpos($address, '>', $pos1);
  1405. $address = substr($address, $pos1 + 1, ($pos2 ? $pos2 : strlen($address)) - $pos1 - 1);
  1406. }
  1407. return $address;
  1408. }
  1409. /**
  1410. * Formats a string for output between <textarea>-tags
  1411. * All content outputted in a textarea form should be passed through this function
  1412. * Not only is the content htmlspecialchar'ed on output but there is also a single newline added in the top. The newline is necessary because browsers will ignore the first newline after <textarea> if that is the first character. Therefore better set it!
  1413. * Usage: 23
  1414. *
  1415. * @param string Input string to be formatted.
  1416. * @return string Formatted for <textarea>-tags
  1417. */
  1418. public static function formatForTextarea($content) {
  1419. return LF.htmlspecialchars($content);
  1420. }
  1421. /**
  1422. * Converts string to uppercase
  1423. * The function converts all Latin characters (a-z, but no accents, etc) to
  1424. * uppercase. It is safe for all supported character sets (incl. utf-8).
  1425. * Unlike strtoupper() it does not honour the locale.
  1426. *
  1427. * @param string Input string
  1428. * @return string Uppercase String
  1429. */
  1430. public static function strtoupper($str) {
  1431. return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  1432. }
  1433. /**
  1434. * Converts string to lowercase
  1435. * The function converts all Latin characters (A-Z, but no accents, etc) to
  1436. * lowercase. It is safe for all supported character sets (incl. utf-8).
  1437. * Unlike strtolower() it does not honour the locale.
  1438. *
  1439. * @param string Input string
  1440. * @return string Lowercase String
  1441. */
  1442. public static function strtolower($str) {
  1443. return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
  1444. }
  1445. /**
  1446. * Returns a string of highly randomized bytes (over the full 8-bit range).
  1447. *
  1448. * @copyright Drupal CMS
  1449. * @license GNU General Public License version 2
  1450. * @param integer Number of characters (bytes) to return
  1451. * @return string Random Bytes
  1452. */
  1453. public static function generateRandomBytes($count) {
  1454. $output = '';
  1455. // /dev/urandom is available on many *nix systems and is considered
  1456. // the best commonly available pseudo-random source.
  1457. if (TYPO3_OS != 'WIN' && ($fh = @fopen('/dev/urandom', 'rb'))) {
  1458. $output = fread($fh, $count);
  1459. fclose($fh);
  1460. }
  1461. // fallback if /dev/urandom is not available
  1462. if (!isset($output{$count - 1})) {
  1463. // We initialize with the somewhat random.
  1464. $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
  1465. . microtime() . getmypid();
  1466. while (!isset($output{$count - 1})) {
  1467. $randomState = md5(microtime() . mt_rand() . $randomState);
  1468. $output .= md5(mt_rand() . $randomState, true);
  1469. }
  1470. $output = substr($output, strlen($output) - $count, $count);
  1471. }
  1472. return $output;
  1473. }
  1474. /**
  1475. * Returns a given string with underscores as UpperCamelCase.
  1476. * Example: Converts blog_example to BlogExample
  1477. *
  1478. * @param string $string: String to be converted to camel case
  1479. * @return string UpperCamelCasedWord
  1480. */
  1481. public static function underscoredToUpperCamelCase($string) {
  1482. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1483. return $upperCamelCase;
  1484. }
  1485. /**
  1486. * Returns a given string with underscores as lowerCamelCase.
  1487. * Example: Converts minimal_value to minimalValue
  1488. *
  1489. * @param string $string: String to be converted to camel case
  1490. * @return string lowerCamelCasedWord
  1491. */
  1492. public static function underscoredToLowerCamelCase($string) {
  1493. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1494. $lowerCamelCase = self::lcfirst($upperCamelCase);
  1495. return $lowerCamelCase;
  1496. }
  1497. /**
  1498. * Returns a given CamelCasedString as an lowercase string with underscores.
  1499. * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
  1500. *
  1501. * @param string $string: String to be converted to lowercase underscore
  1502. * @return string lowercase_and_underscored_string
  1503. */
  1504. public static function camelCaseToLowerCaseUnderscored($string) {
  1505. return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
  1506. }
  1507. /**
  1508. * Converts the first char of a string to lowercase if it is a latin character (A-Z).
  1509. * Example: Converts "Hello World" to "hello World"
  1510. *
  1511. * @param string $string: The string to be used to lowercase the first character
  1512. * @return string The string with the first character as lowercase
  1513. */
  1514. public static function lcfirst($string) {
  1515. return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
  1516. }
  1517. /**
  1518. * Checks if a given string is a Uniform Resource Locator (URL).
  1519. *
  1520. * @param string $url: The URL to be validated
  1521. * @return boolean Whether the given URL is valid
  1522. */
  1523. public static function isValidUrl($url) {
  1524. return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== false);
  1525. }
  1526. /*************************
  1527. *
  1528. * ARRAY FUNCTIONS
  1529. *
  1530. *************************/
  1531. /**
  1532. * Check if an string item exists in an array.
  1533. * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
  1534. *
  1535. * Comparison to PHP in_array():
  1536. * -> $array = array(0, 1, 2, 3);
  1537. * -> variant_a := t3lib_div::inArray($array, $needle)
  1538. * -> variant_b := in_array($needle, $array)
  1539. * -> variant_c := in_array($needle, $array, true)
  1540. * +---------+-----------+-----------+-----------+
  1541. * | $needle | variant_a | variant_b | variant_c |
  1542. * +---------+-----------+-----------+-----------+
  1543. * | '1a' | false | true | false |
  1544. * | '' | false | true | false |
  1545. * | '0' | true | true | false |
  1546. * | 0 | true | true | true |
  1547. * +---------+-----------+-----------+-----------+
  1548. * Usage: 3
  1549. *
  1550. * @param array one-dimensional array of items
  1551. * @param string item to check for
  1552. * @return boolean true if $item is in the one-dimensional array $in_array
  1553. */
  1554. public static function inArray(array $in_array, $item) {
  1555. foreach ($in_array as $val) {
  1556. if (!is_array($val) && !strcmp($val, $item)) {
  1557. return true;
  1558. }
  1559. }
  1560. return false;
  1561. }
  1562. /**
  1563. * Explodes a $string delimited by $delim and passes each item in the array through intval().
  1564. * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
  1565. * Usage: 76
  1566. *
  1567. * @param string Delimiter string to explode with
  1568. * @param string The string to explode
  1569. * @param boolean If set, all empty values (='') will NOT be set in output
  1570. * @param integer If positive, the result will contain a maximum of limit elements,
  1571. * if negative, all components except the last -limit are returned,
  1572. * if zero (default), the result is not limited at all
  1573. * @return array Exploded values, all converted to integers
  1574. */
  1575. public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
  1576. $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
  1577. return array_map('intval', $explodedValues);
  1578. }
  1579. /**
  1580. * Reverse explode which explodes the string counting from behind.
  1581. * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
  1582. * Usage: 8
  1583. *
  1584. * @param string Delimiter string to explode with
  1585. * @param string The string to explode
  1586. * @param integer Number of array entries
  1587. * @return array Exploded values
  1588. */
  1589. public static function revExplode($delimiter, $string, $count=0) {
  1590. $explodedValues = explode($delimiter, strrev($string), $count);
  1591. $explodedValues = array_map('strrev', $explodedValues);
  1592. return array_reverse($explodedValues);
  1593. }
  1594. /**
  1595. * Explodes a string and trims all values for whitespace in the ends.
  1596. * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
  1597. * Usage: 256
  1598. *
  1599. * @param string Delimiter string to explode with
  1600. * @param string The string to explode
  1601. * @param boolean If set, all empty values will be removed in output
  1602. * @param integer If positive, the result will contain a maximum of
  1603. * $limit elements, if negative, all components except
  1604. * the last -$limit are returned, if zero (default),
  1605. * the result is not limited at all. Attention though
  1606. * that the use of this parameter can slow down this
  1607. * function.
  1608. * @return array Exploded values
  1609. */
  1610. public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0) {
  1611. $explodedValues = explode($delim, $string);
  1612. $result = array_map('trim', $explodedValues);
  1613. if ($removeEmptyValues) {
  1614. $temp = array();
  1615. foreach($result as $value) {
  1616. if ($value !== '') {
  1617. $temp[] = $value;
  1618. }
  1619. }
  1620. $result = $temp;
  1621. }
  1622. if ($limit != 0) {
  1623. if ($limit < 0) {
  1624. $result = array_slice($result, 0, $limit);
  1625. } elseif (count($result) > $limit) {
  1626. $lastElements = array_slice($result, $limit - 1);
  1627. $result = array_slice($result, 0, $limit - 1);
  1628. $result[] = implode($delim, $lastElements);
  1629. }
  1630. }
  1631. return $result;
  1632. }
  1633. /**
  1634. * Remove duplicate values from an array
  1635. * Usage: 0
  1636. *
  1637. * @param array Array of values to make unique
  1638. * @return array
  1639. * @ignore
  1640. * @deprecated since TYPO3 3.5 - Use the PHP function array_unique instead
  1641. */
  1642. public static function uniqueArray(array $valueArray) {
  1643. self::logDeprecatedFunction();
  1644. return array_unique($valueArray);
  1645. }
  1646. /**
  1647. * Removes the value $cmpValue from the $array if found there. Returns the modified array
  1648. * Usage: 3
  1649. *
  1650. * @param array Array containing the values
  1651. * @param string Value to search for and if found remove array entry where found.
  1652. * @return array Output array with entries removed if search string is found
  1653. */
  1654. public static function removeArrayEntryByValue(array $array, $cmpValue) {
  1655. foreach ($array as $k => $v) {
  1656. if (is_array($v)) {
  1657. $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
  1658. } elseif (!strcmp($v, $cmpValue)) {
  1659. unset($array[$k]);
  1660. }
  1661. }
  1662. return $array;
  1663. }
  1664. /**
  1665. * Filters an array to reduce its elements to match the condition.
  1666. * The values in $keepItems can be optionally evaluated by a custom callback function.
  1667. *
  1668. * Example (arguments used to call this function):
  1669. * $array = array(
  1670. * array('aa' => array('first', 'second'),
  1671. * array('bb' => array('third', 'fourth'),
  1672. * array('cc' => array('fifth', 'sixth'),
  1673. * );
  1674. * $keepItems = array('third');
  1675. * $getValueFunc = create_function('$value', 'return $value[0];');
  1676. *
  1677. * Returns:
  1678. * array(
  1679. * array('bb' => array('third', 'fourth'),
  1680. * )
  1681. *
  1682. * @param array $array: The initial array to be filtered/reduced
  1683. * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
  1684. * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
  1685. * @return array The filtered/reduced array with the kept items
  1686. */
  1687. public static function keepItemsInArray(array $array, $keepItems, $getValueFunc=null) {
  1688. if ($array) {
  1689. // Convert strings to arrays:
  1690. if (is_string($keepItems)) {
  1691. $keepItems = self::trimExplode(',', $keepItems);
  1692. }
  1693. // create_function() returns a string:
  1694. if (!is_string($getValueFunc)) {
  1695. $getValueFunc = null;
  1696. }
  1697. // Do the filtering:
  1698. if (is_array($keepItems) && count($keepItems)) {
  1699. foreach ($array as $key => $value) {
  1700. // Get the value to compare by using the callback function:
  1701. $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
  1702. if (!in_array($keepValue, $keepItems)) {
  1703. unset($array[$key]);
  1704. }
  1705. }
  1706. }
  1707. }
  1708. return $array;
  1709. }
  1710. /**
  1711. * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
  1712. * Usage: 24
  1713. *
  1714. * @param string Name prefix for entries. Set to blank if you wish none.
  1715. * @param array The (multidim) array to implode
  1716. * @param string (keep blank)
  1717. * @param boolean If set, parameters which were blank strings would be removed.
  1718. * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
  1719. * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
  1720. * @see explodeUrl2Array()
  1721. */
  1722. public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) {
  1723. foreach($theArray as $Akey => $AVal) {
  1724. $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
  1725. if (is_array($AVal)) {
  1726. $str = self::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
  1727. } else {
  1728. if (!$skipBlank || strcmp($AVal,'')) {
  1729. $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
  1730. '='.rawurlencode($AVal);
  1731. }
  1732. }
  1733. }
  1734. return $str;
  1735. }
  1736. /**
  1737. * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
  1738. *
  1739. * @param string GETvars string
  1740. * @param boolean If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
  1741. * @return array Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!
  1742. * @see implodeArrayForUrl()
  1743. */
  1744. public static function explodeUrl2Array($string,$multidim=FALSE) {
  1745. $output = array();
  1746. if ($multidim) {
  1747. parse_str($string,$output);
  1748. } else {
  1749. $p = explode('&',$string);
  1750. foreach($p as $v) {
  1751. if (strlen($v)) {
  1752. list($pK,$pV) = explode('=',$v,2);
  1753. $output[rawurldecode($pK)] = rawurldecode($pV);
  1754. }
  1755. }
  1756. }
  1757. return $output;
  1758. }
  1759. /**
  1760. * Returns an array with selected keys from incoming data.
  1761. * (Better read source code if you want to find out...)
  1762. * Usage: 3
  1763. *
  1764. * @param string List of variable/key names
  1765. * @param array Array from where to get values based on the keys in $varList
  1766. * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
  1767. * @return array Output array with selected variables.
  1768. */
  1769. public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
  1770. $keys = self::trimExplode(',',$varList,1);
  1771. $outArr = array();
  1772. foreach($keys as $v) {
  1773. if (isset($getArray[$v])) {
  1774. $outArr[$v] = $getArray[$v];
  1775. } elseif ($GPvarAlt) {
  1776. $outArr[$v] = self::_GP($v);
  1777. }
  1778. }
  1779. return $outArr;
  1780. }
  1781. /**
  1782. * AddSlash array
  1783. * This function traverses a multidimentional array and adds slashes to the values.
  1784. * NOTE that the input array is and argument by reference.!!
  1785. * Twin-function to stripSlashesOnArray
  1786. * Usage: 8
  1787. *
  1788. * @param array Multidimensional input array, (REFERENCE!)
  1789. * @return array
  1790. */
  1791. public static function addSlashesOnArray(array &$theArray) {
  1792. foreach ($theArray as &$value) {
  1793. if (is_array($value)) {
  1794. self::addSlashesOnArray($value);
  1795. } else {
  1796. $value = addslashes($value);
  1797. }
  1798. unset($value);
  1799. }
  1800. reset($theArray);
  1801. }
  1802. /**
  1803. * StripSlash array
  1804. * This function traverses a multidimentional array and strips slashes to the values.
  1805. * NOTE that the input array is and argument by reference.!!
  1806. * Twin-function to addSlashesOnArray
  1807. * Usage: 10
  1808. *
  1809. * @param array Multidimensional input array, (REFERENCE!)
  1810. * @return array
  1811. */
  1812. public static function stripSlashesOnArray(array &$theArray) {
  1813. foreach ($theArray as &$value) {
  1814. if (is_array($value)) {
  1815. self::stripSlashesOnArray($value);
  1816. } else {
  1817. $value = stripslashes($value);
  1818. }
  1819. unset($value);
  1820. }
  1821. reset($theArray);
  1822. }
  1823. /**
  1824. * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
  1825. * Usage: 0
  1826. *
  1827. * @param array Multidimensional input array
  1828. * @param string "add" or "strip", depending on usage you wish.
  1829. * @return array
  1830. */
  1831. public static function slashArray(array $arr,$cmd) {
  1832. if ($cmd=='strip') self::stripSlashesOnArray($arr);
  1833. if ($cmd=='add') self::addSlashesOnArray($arr);
  1834. return $arr;
  1835. }
  1836. /**
  1837. * Rename Array keys with a given mapping table
  1838. * @param array Array by reference which should be remapped
  1839. * @param array Array with remap information, array/$oldKey => $newKey)
  1840. */
  1841. function remapArrayKeys(&$array, $mappingTable) {
  1842. if (is_array($mappingTable)) {
  1843. foreach ($mappingTable as $old => $new) {
  1844. if ($new && isset($array[$old])) {
  1845. $array[$new] = $array[$old];
  1846. unset ($array[$old]);
  1847. }
  1848. }
  1849. }
  1850. }
  1851. /**
  1852. * Merges two arrays recursively and "binary safe" (integer keys are
  1853. * overridden as well), overruling similar values in the first array
  1854. * ($arr0) with the values of the second array ($arr1)
  1855. * In case of identical keys, ie. keeping the values of the second.
  1856. * Usage: 0
  1857. *
  1858. * @param array First array
  1859. * @param array Second array, overruling the first array
  1860. * @param boolean If set, keys that are NOT found in $arr0 (first array) will not be set. Thus only existing value can/will be overruled from second array.
  1861. * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: true
  1862. * @return array Resulting array where $arr1 values has overruled $arr0 values
  1863. */
  1864. public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
  1865. foreach ($arr1 as $key => $val) {
  1866. if(is_array($arr0[$key])) {
  1867. if (is_array($arr1[$key])) {
  1868. $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
  1869. }
  1870. } else {
  1871. if ($notAddKeys) {
  1872. if (isset($arr0[$key])) {
  1873. if ($includeEmtpyValues || $val) {
  1874. $arr0[$key] = $val;
  1875. }
  1876. }
  1877. } else {
  1878. if ($includeEmtpyValues || $val) {
  1879. $arr0[$key] = $val;
  1880. }
  1881. }
  1882. }
  1883. }
  1884. reset($arr0);
  1885. return $arr0;
  1886. }
  1887. /**
  1888. * An array_merge function where the keys are NOT renumbered as they happen to be with the real php-array_merge function. It is "binary safe" in the sense that integer keys are overridden as well.
  1889. * Usage: 16
  1890. *
  1891. * @param array First array
  1892. * @param array Second array
  1893. * @return array Merged result.
  1894. */
  1895. public static function array_merge(array $arr1,array $arr2) {
  1896. return $arr2+$arr1;
  1897. }
  1898. /**
  1899. * Filters keys off from first array that also exist in second array. Comparision is done by keys.
  1900. * This method is a recursive version of php array_diff_assoc()
  1901. *
  1902. * @param array Source array
  1903. * @param array Reduce source array by this array
  1904. * @return array Source array reduced by keys also present in second array
  1905. */
  1906. public static function arrayDiffAssocRecursive(array $array1, array $array2) {
  1907. $differenceArray = array();
  1908. foreach ($array1 as $key => $value) {
  1909. if (!array_key_exists($key, $array2)) {
  1910. $differenceArray[$key] = $value;
  1911. } elseif (is_array($value)) {
  1912. if (is_array($array2[$key])) {
  1913. $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
  1914. }
  1915. }
  1916. }
  1917. return $differenceArray;
  1918. }
  1919. /**
  1920. * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
  1921. * Usage: 5
  1922. *
  1923. * @param array Input array of values
  1924. * @param string Delimited, default is comman
  1925. * @param string Quote-character to wrap around the values.
  1926. * @return string A single line of CSV
  1927. */
  1928. public static function csvValues(array $row,$delim=',',$quote='"') {
  1929. reset($row);
  1930. $out=array();
  1931. foreach ($row as $value) {
  1932. $out[] = str_replace($quote, $quote.$quote, $value);
  1933. }
  1934. $str = $quote.implode($quote.$delim.$quote,$out).$quote;
  1935. return $str;
  1936. }
  1937. /**
  1938. * Creates recursively a JSON literal from a multidimensional associative array.
  1939. * Uses native function of PHP >= 5.2.0
  1940. *
  1941. * @param array $jsonArray: The array to be transformed to JSON
  1942. * @return string JSON string
  1943. * @deprecated since TYPO3 4.3, use PHP native function json_encode() instead, will be removed in TYPO3 4.5
  1944. */
  1945. public static function array2json(array $jsonArray) {
  1946. self::logDeprecatedFunction();
  1947. return json_encode($jsonArray);
  1948. }
  1949. /**
  1950. * Removes dots "." from end of a key identifier of TypoScript styled array.
  1951. * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
  1952. *
  1953. * @param array $ts: TypoScript configuration array
  1954. * @return array TypoScript configuration array without dots at the end of all keys
  1955. */
  1956. public static function removeDotsFromTS(array $ts) {
  1957. $out = array();
  1958. foreach ($ts as $key => $value) {
  1959. if (is_array($value)) {
  1960. $key = rtrim($key, '.');
  1961. $out[$key] = self::removeDotsFromTS($value);
  1962. } else {
  1963. $out[$key] = $value;
  1964. }
  1965. }
  1966. return $out;
  1967. }
  1968. /*************************
  1969. *
  1970. * HTML/XML PROCESSING
  1971. *
  1972. *************************/
  1973. /**
  1974. * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
  1975. * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
  1976. * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
  1977. * Usage: 8
  1978. *
  1979. * @param string HTML-tag string (or attributes only)
  1980. * @return array Array with the attribute values.
  1981. */
  1982. public static function get_tag_attributes($tag) {
  1983. $components = self::split_tag_attributes($tag);
  1984. $name = ''; // attribute name is stored here
  1985. $valuemode = false;
  1986. $attributes = array();
  1987. foreach ($components as $key => $val) {
  1988. if ($val != '=') { // Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
  1989. if ($valuemode) {
  1990. if ($name) {
  1991. $attributes[$name] = $val;
  1992. $name = '';
  1993. }
  1994. } else {
  1995. if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/','',$val))) {
  1996. $attributes[$key] = '';
  1997. $name = $key;
  1998. }
  1999. }
  2000. $valuemode = false;
  2001. } else {
  2002. $valuemode = true;
  2003. }
  2004. }
  2005. return $attributes;
  2006. }
  2007. /**
  2008. * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
  2009. * Removes tag-name if found
  2010. * Usage: 2
  2011. *
  2012. * @param string HTML-tag string (or attributes only)
  2013. * @return array Array with the attribute values.
  2014. */
  2015. public static function split_tag_attributes($tag) {
  2016. $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/','',trim($tag)));
  2017. // Removes any > in the end of the string
  2018. $tag_tmp = trim(rtrim($tag_tmp, '>'));
  2019. $value = array();
  2020. while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
  2021. $firstChar=substr($tag_tmp,0,1);
  2022. if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
  2023. $reg=explode($firstChar,$tag_tmp,3);
  2024. $value[]=$reg[1];
  2025. $tag_tmp=trim($reg[2]);
  2026. } elseif (!strcmp($firstChar,'=')) {
  2027. $value[] = '=';
  2028. $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
  2029. } else {
  2030. // There are '' around the value. We look for the next ' ' or '>'
  2031. $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
  2032. $value[] = trim($reg[0]);
  2033. $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
  2034. }
  2035. }
  2036. reset($value);
  2037. return $value;
  2038. }
  2039. /**
  2040. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  2041. * Usage: 14
  2042. *
  2043. * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
  2044. * @param boolean If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!
  2045. * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
  2046. * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
  2047. */
  2048. public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  2049. if ($xhtmlSafe) {
  2050. $newArr=array();
  2051. foreach($arr as $p => $v) {
  2052. if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
  2053. }
  2054. $arr = $newArr;
  2055. }
  2056. $list = array();
  2057. foreach($arr as $p => $v) {
  2058. if (strcmp($v,'') || $dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
  2059. }
  2060. return implode(' ',$list);
  2061. }
  2062. /**
  2063. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  2064. *
  2065. * @param array See implodeAttributes()
  2066. * @param boolean See implodeAttributes()
  2067. * @param boolean See implodeAttributes()
  2068. * @return string See implodeAttributes()
  2069. * @deprecated since TYPO3 3.7 - Name was changed into implodeAttributes
  2070. * @see implodeAttributes()
  2071. */
  2072. public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  2073. self::logDeprecatedFunction();
  2074. return self::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
  2075. }
  2076. /**
  2077. * Wraps JavaScript code XHTML ready with <script>-tags
  2078. * Automatic re-identing of the JS code is done by using the first line as ident reference.
  2079. * This is nice for identing JS code with PHP code on the same level.
  2080. *
  2081. * @param string JavaScript code
  2082. * @param boolean Wrap script element in linebreaks? Default is TRUE.
  2083. * @return string The wrapped JS code, ready to put into a XHTML page
  2084. * @author Ingmar Schlecht <ingmars@web.de>
  2085. * @author René Fritz <r.fritz@colorcube.de>
  2086. */
  2087. public static function wrapJS($string, $linebreak=TRUE) {
  2088. if(trim($string)) {
  2089. // <script wrapped in nl?
  2090. $cr = $linebreak? LF : '';
  2091. // remove nl from the beginning
  2092. $string = preg_replace ('/^\n+/', '', $string);
  2093. // re-ident to one tab using the first line as reference
  2094. $match = array();
  2095. if(preg_match('/^(\t+)/',$string,$match)) {
  2096. $string = str_replace($match[1],TAB, $string);
  2097. }
  2098. $string = $cr.'<script type="text/javascript">
  2099. /*<![CDATA[*/
  2100. '.$string.'
  2101. /*]]>*/
  2102. </script>'.$cr;
  2103. }
  2104. return trim($string);
  2105. }
  2106. /**
  2107. * Parses XML input into a PHP array with associative keys
  2108. * Usage: 0
  2109. *
  2110. * @param string XML data input
  2111. * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
  2112. * @return mixed The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.
  2113. * @author bisqwit at iki dot fi dot not dot for dot ads dot invalid / http://dk.php.net/xml_parse_into_struct + kasperYYYY@typo3.com
  2114. */
  2115. public static function xml2tree($string,$depth=999) {
  2116. $parser = xml_parser_create();
  2117. $vals = array();
  2118. $index = array();
  2119. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  2120. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  2121. xml_parse_into_struct($parser, $string, $vals, $index);
  2122. if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  2123. xml_parser_free($parser);
  2124. $stack = array( array() );
  2125. $stacktop = 0;
  2126. $startPoint=0;
  2127. // FIXME don't use unset() - what does that mean? Use NULL or similar.
  2128. unset($tagi);
  2129. foreach($vals as $key => $val) {
  2130. $type = $val['type'];
  2131. // open tag:
  2132. if ($type=='open' || $type=='complete') {
  2133. $stack[$stacktop++] = $tagi;
  2134. if ($depth==$stacktop) {
  2135. $startPoint=$key;
  2136. }
  2137. $tagi = array('tag' => $val['tag']);
  2138. if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
  2139. if(isset($val['value'])) $tagi['values'][] = $val['value'];
  2140. }
  2141. // finish tag:
  2142. if ($type=='complete' || $type=='close') {
  2143. $oldtagi = $tagi;
  2144. $tagi = $stack[--$stacktop];
  2145. $oldtag = $oldtagi['tag'];
  2146. unset($oldtagi['tag']);
  2147. if ($depth==($stacktop+1)) {
  2148. if ($key-$startPoint > 0) {
  2149. $partArray = array_slice(
  2150. $vals,
  2151. $startPoint+1,
  2152. $key-$startPoint-1
  2153. );
  2154. #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
  2155. $oldtagi['XMLvalue']=self::xmlRecompileFromStructValArray($partArray);
  2156. } else {
  2157. $oldtagi['XMLvalue']=$oldtagi['values'][0];
  2158. }
  2159. }
  2160. $tagi['ch'][$oldtag][] = $oldtagi;
  2161. unset($oldtagi);
  2162. }
  2163. // cdata
  2164. if($type=='cdata') {
  2165. $tagi['values'][] = $val['value'];
  2166. }
  2167. }
  2168. return $tagi['ch'];
  2169. }
  2170. /**
  2171. * Turns PHP array into XML. See array2xml()
  2172. *
  2173. * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  2174. * @param string Alternative document tag. Default is "phparray".
  2175. * @param array Options for the compilation. See array2xml() for description.
  2176. * @param string Forced charset to prologue
  2177. * @return string An XML string made from the input content in the array.
  2178. * @see xml2array(),array2xml()
  2179. */
  2180. public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
  2181. // Figure out charset if not given explicitly:
  2182. if (!$charset) {
  2183. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
  2184. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
  2185. } elseif (is_object($GLOBALS['LANG'])) {
  2186. $charset = $GLOBALS['LANG']->charSet; // If "LANG" is around, that will hold the current charset
  2187. } else {
  2188. $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
  2189. }
  2190. }
  2191. // Return XML:
  2192. return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.LF.
  2193. self::array2xml($array,'',0,$docTag,0, $options);
  2194. }
  2195. /**
  2196. * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
  2197. *
  2198. * Converts a PHP array into an XML string.
  2199. * The XML output is optimized for readability since associative keys are used as tagnames.
  2200. * This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem.
  2201. * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
  2202. * The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string
  2203. * The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set.
  2204. * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la <?xml version="1.0" encoding="[charset]" standalone="yes" ?> - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This suchs of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8!
  2205. * However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons...
  2206. * Usage: 5
  2207. *
  2208. * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  2209. * @param string tag-prefix, eg. a namespace prefix like "T3:"
  2210. * @param integer Current recursion level. Don't change, stay at zero!
  2211. * @param string Alternative document tag. Default is "phparray".
  2212. * @param integer If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used
  2213. * @param array Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag')
  2214. * @param string Stack data. Don't touch.
  2215. * @return string An XML string made from the input content in the array.
  2216. * @see xml2array()
  2217. */
  2218. public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
  2219. // The list of byte values which will trigger binary-safe storage. If any value has one of these char values in it, it will be encoded in base64
  2220. $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
  2221. chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
  2222. chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
  2223. chr(30).chr(31);
  2224. // Set indenting mode:
  2225. $indentChar = $spaceInd ? ' ' : TAB;
  2226. $indentN = $spaceInd>0 ? $spaceInd : 1;
  2227. $nl = ($spaceInd >= 0 ? LF : '');
  2228. // Init output variable:
  2229. $output='';
  2230. // Traverse the input array
  2231. foreach($array as $k=>$v) {
  2232. $attr = '';
  2233. $tagName = $k;
  2234. // Construct the tag name.
  2235. if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
  2236. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2237. $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
  2238. }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && self::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
  2239. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2240. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
  2241. }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
  2242. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2243. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
  2244. } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
  2245. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2246. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
  2247. } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
  2248. if ($options['useNindex']) { // If numeric key, prefix "n"
  2249. $tagName = 'n'.$tagName;
  2250. } else { // Use special tag for num. keys:
  2251. $attr.=' index="'.$tagName.'"';
  2252. $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
  2253. }
  2254. } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
  2255. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2256. $tagName = $options['useIndexTagForAssoc'];
  2257. }
  2258. // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
  2259. $tagName = substr(preg_replace('/[^[:alnum:]_-]/','',$tagName),0,100);
  2260. // If the value is an array then we will call this function recursively:
  2261. if (is_array($v)) {
  2262. // Sub elements:
  2263. if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
  2264. $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
  2265. $clearStackPath = $subOptions['clearStackPath'];
  2266. } else {
  2267. $subOptions = $options;
  2268. $clearStackPath = FALSE;
  2269. }
  2270. $content = $nl .
  2271. self::array2xml(
  2272. $v,
  2273. $NSprefix,
  2274. $level+1,
  2275. '',
  2276. $spaceInd,
  2277. $subOptions,
  2278. array(
  2279. 'parentTagName' => $tagName,
  2280. 'grandParentTagName' => $stackData['parentTagName'],
  2281. 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
  2282. )
  2283. ).
  2284. ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
  2285. if ((int)$options['disableTypeAttrib']!=2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
  2286. $attr.=' type="array"';
  2287. }
  2288. } else { // Just a value:
  2289. // Look for binary chars:
  2290. $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
  2291. if ($vLen && strcspn($v,$binaryChars) != $vLen) { // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
  2292. // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
  2293. $content = $nl.chunk_split(base64_encode($v));
  2294. $attr.=' base64="1"';
  2295. } else {
  2296. // Otherwise, just htmlspecialchar the stuff:
  2297. $content = htmlspecialchars($v);
  2298. $dType = gettype($v);
  2299. if ($dType == 'string') {
  2300. if ($options['useCDATA'] && $content != $v) {
  2301. $content = '<![CDATA[' . $v . ']]>';
  2302. }
  2303. } elseif (!$options['disableTypeAttrib']) {
  2304. $attr.= ' type="'.$dType.'"';
  2305. }
  2306. }
  2307. }
  2308. // Add the element to the output string:
  2309. $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
  2310. }
  2311. // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
  2312. if (!$level) {
  2313. $output =
  2314. '<'.$docTag.'>'.$nl.
  2315. $output.
  2316. '</'.$docTag.'>';
  2317. }
  2318. return $output;
  2319. }
  2320. /**
  2321. * Converts an XML string to a PHP array.
  2322. * This is the reverse function of array2xml()
  2323. * This is a wrapper for xml2arrayProcess that adds a two-level cache
  2324. * Usage: 17
  2325. *
  2326. * @param string XML content to convert into an array
  2327. * @param string The tag-prefix resolve, eg. a namespace like "T3:"
  2328. * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
  2329. * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
  2330. * @see array2xml(),xml2arrayProcess()
  2331. * @author Fabrizio Branca <typo3@fabrizio-branca.de> (added caching)
  2332. */
  2333. public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
  2334. static $firstLevelCache = array();
  2335. $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
  2336. // look up in first level cache
  2337. if (!empty($firstLevelCache[$identifier])) {
  2338. $array = $firstLevelCache[$identifier];
  2339. } else {
  2340. // look up in second level cache
  2341. $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
  2342. $array = unserialize($cacheContent);
  2343. if ($array === false) {
  2344. $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
  2345. t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
  2346. }
  2347. // store content in first level cache
  2348. $firstLevelCache[$identifier] = $array;
  2349. }
  2350. return $array;
  2351. }
  2352. /**
  2353. * Converts an XML string to a PHP array.
  2354. * This is the reverse function of array2xml()
  2355. * Usage: 1
  2356. *
  2357. * @param string XML content to convert into an array
  2358. * @param string The tag-prefix resolve, eg. a namespace like "T3:"
  2359. * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
  2360. * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
  2361. * @see array2xml()
  2362. */
  2363. protected function xml2arrayProcess($string,$NSprefix='',$reportDocTag=FALSE) {
  2364. global $TYPO3_CONF_VARS;
  2365. // Create parser:
  2366. $parser = xml_parser_create();
  2367. $vals = array();
  2368. $index = array();
  2369. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  2370. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  2371. // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
  2372. $match = array();
  2373. preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
  2374. $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
  2375. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
  2376. // Parse content:
  2377. xml_parse_into_struct($parser, $string, $vals, $index);
  2378. // If error, return error message:
  2379. if (xml_get_error_code($parser)) {
  2380. return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  2381. }
  2382. xml_parser_free($parser);
  2383. // Init vars:
  2384. $stack = array(array());
  2385. $stacktop = 0;
  2386. $current = array();
  2387. $tagName = '';
  2388. $documentTag = '';
  2389. // Traverse the parsed XML structure:
  2390. foreach($vals as $key => $val) {
  2391. // First, process the tag-name (which is used in both cases, whether "complete" or "close")
  2392. $tagName = $val['tag'];
  2393. if (!$documentTag) $documentTag = $tagName;
  2394. // Test for name space:
  2395. $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
  2396. // Test for numeric tag, encoded on the form "nXXX":
  2397. $testNtag = substr($tagName,1); // Closing tag.
  2398. $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
  2399. // Test for alternative index value:
  2400. if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
  2401. // Setting tag-values, manage stack:
  2402. switch($val['type']) {
  2403. case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
  2404. $current[$tagName] = array(); // Setting blank place holder
  2405. $stack[$stacktop++] = $current;
  2406. $current = array();
  2407. break;
  2408. case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
  2409. $oldCurrent = $current;
  2410. $current = $stack[--$stacktop];
  2411. end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
  2412. $current[key($current)] = $oldCurrent;
  2413. unset($oldCurrent);
  2414. break;
  2415. case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
  2416. if ($val['attributes']['base64']) {
  2417. $current[$tagName] = base64_decode($val['value']);
  2418. } else {
  2419. $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
  2420. // Cast type:
  2421. switch((string)$val['attributes']['type']) {
  2422. case 'integer':
  2423. $current[$tagName] = (integer)$current[$tagName];
  2424. break;
  2425. case 'double':
  2426. $current[$tagName] = (double)$current[$tagName];
  2427. break;
  2428. case 'boolean':
  2429. $current[$tagName] = (bool)$current[$tagName];
  2430. break;
  2431. case 'array':
  2432. $current[$tagName] = array(); // MUST be an empty array since it is processed as a value; Empty arrays would end up here because they would have no tags inside...
  2433. break;
  2434. }
  2435. }
  2436. break;
  2437. }
  2438. }
  2439. if ($reportDocTag) {
  2440. $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
  2441. }
  2442. // Finally return the content of the document tag.
  2443. return $current[$tagName];
  2444. }
  2445. /**
  2446. * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
  2447. * Usage: 2
  2448. *
  2449. * @param array A array of XML parts, see xml2tree
  2450. * @return string Re-compiled XML data.
  2451. */
  2452. public static function xmlRecompileFromStructValArray(array $vals) {
  2453. $XMLcontent='';
  2454. foreach($vals as $val) {
  2455. $type = $val['type'];
  2456. // open tag:
  2457. if ($type=='open' || $type=='complete') {
  2458. $XMLcontent.='<'.$val['tag'];
  2459. if(isset($val['attributes'])) {
  2460. foreach($val['attributes'] as $k => $v) {
  2461. $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
  2462. }
  2463. }
  2464. if ($type=='complete') {
  2465. if(isset($val['value'])) {
  2466. $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
  2467. } else $XMLcontent.='/>';
  2468. } else $XMLcontent.='>';
  2469. if ($type=='open' && isset($val['value'])) {
  2470. $XMLcontent.=htmlspecialchars($val['value']);
  2471. }
  2472. }
  2473. // finish tag:
  2474. if ($type=='close') {
  2475. $XMLcontent.='</'.$val['tag'].'>';
  2476. }
  2477. // cdata
  2478. if($type=='cdata') {
  2479. $XMLcontent.=htmlspecialchars($val['value']);
  2480. }
  2481. }
  2482. return $XMLcontent;
  2483. }
  2484. /**
  2485. * Extracts the attributes (typically encoding and version) of an XML prologue (header).
  2486. * Usage: 1
  2487. *
  2488. * @param string XML data
  2489. * @return array Attributes of the xml prologue (header)
  2490. */
  2491. public static function xmlGetHeaderAttribs($xmlData) {
  2492. $match = array();
  2493. if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
  2494. return self::get_tag_attributes($match[1]);
  2495. }
  2496. }
  2497. /**
  2498. * Minifies JavaScript
  2499. *
  2500. * @param string $script Script to minify
  2501. * @param string $error Error message (if any)
  2502. * @return string Minified script or source string if error happened
  2503. */
  2504. public static function minifyJavaScript($script, &$error = '') {
  2505. require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
  2506. try {
  2507. $error = '';
  2508. $script = trim(JSMin::minify(str_replace(CR, '', $script)));
  2509. }
  2510. catch(JSMinException $e) {
  2511. $error = 'Error while minifying JavaScript: ' . $e->getMessage();
  2512. self::devLog($error, 't3lib_div', 2,
  2513. array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
  2514. }
  2515. return $script;
  2516. }
  2517. /*************************
  2518. *
  2519. * FILES FUNCTIONS
  2520. *
  2521. *************************/
  2522. /**
  2523. * Reads the file or url $url and returns the content
  2524. * If you are having trouble with proxys when reading URLs you can configure your way out of that with settings like $TYPO3_CONF_VARS['SYS']['curlUse'] etc.
  2525. * Usage: 83
  2526. *
  2527. * @param string File/URL to read
  2528. * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
  2529. * @param array HTTP headers to be used in the request
  2530. * @param array Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
  2531. * @return string The content from the resource given as input. FALSE if an error has occured.
  2532. */
  2533. public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) {
  2534. $content = false;
  2535. if (isset($report)) {
  2536. $report['error'] = 0;
  2537. $report['message'] = '';
  2538. }
  2539. // use cURL for: http, https, ftp, ftps, sftp and scp
  2540. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
  2541. if (isset($report)) {
  2542. $report['lib'] = 'cURL';
  2543. }
  2544. // External URL without error checking.
  2545. $ch = curl_init();
  2546. if (!$ch) {
  2547. if (isset($report)) {
  2548. $report['error'] = -1;
  2549. $report['message'] = 'Couldn\'t initialize cURL.';
  2550. }
  2551. return false;
  2552. }
  2553. curl_setopt($ch, CURLOPT_URL, $url);
  2554. curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
  2555. curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
  2556. curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
  2557. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  2558. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  2559. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, max(0, intval($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlTimeout'])));
  2560. // may fail (PHP 5.2.0+ and 5.1.5+) when open_basedir or safe_mode are enabled
  2561. $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  2562. if (is_array($requestHeaders)) {
  2563. curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
  2564. }
  2565. // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
  2566. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
  2567. curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
  2568. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
  2569. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
  2570. }
  2571. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
  2572. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
  2573. }
  2574. }
  2575. $content = curl_exec($ch);
  2576. if (isset($report)) {
  2577. if ($content===FALSE) {
  2578. $report['error'] = curl_errno($ch);
  2579. $report['message'] = curl_error($ch);
  2580. } else {
  2581. $curlInfo = curl_getinfo($ch);
  2582. // We hit a redirection but we couldn't follow it
  2583. if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
  2584. $report['error'] = -1;
  2585. $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
  2586. } elseif($includeHeader) {
  2587. // Set only for $includeHeader to work exactly like PHP variant
  2588. $report['http_code'] = $curlInfo['http_code'];
  2589. $report['content_type'] = $curlInfo['content_type'];
  2590. }
  2591. }
  2592. }
  2593. curl_close($ch);
  2594. } elseif ($includeHeader) {
  2595. if (isset($report)) {
  2596. $report['lib'] = 'socket';
  2597. }
  2598. $parsedURL = parse_url($url);
  2599. if (!preg_match('/^https?/', $parsedURL['scheme'])) {
  2600. if (isset($report)) {
  2601. $report['error'] = -1;
  2602. $report['message'] = 'Reading headers is not allowed for this protocol.';
  2603. }
  2604. return false;
  2605. }
  2606. $port = intval($parsedURL['port']);
  2607. if ($port < 1) {
  2608. if ($parsedURL['scheme'] == 'http') {
  2609. $port = ($port>0 ? $port : 80);
  2610. $scheme = '';
  2611. } else {
  2612. $port = ($port>0 ? $port : 443);
  2613. $scheme = 'ssl://';
  2614. }
  2615. }
  2616. $errno = 0;
  2617. // $errstr = '';
  2618. $fp = @fsockopen($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
  2619. if (!$fp || $errno > 0) {
  2620. if (isset($report)) {
  2621. $report['error'] = $errno ? $errno : -1;
  2622. $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
  2623. }
  2624. return false;
  2625. }
  2626. $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
  2627. $msg = $method . ' ' . $parsedURL['path'] .
  2628. ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
  2629. ' HTTP/1.0' . CRLF . 'Host: ' .
  2630. $parsedURL['host'] . "\r\nConnection: close\r\n";
  2631. if (is_array($requestHeaders)) {
  2632. $msg .= implode(CRLF, $requestHeaders) . CRLF;
  2633. }
  2634. $msg .= CRLF;
  2635. fputs($fp, $msg);
  2636. while (!feof($fp)) {
  2637. $line = fgets($fp, 2048);
  2638. if (isset($report)) {
  2639. if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
  2640. $report['http_code'] = $status[1];
  2641. }
  2642. elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
  2643. $report['content_type'] = $type[1];
  2644. }
  2645. }
  2646. $content .= $line;
  2647. if (!strlen(trim($line))) {
  2648. break; // Stop at the first empty line (= end of header)
  2649. }
  2650. }
  2651. if ($includeHeader != 2) {
  2652. $content .= stream_get_contents($fp);
  2653. }
  2654. fclose($fp);
  2655. } elseif (is_array($requestHeaders)) {
  2656. if (isset($report)) {
  2657. $report['lib'] = 'file/context';
  2658. }
  2659. $parsedURL = parse_url($url);
  2660. if (!preg_match('/^https?/', $parsedURL['scheme'])) {
  2661. if (isset($report)) {
  2662. $report['error'] = -1;
  2663. $report['message'] = 'Sending request headers is not allowed for this protocol.';
  2664. }
  2665. return false;
  2666. }
  2667. $ctx = stream_context_create(array(
  2668. 'http' => array(
  2669. 'header' => implode(CRLF, $requestHeaders)
  2670. )
  2671. )
  2672. );
  2673. $content = @file_get_contents($url, false, $ctx);
  2674. if ($content === false && isset($report)) {
  2675. $phpError = error_get_last();
  2676. $report['error'] = $phpError['type'];
  2677. $report['message'] = $phpError['message'];
  2678. }
  2679. } else {
  2680. if (isset($report)) {
  2681. $report['lib'] = 'file';
  2682. }
  2683. $content = @file_get_contents($url);
  2684. if ($content === false && isset($report)) {
  2685. if (function_exists('error_get_last')) {
  2686. $phpError = error_get_last();
  2687. $report['error'] = $phpError['type'];
  2688. $report['message'] = $phpError['message'];
  2689. } else {
  2690. $report['error'] = -1;
  2691. $report['message'] = 'Couldn\'t get URL.';
  2692. }
  2693. }
  2694. }
  2695. return $content;
  2696. }
  2697. /**
  2698. * Writes $content to the file $file
  2699. * Usage: 30
  2700. *
  2701. * @param string Filepath to write to
  2702. * @param string Content to write
  2703. * @return boolean True if the file was successfully opened and written to.
  2704. */
  2705. public static function writeFile($file,$content) {
  2706. if (!@is_file($file)) $changePermissions = true;
  2707. if ($fd = fopen($file,'wb')) {
  2708. $res = fwrite($fd,$content);
  2709. fclose($fd);
  2710. if ($res===false) return false;
  2711. if ($changePermissions) { // Change the permissions only if the file has just been created
  2712. self::fixPermissions($file);
  2713. }
  2714. return true;
  2715. }
  2716. return false;
  2717. }
  2718. /**
  2719. * Sets the file system mode and group ownership of a file or a folder.
  2720. *
  2721. * @param string Absolute filepath of file or folder, must not be escaped.
  2722. * @param boolean If set, also fixes permissions of files and folders in the folder (if $path is a folder)
  2723. * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
  2724. */
  2725. public static function fixPermissions($path, $recursive = FALSE) {
  2726. if (TYPO3_OS != 'WIN') {
  2727. $result = FALSE;
  2728. if (self::isAllowedAbsPath($path)) {
  2729. if (@is_file($path)) {
  2730. // "@" is there because file is not necessarily OWNED by the user
  2731. $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
  2732. } elseif (@is_dir($path)) {
  2733. $path = preg_replace('|/$|', '', $path);
  2734. // "@" is there because file is not necessarily OWNED by the user
  2735. $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
  2736. }
  2737. // Set createGroup if not empty
  2738. if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
  2739. // "@" is there because file is not necessarily OWNED by the user
  2740. $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
  2741. $result = $changeGroupResult ? $result : FALSE;
  2742. }
  2743. // Call recursive if recursive flag if set and $path is directory
  2744. if ($recursive && @is_dir($path)) {
  2745. $handle = opendir($path);
  2746. while (($file = readdir($handle)) !== FALSE) {
  2747. unset($recursionResult);
  2748. if ($file !== '.' && $file !== '..') {
  2749. if (@is_file($path . '/' . $file)) {
  2750. $recursionResult = self::fixPermissions($path . '/' . $file);
  2751. } elseif (@is_dir($path . '/' . $file)) {
  2752. $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
  2753. }
  2754. if (isset($recursionResult) && !$recursionResult) {
  2755. $result = FALSE;
  2756. }
  2757. }
  2758. }
  2759. closedir($handle);
  2760. }
  2761. }
  2762. } else {
  2763. $result = TRUE;
  2764. }
  2765. return $result;
  2766. }
  2767. /**
  2768. * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
  2769. * Accepts an additional subdirectory in the file path!
  2770. *
  2771. * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
  2772. * @param string Content string to write
  2773. * @return string Returns false on success, otherwise an error string telling about the problem.
  2774. */
  2775. public static function writeFileToTypo3tempDir($filepath,$content) {
  2776. // Parse filepath into directory and basename:
  2777. $fI = pathinfo($filepath);
  2778. $fI['dirname'].= '/';
  2779. // Check parts:
  2780. if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
  2781. if (defined('PATH_site')) {
  2782. $dirName = PATH_site.'typo3temp/'; // Setting main temporary directory name (standard)
  2783. if (@is_dir($dirName)) {
  2784. if (self::isFirstPartOfStr($fI['dirname'],$dirName)) {
  2785. // Checking if the "subdir" is found:
  2786. $subdir = substr($fI['dirname'],strlen($dirName));
  2787. if ($subdir) {
  2788. if (preg_match('/^[[:alnum:]_]+\/$/',$subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/',$subdir)) {
  2789. $dirName.= $subdir;
  2790. if (!@is_dir($dirName)) {
  2791. self::mkdir_deep(PATH_site.'typo3temp/', $subdir);
  2792. }
  2793. } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
  2794. }
  2795. // Checking dir-name again (sub-dir might have been created):
  2796. if (@is_dir($dirName)) {
  2797. if ($filepath == $dirName.$fI['basename']) {
  2798. self::writeFile($filepath, $content);
  2799. if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
  2800. } else return 'Calculated filelocation didn\'t match input $filepath!';
  2801. } else return '"'.$dirName.'" is not a directory!';
  2802. } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
  2803. } else return 'PATH_site + "typo3temp/" was not a directory!';
  2804. } else return 'PATH_site constant was NOT defined!';
  2805. } else return 'Input filepath "'.$filepath.'" was generally invalid!';
  2806. }
  2807. /**
  2808. * Wrapper function for mkdir.
  2809. * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
  2810. * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
  2811. *
  2812. * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
  2813. * @return boolean TRUE if @mkdir went well!
  2814. */
  2815. public static function mkdir($newFolder) {
  2816. $newFolder = preg_replace('|/$|', '', $newFolder);
  2817. $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
  2818. if ($result) {
  2819. self::fixPermissions($newFolder);
  2820. }
  2821. return $result;
  2822. }
  2823. /**
  2824. * Creates a directory - including parent directories if necessary - in the file system
  2825. *
  2826. * @param string Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
  2827. * @param string Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
  2828. * @return string If error, returns error string.
  2829. */
  2830. public static function mkdir_deep($destination,$deepDir) {
  2831. $allParts = self::trimExplode('/',$deepDir,1);
  2832. $root = '';
  2833. foreach($allParts as $part) {
  2834. $root.= $part.'/';
  2835. if (!is_dir($destination.$root)) {
  2836. self::mkdir($destination.$root);
  2837. if (!@is_dir($destination.$root)) {
  2838. return 'Error: The directory "'.$destination.$root.'" could not be created...';
  2839. }
  2840. }
  2841. }
  2842. }
  2843. /**
  2844. * Wrapper function for rmdir, allowing recursive deletion of folders and files
  2845. *
  2846. * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
  2847. * @param boolean Allow deletion of non-empty directories
  2848. * @return boolean true if @rmdir went well!
  2849. */
  2850. public static function rmdir($path,$removeNonEmpty=false) {
  2851. $OK = false;
  2852. $path = preg_replace('|/$|','',$path); // Remove trailing slash
  2853. if (file_exists($path)) {
  2854. $OK = true;
  2855. if (is_dir($path)) {
  2856. if ($removeNonEmpty==true && $handle = opendir($path)) {
  2857. while ($OK && false !== ($file = readdir($handle))) {
  2858. if ($file=='.' || $file=='..') continue;
  2859. $OK = self::rmdir($path.'/'.$file,$removeNonEmpty);
  2860. }
  2861. closedir($handle);
  2862. }
  2863. if ($OK) { $OK = rmdir($path); }
  2864. } else { // If $dirname is a file, simply remove it
  2865. $OK = unlink($path);
  2866. }
  2867. clearstatcache();
  2868. }
  2869. return $OK;
  2870. }
  2871. /**
  2872. * Returns an array with the names of folders in a specific path
  2873. * Will return 'error' (string) if there were an error with reading directory content.
  2874. * Usage: 11
  2875. *
  2876. * @param string Path to list directories from
  2877. * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
  2878. */
  2879. public static function get_dirs($path) {
  2880. if ($path) {
  2881. if (is_dir($path)) {
  2882. $dir = scandir($path);
  2883. $dirs = array();
  2884. foreach ($dir as $entry) {
  2885. if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
  2886. $dirs[] = $entry;
  2887. }
  2888. }
  2889. } else {
  2890. $dirs = 'error';
  2891. }
  2892. }
  2893. return $dirs;
  2894. }
  2895. /**
  2896. * Returns an array with the names of files in a specific path
  2897. * Usage: 18
  2898. *
  2899. * @param string $path: Is the path to the file
  2900. * @param string $extensionList is the comma list of extensions to read only (blank = all)
  2901. * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
  2902. * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
  2903. * @param string A comma seperated list of filenames to exclude, no wildcards
  2904. * @return array Array of the files found
  2905. */
  2906. public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
  2907. // Initialize variabels:
  2908. $filearray = array();
  2909. $sortarray = array();
  2910. $path = rtrim($path, '/');
  2911. // Find files+directories:
  2912. if (@is_dir($path)) {
  2913. $extensionList = strtolower($extensionList);
  2914. $d = dir($path);
  2915. if (is_object($d)) {
  2916. while($entry=$d->read()) {
  2917. if (@is_file($path.'/'.$entry)) {
  2918. $fI = pathinfo($entry);
  2919. $key = md5($path.'/'.$entry); // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
  2920. if ((!strlen($extensionList) || self::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
  2921. $filearray[$key]=($prependPath?$path.'/':'').$entry;
  2922. if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
  2923. elseif ($order) {$sortarray[$key]=$entry;}
  2924. }
  2925. }
  2926. }
  2927. $d->close();
  2928. } else return 'error opening path: "'.$path.'"';
  2929. }
  2930. // Sort them:
  2931. if ($order) {
  2932. asort($sortarray);
  2933. $newArr=array();
  2934. foreach ($sortarray as $k => $v) {
  2935. $newArr[$k]=$filearray[$k];
  2936. }
  2937. $filearray=$newArr;
  2938. }
  2939. // Return result
  2940. reset($filearray);
  2941. return $filearray;
  2942. }
  2943. /**
  2944. * Recursively gather all files and folders of a path.
  2945. * Usage: 5
  2946. *
  2947. * @param array $fileArr: Empty input array (will have files added to it)
  2948. * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
  2949. * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
  2950. * @param boolean $regDirs: If set, directories are also included in output.
  2951. * @param integer $recursivityLevels: The number of levels to dig down...
  2952. * @param string $excludePattern: regex pattern of files/directories to exclude
  2953. * @return array An array with the found files/directories.
  2954. */
  2955. public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
  2956. if ($regDirs) $fileArr[] = $path;
  2957. $fileArr = array_merge($fileArr, self::getFilesInDir($path,$extList,1,1,$excludePattern));
  2958. $dirs = self::get_dirs($path);
  2959. if (is_array($dirs) && $recursivityLevels>0) {
  2960. foreach ($dirs as $subdirs) {
  2961. if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs))) {
  2962. $fileArr = self::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
  2963. }
  2964. }
  2965. }
  2966. return $fileArr;
  2967. }
  2968. /**
  2969. * Removes the absolute part of all files/folders in fileArr
  2970. * Usage: 2
  2971. *
  2972. * @param array $fileArr: The file array to remove the prefix from
  2973. * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
  2974. * @return array The input $fileArr processed.
  2975. */
  2976. public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
  2977. foreach ($fileArr as $k => &$absFileRef) {
  2978. if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
  2979. $absFileRef = substr($absFileRef, strlen($prefixToRemove));
  2980. } else {
  2981. return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
  2982. }
  2983. }
  2984. return $fileArr;
  2985. }
  2986. /**
  2987. * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
  2988. * Usage: 2
  2989. *
  2990. * @param string File path to process
  2991. * @return string
  2992. */
  2993. public static function fixWindowsFilePath($theFile) {
  2994. return str_replace('//','/', str_replace('\\','/', $theFile));
  2995. }
  2996. /**
  2997. * Resolves "../" sections in the input path string.
  2998. * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
  2999. * Usage: 2
  3000. *
  3001. * @param string File path in which "/../" is resolved
  3002. * @return string
  3003. */
  3004. public static function resolveBackPath($pathStr) {
  3005. $parts = explode('/',$pathStr);
  3006. $output=array();
  3007. $c = 0;
  3008. foreach($parts as $pV) {
  3009. if ($pV=='..') {
  3010. if ($c) {
  3011. array_pop($output);
  3012. $c--;
  3013. } else $output[]=$pV;
  3014. } else {
  3015. $c++;
  3016. $output[]=$pV;
  3017. }
  3018. }
  3019. return implode('/',$output);
  3020. }
  3021. /**
  3022. * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
  3023. * - If already having a scheme, nothing is prepended
  3024. * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
  3025. * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
  3026. * Usage: 30
  3027. *
  3028. * @param string URL / path to prepend full URL addressing to.
  3029. * @return string
  3030. */
  3031. public static function locationHeaderUrl($path) {
  3032. $uI = parse_url($path);
  3033. if (substr($path,0,1)=='/') { // relative to HOST
  3034. $path = self::getIndpEnv('TYPO3_REQUEST_HOST').$path;
  3035. } elseif (!$uI['scheme']) { // No scheme either
  3036. $path = self::getIndpEnv('TYPO3_REQUEST_DIR').$path;
  3037. }
  3038. return $path;
  3039. }
  3040. /**
  3041. * Returns the maximum upload size for a file that is allowed. Measured in KB.
  3042. * This might be handy to find out the real upload limit that is possible for this
  3043. * TYPO3 installation. The first parameter can be used to set something that overrides
  3044. * the maxFileSize, usually for the TCA values.
  3045. *
  3046. * @param integer $localLimit: the number of Kilobytes (!) that should be used as
  3047. * the initial Limit, otherwise $TYPO3_CONF_VARS['BE']['maxFileSize'] will be used
  3048. * @return integer the maximum size of uploads that are allowed (measuered in kilobytes)
  3049. */
  3050. public static function getMaxUploadFileSize($localLimit = 0) {
  3051. // don't allow more than the global max file size at all
  3052. $t3Limit = (intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
  3053. // as TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
  3054. $t3Limit = $t3Limit * 1024;
  3055. // check for PHP restrictions of the maximum size of one of the $_FILES
  3056. $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
  3057. // check for PHP restrictions of the maximum $_POST size
  3058. $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
  3059. // if the total amount of post data is smaller (!) than the upload_max_filesize directive,
  3060. // then this is the real limit in PHP
  3061. $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit);
  3062. // is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
  3063. return floor($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit) / 1024;
  3064. }
  3065. /**
  3066. * Gets the bytes value from a measurement string like "100k".
  3067. *
  3068. * @param string $measurement: The measurement (e.g. "100k")
  3069. * @return integer The bytes value (e.g. 102400)
  3070. */
  3071. public static function getBytesFromSizeMeasurement($measurement) {
  3072. if (stripos($measurement, 'G')) {
  3073. $bytes = intval($measurement) * 1024 * 1024 * 1024;
  3074. } else if (stripos($measurement, 'M')) {
  3075. $bytes = intval($measurement) * 1024 * 1024;
  3076. } else if (stripos($measurement, 'K')) {
  3077. $bytes = intval($measurement) * 1024;
  3078. } else {
  3079. $bytes = intval($measurement);
  3080. }
  3081. return $bytes;
  3082. }
  3083. /**
  3084. * Retrieves the maximum path length that is valid in the current environment.
  3085. *
  3086. * @return integer The maximum available path length
  3087. * @author Ingo Renner <ingo@typo3.org>
  3088. */
  3089. public static function getMaximumPathLength() {
  3090. $maximumPathLength = 0;
  3091. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  3092. // rough assumptions
  3093. if (TYPO3_OS == 'WIN') {
  3094. // WIN is usually 255, Vista 260, although NTFS can hold about 2k
  3095. $maximumPathLength = 255;
  3096. } else {
  3097. $maximumPathLength = 2048;
  3098. }
  3099. } else {
  3100. // precise information is available since PHP 5.3
  3101. $maximumPathLength = PHP_MAXPATHLEN;
  3102. }
  3103. return $maximumPathLength;
  3104. }
  3105. /**
  3106. * Function for static version numbers on files, based on the filemtime
  3107. *
  3108. * This will make the filename automatically change when a file is
  3109. * changed, and by that re-cached by the browser. If the file does not
  3110. * exist physically the original file passed to the function is
  3111. * returned without the timestamp.
  3112. *
  3113. * Behaviour is influenced by the setting
  3114. * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
  3115. * = true (BE) / "embed" (FE) : modify filename
  3116. * = false (BE) / "querystring" (FE) : add timestamp as parameter
  3117. *
  3118. * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
  3119. * @param boolean $forceQueryString If settings would suggest to embed in filename, this parameter allows us to force the versioning to occur in the query string. This is needed for scriptaculous.js which cannot have a different filename in order to load its modules (?load=...)
  3120. * @return Relative path with version filename including the timestamp
  3121. * @author Lars Houmark <lars@houmark.com>
  3122. */
  3123. public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
  3124. $lookupFile = explode('?', $file);
  3125. $path = self::resolveBackPath(self::dirname(PATH_thisScript) .'/'. $lookupFile[0]);
  3126. if (TYPO3_MODE == 'FE') {
  3127. $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
  3128. if ($mode === 'embed') {
  3129. $mode = TRUE;
  3130. } else if ($mode === 'querystring') {
  3131. $mode = FALSE;
  3132. } else {
  3133. $doNothing = TRUE;
  3134. }
  3135. } else {
  3136. $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
  3137. }
  3138. if (! file_exists($path) || $doNothing) {
  3139. // File not found, return filename unaltered
  3140. $fullName = $file;
  3141. } else if (! $mode || $forceQueryString) {
  3142. // If use of .htaccess rule is not configured,
  3143. // we use the default query-string method
  3144. if ($lookupFile[1]) {
  3145. $separator = '&';
  3146. } else {
  3147. $separator = '?';
  3148. }
  3149. $fullName = $file . $separator . filemtime($path);
  3150. } else {
  3151. // Change the filename
  3152. $name = explode('.', $lookupFile[0]);
  3153. $extension = array_pop($name);
  3154. array_push($name, filemtime($path), $extension);
  3155. $fullName = implode('.', $name);
  3156. // append potential query string
  3157. $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
  3158. }
  3159. return $fullName;
  3160. }
  3161. /*************************
  3162. *
  3163. * DEBUG helper FUNCTIONS
  3164. *
  3165. *************************/
  3166. /**
  3167. * Returns a string with a list of ascii-values for the first $characters characters in $string
  3168. * Usage: 0
  3169. *
  3170. * @param string String to show ASCII value for
  3171. * @param integer Number of characters to show
  3172. * @return string The string with ASCII values in separated by a space char.
  3173. */
  3174. public static function debug_ordvalue($string,$characters=100) {
  3175. if(strlen($string) < $characters) $characters = strlen($string);
  3176. for ($i=0; $i<$characters; $i++) {
  3177. $valuestring.=' '.ord(substr($string,$i,1));
  3178. }
  3179. return trim($valuestring);
  3180. }
  3181. /**
  3182. * Returns HTML-code, which is a visual representation of a multidimensional array
  3183. * use t3lib_div::print_array() in order to print an array
  3184. * Returns false if $array_in is not an array
  3185. * Usage: 31
  3186. *
  3187. * @param mixed Array to view
  3188. * @return string HTML output
  3189. */
  3190. public static function view_array($array_in) {
  3191. if (is_array($array_in)) {
  3192. $result='
  3193. <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
  3194. if (count($array_in) == 0) {
  3195. $result.= '<tr><td><font face="Verdana,Arial" size="1"><strong>EMPTY!</strong></font></td></tr>';
  3196. } else {
  3197. foreach ($array_in as $key => $val) {
  3198. $result.= '<tr>
  3199. <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
  3200. <td>';
  3201. if (is_array($val)) {
  3202. $result.=self::view_array($val);
  3203. } elseif (is_object($val)) {
  3204. $string = get_class($val);
  3205. if (method_exists($val, '__toString')) {
  3206. $string .= ': '.(string)$val;
  3207. }
  3208. $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
  3209. } else {
  3210. if (gettype($val) == 'object') {
  3211. $string = 'Unknown object';
  3212. } else {
  3213. $string = (string)$val;
  3214. }
  3215. $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
  3216. }
  3217. $result.= '</td>
  3218. </tr>';
  3219. }
  3220. }
  3221. $result.= '</table>';
  3222. } else {
  3223. $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
  3224. <tr>
  3225. <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
  3226. </tr>
  3227. </table>'; // Output it as a string.
  3228. }
  3229. return $result;
  3230. }
  3231. /**
  3232. * Prints an array
  3233. * Usage: 6
  3234. *
  3235. * @param mixed Array to print visually (in a table).
  3236. * @return void
  3237. * @see view_array()
  3238. */
  3239. public static function print_array($array_in) {
  3240. echo self::view_array($array_in);
  3241. }
  3242. /**
  3243. * Makes debug output
  3244. * Prints $var in bold between two vertical lines
  3245. * If not $var the word 'debug' is printed
  3246. * If $var is an array, the array is printed by t3lib_div::print_array()
  3247. * Usage: 8
  3248. *
  3249. * @param mixed Variable to print
  3250. * @param string The header.
  3251. * @param string Group for the debug console
  3252. * @return void
  3253. */
  3254. public static function debug($var = '', $header = '', $group = 'Debug') {
  3255. // buffer the output of debug if no buffering started before
  3256. if (ob_get_level()==0) {
  3257. ob_start();
  3258. }
  3259. $debug = '';
  3260. if ($header) {
  3261. $debug .= '
  3262. <table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;">
  3263. <tr>
  3264. <td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">' .
  3265. htmlspecialchars((string) $header) .
  3266. '</td>
  3267. </tr>
  3268. <tr>
  3269. <td>';
  3270. }
  3271. if (is_array($var)) {
  3272. $debug .= self::view_array($var);
  3273. } elseif (is_object($var)) {
  3274. $debug .= '<strong>|Object:<pre>';
  3275. $debug .= print_r($var, TRUE);
  3276. $debug .= '</pre>|</strong>';
  3277. } elseif ((string) $var !== '') {
  3278. $debug .= '<strong>|' . htmlspecialchars((string)$var) . '|</strong>';
  3279. } else {
  3280. $debug .= '<strong>| debug |</strong>';
  3281. }
  3282. if ($header) {
  3283. $debug .= '
  3284. </td>
  3285. </tr>
  3286. </table>';
  3287. }
  3288. if (TYPO3_MODE === 'BE') {
  3289. $group = htmlspecialchars($group);
  3290. if ($header !== '') {
  3291. $tabHeader = htmlspecialchars($header);
  3292. } else {
  3293. $tabHeader = 'Debug';
  3294. }
  3295. if (is_object($var)) {
  3296. $debug = str_replace(
  3297. array('"', '/', '<', "\n", "\r"),
  3298. array('\"', '\/', '\<', '<br />', ''),
  3299. $debug
  3300. );
  3301. } else {
  3302. $debug = str_replace(
  3303. array('"', '/', '<', "\n", "\r"),
  3304. array('\"', '\/', '\<', '', ''),
  3305. $debug
  3306. );
  3307. }
  3308. $script = '
  3309. (function debug() {
  3310. var debugMessage = "' . $debug . '";
  3311. var header = "' . $tabHeader . '";
  3312. var group = "' . $group . '";
  3313. if (typeof Ext !== "object" && (top && typeof top.Ext !== "object")) {
  3314. document.write(debugMessage);
  3315. return;
  3316. }
  3317. if (top && typeof Ext !== "object") {
  3318. Ext = top.Ext;
  3319. }
  3320. Ext.onReady(function() {
  3321. var TYPO3ViewportInstance = null;
  3322. if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") {
  3323. TYPO3ViewportInstance = top.TYPO3.Backend;
  3324. } else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") {
  3325. TYPO3ViewportInstance = TYPO3.Backend;
  3326. }
  3327. if (TYPO3ViewportInstance !== null) {
  3328. TYPO3ViewportInstance.DebugConsole.addTab(debugMessage, header, group);
  3329. } else {
  3330. document.write(debugMessage);
  3331. }
  3332. });
  3333. })();
  3334. ';
  3335. echo self::wrapJS($script);
  3336. } else {
  3337. echo $debug;
  3338. }
  3339. }
  3340. /**
  3341. * Displays the "path" of the function call stack in a string, using debug_backtrace
  3342. *
  3343. * @return string
  3344. */
  3345. public static function debug_trail() {
  3346. $trail = debug_backtrace();
  3347. $trail = array_reverse($trail);
  3348. array_pop($trail);
  3349. $path = array();
  3350. foreach($trail as $dat) {
  3351. $path[] = $dat['class'].$dat['type'].$dat['function'].'#'.$dat['line'];
  3352. }
  3353. return implode(' // ',$path);
  3354. }
  3355. /**
  3356. * Displays an array as rows in a table. Useful to debug output like an array of database records.
  3357. *
  3358. * @param mixed Array of arrays with similar keys
  3359. * @param string Table header
  3360. * @param boolean If TRUE, will return content instead of echo'ing out.
  3361. * @return void Outputs to browser.
  3362. */
  3363. public static function debugRows($rows,$header='',$returnHTML=FALSE) {
  3364. if (is_array($rows)) {
  3365. reset($rows);
  3366. $firstEl = current($rows);
  3367. if (is_array($firstEl)) {
  3368. $headerColumns = array_keys($firstEl);
  3369. $tRows = array();
  3370. // Header:
  3371. $tRows[] = '<tr><td colspan="'.count($headerColumns).'" style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;"><strong>'.htmlspecialchars($header).'</strong></td></tr>';
  3372. $tCells = array();
  3373. foreach($headerColumns as $key) {
  3374. $tCells[] = '
  3375. <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
  3376. }
  3377. $tRows[] = '
  3378. <tr>'.implode('',$tCells).'
  3379. </tr>';
  3380. // Rows:
  3381. foreach($rows as $singleRow) {
  3382. $tCells = array();
  3383. foreach($headerColumns as $key) {
  3384. $tCells[] = '
  3385. <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? self::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
  3386. }
  3387. $tRows[] = '
  3388. <tr>'.implode('',$tCells).'
  3389. </tr>';
  3390. }
  3391. $table = '
  3392. <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
  3393. </table>';
  3394. if ($returnHTML) return $table; else echo $table;
  3395. } else debug('Empty array of rows',$header);
  3396. } else {
  3397. debug('No array of rows',$header);
  3398. }
  3399. }
  3400. /*************************
  3401. *
  3402. * SYSTEM INFORMATION
  3403. *
  3404. *************************/
  3405. /**
  3406. * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
  3407. * Usage: 1
  3408. *
  3409. * @return string
  3410. */
  3411. public static function getThisUrl() {
  3412. $p=parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
  3413. $dir=self::dirname($p['path']).'/'; // Strip file
  3414. $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
  3415. return $url;
  3416. }
  3417. /**
  3418. * Returns the link-url to the current script.
  3419. * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
  3420. * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
  3421. * Usage: 52
  3422. *
  3423. * @param array Array of GET parameters to include
  3424. * @return string
  3425. */
  3426. public static function linkThisScript(array $getParams = array()) {
  3427. $parts = self::getIndpEnv('SCRIPT_NAME');
  3428. $params = self::_GET();
  3429. foreach ($getParams as $key => $value) {
  3430. if ($value !== '') {
  3431. $params[$key] = $value;
  3432. } else {
  3433. unset($params[$key]);
  3434. }
  3435. }
  3436. $pString = self::implodeArrayForUrl('', $params);
  3437. return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
  3438. }
  3439. /**
  3440. * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
  3441. * So basically it adds the parameters in $getParams to an existing URL, $url
  3442. * Usage: 2
  3443. *
  3444. * @param string URL string
  3445. * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
  3446. * @return string Output URL with added getParams.
  3447. */
  3448. public static function linkThisUrl($url,array $getParams=array()) {
  3449. $parts = parse_url($url);
  3450. $getP = array();
  3451. if ($parts['query']) {
  3452. parse_str($parts['query'],$getP);
  3453. }
  3454. $getP = self::array_merge_recursive_overrule($getP,$getParams);
  3455. $uP = explode('?',$url);
  3456. $params = self::implodeArrayForUrl('',$getP);
  3457. $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
  3458. return $outurl;
  3459. }
  3460. /**
  3461. * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
  3462. * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
  3463. * Usage: 221
  3464. *
  3465. * @param string Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
  3466. * @return string Value based on the input key, independent of server/os environment.
  3467. */
  3468. public static function getIndpEnv($getEnvName) {
  3469. /*
  3470. Conventions:
  3471. output from parse_url():
  3472. URL: http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
  3473. [scheme] => 'http'
  3474. [user] => 'username'
  3475. [pass] => 'password'
  3476. [host] => '192.168.1.4'
  3477. [port] => '8080'
  3478. [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
  3479. [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
  3480. [fragment] => 'link1'
  3481. Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
  3482. [path_dir] = '/typo3/32/temp/phpcheck/'
  3483. [path_info] = '/arg1/arg2/arg3/'
  3484. [path] = [path_script/path_dir][path_info]
  3485. Keys supported:
  3486. URI______:
  3487. REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3488. HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
  3489. SCRIPT_NAME = [path_script]++ = /typo3/32/temp/phpcheck/index.php // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
  3490. PATH_INFO = [path_info] = /arg1/arg2/arg3/
  3491. QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3492. HTTP_REFERER = [scheme]://[host][:[port]][path] = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3493. (Notice: NO username/password + NO fragment)
  3494. CLIENT____:
  3495. REMOTE_ADDR = (client IP)
  3496. REMOTE_HOST = (client host)
  3497. HTTP_USER_AGENT = (client user agent)
  3498. HTTP_ACCEPT_LANGUAGE = (client accept language)
  3499. SERVER____:
  3500. SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
  3501. Special extras:
  3502. TYPO3_HOST_ONLY = [host] = 192.168.1.4
  3503. TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
  3504. TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
  3505. TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
  3506. TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
  3507. TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
  3508. TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
  3509. TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend
  3510. TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
  3511. TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
  3512. TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https)
  3513. TYPO3_PROXY = Returns TRUE if this session runs over a well known proxy
  3514. Notice: [fragment] is apparently NEVER available to the script!
  3515. Testing suggestions:
  3516. - Output all the values.
  3517. - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
  3518. - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
  3519. */
  3520. # if ($getEnvName=='HTTP_REFERER') return '';
  3521. $retVal = '';
  3522. switch ((string)$getEnvName) {
  3523. case 'SCRIPT_NAME':
  3524. $retVal = (PHP_SAPI=='cgi'||PHP_SAPI=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ? ($_SERVER['ORIG_PATH_INFO']?$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
  3525. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3526. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3527. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3528. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
  3529. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3530. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
  3531. }
  3532. }
  3533. break;
  3534. case 'SCRIPT_FILENAME':
  3535. $retVal = str_replace('//','/', str_replace('\\','/', (PHP_SAPI=='cgi'||PHP_SAPI=='isapi' ||PHP_SAPI=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])? ($_SERVER['ORIG_PATH_TRANSLATED']?$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
  3536. break;
  3537. case 'REQUEST_URI':
  3538. // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
  3539. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']) { // This is for URL rewriters that store the original URI in a server variable (eg ISAPI_Rewriter for IIS: HTTP_X_REWRITE_URL)
  3540. list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
  3541. $retVal = $GLOBALS[$v][$n];
  3542. } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
  3543. $retVal = '/'.ltrim(self::getIndpEnv('SCRIPT_NAME'), '/').
  3544. ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
  3545. } else {
  3546. $retVal = $_SERVER['REQUEST_URI'];
  3547. }
  3548. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3549. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3550. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3551. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
  3552. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3553. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
  3554. }
  3555. }
  3556. break;
  3557. case 'PATH_INFO':
  3558. // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
  3559. // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
  3560. // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'PHP_SAPI=='cgi'' might be a better check. Right now strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) will always return false for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO because of PHP_SAPI=='cgi' (see above)
  3561. // if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
  3562. if (PHP_SAPI!='cgi' && PHP_SAPI!='cgi-fcgi') {
  3563. $retVal = $_SERVER['PATH_INFO'];
  3564. }
  3565. break;
  3566. case 'TYPO3_REV_PROXY':
  3567. $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
  3568. break;
  3569. case 'REMOTE_ADDR':
  3570. $retVal = $_SERVER['REMOTE_ADDR'];
  3571. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3572. $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  3573. // choose which IP in list to use
  3574. if (count($ip)) {
  3575. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3576. case 'last':
  3577. $ip = array_pop($ip);
  3578. break;
  3579. case 'first':
  3580. $ip = array_shift($ip);
  3581. break;
  3582. case 'none':
  3583. default:
  3584. $ip = '';
  3585. break;
  3586. }
  3587. }
  3588. if (self::validIP($ip)) {
  3589. $retVal = $ip;
  3590. }
  3591. }
  3592. break;
  3593. case 'HTTP_HOST':
  3594. $retVal = $_SERVER['HTTP_HOST'];
  3595. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3596. $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
  3597. // choose which host in list to use
  3598. if (count($host)) {
  3599. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3600. case 'last':
  3601. $host = array_pop($host);
  3602. break;
  3603. case 'first':
  3604. $host = array_shift($host);
  3605. break;
  3606. case 'none':
  3607. default:
  3608. $host = '';
  3609. break;
  3610. }
  3611. }
  3612. if ($host) {
  3613. $retVal = $host;
  3614. }
  3615. }
  3616. break;
  3617. // These are let through without modification
  3618. case 'HTTP_REFERER':
  3619. case 'HTTP_USER_AGENT':
  3620. case 'HTTP_ACCEPT_ENCODING':
  3621. case 'HTTP_ACCEPT_LANGUAGE':
  3622. case 'REMOTE_HOST':
  3623. case 'QUERY_STRING':
  3624. $retVal = $_SERVER[$getEnvName];
  3625. break;
  3626. case 'TYPO3_DOCUMENT_ROOT':
  3627. // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
  3628. // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
  3629. $SFN = self::getIndpEnv('SCRIPT_FILENAME');
  3630. $SN_A = explode('/',strrev(self::getIndpEnv('SCRIPT_NAME')));
  3631. $SFN_A = explode('/',strrev($SFN));
  3632. $acc = array();
  3633. foreach ($SN_A as $kk => $vv) {
  3634. if (!strcmp($SFN_A[$kk],$vv)) {
  3635. $acc[] = $vv;
  3636. } else break;
  3637. }
  3638. $commonEnd=strrev(implode('/',$acc));
  3639. if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
  3640. $retVal = $DR;
  3641. break;
  3642. case 'TYPO3_HOST_ONLY':
  3643. $p = explode(':',self::getIndpEnv('HTTP_HOST'));
  3644. $retVal = $p[0];
  3645. break;
  3646. case 'TYPO3_PORT':
  3647. $p = explode(':',self::getIndpEnv('HTTP_HOST'));
  3648. $retVal = $p[1];
  3649. break;
  3650. case 'TYPO3_REQUEST_HOST':
  3651. $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
  3652. self::getIndpEnv('HTTP_HOST');
  3653. break;
  3654. case 'TYPO3_REQUEST_URL':
  3655. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('REQUEST_URI');
  3656. break;
  3657. case 'TYPO3_REQUEST_SCRIPT':
  3658. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('SCRIPT_NAME');
  3659. break;
  3660. case 'TYPO3_REQUEST_DIR':
  3661. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::dirname(self::getIndpEnv('SCRIPT_NAME')).'/';
  3662. break;
  3663. case 'TYPO3_SITE_URL':
  3664. if (defined('PATH_thisScript') && defined('PATH_site')) {
  3665. $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
  3666. $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
  3667. $siteUrl = substr($url,0,-strlen($lPath));
  3668. if (substr($siteUrl,-1)!='/') $siteUrl.='/';
  3669. $retVal = $siteUrl;
  3670. }
  3671. break;
  3672. case 'TYPO3_SITE_PATH':
  3673. $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
  3674. break;
  3675. case 'TYPO3_SITE_SCRIPT':
  3676. $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'),strlen(self::getIndpEnv('TYPO3_SITE_URL')));
  3677. break;
  3678. case 'TYPO3_SSL':
  3679. $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
  3680. if ($proxySSL == '*') {
  3681. $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
  3682. }
  3683. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
  3684. $retVal = true;
  3685. } else {
  3686. $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? true : false; // see http://bugs.typo3.org/view.php?id=3909
  3687. }
  3688. break;
  3689. case '_ARRAY':
  3690. $out = array();
  3691. // Here, list ALL possible keys to this function for debug display.
  3692. $envTestVars = self::trimExplode(',','
  3693. HTTP_HOST,
  3694. TYPO3_HOST_ONLY,
  3695. TYPO3_PORT,
  3696. PATH_INFO,
  3697. QUERY_STRING,
  3698. REQUEST_URI,
  3699. HTTP_REFERER,
  3700. TYPO3_REQUEST_HOST,
  3701. TYPO3_REQUEST_URL,
  3702. TYPO3_REQUEST_SCRIPT,
  3703. TYPO3_REQUEST_DIR,
  3704. TYPO3_SITE_URL,
  3705. TYPO3_SITE_SCRIPT,
  3706. TYPO3_SSL,
  3707. TYPO3_REV_PROXY,
  3708. SCRIPT_NAME,
  3709. TYPO3_DOCUMENT_ROOT,
  3710. SCRIPT_FILENAME,
  3711. REMOTE_ADDR,
  3712. REMOTE_HOST,
  3713. HTTP_USER_AGENT,
  3714. HTTP_ACCEPT_LANGUAGE',1);
  3715. foreach ($envTestVars as $v) {
  3716. $out[$v]=self::getIndpEnv($v);
  3717. }
  3718. reset($out);
  3719. $retVal = $out;
  3720. break;
  3721. }
  3722. return $retVal;
  3723. }
  3724. /**
  3725. * Gets the unixtime as milliseconds.
  3726. *
  3727. * @return integer The unixtime as milliseconds
  3728. */
  3729. public static function milliseconds() {
  3730. return round(microtime(true) * 1000);
  3731. }
  3732. /**
  3733. * Client Browser Information
  3734. * Usage: 4
  3735. *
  3736. * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
  3737. * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
  3738. */
  3739. public static function clientInfo($useragent='') {
  3740. if (!$useragent) $useragent=self::getIndpEnv('HTTP_USER_AGENT');
  3741. $bInfo=array();
  3742. // Which browser?
  3743. if (strpos($useragent,'Konqueror') !== false) {
  3744. $bInfo['BROWSER']= 'konqu';
  3745. } elseif (strpos($useragent,'Opera') !== false) {
  3746. $bInfo['BROWSER']= 'opera';
  3747. } elseif (strpos($useragent, 'MSIE') !== false) {
  3748. $bInfo['BROWSER']= 'msie';
  3749. } elseif (strpos($useragent, 'Mozilla') !== false) {
  3750. $bInfo['BROWSER']='net';
  3751. } elseif (strpos($useragent, 'Flash') !== false) {
  3752. $bInfo['BROWSER'] = 'flash';
  3753. }
  3754. if ($bInfo['BROWSER']) {
  3755. // Browser version
  3756. switch($bInfo['BROWSER']) {
  3757. case 'net':
  3758. $bInfo['VERSION']= doubleval(substr($useragent,8));
  3759. if (strpos($useragent,'Netscape6/') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10)); } // Will we ever know if this was a typo or intention...?! :-(
  3760. if (strpos($useragent,'Netscape/6') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10)); }
  3761. if (strpos($useragent,'Netscape/7') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/7'),9)); }
  3762. break;
  3763. case 'msie':
  3764. $tmp = strstr($useragent,'MSIE');
  3765. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,4)));
  3766. break;
  3767. case 'opera':
  3768. $tmp = strstr($useragent,'Opera');
  3769. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,5)));
  3770. break;
  3771. case 'konqu':
  3772. $tmp = strstr($useragent,'Konqueror/');
  3773. $bInfo['VERSION'] = doubleval(substr($tmp,10));
  3774. break;
  3775. }
  3776. // Client system
  3777. if (strpos($useragent,'Win') !== false) {
  3778. $bInfo['SYSTEM'] = 'win';
  3779. } elseif (strpos($useragent,'Mac') !== false) {
  3780. $bInfo['SYSTEM'] = 'mac';
  3781. } elseif (strpos($useragent,'Linux') !== false || strpos($useragent,'X11') !== false || strpos($useragent,'SGI') !== false || strpos($useragent,' SunOS ') !== false || strpos($useragent,' HP-UX ') !== false) {
  3782. $bInfo['SYSTEM'] = 'unix';
  3783. }
  3784. }
  3785. // Is true if the browser supports css to format forms, especially the width
  3786. $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net' && $bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
  3787. return $bInfo;
  3788. }
  3789. /**
  3790. * Get the fully-qualified domain name of the host.
  3791. * Usage: 2
  3792. *
  3793. * @param boolean Use request host (when not in CLI mode).
  3794. * @return string The fully-qualified host name.
  3795. */
  3796. public static function getHostname($requestHost=TRUE) {
  3797. $host = '';
  3798. // If not called from the command-line, resolve on getIndpEnv()
  3799. // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
  3800. if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
  3801. $host = self::getIndpEnv('HTTP_HOST');
  3802. }
  3803. if (!$host) {
  3804. // will fail for PHP 4.1 and 4.2
  3805. $host = @php_uname('n');
  3806. // 'n' is ignored in broken installations
  3807. if (strpos($host, ' ')) $host = '';
  3808. }
  3809. // we have not found a FQDN yet
  3810. if ($host && strpos($host, '.') === false) {
  3811. $ip = gethostbyname($host);
  3812. // we got an IP address
  3813. if ($ip != $host) {
  3814. $fqdn = gethostbyaddr($ip);
  3815. if ($ip != $fqdn) $host = $fqdn;
  3816. }
  3817. }
  3818. if (!$host) $host = 'localhost.localdomain';
  3819. return $host;
  3820. }
  3821. /*************************
  3822. *
  3823. * TYPO3 SPECIFIC FUNCTIONS
  3824. *
  3825. *************************/
  3826. /**
  3827. * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns false if checks failed. Does not check if the file exists.
  3828. * Usage: 24
  3829. *
  3830. * @param string The input filename/filepath to evaluate
  3831. * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
  3832. * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
  3833. * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
  3834. */
  3835. public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE) {
  3836. if (!strcmp($filename,'')) return '';
  3837. if ($relToTYPO3_mainDir) {
  3838. if (!defined('PATH_typo3')) return '';
  3839. $relPathPrefix = PATH_typo3;
  3840. } else {
  3841. $relPathPrefix = PATH_site;
  3842. }
  3843. if (substr($filename,0,4)=='EXT:') { // extension
  3844. list($extKey,$local) = explode('/',substr($filename,4),2);
  3845. $filename='';
  3846. if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
  3847. $filename = t3lib_extMgm::extPath($extKey).$local;
  3848. }
  3849. } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
  3850. $filename=$relPathPrefix.$filename;
  3851. } elseif ($onlyRelative && !self::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
  3852. $filename='';
  3853. }
  3854. if (strcmp($filename,'') && self::validPathStr($filename)) { // checks backpath.
  3855. return $filename;
  3856. }
  3857. }
  3858. /**
  3859. * Checks for malicious file paths.
  3860. * Returns true if no '//', '..' or '\' is in the $theFile
  3861. * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
  3862. * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
  3863. * Usage: 14
  3864. *
  3865. * @param string Filepath to evaluate
  3866. * @return boolean True, if no '//', '\', '/../' is in the $theFile and $theFile doesn't begin with '../'
  3867. * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
  3868. */
  3869. public static function validPathStr($theFile) {
  3870. if (strpos($theFile, '//')===false && strpos($theFile, '\\')===false && !preg_match('#(?:^\.\.|/\.\./)#', $theFile)) {
  3871. return true;
  3872. }
  3873. }
  3874. /**
  3875. * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
  3876. * Usage: 8
  3877. *
  3878. * @param string Filepath to evaluate
  3879. * @return boolean
  3880. */
  3881. public static function isAbsPath($path) {
  3882. return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
  3883. }
  3884. /**
  3885. * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
  3886. * Usage: 5
  3887. *
  3888. * @param string Filepath to evaluate
  3889. * @return boolean
  3890. */
  3891. public static function isAllowedAbsPath($path) {
  3892. if (self::isAbsPath($path) &&
  3893. self::validPathStr($path) &&
  3894. ( self::isFirstPartOfStr($path,PATH_site)
  3895. ||
  3896. ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
  3897. )
  3898. ) return true;
  3899. }
  3900. /**
  3901. * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
  3902. * Usage: 2
  3903. *
  3904. * @param string Filepath to evaluate
  3905. * @return boolean
  3906. */
  3907. public static function verifyFilenameAgainstDenyPattern($filename) {
  3908. if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
  3909. $result = preg_match('/'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'].'/i',$filename);
  3910. if ($result) return false; // so if a matching filename is found, return false;
  3911. }
  3912. return true;
  3913. }
  3914. /**
  3915. * Checks if a given string is a valid frame URL to be loaded in the
  3916. * backend.
  3917. *
  3918. * @param string $url potential URL to check
  3919. *
  3920. * @return string either $url if $url is considered to be harmless, or an
  3921. * empty string otherwise
  3922. */
  3923. public static function sanitizeLocalUrl($url = '') {
  3924. $sanitizedUrl = '';
  3925. $decodedUrl = rawurldecode($url);
  3926. if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
  3927. $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
  3928. $testRelativeUrl = self::resolveBackPath(
  3929. self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
  3930. );
  3931. // Pass if URL is on the current host:
  3932. if (self::isValidUrl($decodedUrl)) {
  3933. if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
  3934. $sanitizedUrl = $url;
  3935. }
  3936. // Pass if URL is an absolute file path:
  3937. } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
  3938. $sanitizedUrl = $url;
  3939. // Pass if URL is absolute and below TYPO3 base directory:
  3940. } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
  3941. $sanitizedUrl = $url;
  3942. // Pass if URL is relative and below TYPO3 base directory:
  3943. } elseif (strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
  3944. $sanitizedUrl = $url;
  3945. }
  3946. }
  3947. if (!empty($url) && empty($sanitizedUrl)) {
  3948. self::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self::SYSLOG_SEVERITY_NOTICE);
  3949. }
  3950. return $sanitizedUrl;
  3951. }
  3952. /**
  3953. * Moves $source file to $destination if uploaded, otherwise try to make a copy
  3954. * Usage: 4
  3955. *
  3956. * @param string Source file, absolute path
  3957. * @param string Destination file, absolute path
  3958. * @return boolean Returns true if the file was moved.
  3959. * @coauthor Dennis Petersen <fessor@software.dk>
  3960. * @see upload_to_tempfile()
  3961. */
  3962. public static function upload_copy_move($source,$destination) {
  3963. if (is_uploaded_file($source)) {
  3964. $uploaded = TRUE;
  3965. // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
  3966. $uploadedResult = move_uploaded_file($source, $destination);
  3967. } else {
  3968. $uploaded = FALSE;
  3969. @copy($source,$destination);
  3970. }
  3971. self::fixPermissions($destination); // Change the permissions of the file
  3972. // If here the file is copied and the temporary $source is still around, so when returning false the user can try unlink to delete the $source
  3973. return $uploaded ? $uploadedResult : FALSE;
  3974. }
  3975. /**
  3976. * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it under safe_mode.
  3977. * Use this function to move uploaded files to where you can work on them.
  3978. * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
  3979. * Usage: 6
  3980. *
  3981. * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
  3982. * @return string If a new file was successfully created, return its filename, otherwise blank string.
  3983. * @see unlink_tempfile(), upload_copy_move()
  3984. */
  3985. public static function upload_to_tempfile($uploadedFileName) {
  3986. if (is_uploaded_file($uploadedFileName)) {
  3987. $tempFile = self::tempnam('upload_temp_');
  3988. move_uploaded_file($uploadedFileName, $tempFile);
  3989. return @is_file($tempFile) ? $tempFile : '';
  3990. }
  3991. }
  3992. /**
  3993. * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
  3994. * The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe.
  3995. * Use this after upload_to_tempfile() or tempnam() from this class!
  3996. * Usage: 9
  3997. *
  3998. * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
  3999. * @return boolean Returns true if the file was unlink()'ed
  4000. * @see upload_to_tempfile(), tempnam()
  4001. */
  4002. public static function unlink_tempfile($uploadedTempFileName) {
  4003. if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
  4004. if (unlink($uploadedTempFileName)) return TRUE;
  4005. }
  4006. }
  4007. /**
  4008. * Create temporary filename (Create file with unique file name)
  4009. * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
  4010. * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
  4011. * Usage: 7
  4012. *
  4013. * @param string Prefix to temp file (which will have no extension btw)
  4014. * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
  4015. * @see unlink_tempfile(), upload_to_tempfile()
  4016. */
  4017. public static function tempnam($filePrefix) {
  4018. return tempnam(PATH_site.'typo3temp/',$filePrefix);
  4019. }
  4020. /**
  4021. * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
  4022. * Usage: 2
  4023. *
  4024. * @param mixed Uid (integer) or record (array)
  4025. * @param string List of fields from the record if that is given.
  4026. * @param integer Length of returned authentication code.
  4027. * @return string MD5 hash of 8 chars.
  4028. */
  4029. public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8) {
  4030. if (is_array($uid_or_record)) {
  4031. $recCopy_temp=array();
  4032. if ($fields) {
  4033. $fieldArr = self::trimExplode(',',$fields,1);
  4034. foreach ($fieldArr as $k => $v) {
  4035. $recCopy_temp[$k]=$uid_or_record[$v];
  4036. }
  4037. } else {
  4038. $recCopy_temp=$uid_or_record;
  4039. }
  4040. $preKey = implode('|',$recCopy_temp);
  4041. } else {
  4042. $preKey = $uid_or_record;
  4043. }
  4044. $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  4045. $authCode = substr(md5($authCode),0,$codeLength);
  4046. return $authCode;
  4047. }
  4048. /**
  4049. * Splits the input query-parameters into an array with certain parameters filtered out.
  4050. * Used to create the cHash value
  4051. *
  4052. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  4053. * @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
  4054. * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
  4055. */
  4056. public static function cHashParams($addQueryParams) {
  4057. $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
  4058. // Make array:
  4059. $pA = array();
  4060. foreach($params as $theP) {
  4061. $pKV = explode('=', $theP); // Splitting single param by '=' sign
  4062. if (!self::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0])) {
  4063. $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
  4064. }
  4065. }
  4066. // Hook: Allows to manipulate the parameters which are taken to build the chash:
  4067. if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
  4068. $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
  4069. if (is_array($cHashParamsHook)) {
  4070. $hookParameters = array(
  4071. 'addQueryParams' => &$addQueryParams,
  4072. 'params' => &$params,
  4073. 'pA' => &$pA,
  4074. );
  4075. $hookReference = null;
  4076. foreach ($cHashParamsHook as $hookFunction) {
  4077. self::callUserFunction($hookFunction, $hookParameters, $hookReference);
  4078. }
  4079. }
  4080. }
  4081. // Finish and sort parameters array by keys:
  4082. $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  4083. ksort($pA);
  4084. return $pA;
  4085. }
  4086. /**
  4087. * Returns the cHash based on provided query parameters and added values from internal call
  4088. *
  4089. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  4090. * @return string Hash of all the values
  4091. * @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
  4092. */
  4093. public static function generateCHash($addQueryParams) {
  4094. $cHashParams = self::cHashParams($addQueryParams);
  4095. $cHash = self::calculateCHash($cHashParams);
  4096. return $cHash;
  4097. }
  4098. /**
  4099. * Calculates the cHash based on the provided parameters
  4100. *
  4101. * @param array Array of key-value pairs
  4102. * @return string Hash of all the values
  4103. */
  4104. public static function calculateCHash($params) {
  4105. $cHash = md5(serialize($params));
  4106. return $cHash;
  4107. }
  4108. /**
  4109. * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
  4110. *
  4111. * @param integer Value from "l18n_cfg" field of a page record
  4112. * @return boolean True if the page should be hidden
  4113. */
  4114. public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
  4115. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
  4116. return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
  4117. } else {
  4118. return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
  4119. }
  4120. }
  4121. /**
  4122. * Includes a locallang file and returns the $LOCAL_LANG array found inside.
  4123. *
  4124. * @param string Input is a file-reference (see t3lib_div::getFileAbsFileName). That file is expected to be a 'locallang.php' file containing a $LOCAL_LANG array (will be included!) or a 'locallang.xml' file conataining a valid XML TYPO3 language structure.
  4125. * @param string Language key
  4126. * @param string Character set (option); if not set, determined by the language key
  4127. * @param integer Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
  4128. * @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
  4129. * Otherwise an empty array and it is FALSE in error case.
  4130. */
  4131. public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
  4132. $result = FALSE;
  4133. $file = self::getFileAbsFileName($fileRef);
  4134. if ($file) {
  4135. $baseFile = preg_replace('/\.(php|xml)$/', '', $file);
  4136. if (@is_file($baseFile.'.xml')) {
  4137. $LOCAL_LANG = self::readLLXMLfile($baseFile.'.xml', $langKey, $charset);
  4138. } elseif (@is_file($baseFile.'.php')) {
  4139. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] || $charset) {
  4140. $LOCAL_LANG = self::readLLPHPfile($baseFile.'.php', $langKey, $charset);
  4141. } else {
  4142. include($baseFile.'.php');
  4143. if (is_array($LOCAL_LANG)) {
  4144. $LOCAL_LANG = array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]); }
  4145. }
  4146. } else {
  4147. $errorMsg = 'File "' . $fileRef. '" not found!';
  4148. if ($errorMode == 2) {
  4149. throw new t3lib_exception($errorMsg);
  4150. } elseif(!$errorMode) {
  4151. self::sysLog($errorMsg, 'Core', self::SYSLOG_SEVERITY_ERROR);
  4152. }
  4153. $fileNotFound = TRUE;
  4154. }
  4155. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef])) {
  4156. foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef] as $overrideFile) {
  4157. $languageOverrideFileName = self::getFileAbsFileName($overrideFile);
  4158. if (@is_file($languageOverrideFileName)) {
  4159. $languageOverrideArray = self::readLLXMLfile($languageOverrideFileName, $langKey, $charset);
  4160. $LOCAL_LANG = self::array_merge_recursive_overrule($LOCAL_LANG, $languageOverrideArray);
  4161. }
  4162. }
  4163. }
  4164. }
  4165. if ($fileNotFound !== TRUE) {
  4166. $result = is_array($LOCAL_LANG) ? $LOCAL_LANG : array();
  4167. }
  4168. return $result;
  4169. }
  4170. /**
  4171. * Includes a locallang-php file and returns the $LOCAL_LANG array
  4172. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  4173. *
  4174. * @param string Absolute reference to locallang-PHP file
  4175. * @param string TYPO3 language key, eg. "dk" or "de" or "default"
  4176. * @param string Character set (optional)
  4177. * @return array LOCAL_LANG array in return.
  4178. */
  4179. public static function readLLPHPfile($fileRef, $langKey, $charset='') {
  4180. if (is_object($GLOBALS['LANG'])) {
  4181. $csConvObj = $GLOBALS['LANG']->csConvObj;
  4182. } elseif (is_object($GLOBALS['TSFE'])) {
  4183. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  4184. } else {
  4185. $csConvObj = self::makeInstance('t3lib_cs');
  4186. }
  4187. if (@is_file($fileRef) && $langKey) {
  4188. // Set charsets:
  4189. $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4190. if ($charset) {
  4191. $targetCharset = $csConvObj->parse_charset($charset);
  4192. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  4193. // when forceCharset is set, we store ALL labels in this charset!!!
  4194. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  4195. } else {
  4196. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4197. }
  4198. // Cache file name:
  4199. $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
  4200. $cacheFileName = PATH_site.'typo3temp/llxml/'.
  4201. substr(basename($fileRef),10,15).
  4202. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4203. // Check if cache file exists...
  4204. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4205. // Get PHP data
  4206. include($fileRef);
  4207. if (!is_array($LOCAL_LANG)) {
  4208. $fileName = substr($fileRef, strlen(PATH_site));
  4209. throw new RuntimeException(
  4210. 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
  4211. 1270853900
  4212. );
  4213. }
  4214. // converting the default language (English)
  4215. // this needs to be done for a few accented loan words and extension names
  4216. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'iso-8859-1') {
  4217. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  4218. $labelValue = $csConvObj->conv($labelValue, 'iso-8859-1', $targetCharset);
  4219. }
  4220. }
  4221. if ($langKey!='default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset!=$targetCharset) {
  4222. foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
  4223. $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
  4224. }
  4225. }
  4226. // Cache the content now:
  4227. $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
  4228. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4229. if ($res) {
  4230. throw new RuntimeException(
  4231. 'TYPO3 Fatal Error: "' . $res,
  4232. 1270853901
  4233. );
  4234. }
  4235. } else {
  4236. // Get content from cache:
  4237. $serContent = unserialize(self::getUrl($cacheFileName));
  4238. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  4239. }
  4240. return $LOCAL_LANG;
  4241. }
  4242. }
  4243. /**
  4244. * Includes a locallang-xml file and returns the $LOCAL_LANG array
  4245. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  4246. *
  4247. * @param string Absolute reference to locallang-XML file
  4248. * @param string TYPO3 language key, eg. "dk" or "de" or "default"
  4249. * @param string Character set (optional)
  4250. * @return array LOCAL_LANG array in return.
  4251. */
  4252. public static function readLLXMLfile($fileRef, $langKey, $charset='') {
  4253. if (is_object($GLOBALS['LANG'])) {
  4254. $csConvObj = $GLOBALS['LANG']->csConvObj;
  4255. } elseif (is_object($GLOBALS['TSFE'])) {
  4256. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  4257. } else {
  4258. $csConvObj = self::makeInstance('t3lib_cs');
  4259. }
  4260. $LOCAL_LANG = NULL;
  4261. if (@is_file($fileRef) && $langKey) {
  4262. // Set charset:
  4263. if ($charset) {
  4264. $targetCharset = $csConvObj->parse_charset($charset);
  4265. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  4266. // when forceCharset is set, we store ALL labels in this charset!!!
  4267. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  4268. } else {
  4269. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4270. }
  4271. // Cache file name:
  4272. $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
  4273. $cacheFileName = PATH_site.'typo3temp/llxml/'.
  4274. substr(basename($fileRef),10,15).
  4275. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4276. // Check if cache file exists...
  4277. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4278. // Read XML, parse it.
  4279. $xmlString = self::getUrl($fileRef);
  4280. $xmlContent = self::xml2array($xmlString);
  4281. if (!is_array($xmlContent)) {
  4282. $fileName = substr($fileRef, strlen(PATH_site));
  4283. throw new RuntimeException(
  4284. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4285. 1270853902
  4286. );
  4287. }
  4288. // Set default LOCAL_LANG array content:
  4289. $LOCAL_LANG = array();
  4290. $LOCAL_LANG['default'] = $xmlContent['data']['default'];
  4291. // converting the default language (English)
  4292. // this needs to be done for a few accented loan words and extension names
  4293. // NOTE: no conversion is done when in UTF-8 mode!
  4294. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
  4295. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  4296. $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
  4297. }
  4298. unset($labelValue);
  4299. }
  4300. // converting other languages to their "native" charsets
  4301. // NOTE: no conversion is done when in UTF-8 mode!
  4302. if ($langKey!='default') {
  4303. // If no entry is found for the language key, then force a value depending on meta-data setting. By default an automated filename will be used:
  4304. $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
  4305. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4306. if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
  4307. $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
  4308. }
  4309. // Checking if charset should be converted.
  4310. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
  4311. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  4312. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
  4313. }
  4314. }
  4315. }
  4316. // Cache the content now:
  4317. $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
  4318. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4319. if ($res) {
  4320. throw new RuntimeException(
  4321. 'TYPO3 Fatal Error: ' . $res,
  4322. 1270853903
  4323. );
  4324. }
  4325. } else {
  4326. // Get content from cache:
  4327. $serContent = unserialize(self::getUrl($cacheFileName));
  4328. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  4329. }
  4330. // Checking for EXTERNAL file for non-default language:
  4331. if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
  4332. // Look for localized file:
  4333. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4334. if ($localized_file && @is_file($localized_file)) {
  4335. // Cache file name:
  4336. $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file)).'|version=2.3';
  4337. $cacheFileName = PATH_site.'typo3temp/llxml/EXT_'.
  4338. substr(basename($localized_file),10,15).
  4339. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4340. // Check if cache file exists...
  4341. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4342. // Read and parse XML content:
  4343. $local_xmlString = self::getUrl($localized_file);
  4344. $local_xmlContent = self::xml2array($local_xmlString);
  4345. if (!is_array($local_xmlContent)) {
  4346. $fileName = substr($localized_file, strlen(PATH_site));
  4347. throw new RuntimeException(
  4348. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4349. 1270853904
  4350. );
  4351. }
  4352. $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
  4353. // Checking if charset should be converted.
  4354. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
  4355. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  4356. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
  4357. }
  4358. }
  4359. // Cache the content now:
  4360. $serContent = array('extlang'=>$langKey, 'origFile'=>$hashSource, 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
  4361. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4362. if ($res) {
  4363. throw new RuntimeException(
  4364. 'TYPO3 Fatal Error: ' . $res,
  4365. 1270853905
  4366. );
  4367. }
  4368. } else {
  4369. // Get content from cache:
  4370. $serContent = unserialize(self::getUrl($cacheFileName));
  4371. $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
  4372. }
  4373. } else {
  4374. $LOCAL_LANG[$langKey] = array();
  4375. }
  4376. }
  4377. return $LOCAL_LANG;
  4378. }
  4379. }
  4380. /**
  4381. * Returns auto-filename for locallang-XML localizations.
  4382. *
  4383. * @param string Absolute file reference to locallang-XML file. Must be inside system/global/local extension
  4384. * @param string Language key
  4385. * @return string Returns the filename reference for the language unless error occured (or local mode is used) in which case it will be NULL
  4386. */
  4387. public static function llXmlAutoFileName($fileRef,$language) {
  4388. // Analyse file reference:
  4389. $location = 'typo3conf/l10n/'.$language.'/'; // Default location of translations
  4390. if (self::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) { // Is system:
  4391. $validatedPrefix = PATH_typo3.'sysext/';
  4392. #$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
  4393. } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3.'ext/')) { // Is global:
  4394. $validatedPrefix = PATH_typo3.'ext/';
  4395. } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/')) { // Is local:
  4396. $validatedPrefix = PATH_typo3conf.'ext/';
  4397. } else {
  4398. $validatedPrefix = '';
  4399. }
  4400. if ($validatedPrefix) {
  4401. // Divide file reference into extension key, directory (if any) and base name:
  4402. list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
  4403. $temp = self::revExplode('/',$file_extPath,2);
  4404. if (count($temp)==1) array_unshift($temp,''); // Add empty first-entry if not there.
  4405. list($file_extPath,$file_fileName) = $temp;
  4406. // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
  4407. return $location.
  4408. $file_extKey.'/'.
  4409. ($file_extPath?$file_extPath.'/':'').
  4410. $language.'.'.$file_fileName;
  4411. } else {
  4412. return NULL;
  4413. }
  4414. }
  4415. /**
  4416. * Loads the $TCA (Table Configuration Array) for the $table
  4417. *
  4418. * Requirements:
  4419. * 1) must be configured table (the ctrl-section configured),
  4420. * 2) columns must not be an array (which it is always if whole table loaded), and
  4421. * 3) there is a value for dynamicConfigFile (filename in typo3conf)
  4422. *
  4423. * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
  4424. * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
  4425. *
  4426. * Usage: 84
  4427. *
  4428. * @param string Table name for which to load the full TCA array part into the global $TCA
  4429. * @return void
  4430. */
  4431. public static function loadTCA($table) {
  4432. global $TCA;
  4433. if (isset($TCA[$table])) {
  4434. $tca = &$TCA[$table];
  4435. if (!$tca['columns']) {
  4436. $dcf = $tca['ctrl']['dynamicConfigFile'];
  4437. if ($dcf) {
  4438. if (!strcmp(substr($dcf,0,6),'T3LIB:')) {
  4439. include(PATH_t3lib.'stddb/'.substr($dcf,6));
  4440. } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
  4441. include($dcf);
  4442. } else include(PATH_typo3conf.$dcf);
  4443. }
  4444. }
  4445. }
  4446. }
  4447. /**
  4448. * Looks for a sheet-definition in the input data structure array. If found it will return the data structure for the sheet given as $sheet (if found).
  4449. * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
  4450. * Usage: 5
  4451. *
  4452. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  4453. * @param string The sheet to return, preferably.
  4454. * @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error happend in which case an error string is returned (string). key1: The used sheet key value!
  4455. */
  4456. public static function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
  4457. if (!is_array ($dataStructArray)) return 'Data structure must be an array';
  4458. if (is_array($dataStructArray['sheets'])) {
  4459. $singleSheet = FALSE;
  4460. if (!isset($dataStructArray['sheets'][$sheet])) {
  4461. $sheet='sDEF';
  4462. }
  4463. $dataStruct = $dataStructArray['sheets'][$sheet];
  4464. // If not an array, but still set, then regard it as a relative reference to a file:
  4465. if ($dataStruct && !is_array($dataStruct)) {
  4466. $file = self::getFileAbsFileName($dataStruct);
  4467. if ($file && @is_file($file)) {
  4468. $dataStruct = self::xml2array(self::getUrl($file));
  4469. }
  4470. }
  4471. } else {
  4472. $singleSheet = TRUE;
  4473. $dataStruct = $dataStructArray;
  4474. if (isset($dataStruct['meta'])) unset($dataStruct['meta']); // Meta data should not appear there.
  4475. $sheet = 'sDEF'; // Default sheet
  4476. }
  4477. return array($dataStruct,$sheet,$singleSheet);
  4478. }
  4479. /**
  4480. * Resolves ALL sheet definitions in dataStructArray
  4481. * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
  4482. *
  4483. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  4484. * @return array Output data structure with all sheets resolved as arrays.
  4485. */
  4486. public static function resolveAllSheetsInDS(array $dataStructArray) {
  4487. if (is_array($dataStructArray['sheets'])) {
  4488. $out=array('sheets'=>array());
  4489. foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
  4490. list($ds,$aS) = self::resolveSheetDefInDS($dataStructArray,$sheetId);
  4491. if ($sheetId==$aS) {
  4492. $out['sheets'][$aS]=$ds;
  4493. }
  4494. }
  4495. } else {
  4496. list($ds) = self::resolveSheetDefInDS($dataStructArray);
  4497. $out = array('sheets' => array('sDEF' => $ds));
  4498. }
  4499. return $out;
  4500. }
  4501. /**
  4502. * Calls a userdefined function/method in class
  4503. * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
  4504. * Usage: 17
  4505. *
  4506. * @param string Function/Method reference, '[file-reference":"]["&"]class/function["->"method-name]'. You can prefix this reference with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl->encodeSpURL". Finally; you can prefix the class name with "&" if you want to reuse a former instance of the same object call ("singleton").
  4507. * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
  4508. * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
  4509. * @param string Required prefix of class or function name
  4510. * @param integer Error mode (when class/function could not be found): 0 - call debug(), 1 - do nothing, 2 - raise an exception (allows to call a user function that may return FALSE)
  4511. * @return mixed Content from method/function call or false if the class/method/function was not found
  4512. * @see getUserObj()
  4513. */
  4514. public static function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$errorMode=0) {
  4515. global $TYPO3_CONF_VARS;
  4516. $content = false;
  4517. // Check persistent object and if found, call directly and exit.
  4518. if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
  4519. return call_user_func_array(
  4520. array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
  4521. $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
  4522. array(&$params, &$ref)
  4523. );
  4524. }
  4525. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4526. if (strpos($funcName,':') !== false) {
  4527. list($file,$funcRef) = self::revExplode(':',$funcName,2);
  4528. $requireFile = self::getFileAbsFileName($file);
  4529. if ($requireFile) self::requireOnce($requireFile);
  4530. } else {
  4531. $funcRef = $funcName;
  4532. }
  4533. // Check for persistent object token, "&"
  4534. if (substr($funcRef,0,1)=='&') {
  4535. $funcRef = substr($funcRef,1);
  4536. $storePersistentObject = true;
  4537. } else {
  4538. $storePersistentObject = false;
  4539. }
  4540. // Check prefix is valid:
  4541. if ($checkPrefix &&
  4542. !self::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
  4543. !self::isFirstPartOfStr(trim($funcRef),'tx_')
  4544. ) {
  4545. $errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
  4546. if ($errorMode == 2) {
  4547. throw new Exception($errorMsg);
  4548. } elseif(!$errorMode) {
  4549. debug($errorMsg, 't3lib_div::callUserFunction');
  4550. }
  4551. return false;
  4552. }
  4553. // Call function or method:
  4554. $parts = explode('->',$funcRef);
  4555. if (count($parts)==2) { // Class
  4556. // Check if class/method exists:
  4557. if (class_exists($parts[0])) {
  4558. // Get/Create object of class:
  4559. if ($storePersistentObject) { // Get reference to current instance of class:
  4560. if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
  4561. $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self::makeInstance($parts[0]);
  4562. }
  4563. $classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
  4564. } else { // Create new object:
  4565. $classObj = self::makeInstance($parts[0]);
  4566. }
  4567. if (method_exists($classObj, $parts[1])) {
  4568. // If persistent object should be created, set reference:
  4569. if ($storePersistentObject) {
  4570. $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
  4571. 'method' => $parts[1],
  4572. 'obj' => &$classObj
  4573. );
  4574. }
  4575. // Call method:
  4576. $content = call_user_func_array(
  4577. array(&$classObj, $parts[1]),
  4578. array(&$params, &$ref)
  4579. );
  4580. } else {
  4581. $errorMsg = "<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0];
  4582. if ($errorMode == 2) {
  4583. throw new Exception($errorMsg);
  4584. } elseif(!$errorMode) {
  4585. debug($errorMsg, 't3lib_div::callUserFunction');
  4586. }
  4587. }
  4588. } else {
  4589. $errorMsg = "<strong>ERROR:</strong> No class named: ".$parts[0];
  4590. if ($errorMode == 2) {
  4591. throw new Exception($errorMsg);
  4592. } elseif(!$errorMode) {
  4593. debug($errorMsg, 't3lib_div::callUserFunction');
  4594. }
  4595. }
  4596. } else { // Function
  4597. if (function_exists($funcRef)) {
  4598. $content = call_user_func_array($funcRef, array(&$params, &$ref));
  4599. } else {
  4600. $errorMsg = "<strong>ERROR:</strong> No function named: ".$funcRef;
  4601. if ($errorMode == 2) {
  4602. throw new Exception($errorMsg);
  4603. } elseif(!$errorMode) {
  4604. debug($errorMsg, 't3lib_div::callUserFunction');
  4605. }
  4606. }
  4607. }
  4608. return $content;
  4609. }
  4610. /**
  4611. * Creates and returns reference to a user defined object.
  4612. * This function can return an object reference if you like. Just prefix the function call with "&": "$objRef = &t3lib_div::getUserObj('EXT:myext/class.tx_myext_myclass.php:&tx_myext_myclass');". This will work ONLY if you prefix the class name with "&" as well. See description of function arguments.
  4613. * Usage: 5
  4614. *
  4615. * @param string Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
  4616. * @param string Required prefix of class name. By default "tx_" is allowed.
  4617. * @param boolean If set, no debug() error message is shown if class/function is not present.
  4618. * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
  4619. * @see callUserFunction()
  4620. */
  4621. public static function getUserObj($classRef, $checkPrefix='user_', $silent=false) {
  4622. global $TYPO3_CONF_VARS;
  4623. // Check persistent object and if found, call directly and exit.
  4624. if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
  4625. return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
  4626. } else {
  4627. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4628. if (strpos($classRef,':') !== false) {
  4629. list($file,$class) = self::revExplode(':',$classRef,2);
  4630. $requireFile = self::getFileAbsFileName($file);
  4631. if ($requireFile) self::requireOnce($requireFile);
  4632. } else {
  4633. $class = $classRef;
  4634. }
  4635. // Check for persistent object token, "&"
  4636. if (substr($class,0,1)=='&') {
  4637. $class = substr($class,1);
  4638. $storePersistentObject = TRUE;
  4639. } else {
  4640. $storePersistentObject = FALSE;
  4641. }
  4642. // Check prefix is valid:
  4643. if ($checkPrefix &&
  4644. !self::isFirstPartOfStr(trim($class),$checkPrefix) &&
  4645. !self::isFirstPartOfStr(trim($class),'tx_')
  4646. ) {
  4647. if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'", 't3lib_div::getUserObj');
  4648. return FALSE;
  4649. }
  4650. // Check if class exists:
  4651. if (class_exists($class)) {
  4652. $classObj = self::makeInstance($class);
  4653. // If persistent object should be created, set reference:
  4654. if ($storePersistentObject) {
  4655. $GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
  4656. }
  4657. return $classObj;
  4658. } else {
  4659. if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$class, 't3lib_div::getUserObj');
  4660. }
  4661. }
  4662. }
  4663. /**
  4664. * Creates an instance of a class taking into account the class-extensions
  4665. * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
  4666. * Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
  4667. * You can also pass arguments for a constructor:
  4668. * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
  4669. *
  4670. * @param string Class name to instantiate
  4671. * @return object A reference to the object
  4672. */
  4673. public static function makeInstance($className) {
  4674. // holds references of singletons
  4675. static $instances = array();
  4676. // Get final classname
  4677. $className = self::getClassName($className);
  4678. if (isset($instances[$className])) {
  4679. // it's a singleton, get the existing instance
  4680. $instance = $instances[$className];
  4681. } else {
  4682. if (func_num_args() > 1) {
  4683. // getting the constructor arguments by removing this
  4684. // method's first argument (the class name)
  4685. $constructorArguments = func_get_args();
  4686. array_shift($constructorArguments);
  4687. $reflectedClass = new ReflectionClass($className);
  4688. $instance = $reflectedClass->newInstanceArgs($constructorArguments);
  4689. } else {
  4690. $instance = new $className;
  4691. }
  4692. if ($instance instanceof t3lib_Singleton) {
  4693. // it's a singleton, save the instance for later reuse
  4694. $instances[$className] = $instance;
  4695. }
  4696. }
  4697. return $instance;
  4698. }
  4699. /**
  4700. * Return classname for new instance
  4701. * Takes the class-extensions API of TYPO3 into account
  4702. * Usage: 17
  4703. *
  4704. * @param string Base Class name to evaluate
  4705. * @return string Final class name to instantiate with "new [classname]"
  4706. * @deprecated since TYPO3 4.3 - Use t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
  4707. */
  4708. public static function makeInstanceClassName($className) {
  4709. self::logDeprecatedFunction();
  4710. return (class_exists($className) && class_exists('ux_'.$className, false) ? self::makeInstanceClassName('ux_' . $className) : $className);
  4711. }
  4712. /**
  4713. * Returns the class name for a new instance, taking into account the
  4714. * class-extension API.
  4715. *
  4716. * @param string Base class name to evaluate
  4717. * @return string Final class name to instantiate with "new [classname]"
  4718. */
  4719. protected function getClassName($className) {
  4720. return (class_exists($className) && class_exists('ux_' . $className, false) ? self::getClassName('ux_' . $className) : $className);
  4721. }
  4722. /**
  4723. * Find the best service and check if it works.
  4724. * Returns object of the service class.
  4725. *
  4726. * @param string Type of service (service key).
  4727. * @param string Sub type like file extensions or similar. Defined by the service.
  4728. * @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
  4729. * @return object The service object or an array with error info's.
  4730. * @author René Fritz <r.fritz@colorcube.de>
  4731. */
  4732. public static function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) {
  4733. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4734. $error = FALSE;
  4735. if (!is_array($excludeServiceKeys) ) {
  4736. $excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, 1);
  4737. }
  4738. while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
  4739. // Check persistent object and if found, call directly and exit.
  4740. if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
  4741. // reset service and return object
  4742. $T3_VAR['makeInstanceService'][$info['className']]->reset();
  4743. return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
  4744. // include file and create object
  4745. } else {
  4746. $requireFile = self::getFileAbsFileName($info['classFile']);
  4747. if (@is_file($requireFile)) {
  4748. self::requireOnce ($requireFile);
  4749. $obj = self::makeInstance($info['className']);
  4750. if (is_object($obj)) {
  4751. if(!@is_callable(array($obj,'init'))) {
  4752. // use silent logging??? I don't think so.
  4753. die ('Broken service:'.self::view_array($info));
  4754. }
  4755. $obj->info = $info;
  4756. if ($obj->init()) { // service available?
  4757. // create persistent object
  4758. $T3_VAR['makeInstanceService'][$info['className']] = $obj;
  4759. // needed to delete temp files
  4760. register_shutdown_function(array(&$obj, '__destruct'));
  4761. return $obj; // object is passed as reference by function definition
  4762. }
  4763. $error = $obj->getLastErrorArray();
  4764. unset($obj);
  4765. }
  4766. }
  4767. }
  4768. // deactivate the service
  4769. t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
  4770. }
  4771. return $error;
  4772. }
  4773. /**
  4774. * Require a class for TYPO3
  4775. * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
  4776. */
  4777. public static function requireOnce($requireFile) {
  4778. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4779. require_once ($requireFile);
  4780. }
  4781. /**
  4782. * Requires a class for TYPO3
  4783. * Useful to require classes from inside other classes (not global scope).
  4784. * A limited set of global variables are available (see function)
  4785. *
  4786. * @param string $requireFile: Path of the file to be included
  4787. * @return void
  4788. */
  4789. public static function requireFile($requireFile) {
  4790. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4791. require $requireFile;
  4792. }
  4793. /**
  4794. * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
  4795. * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
  4796. * Further the output has the charset set to ISO-8859-1 by default.
  4797. * Usage: 4
  4798. *
  4799. * @param string Email address to send to. (see PHP function mail())
  4800. * @param string Subject line, non-encoded. (see PHP function mail())
  4801. * @param string Message content, non-encoded. (see PHP function mail())
  4802. * @param string Headers, separated by LF
  4803. * @param string Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
  4804. * @param string Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
  4805. * @param boolean If set, the header content will not be encoded.
  4806. * @return boolean True if mail was accepted for delivery, false otherwise
  4807. */
  4808. public static function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false) {
  4809. if (!$charset) {
  4810. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
  4811. }
  4812. $email = self::normalizeMailAddress($email);
  4813. if (!$dontEncodeHeader) {
  4814. // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
  4815. $newHeaders=array();
  4816. foreach (explode(LF,$headers) as $line) { // Split the header in lines and convert each line separately
  4817. $parts = explode(': ',$line,2); // Field tags must not be encoded
  4818. if (count($parts)==2) {
  4819. if (0 == strcasecmp($parts[0], 'from')) {
  4820. $parts[1] = self::normalizeMailAddress($parts[1]);
  4821. }
  4822. $parts[1] = self::encodeHeader($parts[1],$encoding,$charset);
  4823. $newHeaders[] = implode(': ',$parts);
  4824. } else {
  4825. $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
  4826. }
  4827. }
  4828. $headers = implode(LF,$newHeaders);
  4829. unset($newHeaders);
  4830. $email = self::encodeHeader($email,$encoding,$charset); // Email address must not be encoded, but it could be appended by a name which should be so (e.g. "Kasper Skårhøj <kasperYYYY@typo3.com>")
  4831. $subject = self::encodeHeader($subject,$encoding,$charset);
  4832. }
  4833. switch ((string)$encoding) {
  4834. case 'base64':
  4835. $headers=trim($headers).LF.
  4836. 'Mime-Version: 1.0'.LF.
  4837. 'Content-Type: text/plain; charset="'.$charset.'"'.LF.
  4838. 'Content-Transfer-Encoding: base64';
  4839. $message=trim(chunk_split(base64_encode($message.LF))).LF; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
  4840. break;
  4841. case '8bit':
  4842. $headers=trim($headers).LF.
  4843. 'Mime-Version: 1.0'.LF.
  4844. 'Content-Type: text/plain; charset='.$charset.LF.
  4845. 'Content-Transfer-Encoding: 8bit';
  4846. break;
  4847. case 'quoted-printable':
  4848. default:
  4849. $headers=trim($headers).LF.
  4850. 'Mime-Version: 1.0'.LF.
  4851. 'Content-Type: text/plain; charset='.$charset.LF.
  4852. 'Content-Transfer-Encoding: quoted-printable';
  4853. $message=self::quoted_printable($message);
  4854. break;
  4855. }
  4856. // Headers must be separated by CRLF according to RFC 2822, not just LF.
  4857. // But many servers (Gmail, for example) behave incorectly and want only LF.
  4858. // So we stick to LF in all cases.
  4859. $headers = trim(implode(LF, self::trimExplode(LF, $headers, true))); // Make sure no empty lines are there.
  4860. return t3lib_utility_Mail::mail($email, $subject, $message, $headers);
  4861. }
  4862. /**
  4863. * Implementation of quoted-printable encode.
  4864. * This functions is buggy. It seems that in the part where the lines are breaked every 76th character, that it fails if the break happens right in a quoted_printable encode character!
  4865. * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
  4866. * Usage: 2
  4867. *
  4868. * @param string Content to encode
  4869. * @param integer Length of the lines, default is 76
  4870. * @return string The QP encoded string
  4871. */
  4872. public static function quoted_printable($string,$maxlen=76) {
  4873. // Make sure the string contains only Unix linebreaks
  4874. $string = str_replace(CRLF, LF, $string); // Replace Windows breaks (\r\n)
  4875. $string = str_replace(CR, LF, $string); // Replace Mac breaks (\r)
  4876. $linebreak = LF; // Default line break for Unix systems.
  4877. if (TYPO3_OS=='WIN') {
  4878. $linebreak = CRLF; // Line break for Windows. This is needed because PHP on Windows systems send mails via SMTP instead of using sendmail, and thus the linebreak needs to be \r\n.
  4879. }
  4880. $newString = '';
  4881. $theLines = explode(LF,$string); // Split lines
  4882. foreach ($theLines as $val) {
  4883. $newVal = '';
  4884. $theValLen = strlen($val);
  4885. $len = 0;
  4886. for ($index=0; $index < $theValLen; $index++) { // Walk through each character of this line
  4887. $char = substr($val,$index,1);
  4888. $ordVal = ord($char);
  4889. if ($len>($maxlen-4) || ($len>($maxlen-14) && $ordVal==32)) {
  4890. $newVal.='='.$linebreak; // Add a line break
  4891. $len=0; // Reset the length counter
  4892. }
  4893. if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
  4894. $newVal.=$char; // This character is ok, add it to the message
  4895. $len++;
  4896. } else {
  4897. $newVal.=sprintf('=%02X',$ordVal); // Special character, needs to be encoded
  4898. $len+=3;
  4899. }
  4900. }
  4901. $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal); // Replaces a possible SPACE-character at the end of a line
  4902. $newVal = preg_replace('/'.TAB.'$/','=09',$newVal); // Replaces a possible TAB-character at the end of a line
  4903. $newString.=$newVal.$linebreak;
  4904. }
  4905. return preg_replace('/'.$linebreak.'$/','',$newString); // Remove last newline
  4906. }
  4907. /**
  4908. * Encode header lines
  4909. * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
  4910. *
  4911. * @param string Content to encode
  4912. * @param string Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
  4913. * @param string Charset used for encoding
  4914. * @return string The encoded string
  4915. */
  4916. public static function encodeHeader($line,$enc='quoted-printable',$charset='iso-8859-1') {
  4917. // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
  4918. if (strpos($line,'###') !== false) {
  4919. return $line;
  4920. }
  4921. // Check if any non-ASCII characters are found - otherwise encoding is not needed
  4922. if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) {
  4923. return $line;
  4924. }
  4925. // Wrap email addresses in a special marker
  4926. $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
  4927. $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
  4928. foreach ($matches as $part) {
  4929. $oldPart = $part;
  4930. switch ((string)$enc) {
  4931. case 'base64':
  4932. $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
  4933. break;
  4934. case 'quoted-printable':
  4935. default:
  4936. $qpValue = self::quoted_printable($part,1000);
  4937. if ($part!=$qpValue) {
  4938. // Encoded words in the header should not contain non-encoded:
  4939. // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
  4940. // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
  4941. $search = array(' ', '?');
  4942. $replace = array('_', '=3F');
  4943. $qpValue = str_replace($search, $replace, $qpValue);
  4944. $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
  4945. }
  4946. break;
  4947. }
  4948. $line = str_replace($oldPart, $part, $line);
  4949. }
  4950. $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
  4951. return $line;
  4952. }
  4953. /**
  4954. * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
  4955. * This function is about preserving long links in messages.
  4956. * Usage: 3
  4957. *
  4958. * @param string Message content
  4959. * @param string URL mode; "76" or "all"
  4960. * @param string URL of index script (see makeRedirectUrl())
  4961. * @return string Processed message content
  4962. * @see makeRedirectUrl()
  4963. */
  4964. public static function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
  4965. // Substitute URLs with shorter links:
  4966. foreach (array('http','https') as $protocol) {
  4967. $urlSplit = explode($protocol.'://',$message);
  4968. foreach ($urlSplit as $c => &$v) {
  4969. if ($c) {
  4970. $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
  4971. $newURL = $protocol.'://'.$newParts[0];
  4972. switch ((string)$urlmode) {
  4973. case 'all':
  4974. $newURL = self::makeRedirectUrl($newURL,0,$index_script_url);
  4975. break;
  4976. case '76':
  4977. $newURL = self::makeRedirectUrl($newURL,76,$index_script_url);
  4978. break;
  4979. }
  4980. $v = $newURL . substr($v,strlen($newParts[0]));
  4981. }
  4982. }
  4983. $message = implode('',$urlSplit);
  4984. }
  4985. return $message;
  4986. }
  4987. /**
  4988. * Subfunction for substUrlsInPlainText() above.
  4989. * Usage: 2
  4990. *
  4991. * @param string Input URL
  4992. * @param integer URL string length limit
  4993. * @param string URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR').'index.php'
  4994. * @return string Processed URL
  4995. */
  4996. public static function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
  4997. if (strlen($inUrl)>$l) {
  4998. $md5 = substr(md5($inUrl),0,20);
  4999. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  5000. '*',
  5001. 'cache_md5params',
  5002. 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
  5003. );
  5004. if (!$count) {
  5005. $insertFields = array(
  5006. 'md5hash' => $md5,
  5007. 'tstamp' => $GLOBALS['EXEC_TIME'],
  5008. 'type' => 2,
  5009. 'params' => $inUrl
  5010. );
  5011. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
  5012. }
  5013. $inUrl=($index_script_url ? $index_script_url : self::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
  5014. '?RDCT='.$md5;
  5015. }
  5016. return $inUrl;
  5017. }
  5018. /**
  5019. * Function to compensate for FreeType2 96 dpi
  5020. * Usage: 21
  5021. *
  5022. * @param integer Fontsize for freetype function call
  5023. * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
  5024. */
  5025. public static function freetypeDpiComp($font_size) {
  5026. $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
  5027. if ($dpi!=72) $font_size = $font_size/$dpi*72;
  5028. return $font_size;
  5029. }
  5030. /**
  5031. * Initialize the system log.
  5032. *
  5033. * @return void
  5034. * @see sysLog()
  5035. */
  5036. public static function initSysLog() {
  5037. global $TYPO3_CONF_VARS;
  5038. // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
  5039. // Note that TYPO3_REQUESTTYPE is not used here as it may not yet be defined
  5040. if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
  5041. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getHostname($requestHost=FALSE).':'.PATH_site;
  5042. }
  5043. // for Web logging name is <protocol>://<request-hostame>/<site-path>
  5044. else {
  5045. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getIndpEnv('TYPO3_SITE_URL');
  5046. }
  5047. // init custom logging
  5048. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  5049. $params = array('initLog'=>TRUE);
  5050. $fakeThis = FALSE;
  5051. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  5052. self::callUserFunction($hookMethod,$params,$fakeThis);
  5053. }
  5054. }
  5055. // init TYPO3 logging
  5056. foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
  5057. list($type,$destination) = explode(',',$log,3);
  5058. if ($type == 'syslog') {
  5059. if (TYPO3_OS == 'WIN') {
  5060. $facility = LOG_USER;
  5061. } else {
  5062. $facility = constant('LOG_'.strtoupper($destination));
  5063. }
  5064. openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
  5065. }
  5066. }
  5067. $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = self::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
  5068. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
  5069. }
  5070. /**
  5071. * Logs message to the system log.
  5072. * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
  5073. * If you want to implement the sysLog in your applications, simply add lines like:
  5074. * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
  5075. *
  5076. * @param string Message (in English).
  5077. * @param string Extension key (from which extension you are calling the log) or "Core"
  5078. * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
  5079. * @return void
  5080. */
  5081. public static function sysLog($msg, $extKey, $severity=0) {
  5082. global $TYPO3_CONF_VARS;
  5083. $severity = self::intInRange($severity,0,4);
  5084. // is message worth logging?
  5085. if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity) return;
  5086. // initialize logging
  5087. if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
  5088. self::initSysLog();
  5089. }
  5090. // do custom logging
  5091. if (isset($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
  5092. is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  5093. $params = array('msg'=>$msg, 'extKey'=>$extKey, 'backTrace'=>debug_backtrace(), 'severity'=>$severity);
  5094. $fakeThis = FALSE;
  5095. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  5096. self::callUserFunction($hookMethod,$params,$fakeThis);
  5097. }
  5098. }
  5099. // TYPO3 logging enabled?
  5100. if (!$TYPO3_CONF_VARS['SYS']['systemLog']) return;
  5101. $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
  5102. $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
  5103. // use all configured logging options
  5104. foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
  5105. list($type,$destination,$level) = explode(',',$log,4);
  5106. // is message worth logging for this log type?
  5107. if (intval($level) > $severity) continue;
  5108. $msgLine = ' - '.$extKey.': '.$msg;
  5109. // write message to a file
  5110. if ($type == 'file') {
  5111. $file = fopen($destination, 'a');
  5112. if ($file) {
  5113. flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
  5114. fwrite($file, date($dateFormat.' '.$timeFormat).$msgLine.LF);
  5115. flock($file, LOCK_UN); // release the lock
  5116. fclose($file);
  5117. }
  5118. }
  5119. // send message per mail
  5120. elseif ($type == 'mail') {
  5121. list($to,$from) = explode('/',$destination);
  5122. t3lib_utility_Mail::mail($to, 'Warning - error in TYPO3 installation',
  5123. 'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].LF.
  5124. 'Extension: '.$extKey.LF.
  5125. 'Severity: '.$severity.LF.
  5126. LF.$msg,
  5127. ($from ? 'From: '.$from : '')
  5128. );
  5129. }
  5130. // use the PHP error log
  5131. elseif ($type == 'error_log') {
  5132. error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
  5133. }
  5134. // use the system log
  5135. elseif ($type == 'syslog') {
  5136. $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
  5137. syslog($priority[(int)$severity], $msgLine);
  5138. }
  5139. }
  5140. }
  5141. /**
  5142. * Logs message to the development log.
  5143. * This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
  5144. * The result is meant to make sense to developers during development or debugging of a site.
  5145. * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
  5146. * If you want to implement the devLog in your applications, simply add lines like:
  5147. * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
  5148. *
  5149. * @param string Message (in english).
  5150. * @param string Extension key (from which extension you are calling the log)
  5151. * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
  5152. * @param array Additional data you want to pass to the logger.
  5153. * @return void
  5154. */
  5155. public static function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
  5156. global $TYPO3_CONF_VARS;
  5157. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
  5158. $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
  5159. $fakeThis = FALSE;
  5160. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
  5161. self::callUserFunction($hookMethod,$params,$fakeThis);
  5162. }
  5163. }
  5164. }
  5165. /**
  5166. * Writes a message to the deprecation log.
  5167. *
  5168. * @param string Message (in English).
  5169. * @return void
  5170. */
  5171. public static function deprecationLog($msg) {
  5172. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5173. return;
  5174. }
  5175. $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
  5176. $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
  5177. // legacy values (no strict comparison, $log can be boolean, string or int)
  5178. if ($log === TRUE || $log == '1') {
  5179. $log = 'file';
  5180. }
  5181. if (stripos($log, 'file') !== FALSE) {
  5182. // write a longer message to the deprecation log
  5183. $destination = self::getDeprecationLogFileName();
  5184. $file = @fopen($destination, 'a');
  5185. if ($file) {
  5186. flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
  5187. @fwrite($file, $date . $msg . LF);
  5188. flock($file, LOCK_UN); // release the lock
  5189. @fclose($file);
  5190. }
  5191. }
  5192. if (stripos($log, 'devlog') !== FALSE) {
  5193. // copy message also to the developer log
  5194. self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
  5195. }
  5196. if (stripos($log, 'console') !== FALSE) {
  5197. self::debug($msg, $date, 'Deprecation Log');
  5198. }
  5199. }
  5200. /**
  5201. * Gets the absolute path to the deprecation log file.
  5202. *
  5203. * @return string absolute path to the deprecation log file
  5204. */
  5205. public static function getDeprecationLogFileName() {
  5206. return PATH_typo3conf .
  5207. 'deprecation_' .
  5208. self::shortMD5(
  5209. PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
  5210. ) .
  5211. '.log';
  5212. }
  5213. /**
  5214. * Logs a call to a deprecated function.
  5215. * The log message will be taken from the annotation.
  5216. * @return void
  5217. */
  5218. public static function logDeprecatedFunction() {
  5219. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5220. return;
  5221. }
  5222. $trail = debug_backtrace();
  5223. if ($trail[1]['type']) {
  5224. $function = new ReflectionMethod($trail[1]['class'], $trail[1]['function']);
  5225. } else {
  5226. $function = new ReflectionFunction($trail[1]['function']);
  5227. }
  5228. $msg = '';
  5229. if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
  5230. $msg = $match[1];
  5231. }
  5232. // trigger PHP error with a short message: <function> is deprecated (called from <source>, defined in <source>)
  5233. $errorMsg = 'Function ' . $trail[1]['function'];
  5234. if ($trail[1]['class']) {
  5235. $errorMsg .= ' of class ' . $trail[1]['class'];
  5236. }
  5237. $errorMsg .= ' is deprecated (called from '.$trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
  5238. // write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>)
  5239. $logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
  5240. $logMsg .= '() - ' . $msg.' - ' . self::debug_trail();
  5241. $logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site)) . '#' . $function->getStartLine() . ')';
  5242. self::deprecationLog($logMsg);
  5243. }
  5244. /**
  5245. * Converts a one dimensional array to a one line string which can be used for logging or debugging output
  5246. * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
  5247. *
  5248. * @param array Data array which should be outputted
  5249. * @param mixed List of keys which should be listed in the output string. Pass a comma list or an array. An empty list outputs the whole array.
  5250. * @param integer Long string values are shortened to this length. Default: 20
  5251. * @return string Output string with key names and their value as string
  5252. */
  5253. public static function arrayToLogString(array $arr, $valueList=array(), $valueLength=20) {
  5254. $str = '';
  5255. if (!is_array($valueList)) {
  5256. $valueList = self::trimExplode(',', $valueList, 1);
  5257. }
  5258. $valListCnt = count($valueList);
  5259. foreach ($arr as $key => $value) {
  5260. if (!$valListCnt || in_array($key, $valueList)) {
  5261. $str .= (string)$key.trim(': '.self::fixed_lgd_cs(str_replace(LF,'|',(string)$value), $valueLength)).'; ';
  5262. }
  5263. }
  5264. return $str;
  5265. }
  5266. /**
  5267. * Compile the command for running ImageMagick/GraphicsMagick.
  5268. *
  5269. * @param string Command to be run: identify, convert or combine/composite
  5270. * @param string The parameters string
  5271. * @param string Override the default path
  5272. * @return string Compiled command that deals with IM6 & GraphicsMagick
  5273. */
  5274. public static function imageMagickCommand($command, $parameters, $path='') {
  5275. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  5276. $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
  5277. $switchCompositeParameters=false;
  5278. if(!$path) { $path = $gfxConf['im_path']; }
  5279. $im_version = strtolower($gfxConf['im_version_5']);
  5280. $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
  5281. if($command==='combine') { // This is only used internally, has no effect outside
  5282. $command = 'composite';
  5283. }
  5284. // Compile the path & command
  5285. if($im_version==='gm') {
  5286. $switchCompositeParameters=true;
  5287. $path .= 'gm'.$isExt.' '.$command;
  5288. } else {
  5289. if($im_version==='im6') { $switchCompositeParameters=true; }
  5290. $path .= (($command=='composite') ? $combineScript : $command).$isExt;
  5291. }
  5292. // strip profile information for thumbnails and reduce their size
  5293. if ($parameters && $command != 'identify' && $gfxConf['im_useStripProfileByDefault'] && $gfxConf['im_stripProfileCommand'] != '') {
  5294. if (strpos($parameters, $gfxConf['im_stripProfileCommand']) === false) {
  5295. // Determine whether the strip profile action has be disabled by TypoScript:
  5296. if ($parameters !== '-version' && strpos($parameters, '###SkipStripProfile###') === false) {
  5297. $parameters = $gfxConf['im_stripProfileCommand'] . ' ' . $parameters;
  5298. } else {
  5299. $parameters = str_replace('###SkipStripProfile###', '', $parameters);
  5300. }
  5301. }
  5302. }
  5303. $cmdLine = $path.' '.$parameters;
  5304. if($command=='composite' && $switchCompositeParameters) { // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
  5305. $paramsArr = self::unQuoteFilenames($parameters);
  5306. if(count($paramsArr)>5) { // The mask image has been specified => swap the parameters
  5307. $tmp = $paramsArr[count($paramsArr)-3];
  5308. $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
  5309. $paramsArr[count($paramsArr)-4] = $tmp;
  5310. }
  5311. $cmdLine = $path.' '.implode(' ', $paramsArr);
  5312. }
  5313. return $cmdLine;
  5314. }
  5315. /**
  5316. * Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. This is mostly needed by the imageMagickCommand function above.
  5317. *
  5318. * @param string The whole parameters string
  5319. * @param boolean If set, the elements of the resulting array are unquoted.
  5320. * @return array Exploded parameters
  5321. */
  5322. public static function unQuoteFilenames($parameters,$unQuote=FALSE) {
  5323. $paramsArr = explode(' ', trim($parameters));
  5324. $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
  5325. foreach ($paramsArr as $k => $v) {
  5326. if($quoteActive > -1) {
  5327. $paramsArr[$quoteActive] .= ' '.$v;
  5328. unset($paramsArr[$k]);
  5329. if(preg_match('/"$/', $v)) { $quoteActive = -1; }
  5330. } elseif(!trim($v)) {
  5331. unset($paramsArr[$k]); // Remove empty elements
  5332. } elseif(preg_match('/^"/', $v)) {
  5333. $quoteActive = $k;
  5334. }
  5335. }
  5336. if($unQuote) {
  5337. foreach ($paramsArr as $key => &$val) {
  5338. $val = preg_replace('/(^"|"$)/','',$val);
  5339. }
  5340. }
  5341. // return reindexed array
  5342. return array_values($paramsArr);
  5343. }
  5344. /**
  5345. * Quotes a string for usage as JS parameter. Depends whether the value is
  5346. * used in script tags (it doesn't need/must not get htmlspecialchar'ed in
  5347. * this case).
  5348. *
  5349. * @param string $value the string to encode, may be empty
  5350. * @param boolean $withinCData
  5351. * whether the escaped data is expected to be used as CDATA and thus
  5352. * does not need to be htmlspecialchared
  5353. *
  5354. * @return string the encoded value already quoted (with single quotes),
  5355. * will not be empty
  5356. */
  5357. static public function quoteJSvalue($value, $withinCData = false) {
  5358. $escapedValue = addcslashes(
  5359. $value, '\'' . '"' . '\\' . TAB . LF . CR
  5360. );
  5361. if (!$withinCData) {
  5362. $escapedValue = htmlspecialchars($escapedValue);
  5363. }
  5364. return '\'' . $escapedValue . '\'';
  5365. }
  5366. /**
  5367. * Ends and cleans all output buffers
  5368. *
  5369. * @return void
  5370. */
  5371. public static function cleanOutputBuffers() {
  5372. while (ob_get_level()) {
  5373. ob_end_clean();
  5374. }
  5375. header('Content-Encoding: None', TRUE);
  5376. }
  5377. /**
  5378. * Ends and flushes all output buffers
  5379. *
  5380. * @return void
  5381. */
  5382. public static function flushOutputBuffers() {
  5383. $obContent = '';
  5384. while (ob_get_level()) {
  5385. $obContent .= ob_get_clean();
  5386. }
  5387. // if previously a "Content-Encoding: whatever" has been set, we have to unset it
  5388. if (!headers_sent()) {
  5389. $headersList = headers_list();
  5390. foreach ($headersList as $header) {
  5391. // split it up at the :
  5392. list($key, $value) = self::trimExplode(':', $header, TRUE);
  5393. // check if we have a Content-Encoding other than 'None'
  5394. if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
  5395. header('Content-Encoding: None');
  5396. break;
  5397. }
  5398. }
  5399. }
  5400. echo $obContent;
  5401. }
  5402. }
  5403. ?>