PageRenderTime 92ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/t3lib/class.t3lib_div.php

https://bitbucket.org/linxpinx/mercurial
PHP | 6043 lines | 3381 code | 575 blank | 2087 comment | 766 complexity | ccb90cf4c442407c102e758f513a4319 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Unlicense, LGPL-2.1, Apache-2.0
  1. <?php
  2. /***************************************************************
  3. * Copyright notice
  4. *
  5. * (c) 1999-2010 Kasper Skaarhoj (kasperYYYY@typo3.com)
  6. * All rights reserved
  7. *
  8. * This script is part of the TYPO3 project. The TYPO3 project is
  9. * free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * The GNU General Public License can be found at
  15. * http://www.gnu.org/copyleft/gpl.html.
  16. * A copy is found in the textfile GPL.txt and important notices to the license
  17. * from the author is found in LICENSE.txt distributed with these scripts.
  18. *
  19. *
  20. * This script is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * This copyright notice MUST APPEAR in all copies of the script!
  26. ***************************************************************/
  27. /**
  28. * Contains the reknown class "t3lib_div" with general purpose functions
  29. *
  30. * $Id: class.t3lib_div.php 8446 2010-07-29 13:20:05Z dmitry $
  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. } elseif (TYPO3_OS == 'WIN') {
  1461. if (class_exists('COM')) {
  1462. try {
  1463. $com = new COM('CAPICOM.Utilities.1');
  1464. $output = base64_decode($com->GetRandom($count, 0));
  1465. } catch(Exception $e) {
  1466. // CAPICOM not installed
  1467. }
  1468. }
  1469. if ($output === '' && version_compare(PHP_VERSION, '5.3.0', '>=')) {
  1470. if (function_exists('mcrypt_create_iv')) {
  1471. $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
  1472. } elseif (function_exists('openssl_random_pseudo_bytes')) {
  1473. $isStrong = null;
  1474. $output = openssl_random_pseudo_bytes($count, $isStrong);
  1475. // skip ssl since it wasn't using the strong algo
  1476. if ($isStrong !== TRUE) {
  1477. $output = '';
  1478. }
  1479. }
  1480. }
  1481. }
  1482. // fallback if other random byte generation failed until now
  1483. if (!isset($output{$count - 1})) {
  1484. // We initialize with the somewhat random.
  1485. $randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
  1486. . base_convert(memory_get_usage() % pow(10, 6), 10, 2)
  1487. . microtime() . uniqid('') . getmypid();
  1488. while (!isset($output{$count - 1})) {
  1489. $randomState = sha1(microtime() . mt_rand() . $randomState);
  1490. $output .= sha1(mt_rand() . $randomState, true);
  1491. }
  1492. $output = substr($output, strlen($output) - $count, $count);
  1493. }
  1494. return $output;
  1495. }
  1496. /**
  1497. * Returns a hex representation of a random byte string.
  1498. *
  1499. * @param integer Number of hex characters to return
  1500. * @return string Random Bytes
  1501. */
  1502. public static function getRandomHexString($count) {
  1503. return substr(bin2hex(self::generateRandomBytes(intval(($count + 1) / 2))), 0, $count);
  1504. }
  1505. /**
  1506. * Returns a given string with underscores as UpperCamelCase.
  1507. * Example: Converts blog_example to BlogExample
  1508. *
  1509. * @param string $string: String to be converted to camel case
  1510. * @return string UpperCamelCasedWord
  1511. */
  1512. public static function underscoredToUpperCamelCase($string) {
  1513. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1514. return $upperCamelCase;
  1515. }
  1516. /**
  1517. * Returns a given string with underscores as lowerCamelCase.
  1518. * Example: Converts minimal_value to minimalValue
  1519. *
  1520. * @param string $string: String to be converted to camel case
  1521. * @return string lowerCamelCasedWord
  1522. */
  1523. public static function underscoredToLowerCamelCase($string) {
  1524. $upperCamelCase = str_replace(' ', '', ucwords(str_replace('_', ' ', self::strtolower($string))));
  1525. $lowerCamelCase = self::lcfirst($upperCamelCase);
  1526. return $lowerCamelCase;
  1527. }
  1528. /**
  1529. * Returns a given CamelCasedString as an lowercase string with underscores.
  1530. * Example: Converts BlogExample to blog_example, and minimalValue to minimal_value
  1531. *
  1532. * @param string $string: String to be converted to lowercase underscore
  1533. * @return string lowercase_and_underscored_string
  1534. */
  1535. public static function camelCaseToLowerCaseUnderscored($string) {
  1536. return self::strtolower(preg_replace('/(?<=\w)([A-Z])/', '_\\1', $string));
  1537. }
  1538. /**
  1539. * Converts the first char of a string to lowercase if it is a latin character (A-Z).
  1540. * Example: Converts "Hello World" to "hello World"
  1541. *
  1542. * @param string $string: The string to be used to lowercase the first character
  1543. * @return string The string with the first character as lowercase
  1544. */
  1545. public static function lcfirst($string) {
  1546. return self::strtolower(substr($string, 0, 1)) . substr($string, 1);
  1547. }
  1548. /**
  1549. * Checks if a given string is a Uniform Resource Locator (URL).
  1550. *
  1551. * @param string $url: The URL to be validated
  1552. * @return boolean Whether the given URL is valid
  1553. */
  1554. public static function isValidUrl($url) {
  1555. return (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== false);
  1556. }
  1557. /*************************
  1558. *
  1559. * ARRAY FUNCTIONS
  1560. *
  1561. *************************/
  1562. /**
  1563. * Check if an string item exists in an array.
  1564. * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
  1565. *
  1566. * Comparison to PHP in_array():
  1567. * -> $array = array(0, 1, 2, 3);
  1568. * -> variant_a := t3lib_div::inArray($array, $needle)
  1569. * -> variant_b := in_array($needle, $array)
  1570. * -> variant_c := in_array($needle, $array, true)
  1571. * +---------+-----------+-----------+-----------+
  1572. * | $needle | variant_a | variant_b | variant_c |
  1573. * +---------+-----------+-----------+-----------+
  1574. * | '1a' | false | true | false |
  1575. * | '' | false | true | false |
  1576. * | '0' | true | true | false |
  1577. * | 0 | true | true | true |
  1578. * +---------+-----------+-----------+-----------+
  1579. * Usage: 3
  1580. *
  1581. * @param array one-dimensional array of items
  1582. * @param string item to check for
  1583. * @return boolean true if $item is in the one-dimensional array $in_array
  1584. */
  1585. public static function inArray(array $in_array, $item) {
  1586. foreach ($in_array as $val) {
  1587. if (!is_array($val) && !strcmp($val, $item)) {
  1588. return true;
  1589. }
  1590. }
  1591. return false;
  1592. }
  1593. /**
  1594. * Explodes a $string delimited by $delim and passes each item in the array through intval().
  1595. * Corresponds to t3lib_div::trimExplode(), but with conversion to integers for all values.
  1596. * Usage: 76
  1597. *
  1598. * @param string Delimiter string to explode with
  1599. * @param string The string to explode
  1600. * @param boolean If set, all empty values (='') will NOT be set in output
  1601. * @param integer If positive, the result will contain a maximum of limit elements,
  1602. * if negative, all components except the last -limit are returned,
  1603. * if zero (default), the result is not limited at all
  1604. * @return array Exploded values, all converted to integers
  1605. */
  1606. public static function intExplode($delimiter, $string, $onlyNonEmptyValues = FALSE, $limit = 0) {
  1607. $explodedValues = self::trimExplode($delimiter, $string, $onlyNonEmptyValues, $limit);
  1608. return array_map('intval', $explodedValues);
  1609. }
  1610. /**
  1611. * Reverse explode which explodes the string counting from behind.
  1612. * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
  1613. * Usage: 8
  1614. *
  1615. * @param string Delimiter string to explode with
  1616. * @param string The string to explode
  1617. * @param integer Number of array entries
  1618. * @return array Exploded values
  1619. */
  1620. public static function revExplode($delimiter, $string, $count=0) {
  1621. $explodedValues = explode($delimiter, strrev($string), $count);
  1622. $explodedValues = array_map('strrev', $explodedValues);
  1623. return array_reverse($explodedValues);
  1624. }
  1625. /**
  1626. * Explodes a string and trims all values for whitespace in the ends.
  1627. * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
  1628. * Usage: 256
  1629. *
  1630. * @param string Delimiter string to explode with
  1631. * @param string The string to explode
  1632. * @param boolean If set, all empty values will be removed in output
  1633. * @param integer If positive, the result will contain a maximum of
  1634. * $limit elements, if negative, all components except
  1635. * the last -$limit are returned, if zero (default),
  1636. * the result is not limited at all. Attention though
  1637. * that the use of this parameter can slow down this
  1638. * function.
  1639. * @return array Exploded values
  1640. */
  1641. public static function trimExplode($delim, $string, $removeEmptyValues = false, $limit = 0) {
  1642. $explodedValues = explode($delim, $string);
  1643. $result = array_map('trim', $explodedValues);
  1644. if ($removeEmptyValues) {
  1645. $temp = array();
  1646. foreach($result as $value) {
  1647. if ($value !== '') {
  1648. $temp[] = $value;
  1649. }
  1650. }
  1651. $result = $temp;
  1652. }
  1653. if ($limit != 0) {
  1654. if ($limit < 0) {
  1655. $result = array_slice($result, 0, $limit);
  1656. } elseif (count($result) > $limit) {
  1657. $lastElements = array_slice($result, $limit - 1);
  1658. $result = array_slice($result, 0, $limit - 1);
  1659. $result[] = implode($delim, $lastElements);
  1660. }
  1661. }
  1662. return $result;
  1663. }
  1664. /**
  1665. * Remove duplicate values from an array
  1666. * Usage: 0
  1667. *
  1668. * @param array Array of values to make unique
  1669. * @return array
  1670. * @ignore
  1671. * @deprecated since TYPO3 3.5 - Use the PHP function array_unique instead
  1672. */
  1673. public static function uniqueArray(array $valueArray) {
  1674. self::logDeprecatedFunction();
  1675. return array_unique($valueArray);
  1676. }
  1677. /**
  1678. * Removes the value $cmpValue from the $array if found there. Returns the modified array
  1679. * Usage: 3
  1680. *
  1681. * @param array Array containing the values
  1682. * @param string Value to search for and if found remove array entry where found.
  1683. * @return array Output array with entries removed if search string is found
  1684. */
  1685. public static function removeArrayEntryByValue(array $array, $cmpValue) {
  1686. foreach ($array as $k => $v) {
  1687. if (is_array($v)) {
  1688. $array[$k] = self::removeArrayEntryByValue($v, $cmpValue);
  1689. } elseif (!strcmp($v, $cmpValue)) {
  1690. unset($array[$k]);
  1691. }
  1692. }
  1693. return $array;
  1694. }
  1695. /**
  1696. * Filters an array to reduce its elements to match the condition.
  1697. * The values in $keepItems can be optionally evaluated by a custom callback function.
  1698. *
  1699. * Example (arguments used to call this function):
  1700. * $array = array(
  1701. * array('aa' => array('first', 'second'),
  1702. * array('bb' => array('third', 'fourth'),
  1703. * array('cc' => array('fifth', 'sixth'),
  1704. * );
  1705. * $keepItems = array('third');
  1706. * $getValueFunc = create_function('$value', 'return $value[0];');
  1707. *
  1708. * Returns:
  1709. * array(
  1710. * array('bb' => array('third', 'fourth'),
  1711. * )
  1712. *
  1713. * @param array $array: The initial array to be filtered/reduced
  1714. * @param mixed $keepItems: The items which are allowed/kept in the array - accepts array or csv string
  1715. * @param string $getValueFunc: (optional) Unique function name set by create_function() used to get the value to keep
  1716. * @return array The filtered/reduced array with the kept items
  1717. */
  1718. public static function keepItemsInArray(array $array, $keepItems, $getValueFunc=null) {
  1719. if ($array) {
  1720. // Convert strings to arrays:
  1721. if (is_string($keepItems)) {
  1722. $keepItems = self::trimExplode(',', $keepItems);
  1723. }
  1724. // create_function() returns a string:
  1725. if (!is_string($getValueFunc)) {
  1726. $getValueFunc = null;
  1727. }
  1728. // Do the filtering:
  1729. if (is_array($keepItems) && count($keepItems)) {
  1730. foreach ($array as $key => $value) {
  1731. // Get the value to compare by using the callback function:
  1732. $keepValue = (isset($getValueFunc) ? $getValueFunc($value) : $value);
  1733. if (!in_array($keepValue, $keepItems)) {
  1734. unset($array[$key]);
  1735. }
  1736. }
  1737. }
  1738. }
  1739. return $array;
  1740. }
  1741. /**
  1742. * Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
  1743. * Usage: 24
  1744. *
  1745. * @param string Name prefix for entries. Set to blank if you wish none.
  1746. * @param array The (multidim) array to implode
  1747. * @param string (keep blank)
  1748. * @param boolean If set, parameters which were blank strings would be removed.
  1749. * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
  1750. * @return string Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3
  1751. * @see explodeUrl2Array()
  1752. */
  1753. public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) {
  1754. foreach($theArray as $Akey => $AVal) {
  1755. $thisKeyName = $name ? $name.'['.$Akey.']' : $Akey;
  1756. if (is_array($AVal)) {
  1757. $str = self::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
  1758. } else {
  1759. if (!$skipBlank || strcmp($AVal,'')) {
  1760. $str.='&'.($rawurlencodeParamName ? rawurlencode($thisKeyName) : $thisKeyName).
  1761. '='.rawurlencode($AVal);
  1762. }
  1763. }
  1764. }
  1765. return $str;
  1766. }
  1767. /**
  1768. * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
  1769. *
  1770. * @param string GETvars string
  1771. * @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())
  1772. * @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!
  1773. * @see implodeArrayForUrl()
  1774. */
  1775. public static function explodeUrl2Array($string,$multidim=FALSE) {
  1776. $output = array();
  1777. if ($multidim) {
  1778. parse_str($string,$output);
  1779. } else {
  1780. $p = explode('&',$string);
  1781. foreach($p as $v) {
  1782. if (strlen($v)) {
  1783. list($pK,$pV) = explode('=',$v,2);
  1784. $output[rawurldecode($pK)] = rawurldecode($pV);
  1785. }
  1786. }
  1787. }
  1788. return $output;
  1789. }
  1790. /**
  1791. * Returns an array with selected keys from incoming data.
  1792. * (Better read source code if you want to find out...)
  1793. * Usage: 3
  1794. *
  1795. * @param string List of variable/key names
  1796. * @param array Array from where to get values based on the keys in $varList
  1797. * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
  1798. * @return array Output array with selected variables.
  1799. */
  1800. public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
  1801. $keys = self::trimExplode(',',$varList,1);
  1802. $outArr = array();
  1803. foreach($keys as $v) {
  1804. if (isset($getArray[$v])) {
  1805. $outArr[$v] = $getArray[$v];
  1806. } elseif ($GPvarAlt) {
  1807. $outArr[$v] = self::_GP($v);
  1808. }
  1809. }
  1810. return $outArr;
  1811. }
  1812. /**
  1813. * AddSlash array
  1814. * This function traverses a multidimentional array and adds slashes to the values.
  1815. * NOTE that the input array is and argument by reference.!!
  1816. * Twin-function to stripSlashesOnArray
  1817. * Usage: 8
  1818. *
  1819. * @param array Multidimensional input array, (REFERENCE!)
  1820. * @return array
  1821. */
  1822. public static function addSlashesOnArray(array &$theArray) {
  1823. foreach ($theArray as &$value) {
  1824. if (is_array($value)) {
  1825. self::addSlashesOnArray($value);
  1826. } else {
  1827. $value = addslashes($value);
  1828. }
  1829. unset($value);
  1830. }
  1831. reset($theArray);
  1832. }
  1833. /**
  1834. * StripSlash array
  1835. * This function traverses a multidimentional array and strips slashes to the values.
  1836. * NOTE that the input array is and argument by reference.!!
  1837. * Twin-function to addSlashesOnArray
  1838. * Usage: 10
  1839. *
  1840. * @param array Multidimensional input array, (REFERENCE!)
  1841. * @return array
  1842. */
  1843. public static function stripSlashesOnArray(array &$theArray) {
  1844. foreach ($theArray as &$value) {
  1845. if (is_array($value)) {
  1846. self::stripSlashesOnArray($value);
  1847. } else {
  1848. $value = stripslashes($value);
  1849. }
  1850. unset($value);
  1851. }
  1852. reset($theArray);
  1853. }
  1854. /**
  1855. * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
  1856. * Usage: 0
  1857. *
  1858. * @param array Multidimensional input array
  1859. * @param string "add" or "strip", depending on usage you wish.
  1860. * @return array
  1861. */
  1862. public static function slashArray(array $arr,$cmd) {
  1863. if ($cmd=='strip') self::stripSlashesOnArray($arr);
  1864. if ($cmd=='add') self::addSlashesOnArray($arr);
  1865. return $arr;
  1866. }
  1867. /**
  1868. * Rename Array keys with a given mapping table
  1869. * @param array Array by reference which should be remapped
  1870. * @param array Array with remap information, array/$oldKey => $newKey)
  1871. */
  1872. function remapArrayKeys(&$array, $mappingTable) {
  1873. if (is_array($mappingTable)) {
  1874. foreach ($mappingTable as $old => $new) {
  1875. if ($new && isset($array[$old])) {
  1876. $array[$new] = $array[$old];
  1877. unset ($array[$old]);
  1878. }
  1879. }
  1880. }
  1881. }
  1882. /**
  1883. * Merges two arrays recursively and "binary safe" (integer keys are
  1884. * overridden as well), overruling similar values in the first array
  1885. * ($arr0) with the values of the second array ($arr1)
  1886. * In case of identical keys, ie. keeping the values of the second.
  1887. * Usage: 0
  1888. *
  1889. * @param array First array
  1890. * @param array Second array, overruling the first array
  1891. * @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.
  1892. * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: true
  1893. * @return array Resulting array where $arr1 values has overruled $arr0 values
  1894. */
  1895. public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
  1896. foreach ($arr1 as $key => $val) {
  1897. if(is_array($arr0[$key])) {
  1898. if (is_array($arr1[$key])) {
  1899. $arr0[$key] = self::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
  1900. }
  1901. } else {
  1902. if ($notAddKeys) {
  1903. if (isset($arr0[$key])) {
  1904. if ($includeEmtpyValues || $val) {
  1905. $arr0[$key] = $val;
  1906. }
  1907. }
  1908. } else {
  1909. if ($includeEmtpyValues || $val) {
  1910. $arr0[$key] = $val;
  1911. }
  1912. }
  1913. }
  1914. }
  1915. reset($arr0);
  1916. return $arr0;
  1917. }
  1918. /**
  1919. * 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.
  1920. * Usage: 16
  1921. *
  1922. * @param array First array
  1923. * @param array Second array
  1924. * @return array Merged result.
  1925. */
  1926. public static function array_merge(array $arr1,array $arr2) {
  1927. return $arr2+$arr1;
  1928. }
  1929. /**
  1930. * Filters keys off from first array that also exist in second array. Comparision is done by keys.
  1931. * This method is a recursive version of php array_diff_assoc()
  1932. *
  1933. * @param array Source array
  1934. * @param array Reduce source array by this array
  1935. * @return array Source array reduced by keys also present in second array
  1936. */
  1937. public static function arrayDiffAssocRecursive(array $array1, array $array2) {
  1938. $differenceArray = array();
  1939. foreach ($array1 as $key => $value) {
  1940. if (!array_key_exists($key, $array2)) {
  1941. $differenceArray[$key] = $value;
  1942. } elseif (is_array($value)) {
  1943. if (is_array($array2[$key])) {
  1944. $differenceArray[$key] = self::arrayDiffAssocRecursive($value, $array2[$key]);
  1945. }
  1946. }
  1947. }
  1948. return $differenceArray;
  1949. }
  1950. /**
  1951. * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
  1952. * Usage: 5
  1953. *
  1954. * @param array Input array of values
  1955. * @param string Delimited, default is comman
  1956. * @param string Quote-character to wrap around the values.
  1957. * @return string A single line of CSV
  1958. */
  1959. public static function csvValues(array $row,$delim=',',$quote='"') {
  1960. reset($row);
  1961. $out=array();
  1962. foreach ($row as $value) {
  1963. $out[] = str_replace($quote, $quote.$quote, $value);
  1964. }
  1965. $str = $quote.implode($quote.$delim.$quote,$out).$quote;
  1966. return $str;
  1967. }
  1968. /**
  1969. * Creates recursively a JSON literal from a multidimensional associative array.
  1970. * Uses native function of PHP >= 5.2.0
  1971. *
  1972. * @param array $jsonArray: The array to be transformed to JSON
  1973. * @return string JSON string
  1974. * @deprecated since TYPO3 4.3, use PHP native function json_encode() instead, will be removed in TYPO3 4.5
  1975. */
  1976. public static function array2json(array $jsonArray) {
  1977. self::logDeprecatedFunction();
  1978. return json_encode($jsonArray);
  1979. }
  1980. /**
  1981. * Removes dots "." from end of a key identifier of TypoScript styled array.
  1982. * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
  1983. *
  1984. * @param array $ts: TypoScript configuration array
  1985. * @return array TypoScript configuration array without dots at the end of all keys
  1986. */
  1987. public static function removeDotsFromTS(array $ts) {
  1988. $out = array();
  1989. foreach ($ts as $key => $value) {
  1990. if (is_array($value)) {
  1991. $key = rtrim($key, '.');
  1992. $out[$key] = self::removeDotsFromTS($value);
  1993. } else {
  1994. $out[$key] = $value;
  1995. }
  1996. }
  1997. return $out;
  1998. }
  1999. /*************************
  2000. *
  2001. * HTML/XML PROCESSING
  2002. *
  2003. *************************/
  2004. /**
  2005. * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
  2006. * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
  2007. * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
  2008. * Usage: 8
  2009. *
  2010. * @param string HTML-tag string (or attributes only)
  2011. * @return array Array with the attribute values.
  2012. */
  2013. public static function get_tag_attributes($tag) {
  2014. $components = self::split_tag_attributes($tag);
  2015. $name = ''; // attribute name is stored here
  2016. $valuemode = false;
  2017. $attributes = array();
  2018. foreach ($components as $key => $val) {
  2019. 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
  2020. if ($valuemode) {
  2021. if ($name) {
  2022. $attributes[$name] = $val;
  2023. $name = '';
  2024. }
  2025. } else {
  2026. if ($key = strtolower(preg_replace('/[^a-zA-Z0-9]/','',$val))) {
  2027. $attributes[$key] = '';
  2028. $name = $key;
  2029. }
  2030. }
  2031. $valuemode = false;
  2032. } else {
  2033. $valuemode = true;
  2034. }
  2035. }
  2036. return $attributes;
  2037. }
  2038. /**
  2039. * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
  2040. * Removes tag-name if found
  2041. * Usage: 2
  2042. *
  2043. * @param string HTML-tag string (or attributes only)
  2044. * @return array Array with the attribute values.
  2045. */
  2046. public static function split_tag_attributes($tag) {
  2047. $tag_tmp = trim(preg_replace('/^<[^[:space:]]*/','',trim($tag)));
  2048. // Removes any > in the end of the string
  2049. $tag_tmp = trim(rtrim($tag_tmp, '>'));
  2050. $value = array();
  2051. while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
  2052. $firstChar=substr($tag_tmp,0,1);
  2053. if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'")) {
  2054. $reg=explode($firstChar,$tag_tmp,3);
  2055. $value[]=$reg[1];
  2056. $tag_tmp=trim($reg[2]);
  2057. } elseif (!strcmp($firstChar,'=')) {
  2058. $value[] = '=';
  2059. $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
  2060. } else {
  2061. // There are '' around the value. We look for the next ' ' or '>'
  2062. $reg = preg_split('/[[:space:]=]/', $tag_tmp, 2);
  2063. $value[] = trim($reg[0]);
  2064. $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
  2065. }
  2066. }
  2067. reset($value);
  2068. return $value;
  2069. }
  2070. /**
  2071. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  2072. * Usage: 14
  2073. *
  2074. * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
  2075. * @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!
  2076. * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
  2077. * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
  2078. */
  2079. public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  2080. if ($xhtmlSafe) {
  2081. $newArr=array();
  2082. foreach($arr as $p => $v) {
  2083. if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
  2084. }
  2085. $arr = $newArr;
  2086. }
  2087. $list = array();
  2088. foreach($arr as $p => $v) {
  2089. if (strcmp($v,'') || $dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
  2090. }
  2091. return implode(' ',$list);
  2092. }
  2093. /**
  2094. * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
  2095. *
  2096. * @param array See implodeAttributes()
  2097. * @param boolean See implodeAttributes()
  2098. * @param boolean See implodeAttributes()
  2099. * @return string See implodeAttributes()
  2100. * @deprecated since TYPO3 3.7 - Name was changed into implodeAttributes
  2101. * @see implodeAttributes()
  2102. */
  2103. public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
  2104. self::logDeprecatedFunction();
  2105. return self::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
  2106. }
  2107. /**
  2108. * Wraps JavaScript code XHTML ready with <script>-tags
  2109. * Automatic re-identing of the JS code is done by using the first line as ident reference.
  2110. * This is nice for identing JS code with PHP code on the same level.
  2111. *
  2112. * @param string JavaScript code
  2113. * @param boolean Wrap script element in linebreaks? Default is TRUE.
  2114. * @return string The wrapped JS code, ready to put into a XHTML page
  2115. * @author Ingmar Schlecht <ingmars@web.de>
  2116. * @author René Fritz <r.fritz@colorcube.de>
  2117. */
  2118. public static function wrapJS($string, $linebreak=TRUE) {
  2119. if(trim($string)) {
  2120. // <script wrapped in nl?
  2121. $cr = $linebreak? LF : '';
  2122. // remove nl from the beginning
  2123. $string = preg_replace ('/^\n+/', '', $string);
  2124. // re-ident to one tab using the first line as reference
  2125. $match = array();
  2126. if(preg_match('/^(\t+)/',$string,$match)) {
  2127. $string = str_replace($match[1],TAB, $string);
  2128. }
  2129. $string = $cr.'<script type="text/javascript">
  2130. /*<![CDATA[*/
  2131. '.$string.'
  2132. /*]]>*/
  2133. </script>'.$cr;
  2134. }
  2135. return trim($string);
  2136. }
  2137. /**
  2138. * Parses XML input into a PHP array with associative keys
  2139. * Usage: 0
  2140. *
  2141. * @param string XML data input
  2142. * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
  2143. * @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.
  2144. * @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
  2145. */
  2146. public static function xml2tree($string,$depth=999) {
  2147. $parser = xml_parser_create();
  2148. $vals = array();
  2149. $index = array();
  2150. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  2151. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  2152. xml_parse_into_struct($parser, $string, $vals, $index);
  2153. if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  2154. xml_parser_free($parser);
  2155. $stack = array( array() );
  2156. $stacktop = 0;
  2157. $startPoint=0;
  2158. // FIXME don't use unset() - what does that mean? Use NULL or similar.
  2159. unset($tagi);
  2160. foreach($vals as $key => $val) {
  2161. $type = $val['type'];
  2162. // open tag:
  2163. if ($type=='open' || $type=='complete') {
  2164. $stack[$stacktop++] = $tagi;
  2165. if ($depth==$stacktop) {
  2166. $startPoint=$key;
  2167. }
  2168. $tagi = array('tag' => $val['tag']);
  2169. if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
  2170. if(isset($val['value'])) $tagi['values'][] = $val['value'];
  2171. }
  2172. // finish tag:
  2173. if ($type=='complete' || $type=='close') {
  2174. $oldtagi = $tagi;
  2175. $tagi = $stack[--$stacktop];
  2176. $oldtag = $oldtagi['tag'];
  2177. unset($oldtagi['tag']);
  2178. if ($depth==($stacktop+1)) {
  2179. if ($key-$startPoint > 0) {
  2180. $partArray = array_slice(
  2181. $vals,
  2182. $startPoint+1,
  2183. $key-$startPoint-1
  2184. );
  2185. #$oldtagi=array('XMLvalue'=>self::xmlRecompileFromStructValArray($partArray));
  2186. $oldtagi['XMLvalue']=self::xmlRecompileFromStructValArray($partArray);
  2187. } else {
  2188. $oldtagi['XMLvalue']=$oldtagi['values'][0];
  2189. }
  2190. }
  2191. $tagi['ch'][$oldtag][] = $oldtagi;
  2192. unset($oldtagi);
  2193. }
  2194. // cdata
  2195. if($type=='cdata') {
  2196. $tagi['values'][] = $val['value'];
  2197. }
  2198. }
  2199. return $tagi['ch'];
  2200. }
  2201. /**
  2202. * Turns PHP array into XML. See array2xml()
  2203. *
  2204. * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  2205. * @param string Alternative document tag. Default is "phparray".
  2206. * @param array Options for the compilation. See array2xml() for description.
  2207. * @param string Forced charset to prologue
  2208. * @return string An XML string made from the input content in the array.
  2209. * @see xml2array(),array2xml()
  2210. */
  2211. public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
  2212. // Figure out charset if not given explicitly:
  2213. if (!$charset) {
  2214. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
  2215. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
  2216. } elseif (is_object($GLOBALS['LANG'])) {
  2217. $charset = $GLOBALS['LANG']->charSet; // If "LANG" is around, that will hold the current charset
  2218. } else {
  2219. $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
  2220. }
  2221. }
  2222. // Return XML:
  2223. return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.LF.
  2224. self::array2xml($array,'',0,$docTag,0, $options);
  2225. }
  2226. /**
  2227. * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
  2228. *
  2229. * Converts a PHP array into an XML string.
  2230. * The XML output is optimized for readability since associative keys are used as tagnames.
  2231. * 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.
  2232. * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
  2233. * 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
  2234. * 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.
  2235. * 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!
  2236. * 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...
  2237. * Usage: 5
  2238. *
  2239. * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
  2240. * @param string tag-prefix, eg. a namespace prefix like "T3:"
  2241. * @param integer Current recursion level. Don't change, stay at zero!
  2242. * @param string Alternative document tag. Default is "phparray".
  2243. * @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
  2244. * @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')
  2245. * @param string Stack data. Don't touch.
  2246. * @return string An XML string made from the input content in the array.
  2247. * @see xml2array()
  2248. */
  2249. public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
  2250. // 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
  2251. $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
  2252. chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
  2253. chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
  2254. chr(30).chr(31);
  2255. // Set indenting mode:
  2256. $indentChar = $spaceInd ? ' ' : TAB;
  2257. $indentN = $spaceInd>0 ? $spaceInd : 1;
  2258. $nl = ($spaceInd >= 0 ? LF : '');
  2259. // Init output variable:
  2260. $output='';
  2261. // Traverse the input array
  2262. foreach($array as $k=>$v) {
  2263. $attr = '';
  2264. $tagName = $k;
  2265. // Construct the tag name.
  2266. if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
  2267. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2268. $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
  2269. }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && self::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
  2270. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2271. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
  2272. }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
  2273. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2274. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
  2275. } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
  2276. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2277. $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
  2278. } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
  2279. if ($options['useNindex']) { // If numeric key, prefix "n"
  2280. $tagName = 'n'.$tagName;
  2281. } else { // Use special tag for num. keys:
  2282. $attr.=' index="'.$tagName.'"';
  2283. $tagName = $options['useIndexTagForNum'] ? $options['useIndexTagForNum'] : 'numIndex';
  2284. }
  2285. } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
  2286. $attr.=' index="'.htmlspecialchars($tagName).'"';
  2287. $tagName = $options['useIndexTagForAssoc'];
  2288. }
  2289. // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
  2290. $tagName = substr(preg_replace('/[^[:alnum:]_-]/','',$tagName),0,100);
  2291. // If the value is an array then we will call this function recursively:
  2292. if (is_array($v)) {
  2293. // Sub elements:
  2294. if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
  2295. $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
  2296. $clearStackPath = $subOptions['clearStackPath'];
  2297. } else {
  2298. $subOptions = $options;
  2299. $clearStackPath = FALSE;
  2300. }
  2301. $content = $nl .
  2302. self::array2xml(
  2303. $v,
  2304. $NSprefix,
  2305. $level+1,
  2306. '',
  2307. $spaceInd,
  2308. $subOptions,
  2309. array(
  2310. 'parentTagName' => $tagName,
  2311. 'grandParentTagName' => $stackData['parentTagName'],
  2312. 'path' => $clearStackPath ? '' : $stackData['path'].'/'.$tagName,
  2313. )
  2314. ).
  2315. ($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '');
  2316. if ((int)$options['disableTypeAttrib']!=2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
  2317. $attr.=' type="array"';
  2318. }
  2319. } else { // Just a value:
  2320. // Look for binary chars:
  2321. $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
  2322. 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!
  2323. // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
  2324. $content = $nl.chunk_split(base64_encode($v));
  2325. $attr.=' base64="1"';
  2326. } else {
  2327. // Otherwise, just htmlspecialchar the stuff:
  2328. $content = htmlspecialchars($v);
  2329. $dType = gettype($v);
  2330. if ($dType == 'string') {
  2331. if ($options['useCDATA'] && $content != $v) {
  2332. $content = '<![CDATA[' . $v . ']]>';
  2333. }
  2334. } elseif (!$options['disableTypeAttrib']) {
  2335. $attr.= ' type="'.$dType.'"';
  2336. }
  2337. }
  2338. }
  2339. // Add the element to the output string:
  2340. $output.=($spaceInd >= 0 ? str_pad('',($level+1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
  2341. }
  2342. // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
  2343. if (!$level) {
  2344. $output =
  2345. '<'.$docTag.'>'.$nl.
  2346. $output.
  2347. '</'.$docTag.'>';
  2348. }
  2349. return $output;
  2350. }
  2351. /**
  2352. * Converts an XML string to a PHP array.
  2353. * This is the reverse function of array2xml()
  2354. * This is a wrapper for xml2arrayProcess that adds a two-level cache
  2355. * Usage: 17
  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(),xml2arrayProcess()
  2362. * @author Fabrizio Branca <typo3@fabrizio-branca.de> (added caching)
  2363. */
  2364. public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
  2365. static $firstLevelCache = array();
  2366. $identifier = md5($string . $NSprefix . ($reportDocTag ? '1' : '0'));
  2367. // look up in first level cache
  2368. if (!empty($firstLevelCache[$identifier])) {
  2369. $array = $firstLevelCache[$identifier];
  2370. } else {
  2371. // look up in second level cache
  2372. $cacheContent = t3lib_pageSelect::getHash($identifier, 0);
  2373. $array = unserialize($cacheContent);
  2374. if ($array === false) {
  2375. $array = self::xml2arrayProcess($string, $NSprefix, $reportDocTag);
  2376. t3lib_pageSelect::storeHash($identifier, serialize($array), 'ident_xml2array');
  2377. }
  2378. // store content in first level cache
  2379. $firstLevelCache[$identifier] = $array;
  2380. }
  2381. return $array;
  2382. }
  2383. /**
  2384. * Converts an XML string to a PHP array.
  2385. * This is the reverse function of array2xml()
  2386. * Usage: 1
  2387. *
  2388. * @param string XML content to convert into an array
  2389. * @param string The tag-prefix resolve, eg. a namespace like "T3:"
  2390. * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
  2391. * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
  2392. * @see array2xml()
  2393. */
  2394. protected function xml2arrayProcess($string,$NSprefix='',$reportDocTag=FALSE) {
  2395. global $TYPO3_CONF_VARS;
  2396. // Create parser:
  2397. $parser = xml_parser_create();
  2398. $vals = array();
  2399. $index = array();
  2400. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  2401. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  2402. // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
  2403. $match = array();
  2404. preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
  2405. $theCharset = $match[1] ? $match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
  2406. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
  2407. // Parse content:
  2408. xml_parse_into_struct($parser, $string, $vals, $index);
  2409. // If error, return error message:
  2410. if (xml_get_error_code($parser)) {
  2411. return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
  2412. }
  2413. xml_parser_free($parser);
  2414. // Init vars:
  2415. $stack = array(array());
  2416. $stacktop = 0;
  2417. $current = array();
  2418. $tagName = '';
  2419. $documentTag = '';
  2420. // Traverse the parsed XML structure:
  2421. foreach($vals as $key => $val) {
  2422. // First, process the tag-name (which is used in both cases, whether "complete" or "close")
  2423. $tagName = $val['tag'];
  2424. if (!$documentTag) $documentTag = $tagName;
  2425. // Test for name space:
  2426. $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ? substr($tagName,strlen($NSprefix)) : $tagName;
  2427. // Test for numeric tag, encoded on the form "nXXX":
  2428. $testNtag = substr($tagName,1); // Closing tag.
  2429. $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ? intval($testNtag) : $tagName;
  2430. // Test for alternative index value:
  2431. if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
  2432. // Setting tag-values, manage stack:
  2433. switch($val['type']) {
  2434. case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
  2435. $current[$tagName] = array(); // Setting blank place holder
  2436. $stack[$stacktop++] = $current;
  2437. $current = array();
  2438. break;
  2439. case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
  2440. $oldCurrent = $current;
  2441. $current = $stack[--$stacktop];
  2442. end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
  2443. $current[key($current)] = $oldCurrent;
  2444. unset($oldCurrent);
  2445. break;
  2446. case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
  2447. if ($val['attributes']['base64']) {
  2448. $current[$tagName] = base64_decode($val['value']);
  2449. } else {
  2450. $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
  2451. // Cast type:
  2452. switch((string)$val['attributes']['type']) {
  2453. case 'integer':
  2454. $current[$tagName] = (integer)$current[$tagName];
  2455. break;
  2456. case 'double':
  2457. $current[$tagName] = (double)$current[$tagName];
  2458. break;
  2459. case 'boolean':
  2460. $current[$tagName] = (bool)$current[$tagName];
  2461. break;
  2462. case 'array':
  2463. $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...
  2464. break;
  2465. }
  2466. }
  2467. break;
  2468. }
  2469. }
  2470. if ($reportDocTag) {
  2471. $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
  2472. }
  2473. // Finally return the content of the document tag.
  2474. return $current[$tagName];
  2475. }
  2476. /**
  2477. * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
  2478. * Usage: 2
  2479. *
  2480. * @param array A array of XML parts, see xml2tree
  2481. * @return string Re-compiled XML data.
  2482. */
  2483. public static function xmlRecompileFromStructValArray(array $vals) {
  2484. $XMLcontent='';
  2485. foreach($vals as $val) {
  2486. $type = $val['type'];
  2487. // open tag:
  2488. if ($type=='open' || $type=='complete') {
  2489. $XMLcontent.='<'.$val['tag'];
  2490. if(isset($val['attributes'])) {
  2491. foreach($val['attributes'] as $k => $v) {
  2492. $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
  2493. }
  2494. }
  2495. if ($type=='complete') {
  2496. if(isset($val['value'])) {
  2497. $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
  2498. } else $XMLcontent.='/>';
  2499. } else $XMLcontent.='>';
  2500. if ($type=='open' && isset($val['value'])) {
  2501. $XMLcontent.=htmlspecialchars($val['value']);
  2502. }
  2503. }
  2504. // finish tag:
  2505. if ($type=='close') {
  2506. $XMLcontent.='</'.$val['tag'].'>';
  2507. }
  2508. // cdata
  2509. if($type=='cdata') {
  2510. $XMLcontent.=htmlspecialchars($val['value']);
  2511. }
  2512. }
  2513. return $XMLcontent;
  2514. }
  2515. /**
  2516. * Extracts the attributes (typically encoding and version) of an XML prologue (header).
  2517. * Usage: 1
  2518. *
  2519. * @param string XML data
  2520. * @return array Attributes of the xml prologue (header)
  2521. */
  2522. public static function xmlGetHeaderAttribs($xmlData) {
  2523. $match = array();
  2524. if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
  2525. return self::get_tag_attributes($match[1]);
  2526. }
  2527. }
  2528. /**
  2529. * Minifies JavaScript
  2530. *
  2531. * @param string $script Script to minify
  2532. * @param string $error Error message (if any)
  2533. * @return string Minified script or source string if error happened
  2534. */
  2535. public static function minifyJavaScript($script, &$error = '') {
  2536. require_once(PATH_typo3 . 'contrib/jsmin/jsmin.php');
  2537. try {
  2538. $error = '';
  2539. $script = trim(JSMin::minify(str_replace(CR, '', $script)));
  2540. }
  2541. catch(JSMinException $e) {
  2542. $error = 'Error while minifying JavaScript: ' . $e->getMessage();
  2543. self::devLog($error, 't3lib_div', 2,
  2544. array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
  2545. }
  2546. return $script;
  2547. }
  2548. /*************************
  2549. *
  2550. * FILES FUNCTIONS
  2551. *
  2552. *************************/
  2553. /**
  2554. * Reads the file or url $url and returns the content
  2555. * 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.
  2556. * Usage: 83
  2557. *
  2558. * @param string File/URL to read
  2559. * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
  2560. * @param array HTTP headers to be used in the request
  2561. * @param array Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
  2562. * @return string The content from the resource given as input. FALSE if an error has occured.
  2563. */
  2564. public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) {
  2565. $content = false;
  2566. if (isset($report)) {
  2567. $report['error'] = 0;
  2568. $report['message'] = '';
  2569. }
  2570. // use cURL for: http, https, ftp, ftps, sftp and scp
  2571. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
  2572. if (isset($report)) {
  2573. $report['lib'] = 'cURL';
  2574. }
  2575. // External URL without error checking.
  2576. $ch = curl_init();
  2577. if (!$ch) {
  2578. if (isset($report)) {
  2579. $report['error'] = -1;
  2580. $report['message'] = 'Couldn\'t initialize cURL.';
  2581. }
  2582. return false;
  2583. }
  2584. curl_setopt($ch, CURLOPT_URL, $url);
  2585. curl_setopt($ch, CURLOPT_HEADER, $includeHeader ? 1 : 0);
  2586. curl_setopt($ch, CURLOPT_NOBODY, $includeHeader == 2 ? 1 : 0);
  2587. curl_setopt($ch, CURLOPT_HTTPGET, $includeHeader == 2 ? 'HEAD' : 'GET');
  2588. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  2589. curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  2590. // may fail (PHP 5.2.0+ and 5.1.5+) when open_basedir or safe_mode are enabled
  2591. $followLocation = @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  2592. if (is_array($requestHeaders)) {
  2593. curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
  2594. }
  2595. // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
  2596. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
  2597. curl_setopt($ch, CURLOPT_PROXY, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
  2598. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
  2599. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
  2600. }
  2601. if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
  2602. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
  2603. }
  2604. }
  2605. $content = curl_exec($ch);
  2606. if (isset($report)) {
  2607. if ($content===FALSE) {
  2608. $report['error'] = curl_errno($ch);
  2609. $report['message'] = curl_error($ch);
  2610. } else {
  2611. $curlInfo = curl_getinfo($ch);
  2612. // We hit a redirection but we couldn't follow it
  2613. if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
  2614. $report['error'] = -1;
  2615. $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
  2616. } elseif($includeHeader) {
  2617. // Set only for $includeHeader to work exactly like PHP variant
  2618. $report['http_code'] = $curlInfo['http_code'];
  2619. $report['content_type'] = $curlInfo['content_type'];
  2620. }
  2621. }
  2622. }
  2623. curl_close($ch);
  2624. } elseif ($includeHeader) {
  2625. if (isset($report)) {
  2626. $report['lib'] = 'socket';
  2627. }
  2628. $parsedURL = parse_url($url);
  2629. if (!preg_match('/^https?/', $parsedURL['scheme'])) {
  2630. if (isset($report)) {
  2631. $report['error'] = -1;
  2632. $report['message'] = 'Reading headers is not allowed for this protocol.';
  2633. }
  2634. return false;
  2635. }
  2636. $port = intval($parsedURL['port']);
  2637. if ($port < 1) {
  2638. if ($parsedURL['scheme'] == 'http') {
  2639. $port = ($port>0 ? $port : 80);
  2640. $scheme = '';
  2641. } else {
  2642. $port = ($port>0 ? $port : 443);
  2643. $scheme = 'ssl://';
  2644. }
  2645. }
  2646. $errno = 0;
  2647. // $errstr = '';
  2648. $fp = @fsockopen($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
  2649. if (!$fp || $errno > 0) {
  2650. if (isset($report)) {
  2651. $report['error'] = $errno ? $errno : -1;
  2652. $report['message'] = $errno ? ($errstr ? $errstr : 'Socket error.') : 'Socket initialization error.';
  2653. }
  2654. return false;
  2655. }
  2656. $method = ($includeHeader == 2) ? 'HEAD' : 'GET';
  2657. $msg = $method . ' ' . $parsedURL['path'] .
  2658. ($parsedURL['query'] ? '?' . $parsedURL['query'] : '') .
  2659. ' HTTP/1.0' . CRLF . 'Host: ' .
  2660. $parsedURL['host'] . "\r\nConnection: close\r\n";
  2661. if (is_array($requestHeaders)) {
  2662. $msg .= implode(CRLF, $requestHeaders) . CRLF;
  2663. }
  2664. $msg .= CRLF;
  2665. fputs($fp, $msg);
  2666. while (!feof($fp)) {
  2667. $line = fgets($fp, 2048);
  2668. if (isset($report)) {
  2669. if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
  2670. $report['http_code'] = $status[1];
  2671. }
  2672. elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
  2673. $report['content_type'] = $type[1];
  2674. }
  2675. }
  2676. $content .= $line;
  2677. if (!strlen(trim($line))) {
  2678. break; // Stop at the first empty line (= end of header)
  2679. }
  2680. }
  2681. if ($includeHeader != 2) {
  2682. $content .= stream_get_contents($fp);
  2683. }
  2684. fclose($fp);
  2685. } elseif (is_array($requestHeaders)) {
  2686. if (isset($report)) {
  2687. $report['lib'] = 'file/context';
  2688. }
  2689. $parsedURL = parse_url($url);
  2690. if (!preg_match('/^https?/', $parsedURL['scheme'])) {
  2691. if (isset($report)) {
  2692. $report['error'] = -1;
  2693. $report['message'] = 'Sending request headers is not allowed for this protocol.';
  2694. }
  2695. return false;
  2696. }
  2697. $ctx = stream_context_create(array(
  2698. 'http' => array(
  2699. 'header' => implode(CRLF, $requestHeaders)
  2700. )
  2701. )
  2702. );
  2703. $content = @file_get_contents($url, false, $ctx);
  2704. if ($content === false && isset($report)) {
  2705. $phpError = error_get_last();
  2706. $report['error'] = $phpError['type'];
  2707. $report['message'] = $phpError['message'];
  2708. }
  2709. } else {
  2710. if (isset($report)) {
  2711. $report['lib'] = 'file';
  2712. }
  2713. $content = @file_get_contents($url);
  2714. if ($content === false && isset($report)) {
  2715. if (function_exists('error_get_last')) {
  2716. $phpError = error_get_last();
  2717. $report['error'] = $phpError['type'];
  2718. $report['message'] = $phpError['message'];
  2719. } else {
  2720. $report['error'] = -1;
  2721. $report['message'] = 'Couldn\'t get URL.';
  2722. }
  2723. }
  2724. }
  2725. return $content;
  2726. }
  2727. /**
  2728. * Writes $content to the file $file
  2729. * Usage: 30
  2730. *
  2731. * @param string Filepath to write to
  2732. * @param string Content to write
  2733. * @return boolean True if the file was successfully opened and written to.
  2734. */
  2735. public static function writeFile($file,$content) {
  2736. if (!@is_file($file)) $changePermissions = true;
  2737. if ($fd = fopen($file,'wb')) {
  2738. $res = fwrite($fd,$content);
  2739. fclose($fd);
  2740. if ($res===false) return false;
  2741. if ($changePermissions) { // Change the permissions only if the file has just been created
  2742. self::fixPermissions($file);
  2743. }
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. /**
  2749. * Sets the file system mode and group ownership of a file or a folder.
  2750. *
  2751. * @param string Absolute filepath of file or folder, must not be escaped.
  2752. * @param boolean If set, also fixes permissions of files and folders in the folder (if $path is a folder)
  2753. * @return mixed TRUE on success, FALSE on error, always TRUE on Windows OS
  2754. */
  2755. public static function fixPermissions($path, $recursive = FALSE) {
  2756. if (TYPO3_OS != 'WIN') {
  2757. $result = FALSE;
  2758. if (self::isAllowedAbsPath($path)) {
  2759. if (@is_file($path)) {
  2760. // "@" is there because file is not necessarily OWNED by the user
  2761. $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
  2762. } elseif (@is_dir($path)) {
  2763. $path = preg_replace('|/$|', '', $path);
  2764. // "@" is there because file is not necessarily OWNED by the user
  2765. $result = @chmod($path, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
  2766. }
  2767. // Set createGroup if not empty
  2768. if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) {
  2769. // "@" is there because file is not necessarily OWNED by the user
  2770. $changeGroupResult = @chgrp($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
  2771. $result = $changeGroupResult ? $result : FALSE;
  2772. }
  2773. // Call recursive if recursive flag if set and $path is directory
  2774. if ($recursive && @is_dir($path)) {
  2775. $handle = opendir($path);
  2776. while (($file = readdir($handle)) !== FALSE) {
  2777. unset($recursionResult);
  2778. if ($file !== '.' && $file !== '..') {
  2779. if (@is_file($path . '/' . $file)) {
  2780. $recursionResult = self::fixPermissions($path . '/' . $file);
  2781. } elseif (@is_dir($path . '/' . $file)) {
  2782. $recursionResult = self::fixPermissions($path . '/' . $file, TRUE);
  2783. }
  2784. if (isset($recursionResult) && !$recursionResult) {
  2785. $result = FALSE;
  2786. }
  2787. }
  2788. }
  2789. closedir($handle);
  2790. }
  2791. }
  2792. } else {
  2793. $result = TRUE;
  2794. }
  2795. return $result;
  2796. }
  2797. /**
  2798. * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
  2799. * Accepts an additional subdirectory in the file path!
  2800. *
  2801. * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
  2802. * @param string Content string to write
  2803. * @return string Returns false on success, otherwise an error string telling about the problem.
  2804. */
  2805. public static function writeFileToTypo3tempDir($filepath,$content) {
  2806. // Parse filepath into directory and basename:
  2807. $fI = pathinfo($filepath);
  2808. $fI['dirname'].= '/';
  2809. // Check parts:
  2810. if (self::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
  2811. if (defined('PATH_site')) {
  2812. $dirName = PATH_site.'typo3temp/'; // Setting main temporary directory name (standard)
  2813. if (@is_dir($dirName)) {
  2814. if (self::isFirstPartOfStr($fI['dirname'],$dirName)) {
  2815. // Checking if the "subdir" is found:
  2816. $subdir = substr($fI['dirname'],strlen($dirName));
  2817. if ($subdir) {
  2818. if (preg_match('/^[[:alnum:]_]+\/$/',$subdir) || preg_match('/^[[:alnum:]_]+\/[[:alnum:]_]+\/$/',$subdir)) {
  2819. $dirName.= $subdir;
  2820. if (!@is_dir($dirName)) {
  2821. self::mkdir_deep(PATH_site.'typo3temp/', $subdir);
  2822. }
  2823. } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
  2824. }
  2825. // Checking dir-name again (sub-dir might have been created):
  2826. if (@is_dir($dirName)) {
  2827. if ($filepath == $dirName.$fI['basename']) {
  2828. self::writeFile($filepath, $content);
  2829. if (!@is_file($filepath)) return 'File not written to disk! Write permission error in filesystem?';
  2830. } else return 'Calculated filelocation didn\'t match input $filepath!';
  2831. } else return '"'.$dirName.'" is not a directory!';
  2832. } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
  2833. } else return 'PATH_site + "typo3temp/" was not a directory!';
  2834. } else return 'PATH_site constant was NOT defined!';
  2835. } else return 'Input filepath "'.$filepath.'" was generally invalid!';
  2836. }
  2837. /**
  2838. * Wrapper function for mkdir.
  2839. * Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']
  2840. * and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
  2841. *
  2842. * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
  2843. * @return boolean TRUE if @mkdir went well!
  2844. */
  2845. public static function mkdir($newFolder) {
  2846. $newFolder = preg_replace('|/$|', '', $newFolder);
  2847. $result = @mkdir($newFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']));
  2848. if ($result) {
  2849. self::fixPermissions($newFolder);
  2850. }
  2851. return $result;
  2852. }
  2853. /**
  2854. * Creates a directory - including parent directories if necessary - in the file system
  2855. *
  2856. * @param string Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
  2857. * @param string Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
  2858. * @return string If error, returns error string.
  2859. */
  2860. public static function mkdir_deep($destination,$deepDir) {
  2861. $allParts = self::trimExplode('/',$deepDir,1);
  2862. $root = '';
  2863. foreach($allParts as $part) {
  2864. $root.= $part.'/';
  2865. if (!is_dir($destination.$root)) {
  2866. self::mkdir($destination.$root);
  2867. if (!@is_dir($destination.$root)) {
  2868. return 'Error: The directory "'.$destination.$root.'" could not be created...';
  2869. }
  2870. }
  2871. }
  2872. }
  2873. /**
  2874. * Wrapper function for rmdir, allowing recursive deletion of folders and files
  2875. *
  2876. * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
  2877. * @param boolean Allow deletion of non-empty directories
  2878. * @return boolean true if @rmdir went well!
  2879. */
  2880. public static function rmdir($path,$removeNonEmpty=false) {
  2881. $OK = false;
  2882. $path = preg_replace('|/$|','',$path); // Remove trailing slash
  2883. if (file_exists($path)) {
  2884. $OK = true;
  2885. if (is_dir($path)) {
  2886. if ($removeNonEmpty==true && $handle = opendir($path)) {
  2887. while ($OK && false !== ($file = readdir($handle))) {
  2888. if ($file=='.' || $file=='..') continue;
  2889. $OK = self::rmdir($path.'/'.$file,$removeNonEmpty);
  2890. }
  2891. closedir($handle);
  2892. }
  2893. if ($OK) { $OK = rmdir($path); }
  2894. } else { // If $dirname is a file, simply remove it
  2895. $OK = unlink($path);
  2896. }
  2897. clearstatcache();
  2898. }
  2899. return $OK;
  2900. }
  2901. /**
  2902. * Returns an array with the names of folders in a specific path
  2903. * Will return 'error' (string) if there were an error with reading directory content.
  2904. * Usage: 11
  2905. *
  2906. * @param string Path to list directories from
  2907. * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
  2908. */
  2909. public static function get_dirs($path) {
  2910. if ($path) {
  2911. if (is_dir($path)) {
  2912. $dir = scandir($path);
  2913. $dirs = array();
  2914. foreach ($dir as $entry) {
  2915. if (is_dir($path . '/' . $entry) && $entry != '..' && $entry != '.') {
  2916. $dirs[] = $entry;
  2917. }
  2918. }
  2919. } else {
  2920. $dirs = 'error';
  2921. }
  2922. }
  2923. return $dirs;
  2924. }
  2925. /**
  2926. * Returns an array with the names of files in a specific path
  2927. * Usage: 18
  2928. *
  2929. * @param string $path: Is the path to the file
  2930. * @param string $extensionList is the comma list of extensions to read only (blank = all)
  2931. * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
  2932. * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
  2933. * @param string A comma seperated list of filenames to exclude, no wildcards
  2934. * @return array Array of the files found
  2935. */
  2936. public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
  2937. // Initialize variabels:
  2938. $filearray = array();
  2939. $sortarray = array();
  2940. $path = rtrim($path, '/');
  2941. // Find files+directories:
  2942. if (@is_dir($path)) {
  2943. $extensionList = strtolower($extensionList);
  2944. $d = dir($path);
  2945. if (is_object($d)) {
  2946. while($entry=$d->read()) {
  2947. if (@is_file($path.'/'.$entry)) {
  2948. $fI = pathinfo($entry);
  2949. $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)
  2950. if ((!strlen($extensionList) || self::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$entry))) {
  2951. $filearray[$key]=($prependPath?$path.'/':'').$entry;
  2952. if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
  2953. elseif ($order) {$sortarray[$key]=$entry;}
  2954. }
  2955. }
  2956. }
  2957. $d->close();
  2958. } else return 'error opening path: "'.$path.'"';
  2959. }
  2960. // Sort them:
  2961. if ($order) {
  2962. asort($sortarray);
  2963. $newArr=array();
  2964. foreach ($sortarray as $k => $v) {
  2965. $newArr[$k]=$filearray[$k];
  2966. }
  2967. $filearray=$newArr;
  2968. }
  2969. // Return result
  2970. reset($filearray);
  2971. return $filearray;
  2972. }
  2973. /**
  2974. * Recursively gather all files and folders of a path.
  2975. * Usage: 5
  2976. *
  2977. * @param array $fileArr: Empty input array (will have files added to it)
  2978. * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
  2979. * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
  2980. * @param boolean $regDirs: If set, directories are also included in output.
  2981. * @param integer $recursivityLevels: The number of levels to dig down...
  2982. * @param string $excludePattern: regex pattern of files/directories to exclude
  2983. * @return array An array with the found files/directories.
  2984. */
  2985. public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
  2986. if ($regDirs) $fileArr[] = $path;
  2987. $fileArr = array_merge($fileArr, self::getFilesInDir($path,$extList,1,1,$excludePattern));
  2988. $dirs = self::get_dirs($path);
  2989. if (is_array($dirs) && $recursivityLevels>0) {
  2990. foreach ($dirs as $subdirs) {
  2991. if ((string)$subdirs!='' && (!strlen($excludePattern) || !preg_match('/^'.$excludePattern.'$/',$subdirs))) {
  2992. $fileArr = self::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
  2993. }
  2994. }
  2995. }
  2996. return $fileArr;
  2997. }
  2998. /**
  2999. * Removes the absolute part of all files/folders in fileArr
  3000. * Usage: 2
  3001. *
  3002. * @param array $fileArr: The file array to remove the prefix from
  3003. * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
  3004. * @return array The input $fileArr processed.
  3005. */
  3006. public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
  3007. foreach ($fileArr as $k => &$absFileRef) {
  3008. if (self::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
  3009. $absFileRef = substr($absFileRef, strlen($prefixToRemove));
  3010. } else {
  3011. return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
  3012. }
  3013. }
  3014. return $fileArr;
  3015. }
  3016. /**
  3017. * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
  3018. * Usage: 2
  3019. *
  3020. * @param string File path to process
  3021. * @return string
  3022. */
  3023. public static function fixWindowsFilePath($theFile) {
  3024. return str_replace('//','/', str_replace('\\','/', $theFile));
  3025. }
  3026. /**
  3027. * Resolves "../" sections in the input path string.
  3028. * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
  3029. * Usage: 2
  3030. *
  3031. * @param string File path in which "/../" is resolved
  3032. * @return string
  3033. */
  3034. public static function resolveBackPath($pathStr) {
  3035. $parts = explode('/',$pathStr);
  3036. $output=array();
  3037. $c = 0;
  3038. foreach($parts as $pV) {
  3039. if ($pV=='..') {
  3040. if ($c) {
  3041. array_pop($output);
  3042. $c--;
  3043. } else $output[]=$pV;
  3044. } else {
  3045. $c++;
  3046. $output[]=$pV;
  3047. }
  3048. }
  3049. return implode('/',$output);
  3050. }
  3051. /**
  3052. * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
  3053. * - If already having a scheme, nothing is prepended
  3054. * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
  3055. * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
  3056. * Usage: 30
  3057. *
  3058. * @param string URL / path to prepend full URL addressing to.
  3059. * @return string
  3060. */
  3061. public static function locationHeaderUrl($path) {
  3062. $uI = parse_url($path);
  3063. if (substr($path,0,1)=='/') { // relative to HOST
  3064. $path = self::getIndpEnv('TYPO3_REQUEST_HOST').$path;
  3065. } elseif (!$uI['scheme']) { // No scheme either
  3066. $path = self::getIndpEnv('TYPO3_REQUEST_DIR').$path;
  3067. }
  3068. return $path;
  3069. }
  3070. /**
  3071. * Returns the maximum upload size for a file that is allowed. Measured in KB.
  3072. * This might be handy to find out the real upload limit that is possible for this
  3073. * TYPO3 installation. The first parameter can be used to set something that overrides
  3074. * the maxFileSize, usually for the TCA values.
  3075. *
  3076. * @param integer $localLimit: the number of Kilobytes (!) that should be used as
  3077. * the initial Limit, otherwise $TYPO3_CONF_VARS['BE']['maxFileSize'] will be used
  3078. * @return integer the maximum size of uploads that are allowed (measuered in kilobytes)
  3079. */
  3080. public static function getMaxUploadFileSize($localLimit = 0) {
  3081. // don't allow more than the global max file size at all
  3082. $t3Limit = (intval($localLimit > 0 ? $localLimit : $GLOBALS['TYPO3_CONF_VARS']['BE']['maxFileSize']));
  3083. // as TYPO3 is handling the file size in KB, multiply by 1024 to get bytes
  3084. $t3Limit = $t3Limit * 1024;
  3085. // check for PHP restrictions of the maximum size of one of the $_FILES
  3086. $phpUploadLimit = self::getBytesFromSizeMeasurement(ini_get('upload_max_filesize'));
  3087. // check for PHP restrictions of the maximum $_POST size
  3088. $phpPostLimit = self::getBytesFromSizeMeasurement(ini_get('post_max_size'));
  3089. // if the total amount of post data is smaller (!) than the upload_max_filesize directive,
  3090. // then this is the real limit in PHP
  3091. $phpUploadLimit = ($phpPostLimit < $phpUploadLimit ? $phpPostLimit : $phpUploadLimit);
  3092. // is the allowed PHP limit (upload_max_filesize) lower than the TYPO3 limit?, also: revert back to KB
  3093. return floor($phpUploadLimit < $t3Limit ? $phpUploadLimit : $t3Limit) / 1024;
  3094. }
  3095. /**
  3096. * Gets the bytes value from a measurement string like "100k".
  3097. *
  3098. * @param string $measurement: The measurement (e.g. "100k")
  3099. * @return integer The bytes value (e.g. 102400)
  3100. */
  3101. public static function getBytesFromSizeMeasurement($measurement) {
  3102. if (stripos($measurement, 'G')) {
  3103. $bytes = intval($measurement) * 1024 * 1024 * 1024;
  3104. } else if (stripos($measurement, 'M')) {
  3105. $bytes = intval($measurement) * 1024 * 1024;
  3106. } else if (stripos($measurement, 'K')) {
  3107. $bytes = intval($measurement) * 1024;
  3108. } else {
  3109. $bytes = intval($measurement);
  3110. }
  3111. return $bytes;
  3112. }
  3113. /**
  3114. * Retrieves the maximum path length that is valid in the current environment.
  3115. *
  3116. * @return integer The maximum available path length
  3117. * @author Ingo Renner <ingo@typo3.org>
  3118. */
  3119. public static function getMaximumPathLength() {
  3120. $maximumPathLength = 0;
  3121. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  3122. // rough assumptions
  3123. if (TYPO3_OS == 'WIN') {
  3124. // WIN is usually 255, Vista 260, although NTFS can hold about 2k
  3125. $maximumPathLength = 255;
  3126. } else {
  3127. $maximumPathLength = 2048;
  3128. }
  3129. } else {
  3130. // precise information is available since PHP 5.3
  3131. $maximumPathLength = PHP_MAXPATHLEN;
  3132. }
  3133. return $maximumPathLength;
  3134. }
  3135. /**
  3136. * Function for static version numbers on files, based on the filemtime
  3137. *
  3138. * This will make the filename automatically change when a file is
  3139. * changed, and by that re-cached by the browser. If the file does not
  3140. * exist physically the original file passed to the function is
  3141. * returned without the timestamp.
  3142. *
  3143. * Behaviour is influenced by the setting
  3144. * TYPO3_CONF_VARS[TYPO3_MODE][versionNumberInFilename]
  3145. * = true (BE) / "embed" (FE) : modify filename
  3146. * = false (BE) / "querystring" (FE) : add timestamp as parameter
  3147. *
  3148. * @param string $file Relative path to file including all potential query parameters (not htmlspecialchared yet)
  3149. * @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=...)
  3150. * @return Relative path with version filename including the timestamp
  3151. * @author Lars Houmark <lars@houmark.com>
  3152. */
  3153. public static function createVersionNumberedFilename($file, $forceQueryString = FALSE) {
  3154. $lookupFile = explode('?', $file);
  3155. $path = self::resolveBackPath(self::dirname(PATH_thisScript) .'/'. $lookupFile[0]);
  3156. if (TYPO3_MODE == 'FE') {
  3157. $mode = strtolower($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename']);
  3158. if ($mode === 'embed') {
  3159. $mode = TRUE;
  3160. } else if ($mode === 'querystring') {
  3161. $mode = FALSE;
  3162. } else {
  3163. $doNothing = TRUE;
  3164. }
  3165. } else {
  3166. $mode = $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['versionNumberInFilename'];
  3167. }
  3168. if (! file_exists($path) || $doNothing) {
  3169. // File not found, return filename unaltered
  3170. $fullName = $file;
  3171. } else if (! $mode || $forceQueryString) {
  3172. // If use of .htaccess rule is not configured,
  3173. // we use the default query-string method
  3174. if ($lookupFile[1]) {
  3175. $separator = '&';
  3176. } else {
  3177. $separator = '?';
  3178. }
  3179. $fullName = $file . $separator . filemtime($path);
  3180. } else {
  3181. // Change the filename
  3182. $name = explode('.', $lookupFile[0]);
  3183. $extension = array_pop($name);
  3184. array_push($name, filemtime($path), $extension);
  3185. $fullName = implode('.', $name);
  3186. // append potential query string
  3187. $fullName .= $lookupFile[1] ? '?' . $lookupFile[1] : '';
  3188. }
  3189. return $fullName;
  3190. }
  3191. /*************************
  3192. *
  3193. * DEBUG helper FUNCTIONS
  3194. *
  3195. *************************/
  3196. /**
  3197. * Returns a string with a list of ascii-values for the first $characters characters in $string
  3198. * Usage: 0
  3199. *
  3200. * @param string String to show ASCII value for
  3201. * @param integer Number of characters to show
  3202. * @return string The string with ASCII values in separated by a space char.
  3203. */
  3204. public static function debug_ordvalue($string,$characters=100) {
  3205. if(strlen($string) < $characters) $characters = strlen($string);
  3206. for ($i=0; $i<$characters; $i++) {
  3207. $valuestring.=' '.ord(substr($string,$i,1));
  3208. }
  3209. return trim($valuestring);
  3210. }
  3211. /**
  3212. * Returns HTML-code, which is a visual representation of a multidimensional array
  3213. * use t3lib_div::print_array() in order to print an array
  3214. * Returns false if $array_in is not an array
  3215. * Usage: 31
  3216. *
  3217. * @param mixed Array to view
  3218. * @return string HTML output
  3219. */
  3220. public static function view_array($array_in) {
  3221. if (is_array($array_in)) {
  3222. $result='
  3223. <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
  3224. if (count($array_in) == 0) {
  3225. $result.= '<tr><td><font face="Verdana,Arial" size="1"><strong>EMPTY!</strong></font></td></tr>';
  3226. } else {
  3227. foreach ($array_in as $key => $val) {
  3228. $result.= '<tr>
  3229. <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
  3230. <td>';
  3231. if (is_array($val)) {
  3232. $result.=self::view_array($val);
  3233. } elseif (is_object($val)) {
  3234. $string = get_class($val);
  3235. if (method_exists($val, '__toString')) {
  3236. $string .= ': '.(string)$val;
  3237. }
  3238. $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
  3239. } else {
  3240. if (gettype($val) == 'object') {
  3241. $string = 'Unknown object';
  3242. } else {
  3243. $string = (string)$val;
  3244. }
  3245. $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
  3246. }
  3247. $result.= '</td>
  3248. </tr>';
  3249. }
  3250. }
  3251. $result.= '</table>';
  3252. } else {
  3253. $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
  3254. <tr>
  3255. <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
  3256. </tr>
  3257. </table>'; // Output it as a string.
  3258. }
  3259. return $result;
  3260. }
  3261. /**
  3262. * Prints an array
  3263. * Usage: 6
  3264. *
  3265. * @param mixed Array to print visually (in a table).
  3266. * @return void
  3267. * @see view_array()
  3268. */
  3269. public static function print_array($array_in) {
  3270. echo self::view_array($array_in);
  3271. }
  3272. /**
  3273. * Makes debug output
  3274. * Prints $var in bold between two vertical lines
  3275. * If not $var the word 'debug' is printed
  3276. * If $var is an array, the array is printed by t3lib_div::print_array()
  3277. * Usage: 8
  3278. *
  3279. * @param mixed Variable to print
  3280. * @param string The header.
  3281. * @param string Group for the debug console
  3282. * @return void
  3283. */
  3284. public static function debug($var = '', $header = '', $group = 'Debug') {
  3285. // buffer the output of debug if no buffering started before
  3286. if (ob_get_level()==0) {
  3287. ob_start();
  3288. }
  3289. $debug = '';
  3290. if ($header) {
  3291. $debug .= '
  3292. <table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;">
  3293. <tr>
  3294. <td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">' .
  3295. htmlspecialchars((string) $header) .
  3296. '</td>
  3297. </tr>
  3298. <tr>
  3299. <td>';
  3300. }
  3301. if (is_array($var)) {
  3302. $debug .= self::view_array($var);
  3303. } elseif (is_object($var)) {
  3304. $debug .= '<strong>|Object:<pre>';
  3305. $debug .= print_r($var, TRUE);
  3306. $debug .= '</pre>|</strong>';
  3307. } elseif ((string) $var !== '') {
  3308. $debug .= '<strong>|' . htmlspecialchars((string)$var) . '|</strong>';
  3309. } else {
  3310. $debug .= '<strong>| debug |</strong>';
  3311. }
  3312. if ($header) {
  3313. $debug .= '
  3314. </td>
  3315. </tr>
  3316. </table>';
  3317. }
  3318. if (TYPO3_MODE === 'BE') {
  3319. $group = htmlspecialchars($group);
  3320. if ($header !== '') {
  3321. $tabHeader = htmlspecialchars($header);
  3322. } else {
  3323. $tabHeader = 'Debug';
  3324. }
  3325. if (is_object($var)) {
  3326. $debug = str_replace(
  3327. array('"', '/', '<', "\n", "\r"),
  3328. array('\"', '\/', '\<', '<br />', ''),
  3329. $debug
  3330. );
  3331. } else {
  3332. $debug = str_replace(
  3333. array('"', '/', '<', "\n", "\r"),
  3334. array('\"', '\/', '\<', '', ''),
  3335. $debug
  3336. );
  3337. }
  3338. $script = '
  3339. (function debug() {
  3340. var debugMessage = "' . $debug . '";
  3341. var header = "' . $tabHeader . '";
  3342. var group = "' . $group . '";
  3343. if (typeof Ext !== "object" && (top && typeof top.Ext !== "object")) {
  3344. document.write(debugMessage);
  3345. return;
  3346. }
  3347. if (top && typeof Ext !== "object") {
  3348. Ext = top.Ext;
  3349. }
  3350. Ext.onReady(function() {
  3351. var TYPO3ViewportInstance = null;
  3352. if (top && top.TYPO3 && typeof top.TYPO3.Backend === "object") {
  3353. TYPO3ViewportInstance = top.TYPO3.Backend;
  3354. } else if (typeof TYPO3 === "object" && typeof TYPO3.Backend === "object") {
  3355. TYPO3ViewportInstance = TYPO3.Backend;
  3356. }
  3357. if (TYPO3ViewportInstance !== null) {
  3358. TYPO3ViewportInstance.DebugConsole.addTab(debugMessage, header, group);
  3359. } else {
  3360. document.write(debugMessage);
  3361. }
  3362. });
  3363. })();
  3364. ';
  3365. echo self::wrapJS($script);
  3366. } else {
  3367. echo $debug;
  3368. }
  3369. }
  3370. /**
  3371. * Displays the "path" of the function call stack in a string, using debug_backtrace
  3372. *
  3373. * @return string
  3374. */
  3375. public static function debug_trail() {
  3376. $trail = debug_backtrace();
  3377. $trail = array_reverse($trail);
  3378. array_pop($trail);
  3379. $path = array();
  3380. foreach($trail as $dat) {
  3381. $path[] = $dat['class'].$dat['type'].$dat['function'].'#'.$dat['line'];
  3382. }
  3383. return implode(' // ',$path);
  3384. }
  3385. /**
  3386. * Displays an array as rows in a table. Useful to debug output like an array of database records.
  3387. *
  3388. * @param mixed Array of arrays with similar keys
  3389. * @param string Table header
  3390. * @param boolean If TRUE, will return content instead of echo'ing out.
  3391. * @return void Outputs to browser.
  3392. */
  3393. public static function debugRows($rows,$header='',$returnHTML=FALSE) {
  3394. if (is_array($rows)) {
  3395. reset($rows);
  3396. $firstEl = current($rows);
  3397. if (is_array($firstEl)) {
  3398. $headerColumns = array_keys($firstEl);
  3399. $tRows = array();
  3400. // Header:
  3401. $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>';
  3402. $tCells = array();
  3403. foreach($headerColumns as $key) {
  3404. $tCells[] = '
  3405. <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
  3406. }
  3407. $tRows[] = '
  3408. <tr>'.implode('',$tCells).'
  3409. </tr>';
  3410. // Rows:
  3411. foreach($rows as $singleRow) {
  3412. $tCells = array();
  3413. foreach($headerColumns as $key) {
  3414. $tCells[] = '
  3415. <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? self::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
  3416. }
  3417. $tRows[] = '
  3418. <tr>'.implode('',$tCells).'
  3419. </tr>';
  3420. }
  3421. $table = '
  3422. <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
  3423. </table>';
  3424. if ($returnHTML) return $table; else echo $table;
  3425. } else debug('Empty array of rows',$header);
  3426. } else {
  3427. debug('No array of rows',$header);
  3428. }
  3429. }
  3430. /*************************
  3431. *
  3432. * SYSTEM INFORMATION
  3433. *
  3434. *************************/
  3435. /**
  3436. * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
  3437. * Usage: 1
  3438. *
  3439. * @return string
  3440. */
  3441. public static function getThisUrl() {
  3442. $p=parse_url(self::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
  3443. $dir=self::dirname($p['path']).'/'; // Strip file
  3444. $url = str_replace('//','/',$p['host'].($p['port']?':'.$p['port']:'').$dir);
  3445. return $url;
  3446. }
  3447. /**
  3448. * Returns the link-url to the current script.
  3449. * 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.
  3450. * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
  3451. * Usage: 52
  3452. *
  3453. * @param array Array of GET parameters to include
  3454. * @return string
  3455. */
  3456. public static function linkThisScript(array $getParams = array()) {
  3457. $parts = self::getIndpEnv('SCRIPT_NAME');
  3458. $params = self::_GET();
  3459. foreach ($getParams as $key => $value) {
  3460. if ($value !== '') {
  3461. $params[$key] = $value;
  3462. } else {
  3463. unset($params[$key]);
  3464. }
  3465. }
  3466. $pString = self::implodeArrayForUrl('', $params);
  3467. return $pString ? $parts . '?' . preg_replace('/^&/', '', $pString) : $parts;
  3468. }
  3469. /**
  3470. * 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.
  3471. * So basically it adds the parameters in $getParams to an existing URL, $url
  3472. * Usage: 2
  3473. *
  3474. * @param string URL string
  3475. * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
  3476. * @return string Output URL with added getParams.
  3477. */
  3478. public static function linkThisUrl($url,array $getParams=array()) {
  3479. $parts = parse_url($url);
  3480. $getP = array();
  3481. if ($parts['query']) {
  3482. parse_str($parts['query'],$getP);
  3483. }
  3484. $getP = self::array_merge_recursive_overrule($getP,$getParams);
  3485. $uP = explode('?',$url);
  3486. $params = self::implodeArrayForUrl('',$getP);
  3487. $outurl = $uP[0].($params ? '?'.substr($params, 1) : '');
  3488. return $outurl;
  3489. }
  3490. /**
  3491. * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
  3492. * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
  3493. * Usage: 221
  3494. *
  3495. * @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
  3496. * @return string Value based on the input key, independent of server/os environment.
  3497. */
  3498. public static function getIndpEnv($getEnvName) {
  3499. /*
  3500. Conventions:
  3501. output from parse_url():
  3502. 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
  3503. [scheme] => 'http'
  3504. [user] => 'username'
  3505. [pass] => 'password'
  3506. [host] => '192.168.1.4'
  3507. [port] => '8080'
  3508. [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
  3509. [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
  3510. [fragment] => 'link1'
  3511. Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
  3512. [path_dir] = '/typo3/32/temp/phpcheck/'
  3513. [path_info] = '/arg1/arg2/arg3/'
  3514. [path] = [path_script/path_dir][path_info]
  3515. Keys supported:
  3516. URI______:
  3517. REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3518. HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
  3519. 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')!
  3520. PATH_INFO = [path_info] = /arg1/arg2/arg3/
  3521. QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
  3522. 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
  3523. (Notice: NO username/password + NO fragment)
  3524. CLIENT____:
  3525. REMOTE_ADDR = (client IP)
  3526. REMOTE_HOST = (client host)
  3527. HTTP_USER_AGENT = (client user agent)
  3528. HTTP_ACCEPT_LANGUAGE = (client accept language)
  3529. SERVER____:
  3530. SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
  3531. Special extras:
  3532. TYPO3_HOST_ONLY = [host] = 192.168.1.4
  3533. TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
  3534. TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
  3535. TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (scheme will by default be "http" until we can detect something different)
  3536. TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
  3537. TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
  3538. TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
  3539. TYPO3_SITE_PATH = [path_dir] of the TYPO3 website frontend
  3540. TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
  3541. TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
  3542. TYPO3_SSL = Returns TRUE if this session uses SSL/TLS (https)
  3543. TYPO3_PROXY = Returns TRUE if this session runs over a well known proxy
  3544. Notice: [fragment] is apparently NEVER available to the script!
  3545. Testing suggestions:
  3546. - Output all the values.
  3547. - 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
  3548. - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
  3549. */
  3550. # if ($getEnvName=='HTTP_REFERER') return '';
  3551. $retVal = '';
  3552. switch ((string)$getEnvName) {
  3553. case 'SCRIPT_NAME':
  3554. $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']);
  3555. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3556. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3557. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3558. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
  3559. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3560. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
  3561. }
  3562. }
  3563. break;
  3564. case 'SCRIPT_FILENAME':
  3565. $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'])));
  3566. break;
  3567. case 'REQUEST_URI':
  3568. // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
  3569. 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)
  3570. list($v,$n) = explode('|',$GLOBALS['TYPO3_CONF_VARS']['SYS']['requestURIvar']);
  3571. $retVal = $GLOBALS[$v][$n];
  3572. } elseif (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
  3573. $retVal = '/'.ltrim(self::getIndpEnv('SCRIPT_NAME'), '/').
  3574. ($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:'');
  3575. } else {
  3576. $retVal = $_SERVER['REQUEST_URI'];
  3577. }
  3578. // add a prefix if TYPO3 is behind a proxy: ext-domain.com => int-server.com/prefix
  3579. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3580. if (self::getIndpEnv('TYPO3_SSL') && $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL']) {
  3581. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefixSSL'].$retVal;
  3582. } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix']) {
  3583. $retVal = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyPrefix'].$retVal;
  3584. }
  3585. }
  3586. break;
  3587. case 'PATH_INFO':
  3588. // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
  3589. // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
  3590. // 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)
  3591. // if (strcmp($_SERVER['PATH_INFO'],self::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
  3592. if (PHP_SAPI!='cgi' && PHP_SAPI!='cgi-fcgi') {
  3593. $retVal = $_SERVER['PATH_INFO'];
  3594. }
  3595. break;
  3596. case 'TYPO3_REV_PROXY':
  3597. $retVal = self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP']);
  3598. break;
  3599. case 'REMOTE_ADDR':
  3600. $retVal = $_SERVER['REMOTE_ADDR'];
  3601. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3602. $ip = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  3603. // choose which IP in list to use
  3604. if (count($ip)) {
  3605. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3606. case 'last':
  3607. $ip = array_pop($ip);
  3608. break;
  3609. case 'first':
  3610. $ip = array_shift($ip);
  3611. break;
  3612. case 'none':
  3613. default:
  3614. $ip = '';
  3615. break;
  3616. }
  3617. }
  3618. if (self::validIP($ip)) {
  3619. $retVal = $ip;
  3620. }
  3621. }
  3622. break;
  3623. case 'HTTP_HOST':
  3624. $retVal = $_SERVER['HTTP_HOST'];
  3625. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'])) {
  3626. $host = self::trimExplode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
  3627. // choose which host in list to use
  3628. if (count($host)) {
  3629. switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyHeaderMultiValue']) {
  3630. case 'last':
  3631. $host = array_pop($host);
  3632. break;
  3633. case 'first':
  3634. $host = array_shift($host);
  3635. break;
  3636. case 'none':
  3637. default:
  3638. $host = '';
  3639. break;
  3640. }
  3641. }
  3642. if ($host) {
  3643. $retVal = $host;
  3644. }
  3645. }
  3646. break;
  3647. // These are let through without modification
  3648. case 'HTTP_REFERER':
  3649. case 'HTTP_USER_AGENT':
  3650. case 'HTTP_ACCEPT_ENCODING':
  3651. case 'HTTP_ACCEPT_LANGUAGE':
  3652. case 'REMOTE_HOST':
  3653. case 'QUERY_STRING':
  3654. $retVal = $_SERVER[$getEnvName];
  3655. break;
  3656. case 'TYPO3_DOCUMENT_ROOT':
  3657. // 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.
  3658. // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
  3659. $SFN = self::getIndpEnv('SCRIPT_FILENAME');
  3660. $SN_A = explode('/',strrev(self::getIndpEnv('SCRIPT_NAME')));
  3661. $SFN_A = explode('/',strrev($SFN));
  3662. $acc = array();
  3663. foreach ($SN_A as $kk => $vv) {
  3664. if (!strcmp($SFN_A[$kk],$vv)) {
  3665. $acc[] = $vv;
  3666. } else break;
  3667. }
  3668. $commonEnd=strrev(implode('/',$acc));
  3669. if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+1)); }
  3670. $retVal = $DR;
  3671. break;
  3672. case 'TYPO3_HOST_ONLY':
  3673. $p = explode(':',self::getIndpEnv('HTTP_HOST'));
  3674. $retVal = $p[0];
  3675. break;
  3676. case 'TYPO3_PORT':
  3677. $p = explode(':',self::getIndpEnv('HTTP_HOST'));
  3678. $retVal = $p[1];
  3679. break;
  3680. case 'TYPO3_REQUEST_HOST':
  3681. $retVal = (self::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').
  3682. self::getIndpEnv('HTTP_HOST');
  3683. break;
  3684. case 'TYPO3_REQUEST_URL':
  3685. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('REQUEST_URI');
  3686. break;
  3687. case 'TYPO3_REQUEST_SCRIPT':
  3688. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::getIndpEnv('SCRIPT_NAME');
  3689. break;
  3690. case 'TYPO3_REQUEST_DIR':
  3691. $retVal = self::getIndpEnv('TYPO3_REQUEST_HOST').self::dirname(self::getIndpEnv('SCRIPT_NAME')).'/';
  3692. break;
  3693. case 'TYPO3_SITE_URL':
  3694. if (defined('PATH_thisScript') && defined('PATH_site')) {
  3695. $lPath = substr(dirname(PATH_thisScript),strlen(PATH_site)).'/';
  3696. $url = self::getIndpEnv('TYPO3_REQUEST_DIR');
  3697. $siteUrl = substr($url,0,-strlen($lPath));
  3698. if (substr($siteUrl,-1)!='/') $siteUrl.='/';
  3699. $retVal = $siteUrl;
  3700. }
  3701. break;
  3702. case 'TYPO3_SITE_PATH':
  3703. $retVal = substr(self::getIndpEnv('TYPO3_SITE_URL'), strlen(self::getIndpEnv('TYPO3_REQUEST_HOST')));
  3704. break;
  3705. case 'TYPO3_SITE_SCRIPT':
  3706. $retVal = substr(self::getIndpEnv('TYPO3_REQUEST_URL'),strlen(self::getIndpEnv('TYPO3_SITE_URL')));
  3707. break;
  3708. case 'TYPO3_SSL':
  3709. $proxySSL = trim($GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxySSL']);
  3710. if ($proxySSL == '*') {
  3711. $proxySSL = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'];
  3712. }
  3713. if (self::cmpIP($_SERVER['REMOTE_ADDR'], $proxySSL)) {
  3714. $retVal = true;
  3715. } else {
  3716. $retVal = $_SERVER['SSL_SESSION_ID'] || !strcasecmp($_SERVER['HTTPS'], 'on') || !strcmp($_SERVER['HTTPS'], '1') ? true : false; // see http://bugs.typo3.org/view.php?id=3909
  3717. }
  3718. break;
  3719. case '_ARRAY':
  3720. $out = array();
  3721. // Here, list ALL possible keys to this function for debug display.
  3722. $envTestVars = self::trimExplode(',','
  3723. HTTP_HOST,
  3724. TYPO3_HOST_ONLY,
  3725. TYPO3_PORT,
  3726. PATH_INFO,
  3727. QUERY_STRING,
  3728. REQUEST_URI,
  3729. HTTP_REFERER,
  3730. TYPO3_REQUEST_HOST,
  3731. TYPO3_REQUEST_URL,
  3732. TYPO3_REQUEST_SCRIPT,
  3733. TYPO3_REQUEST_DIR,
  3734. TYPO3_SITE_URL,
  3735. TYPO3_SITE_SCRIPT,
  3736. TYPO3_SSL,
  3737. TYPO3_REV_PROXY,
  3738. SCRIPT_NAME,
  3739. TYPO3_DOCUMENT_ROOT,
  3740. SCRIPT_FILENAME,
  3741. REMOTE_ADDR,
  3742. REMOTE_HOST,
  3743. HTTP_USER_AGENT,
  3744. HTTP_ACCEPT_LANGUAGE',1);
  3745. foreach ($envTestVars as $v) {
  3746. $out[$v]=self::getIndpEnv($v);
  3747. }
  3748. reset($out);
  3749. $retVal = $out;
  3750. break;
  3751. }
  3752. return $retVal;
  3753. }
  3754. /**
  3755. * Gets the unixtime as milliseconds.
  3756. *
  3757. * @return integer The unixtime as milliseconds
  3758. */
  3759. public static function milliseconds() {
  3760. return round(microtime(true) * 1000);
  3761. }
  3762. /**
  3763. * Client Browser Information
  3764. * Usage: 4
  3765. *
  3766. * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
  3767. * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
  3768. */
  3769. public static function clientInfo($useragent='') {
  3770. if (!$useragent) $useragent=self::getIndpEnv('HTTP_USER_AGENT');
  3771. $bInfo=array();
  3772. // Which browser?
  3773. if (strpos($useragent,'Konqueror') !== false) {
  3774. $bInfo['BROWSER']= 'konqu';
  3775. } elseif (strpos($useragent,'Opera') !== false) {
  3776. $bInfo['BROWSER']= 'opera';
  3777. } elseif (strpos($useragent, 'MSIE') !== false) {
  3778. $bInfo['BROWSER']= 'msie';
  3779. } elseif (strpos($useragent, 'Mozilla') !== false) {
  3780. $bInfo['BROWSER']='net';
  3781. } elseif (strpos($useragent, 'Flash') !== false) {
  3782. $bInfo['BROWSER'] = 'flash';
  3783. }
  3784. if ($bInfo['BROWSER']) {
  3785. // Browser version
  3786. switch($bInfo['BROWSER']) {
  3787. case 'net':
  3788. $bInfo['VERSION']= doubleval(substr($useragent,8));
  3789. if (strpos($useragent,'Netscape6/') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape6/'),10)); } // Will we ever know if this was a typo or intention...?! :-(
  3790. if (strpos($useragent,'Netscape/6') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/6'),10)); }
  3791. if (strpos($useragent,'Netscape/7') !== false) { $bInfo['VERSION'] = doubleval(substr(strstr($useragent,'Netscape/7'),9)); }
  3792. break;
  3793. case 'msie':
  3794. $tmp = strstr($useragent,'MSIE');
  3795. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,4)));
  3796. break;
  3797. case 'opera':
  3798. $tmp = strstr($useragent,'Opera');
  3799. $bInfo['VERSION'] = doubleval(preg_replace('/^[^0-9]*/','',substr($tmp,5)));
  3800. break;
  3801. case 'konqu':
  3802. $tmp = strstr($useragent,'Konqueror/');
  3803. $bInfo['VERSION'] = doubleval(substr($tmp,10));
  3804. break;
  3805. }
  3806. // Client system
  3807. if (strpos($useragent,'Win') !== false) {
  3808. $bInfo['SYSTEM'] = 'win';
  3809. } elseif (strpos($useragent,'Mac') !== false) {
  3810. $bInfo['SYSTEM'] = 'mac';
  3811. } elseif (strpos($useragent,'Linux') !== false || strpos($useragent,'X11') !== false || strpos($useragent,'SGI') !== false || strpos($useragent,' SunOS ') !== false || strpos($useragent,' HP-UX ') !== false) {
  3812. $bInfo['SYSTEM'] = 'unix';
  3813. }
  3814. }
  3815. // Is true if the browser supports css to format forms, especially the width
  3816. $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' || ($bInfo['BROWSER']=='net' && $bInfo['VERSION']>=5) || $bInfo['BROWSER']=='opera' || $bInfo['BROWSER']=='konqu');
  3817. return $bInfo;
  3818. }
  3819. /**
  3820. * Get the fully-qualified domain name of the host.
  3821. * Usage: 2
  3822. *
  3823. * @param boolean Use request host (when not in CLI mode).
  3824. * @return string The fully-qualified host name.
  3825. */
  3826. public static function getHostname($requestHost=TRUE) {
  3827. $host = '';
  3828. if ($requestHost && (!defined('TYPO3_cliMode') || !TYPO3_cliMode)) {
  3829. $host = self::getIndpEnv('HTTP_HOST');
  3830. }
  3831. if (!$host) {
  3832. // will fail for PHP 4.1 and 4.2
  3833. $host = @php_uname('n');
  3834. // 'n' is ignored in broken installations
  3835. if (strpos($host, ' ')) $host = '';
  3836. }
  3837. // we have not found a FQDN yet
  3838. if ($host && strpos($host, '.') === false) {
  3839. $ip = gethostbyname($host);
  3840. // we got an IP address
  3841. if ($ip != $host) {
  3842. $fqdn = gethostbyaddr($ip);
  3843. if ($ip != $fqdn) $host = $fqdn;
  3844. }
  3845. }
  3846. if (!$host) $host = 'localhost.localdomain';
  3847. return $host;
  3848. }
  3849. /*************************
  3850. *
  3851. * TYPO3 SPECIFIC FUNCTIONS
  3852. *
  3853. *************************/
  3854. /**
  3855. * 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.
  3856. * Usage: 24
  3857. *
  3858. * @param string The input filename/filepath to evaluate
  3859. * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
  3860. * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
  3861. * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
  3862. */
  3863. public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE) {
  3864. if (!strcmp($filename,'')) return '';
  3865. if ($relToTYPO3_mainDir) {
  3866. if (!defined('PATH_typo3')) return '';
  3867. $relPathPrefix = PATH_typo3;
  3868. } else {
  3869. $relPathPrefix = PATH_site;
  3870. }
  3871. if (substr($filename,0,4)=='EXT:') { // extension
  3872. list($extKey,$local) = explode('/',substr($filename,4),2);
  3873. $filename='';
  3874. if (strcmp($extKey,'') && t3lib_extMgm::isLoaded($extKey) && strcmp($local,'')) {
  3875. $filename = t3lib_extMgm::extPath($extKey).$local;
  3876. }
  3877. } elseif (!self::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
  3878. $filename=$relPathPrefix.$filename;
  3879. } elseif ($onlyRelative && !self::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
  3880. $filename='';
  3881. }
  3882. if (strcmp($filename,'') && self::validPathStr($filename)) { // checks backpath.
  3883. return $filename;
  3884. }
  3885. }
  3886. /**
  3887. * Checks for malicious file paths.
  3888. * Returns true if no '//', '..' or '\' is in the $theFile
  3889. * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
  3890. * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
  3891. * Usage: 14
  3892. *
  3893. * @param string Filepath to evaluate
  3894. * @return boolean True, if no '//', '\', '/../' is in the $theFile and $theFile doesn't begin with '../'
  3895. * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
  3896. */
  3897. public static function validPathStr($theFile) {
  3898. if (strpos($theFile, '//')===false && strpos($theFile, '\\')===false && !preg_match('#(?:^\.\.|/\.\./)#', $theFile)) {
  3899. return true;
  3900. }
  3901. }
  3902. /**
  3903. * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
  3904. * Usage: 8
  3905. *
  3906. * @param string Filepath to evaluate
  3907. * @return boolean
  3908. */
  3909. public static function isAbsPath($path) {
  3910. return TYPO3_OS=='WIN' ? substr($path,1,2)==':/' : substr($path,0,1)=='/';
  3911. }
  3912. /**
  3913. * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
  3914. * Usage: 5
  3915. *
  3916. * @param string Filepath to evaluate
  3917. * @return boolean
  3918. */
  3919. public static function isAllowedAbsPath($path) {
  3920. if (self::isAbsPath($path) &&
  3921. self::validPathStr($path) &&
  3922. ( self::isFirstPartOfStr($path,PATH_site)
  3923. ||
  3924. ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && self::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
  3925. )
  3926. ) return true;
  3927. }
  3928. /**
  3929. * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
  3930. * Usage: 2
  3931. *
  3932. * @param string Filepath to evaluate
  3933. * @return boolean
  3934. */
  3935. public static function verifyFilenameAgainstDenyPattern($filename) {
  3936. if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
  3937. $result = preg_match('/'.$GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'].'/i',$filename);
  3938. if ($result) return false; // so if a matching filename is found, return false;
  3939. }
  3940. return true;
  3941. }
  3942. /**
  3943. * Checks if a given string is a valid frame URL to be loaded in the
  3944. * backend.
  3945. *
  3946. * @param string $url potential URL to check
  3947. *
  3948. * @return string either $url if $url is considered to be harmless, or an
  3949. * empty string otherwise
  3950. */
  3951. public static function sanitizeLocalUrl($url = '') {
  3952. $sanitizedUrl = '';
  3953. $decodedUrl = rawurldecode($url);
  3954. if (!empty($url) && self::removeXSS($decodedUrl) === $decodedUrl) {
  3955. $testAbsoluteUrl = self::resolveBackPath($decodedUrl);
  3956. $testRelativeUrl = self::resolveBackPath(
  3957. self::dirname(self::getIndpEnv('SCRIPT_NAME')) . '/' . $decodedUrl
  3958. );
  3959. // Pass if URL is on the current host:
  3960. if (self::isValidUrl($decodedUrl)) {
  3961. if (self::isOnCurrentHost($decodedUrl) && strpos($decodedUrl, self::getIndpEnv('TYPO3_SITE_URL')) === 0) {
  3962. $sanitizedUrl = $url;
  3963. }
  3964. // Pass if URL is an absolute file path:
  3965. } elseif (self::isAbsPath($decodedUrl) && self::isAllowedAbsPath($decodedUrl)) {
  3966. $sanitizedUrl = $url;
  3967. // Pass if URL is absolute and below TYPO3 base directory:
  3968. } elseif (strpos($testAbsoluteUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) === '/') {
  3969. $sanitizedUrl = $url;
  3970. // Pass if URL is relative and below TYPO3 base directory:
  3971. } elseif (strpos($testRelativeUrl, self::getIndpEnv('TYPO3_SITE_PATH')) === 0 && substr($decodedUrl, 0, 1) !== '/') {
  3972. $sanitizedUrl = $url;
  3973. }
  3974. }
  3975. if (!empty($url) && empty($sanitizedUrl)) {
  3976. self::sysLog('The URL "' . $url . '" is not considered to be local and was denied.', 'Core', self::SYSLOG_SEVERITY_NOTICE);
  3977. }
  3978. return $sanitizedUrl;
  3979. }
  3980. /**
  3981. * Moves $source file to $destination if uploaded, otherwise try to make a copy
  3982. * Usage: 4
  3983. *
  3984. * @param string Source file, absolute path
  3985. * @param string Destination file, absolute path
  3986. * @return boolean Returns true if the file was moved.
  3987. * @coauthor Dennis Petersen <fessor@software.dk>
  3988. * @see upload_to_tempfile()
  3989. */
  3990. public static function upload_copy_move($source,$destination) {
  3991. if (is_uploaded_file($source)) {
  3992. $uploaded = TRUE;
  3993. // 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:
  3994. $uploadedResult = move_uploaded_file($source, $destination);
  3995. } else {
  3996. $uploaded = FALSE;
  3997. @copy($source,$destination);
  3998. }
  3999. self::fixPermissions($destination); // Change the permissions of the file
  4000. // 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
  4001. return $uploaded ? $uploadedResult : FALSE;
  4002. }
  4003. /**
  4004. * 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.
  4005. * Use this function to move uploaded files to where you can work on them.
  4006. * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
  4007. * Usage: 6
  4008. *
  4009. * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
  4010. * @return string If a new file was successfully created, return its filename, otherwise blank string.
  4011. * @see unlink_tempfile(), upload_copy_move()
  4012. */
  4013. public static function upload_to_tempfile($uploadedFileName) {
  4014. if (is_uploaded_file($uploadedFileName)) {
  4015. $tempFile = self::tempnam('upload_temp_');
  4016. move_uploaded_file($uploadedFileName, $tempFile);
  4017. return @is_file($tempFile) ? $tempFile : '';
  4018. }
  4019. }
  4020. /**
  4021. * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
  4022. * 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.
  4023. * Use this after upload_to_tempfile() or tempnam() from this class!
  4024. * Usage: 9
  4025. *
  4026. * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
  4027. * @return boolean Returns true if the file was unlink()'ed
  4028. * @see upload_to_tempfile(), tempnam()
  4029. */
  4030. public static function unlink_tempfile($uploadedTempFileName) {
  4031. if ($uploadedTempFileName && self::validPathStr($uploadedTempFileName) && self::isFirstPartOfStr($uploadedTempFileName,PATH_site.'typo3temp/') && @is_file($uploadedTempFileName)) {
  4032. if (unlink($uploadedTempFileName)) return TRUE;
  4033. }
  4034. }
  4035. /**
  4036. * Create temporary filename (Create file with unique file name)
  4037. * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
  4038. * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
  4039. * Usage: 7
  4040. *
  4041. * @param string Prefix to temp file (which will have no extension btw)
  4042. * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
  4043. * @see unlink_tempfile(), upload_to_tempfile()
  4044. */
  4045. public static function tempnam($filePrefix) {
  4046. return tempnam(PATH_site.'typo3temp/',$filePrefix);
  4047. }
  4048. /**
  4049. * Standard authentication code (used in Direct Mail, checkJumpUrl and setfixed links computations)
  4050. * Usage: 2
  4051. *
  4052. * @param mixed Uid (integer) or record (array)
  4053. * @param string List of fields from the record if that is given.
  4054. * @param integer Length of returned authentication code.
  4055. * @return string MD5 hash of 8 chars.
  4056. */
  4057. public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8) {
  4058. if (is_array($uid_or_record)) {
  4059. $recCopy_temp=array();
  4060. if ($fields) {
  4061. $fieldArr = self::trimExplode(',',$fields,1);
  4062. foreach ($fieldArr as $k => $v) {
  4063. $recCopy_temp[$k]=$uid_or_record[$v];
  4064. }
  4065. } else {
  4066. $recCopy_temp=$uid_or_record;
  4067. }
  4068. $preKey = implode('|',$recCopy_temp);
  4069. } else {
  4070. $preKey = $uid_or_record;
  4071. }
  4072. $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  4073. $authCode = substr(md5($authCode),0,$codeLength);
  4074. return $authCode;
  4075. }
  4076. /**
  4077. * Splits the input query-parameters into an array with certain parameters filtered out.
  4078. * Used to create the cHash value
  4079. *
  4080. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  4081. * @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
  4082. * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink(), t3lib_div::calculateCHash()
  4083. */
  4084. public static function cHashParams($addQueryParams) {
  4085. $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
  4086. // Make array:
  4087. $pA = array();
  4088. foreach($params as $theP) {
  4089. $pKV = explode('=', $theP); // Splitting single param by '=' sign
  4090. if (!self::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0]) && !preg_match('/TSFE_ADMIN_PANEL\[.*?\]/',$pKV[0])) {
  4091. $pA[rawurldecode($pKV[0])] = (string)rawurldecode($pKV[1]);
  4092. }
  4093. }
  4094. // Hook: Allows to manipulate the parameters which are taken to build the chash:
  4095. if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'])) {
  4096. $cHashParamsHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_div.php']['cHashParamsHook'];
  4097. if (is_array($cHashParamsHook)) {
  4098. $hookParameters = array(
  4099. 'addQueryParams' => &$addQueryParams,
  4100. 'params' => &$params,
  4101. 'pA' => &$pA,
  4102. );
  4103. $hookReference = null;
  4104. foreach ($cHashParamsHook as $hookFunction) {
  4105. self::callUserFunction($hookFunction, $hookParameters, $hookReference);
  4106. }
  4107. }
  4108. }
  4109. // Finish and sort parameters array by keys:
  4110. $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
  4111. ksort($pA);
  4112. return $pA;
  4113. }
  4114. /**
  4115. * Returns the cHash based on provided query parameters and added values from internal call
  4116. *
  4117. * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
  4118. * @return string Hash of all the values
  4119. * @see t3lib_div::cHashParams(), t3lib_div::calculateCHash()
  4120. */
  4121. public static function generateCHash($addQueryParams) {
  4122. $cHashParams = self::cHashParams($addQueryParams);
  4123. $cHash = self::calculateCHash($cHashParams);
  4124. return $cHash;
  4125. }
  4126. /**
  4127. * Calculates the cHash based on the provided parameters
  4128. *
  4129. * @param array Array of key-value pairs
  4130. * @return string Hash of all the values
  4131. */
  4132. public static function calculateCHash($params) {
  4133. $cHash = md5(serialize($params));
  4134. return $cHash;
  4135. }
  4136. /**
  4137. * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
  4138. *
  4139. * @param integer Value from "l18n_cfg" field of a page record
  4140. * @return boolean True if the page should be hidden
  4141. */
  4142. public static function hideIfNotTranslated($l18n_cfg_fieldValue) {
  4143. if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
  4144. return $l18n_cfg_fieldValue&2 ? FALSE : TRUE;
  4145. } else {
  4146. return $l18n_cfg_fieldValue&2 ? TRUE : FALSE;
  4147. }
  4148. }
  4149. /**
  4150. * Includes a locallang file and returns the $LOCAL_LANG array found inside.
  4151. *
  4152. * @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.
  4153. * @param string Language key
  4154. * @param string Character set (option); if not set, determined by the language key
  4155. * @param integer Error mode (when file could not be found): 0 - syslog entry, 1 - do nothing, 2 - throw an exception
  4156. * @return array Value of $LOCAL_LANG found in the included file. If that array is found it will returned.
  4157. * Otherwise an empty array and it is FALSE in error case.
  4158. */
  4159. public static function readLLfile($fileRef, $langKey, $charset = '', $errorMode = 0) {
  4160. $result = FALSE;
  4161. $file = self::getFileAbsFileName($fileRef);
  4162. if ($file) {
  4163. $baseFile = preg_replace('/\.(php|xml)$/', '', $file);
  4164. if (@is_file($baseFile.'.xml')) {
  4165. $LOCAL_LANG = self::readLLXMLfile($baseFile.'.xml', $langKey, $charset);
  4166. } elseif (@is_file($baseFile.'.php')) {
  4167. if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] || $charset) {
  4168. $LOCAL_LANG = self::readLLPHPfile($baseFile.'.php', $langKey, $charset);
  4169. } else {
  4170. include($baseFile.'.php');
  4171. if (is_array($LOCAL_LANG)) {
  4172. $LOCAL_LANG = array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]); }
  4173. }
  4174. } else {
  4175. $errorMsg = 'File "' . $fileRef. '" not found!';
  4176. if ($errorMode == 2) {
  4177. throw new t3lib_exception($errorMsg);
  4178. } elseif(!$errorMode) {
  4179. self::sysLog($errorMsg, 'Core', self::SYSLOG_SEVERITY_ERROR);
  4180. }
  4181. $fileNotFound = TRUE;
  4182. }
  4183. if (is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef])) {
  4184. foreach ($GLOBALS['TYPO3_CONF_VARS']['SYS']['locallangXMLOverride'][$fileRef] as $overrideFile) {
  4185. $languageOverrideFileName = self::getFileAbsFileName($overrideFile);
  4186. if (@is_file($languageOverrideFileName)) {
  4187. $languageOverrideArray = self::readLLXMLfile($languageOverrideFileName, $langKey, $charset);
  4188. $LOCAL_LANG = self::array_merge_recursive_overrule($LOCAL_LANG, $languageOverrideArray);
  4189. }
  4190. }
  4191. }
  4192. }
  4193. if ($fileNotFound !== TRUE) {
  4194. $result = is_array($LOCAL_LANG) ? $LOCAL_LANG : array();
  4195. }
  4196. return $result;
  4197. }
  4198. /**
  4199. * Includes a locallang-php file and returns the $LOCAL_LANG array
  4200. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  4201. *
  4202. * @param string Absolute reference to locallang-PHP file
  4203. * @param string TYPO3 language key, eg. "dk" or "de" or "default"
  4204. * @param string Character set (optional)
  4205. * @return array LOCAL_LANG array in return.
  4206. */
  4207. public static function readLLPHPfile($fileRef, $langKey, $charset='') {
  4208. if (is_object($GLOBALS['LANG'])) {
  4209. $csConvObj = $GLOBALS['LANG']->csConvObj;
  4210. } elseif (is_object($GLOBALS['TSFE'])) {
  4211. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  4212. } else {
  4213. $csConvObj = self::makeInstance('t3lib_cs');
  4214. }
  4215. if (@is_file($fileRef) && $langKey) {
  4216. // Set charsets:
  4217. $sourceCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4218. if ($charset) {
  4219. $targetCharset = $csConvObj->parse_charset($charset);
  4220. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  4221. // when forceCharset is set, we store ALL labels in this charset!!!
  4222. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  4223. } else {
  4224. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4225. }
  4226. // Cache file name:
  4227. $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
  4228. $cacheFileName = PATH_site.'typo3temp/llxml/'.
  4229. substr(basename($fileRef),10,15).
  4230. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4231. // Check if cache file exists...
  4232. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4233. // Get PHP data
  4234. include($fileRef);
  4235. if (!is_array($LOCAL_LANG)) {
  4236. $fileName = substr($fileRef, strlen(PATH_site));
  4237. throw new RuntimeException(
  4238. 'TYPO3 Fatal Error: "' . $fileName . '" is no TYPO3 language file!',
  4239. 1270853900
  4240. );
  4241. }
  4242. // converting the default language (English)
  4243. // this needs to be done for a few accented loan words and extension names
  4244. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'iso-8859-1') {
  4245. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  4246. $labelValue = $csConvObj->conv($labelValue, 'iso-8859-1', $targetCharset);
  4247. }
  4248. }
  4249. if ($langKey!='default' && is_array($LOCAL_LANG[$langKey]) && $sourceCharset!=$targetCharset) {
  4250. foreach ($LOCAL_LANG[$langKey] as &$labelValue) {
  4251. $labelValue = $csConvObj->conv($labelValue, $sourceCharset, $targetCharset);
  4252. }
  4253. }
  4254. // Cache the content now:
  4255. $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
  4256. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4257. if ($res) {
  4258. throw new RuntimeException(
  4259. 'TYPO3 Fatal Error: "' . $res,
  4260. 1270853901
  4261. );
  4262. }
  4263. } else {
  4264. // Get content from cache:
  4265. $serContent = unserialize(self::getUrl($cacheFileName));
  4266. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  4267. }
  4268. return $LOCAL_LANG;
  4269. }
  4270. }
  4271. /**
  4272. * Includes a locallang-xml file and returns the $LOCAL_LANG array
  4273. * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
  4274. *
  4275. * @param string Absolute reference to locallang-XML file
  4276. * @param string TYPO3 language key, eg. "dk" or "de" or "default"
  4277. * @param string Character set (optional)
  4278. * @return array LOCAL_LANG array in return.
  4279. */
  4280. public static function readLLXMLfile($fileRef, $langKey, $charset='') {
  4281. if (is_object($GLOBALS['LANG'])) {
  4282. $csConvObj = $GLOBALS['LANG']->csConvObj;
  4283. } elseif (is_object($GLOBALS['TSFE'])) {
  4284. $csConvObj = $GLOBALS['TSFE']->csConvObj;
  4285. } else {
  4286. $csConvObj = self::makeInstance('t3lib_cs');
  4287. }
  4288. $LOCAL_LANG = NULL;
  4289. if (@is_file($fileRef) && $langKey) {
  4290. // Set charset:
  4291. if ($charset) {
  4292. $targetCharset = $csConvObj->parse_charset($charset);
  4293. } elseif ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) {
  4294. // when forceCharset is set, we store ALL labels in this charset!!!
  4295. $targetCharset = $csConvObj->parse_charset($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']);
  4296. } else {
  4297. $targetCharset = $csConvObj->parse_charset($csConvObj->charSetArray[$langKey] ? $csConvObj->charSetArray[$langKey] : 'iso-8859-1');
  4298. }
  4299. // Cache file name:
  4300. $hashSource = substr($fileRef,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($fileRef)).'|version=2.3';
  4301. $cacheFileName = PATH_site.'typo3temp/llxml/'.
  4302. substr(basename($fileRef),10,15).
  4303. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4304. // Check if cache file exists...
  4305. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4306. // Read XML, parse it.
  4307. $xmlString = self::getUrl($fileRef);
  4308. $xmlContent = self::xml2array($xmlString);
  4309. if (!is_array($xmlContent)) {
  4310. $fileName = substr($fileRef, strlen(PATH_site));
  4311. throw new RuntimeException(
  4312. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4313. 1270853902
  4314. );
  4315. }
  4316. // Set default LOCAL_LANG array content:
  4317. $LOCAL_LANG = array();
  4318. $LOCAL_LANG['default'] = $xmlContent['data']['default'];
  4319. // converting the default language (English)
  4320. // this needs to be done for a few accented loan words and extension names
  4321. // NOTE: no conversion is done when in UTF-8 mode!
  4322. if (is_array($LOCAL_LANG['default']) && $targetCharset != 'utf-8') {
  4323. foreach ($LOCAL_LANG['default'] as &$labelValue) {
  4324. $labelValue = $csConvObj->utf8_decode($labelValue, $targetCharset);
  4325. }
  4326. unset($labelValue);
  4327. }
  4328. // converting other languages to their "native" charsets
  4329. // NOTE: no conversion is done when in UTF-8 mode!
  4330. if ($langKey!='default') {
  4331. // 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:
  4332. $LOCAL_LANG[$langKey] = self::llXmlAutoFileName($fileRef, $langKey);
  4333. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4334. if (!@is_file($localized_file) && isset($xmlContent['data'][$langKey])) {
  4335. $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
  4336. }
  4337. // Checking if charset should be converted.
  4338. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
  4339. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  4340. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
  4341. }
  4342. }
  4343. }
  4344. // Cache the content now:
  4345. $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>array('default'=>$LOCAL_LANG['default'], $langKey=>$LOCAL_LANG[$langKey]));
  4346. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4347. if ($res) {
  4348. throw new RuntimeException(
  4349. 'TYPO3 Fatal Error: ' . $res,
  4350. 1270853903
  4351. );
  4352. }
  4353. } else {
  4354. // Get content from cache:
  4355. $serContent = unserialize(self::getUrl($cacheFileName));
  4356. $LOCAL_LANG = $serContent['LOCAL_LANG'];
  4357. }
  4358. // Checking for EXTERNAL file for non-default language:
  4359. if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
  4360. // Look for localized file:
  4361. $localized_file = self::getFileAbsFileName($LOCAL_LANG[$langKey]);
  4362. if ($localized_file && @is_file($localized_file)) {
  4363. // Cache file name:
  4364. $hashSource = substr($localized_file,strlen(PATH_site)).'|'.date('d-m-Y H:i:s',filemtime($localized_file)).'|version=2.3';
  4365. $cacheFileName = PATH_site.'typo3temp/llxml/EXT_'.
  4366. substr(basename($localized_file),10,15).
  4367. '_'.self::shortMD5($hashSource).'.'.$langKey.'.'.$targetCharset.'.cache';
  4368. // Check if cache file exists...
  4369. if (!@is_file($cacheFileName)) { // ... if it doesn't, create content and write it:
  4370. // Read and parse XML content:
  4371. $local_xmlString = self::getUrl($localized_file);
  4372. $local_xmlContent = self::xml2array($local_xmlString);
  4373. if (!is_array($local_xmlContent)) {
  4374. $fileName = substr($localized_file, strlen(PATH_site));
  4375. throw new RuntimeException(
  4376. 'TYPO3 Fatal Error: The file "' . $fileName . '" is no TYPO3 language file!',
  4377. 1270853904
  4378. );
  4379. }
  4380. $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ? $local_xmlContent['data'][$langKey] : array();
  4381. // Checking if charset should be converted.
  4382. if (is_array($LOCAL_LANG[$langKey]) && $targetCharset!='utf-8') {
  4383. foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
  4384. $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$targetCharset);
  4385. }
  4386. }
  4387. // Cache the content now:
  4388. $serContent = array('extlang'=>$langKey, 'origFile'=>$hashSource, 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
  4389. $res = self::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
  4390. if ($res) {
  4391. throw new RuntimeException(
  4392. 'TYPO3 Fatal Error: ' . $res,
  4393. 1270853905
  4394. );
  4395. }
  4396. } else {
  4397. // Get content from cache:
  4398. $serContent = unserialize(self::getUrl($cacheFileName));
  4399. $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
  4400. }
  4401. } else {
  4402. $LOCAL_LANG[$langKey] = array();
  4403. }
  4404. }
  4405. return $LOCAL_LANG;
  4406. }
  4407. }
  4408. /**
  4409. * Returns auto-filename for locallang-XML localizations.
  4410. *
  4411. * @param string Absolute file reference to locallang-XML file. Must be inside system/global/local extension
  4412. * @param string Language key
  4413. * @return string Returns the filename reference for the language unless error occured (or local mode is used) in which case it will be NULL
  4414. */
  4415. public static function llXmlAutoFileName($fileRef,$language) {
  4416. // Analyse file reference:
  4417. $location = 'typo3conf/l10n/'.$language.'/'; // Default location of translations
  4418. if (self::isFirstPartOfStr($fileRef,PATH_typo3.'sysext/')) { // Is system:
  4419. $validatedPrefix = PATH_typo3.'sysext/';
  4420. #$location = 'EXT:csh_'.$language.'/'; // For system extensions translations are found in "csh_*" extensions (language packs)
  4421. } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3.'ext/')) { // Is global:
  4422. $validatedPrefix = PATH_typo3.'ext/';
  4423. } elseif (self::isFirstPartOfStr($fileRef,PATH_typo3conf.'ext/')) { // Is local:
  4424. $validatedPrefix = PATH_typo3conf.'ext/';
  4425. } else {
  4426. $validatedPrefix = '';
  4427. }
  4428. if ($validatedPrefix) {
  4429. // Divide file reference into extension key, directory (if any) and base name:
  4430. list($file_extKey,$file_extPath) = explode('/',substr($fileRef,strlen($validatedPrefix)),2);
  4431. $temp = self::revExplode('/',$file_extPath,2);
  4432. if (count($temp)==1) array_unshift($temp,''); // Add empty first-entry if not there.
  4433. list($file_extPath,$file_fileName) = $temp;
  4434. // The filename is prefixed with "[language key]." because it prevents the llxmltranslate tool from detecting it.
  4435. return $location.
  4436. $file_extKey.'/'.
  4437. ($file_extPath?$file_extPath.'/':'').
  4438. $language.'.'.$file_fileName;
  4439. } else {
  4440. return NULL;
  4441. }
  4442. }
  4443. /**
  4444. * Loads the $TCA (Table Configuration Array) for the $table
  4445. *
  4446. * Requirements:
  4447. * 1) must be configured table (the ctrl-section configured),
  4448. * 2) columns must not be an array (which it is always if whole table loaded), and
  4449. * 3) there is a value for dynamicConfigFile (filename in typo3conf)
  4450. *
  4451. * Note: For the frontend this loads only 'ctrl' and 'feInterface' parts.
  4452. * For complete TCA use $GLOBALS['TSFE']->includeTCA() instead.
  4453. *
  4454. * Usage: 84
  4455. *
  4456. * @param string Table name for which to load the full TCA array part into the global $TCA
  4457. * @return void
  4458. */
  4459. public static function loadTCA($table) {
  4460. global $TCA;
  4461. if (isset($TCA[$table])) {
  4462. $tca = &$TCA[$table];
  4463. if (!$tca['columns']) {
  4464. $dcf = $tca['ctrl']['dynamicConfigFile'];
  4465. if ($dcf) {
  4466. if (!strcmp(substr($dcf,0,6),'T3LIB:')) {
  4467. include(PATH_t3lib.'stddb/'.substr($dcf,6));
  4468. } elseif (self::isAbsPath($dcf) && @is_file($dcf)) { // Absolute path...
  4469. include($dcf);
  4470. } else include(PATH_typo3conf.$dcf);
  4471. }
  4472. }
  4473. }
  4474. }
  4475. /**
  4476. * 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).
  4477. * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
  4478. * Usage: 5
  4479. *
  4480. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  4481. * @param string The sheet to return, preferably.
  4482. * @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!
  4483. */
  4484. public static function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
  4485. if (!is_array ($dataStructArray)) return 'Data structure must be an array';
  4486. if (is_array($dataStructArray['sheets'])) {
  4487. $singleSheet = FALSE;
  4488. if (!isset($dataStructArray['sheets'][$sheet])) {
  4489. $sheet='sDEF';
  4490. }
  4491. $dataStruct = $dataStructArray['sheets'][$sheet];
  4492. // If not an array, but still set, then regard it as a relative reference to a file:
  4493. if ($dataStruct && !is_array($dataStruct)) {
  4494. $file = self::getFileAbsFileName($dataStruct);
  4495. if ($file && @is_file($file)) {
  4496. $dataStruct = self::xml2array(self::getUrl($file));
  4497. }
  4498. }
  4499. } else {
  4500. $singleSheet = TRUE;
  4501. $dataStruct = $dataStructArray;
  4502. if (isset($dataStruct['meta'])) unset($dataStruct['meta']); // Meta data should not appear there.
  4503. $sheet = 'sDEF'; // Default sheet
  4504. }
  4505. return array($dataStruct,$sheet,$singleSheet);
  4506. }
  4507. /**
  4508. * Resolves ALL sheet definitions in dataStructArray
  4509. * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
  4510. *
  4511. * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
  4512. * @return array Output data structure with all sheets resolved as arrays.
  4513. */
  4514. public static function resolveAllSheetsInDS(array $dataStructArray) {
  4515. if (is_array($dataStructArray['sheets'])) {
  4516. $out=array('sheets'=>array());
  4517. foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
  4518. list($ds,$aS) = self::resolveSheetDefInDS($dataStructArray,$sheetId);
  4519. if ($sheetId==$aS) {
  4520. $out['sheets'][$aS]=$ds;
  4521. }
  4522. }
  4523. } else {
  4524. list($ds) = self::resolveSheetDefInDS($dataStructArray);
  4525. $out = array('sheets' => array('sDEF' => $ds));
  4526. }
  4527. return $out;
  4528. }
  4529. /**
  4530. * Calls a userdefined function/method in class
  4531. * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
  4532. * Usage: 17
  4533. *
  4534. * @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").
  4535. * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
  4536. * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
  4537. * @param string Required prefix of class or function name
  4538. * @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)
  4539. * @return mixed Content from method/function call or false if the class/method/function was not found
  4540. * @see getUserObj()
  4541. */
  4542. public static function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$errorMode=0) {
  4543. global $TYPO3_CONF_VARS;
  4544. $content = false;
  4545. // Check persistent object and if found, call directly and exit.
  4546. if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
  4547. return call_user_func_array(
  4548. array(&$GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
  4549. $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method']),
  4550. array(&$params, &$ref)
  4551. );
  4552. }
  4553. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4554. if (strpos($funcName,':') !== false) {
  4555. list($file,$funcRef) = self::revExplode(':',$funcName,2);
  4556. $requireFile = self::getFileAbsFileName($file);
  4557. if ($requireFile) self::requireOnce($requireFile);
  4558. } else {
  4559. $funcRef = $funcName;
  4560. }
  4561. // Check for persistent object token, "&"
  4562. if (substr($funcRef,0,1)=='&') {
  4563. $funcRef = substr($funcRef,1);
  4564. $storePersistentObject = true;
  4565. } else {
  4566. $storePersistentObject = false;
  4567. }
  4568. // Check prefix is valid:
  4569. if ($checkPrefix &&
  4570. !self::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
  4571. !self::isFirstPartOfStr(trim($funcRef),'tx_')
  4572. ) {
  4573. $errorMsg = "Function/class '$funcRef' was not prepended with '$checkPrefix'";
  4574. if ($errorMode == 2) {
  4575. throw new Exception($errorMsg);
  4576. } elseif(!$errorMode) {
  4577. debug($errorMsg, 't3lib_div::callUserFunction');
  4578. }
  4579. return false;
  4580. }
  4581. // Call function or method:
  4582. $parts = explode('->',$funcRef);
  4583. if (count($parts)==2) { // Class
  4584. // Check if class/method exists:
  4585. if (class_exists($parts[0])) {
  4586. // Get/Create object of class:
  4587. if ($storePersistentObject) { // Get reference to current instance of class:
  4588. if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
  4589. $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = self::makeInstance($parts[0]);
  4590. }
  4591. $classObj = $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
  4592. } else { // Create new object:
  4593. $classObj = self::makeInstance($parts[0]);
  4594. }
  4595. if (method_exists($classObj, $parts[1])) {
  4596. // If persistent object should be created, set reference:
  4597. if ($storePersistentObject) {
  4598. $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
  4599. 'method' => $parts[1],
  4600. 'obj' => &$classObj
  4601. );
  4602. }
  4603. // Call method:
  4604. $content = call_user_func_array(
  4605. array(&$classObj, $parts[1]),
  4606. array(&$params, &$ref)
  4607. );
  4608. } else {
  4609. $errorMsg = "<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0];
  4610. if ($errorMode == 2) {
  4611. throw new Exception($errorMsg);
  4612. } elseif(!$errorMode) {
  4613. debug($errorMsg, 't3lib_div::callUserFunction');
  4614. }
  4615. }
  4616. } else {
  4617. $errorMsg = "<strong>ERROR:</strong> No class named: ".$parts[0];
  4618. if ($errorMode == 2) {
  4619. throw new Exception($errorMsg);
  4620. } elseif(!$errorMode) {
  4621. debug($errorMsg, 't3lib_div::callUserFunction');
  4622. }
  4623. }
  4624. } else { // Function
  4625. if (function_exists($funcRef)) {
  4626. $content = call_user_func_array($funcRef, array(&$params, &$ref));
  4627. } else {
  4628. $errorMsg = "<strong>ERROR:</strong> No function named: ".$funcRef;
  4629. if ($errorMode == 2) {
  4630. throw new Exception($errorMsg);
  4631. } elseif(!$errorMode) {
  4632. debug($errorMsg, 't3lib_div::callUserFunction');
  4633. }
  4634. }
  4635. }
  4636. return $content;
  4637. }
  4638. /**
  4639. * Creates and returns reference to a user defined object.
  4640. * 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.
  4641. * Usage: 5
  4642. *
  4643. * @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!).
  4644. * @param string Required prefix of class name. By default "tx_" is allowed.
  4645. * @param boolean If set, no debug() error message is shown if class/function is not present.
  4646. * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
  4647. * @see callUserFunction()
  4648. */
  4649. public static function getUserObj($classRef, $checkPrefix='user_', $silent=false) {
  4650. global $TYPO3_CONF_VARS;
  4651. // Check persistent object and if found, call directly and exit.
  4652. if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
  4653. return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
  4654. } else {
  4655. // Check file-reference prefix; if found, require_once() the file (should be library of code)
  4656. if (strpos($classRef,':') !== false) {
  4657. list($file,$class) = self::revExplode(':',$classRef,2);
  4658. $requireFile = self::getFileAbsFileName($file);
  4659. if ($requireFile) self::requireOnce($requireFile);
  4660. } else {
  4661. $class = $classRef;
  4662. }
  4663. // Check for persistent object token, "&"
  4664. if (substr($class,0,1)=='&') {
  4665. $class = substr($class,1);
  4666. $storePersistentObject = TRUE;
  4667. } else {
  4668. $storePersistentObject = FALSE;
  4669. }
  4670. // Check prefix is valid:
  4671. if ($checkPrefix &&
  4672. !self::isFirstPartOfStr(trim($class),$checkPrefix) &&
  4673. !self::isFirstPartOfStr(trim($class),'tx_')
  4674. ) {
  4675. if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'", 't3lib_div::getUserObj');
  4676. return FALSE;
  4677. }
  4678. // Check if class exists:
  4679. if (class_exists($class)) {
  4680. $classObj = self::makeInstance($class);
  4681. // If persistent object should be created, set reference:
  4682. if ($storePersistentObject) {
  4683. $GLOBALS['T3_VAR']['getUserObj'][$classRef] = $classObj;
  4684. }
  4685. return $classObj;
  4686. } else {
  4687. if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$class, 't3lib_div::getUserObj');
  4688. }
  4689. }
  4690. }
  4691. /**
  4692. * Creates an instance of a class taking into account the class-extensions
  4693. * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
  4694. * Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
  4695. * You can also pass arguments for a constructor:
  4696. * t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
  4697. *
  4698. * @param string Class name to instantiate
  4699. * @return object A reference to the object
  4700. */
  4701. public static function makeInstance($className) {
  4702. // holds references of singletons
  4703. static $instances = array();
  4704. // Get final classname
  4705. $className = self::getClassName($className);
  4706. if (isset($instances[$className])) {
  4707. // it's a singleton, get the existing instance
  4708. $instance = $instances[$className];
  4709. } else {
  4710. if (func_num_args() > 1) {
  4711. // getting the constructor arguments by removing this
  4712. // method's first argument (the class name)
  4713. $constructorArguments = func_get_args();
  4714. array_shift($constructorArguments);
  4715. $reflectedClass = new ReflectionClass($className);
  4716. $instance = $reflectedClass->newInstanceArgs($constructorArguments);
  4717. } else {
  4718. $instance = new $className;
  4719. }
  4720. if ($instance instanceof t3lib_Singleton) {
  4721. // it's a singleton, save the instance for later reuse
  4722. $instances[$className] = $instance;
  4723. }
  4724. }
  4725. return $instance;
  4726. }
  4727. /**
  4728. * Return classname for new instance
  4729. * Takes the class-extensions API of TYPO3 into account
  4730. * Usage: 17
  4731. *
  4732. * @param string Base Class name to evaluate
  4733. * @return string Final class name to instantiate with "new [classname]"
  4734. * @deprecated since TYPO3 4.3 - Use t3lib_div::makeInstance('myClass', $arg1, $arg2, ..., $argN)
  4735. */
  4736. public static function makeInstanceClassName($className) {
  4737. self::logDeprecatedFunction();
  4738. return (class_exists($className) && class_exists('ux_'.$className, false) ? self::makeInstanceClassName('ux_' . $className) : $className);
  4739. }
  4740. /**
  4741. * Returns the class name for a new instance, taking into account the
  4742. * class-extension API.
  4743. *
  4744. * @param string Base class name to evaluate
  4745. * @return string Final class name to instantiate with "new [classname]"
  4746. */
  4747. protected function getClassName($className) {
  4748. return (class_exists($className) && class_exists('ux_' . $className, false) ? self::getClassName('ux_' . $className) : $className);
  4749. }
  4750. /**
  4751. * Find the best service and check if it works.
  4752. * Returns object of the service class.
  4753. *
  4754. * @param string Type of service (service key).
  4755. * @param string Sub type like file extensions or similar. Defined by the service.
  4756. * @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
  4757. * @return object The service object or an array with error info's.
  4758. * @author René Fritz <r.fritz@colorcube.de>
  4759. */
  4760. public static function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) {
  4761. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4762. $error = FALSE;
  4763. if (!is_array($excludeServiceKeys) ) {
  4764. $excludeServiceKeys = self::trimExplode(',', $excludeServiceKeys, 1);
  4765. }
  4766. while ($info = t3lib_extMgm::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
  4767. // Check persistent object and if found, call directly and exit.
  4768. if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
  4769. // reset service and return object
  4770. $T3_VAR['makeInstanceService'][$info['className']]->reset();
  4771. return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
  4772. // include file and create object
  4773. } else {
  4774. $requireFile = self::getFileAbsFileName($info['classFile']);
  4775. if (@is_file($requireFile)) {
  4776. self::requireOnce ($requireFile);
  4777. $obj = self::makeInstance($info['className']);
  4778. if (is_object($obj)) {
  4779. if(!@is_callable(array($obj,'init'))) {
  4780. // use silent logging??? I don't think so.
  4781. die ('Broken service:'.self::view_array($info));
  4782. }
  4783. $obj->info = $info;
  4784. if ($obj->init()) { // service available?
  4785. // create persistent object
  4786. $T3_VAR['makeInstanceService'][$info['className']] = $obj;
  4787. // needed to delete temp files
  4788. register_shutdown_function(array(&$obj, '__destruct'));
  4789. return $obj; // object is passed as reference by function definition
  4790. }
  4791. $error = $obj->getLastErrorArray();
  4792. unset($obj);
  4793. }
  4794. }
  4795. }
  4796. // deactivate the service
  4797. t3lib_extMgm::deactivateService($info['serviceType'],$info['serviceKey']);
  4798. }
  4799. return $error;
  4800. }
  4801. /**
  4802. * Require a class for TYPO3
  4803. * Useful to require classes from inside other classes (not global scope). A limited set of global variables are available (see function)
  4804. */
  4805. public static function requireOnce($requireFile) {
  4806. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4807. require_once ($requireFile);
  4808. }
  4809. /**
  4810. * Requires a class for TYPO3
  4811. * Useful to require classes from inside other classes (not global scope).
  4812. * A limited set of global variables are available (see function)
  4813. *
  4814. * @param string $requireFile: Path of the file to be included
  4815. * @return void
  4816. */
  4817. public static function requireFile($requireFile) {
  4818. global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
  4819. require $requireFile;
  4820. }
  4821. /**
  4822. * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
  4823. * The fifth parameter ($encoding) will allow you to specify 'base64' encryption for the output (set $encoding=base64)
  4824. * Further the output has the charset set to ISO-8859-1 by default.
  4825. * Usage: 4
  4826. *
  4827. * @param string Email address to send to. (see PHP function mail())
  4828. * @param string Subject line, non-encoded. (see PHP function mail())
  4829. * @param string Message content, non-encoded. (see PHP function mail())
  4830. * @param string Headers, separated by LF
  4831. * @param string Encoding type: "base64", "quoted-printable", "8bit". Default value is "quoted-printable".
  4832. * @param string Charset used in encoding-headers (only if $encoding is set to a valid value which produces such a header)
  4833. * @param boolean If set, the header content will not be encoded.
  4834. * @return boolean True if mail was accepted for delivery, false otherwise
  4835. */
  4836. public static function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false) {
  4837. if (!$charset) {
  4838. $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] ? $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'] : 'ISO-8859-1';
  4839. }
  4840. $email = self::normalizeMailAddress($email);
  4841. if (!$dontEncodeHeader) {
  4842. // Mail headers must be ASCII, therefore we convert the whole header to either base64 or quoted_printable
  4843. $newHeaders=array();
  4844. foreach (explode(LF,$headers) as $line) { // Split the header in lines and convert each line separately
  4845. $parts = explode(': ',$line,2); // Field tags must not be encoded
  4846. if (count($parts)==2) {
  4847. if (0 == strcasecmp($parts[0], 'from')) {
  4848. $parts[1] = self::normalizeMailAddress($parts[1]);
  4849. }
  4850. $parts[1] = self::encodeHeader($parts[1],$encoding,$charset);
  4851. $newHeaders[] = implode(': ',$parts);
  4852. } else {
  4853. $newHeaders[] = $line; // Should never happen - is such a mail header valid? Anyway, just add the unchanged line...
  4854. }
  4855. }
  4856. $headers = implode(LF,$newHeaders);
  4857. unset($newHeaders);
  4858. $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>")
  4859. $subject = self::encodeHeader($subject,$encoding,$charset);
  4860. }
  4861. switch ((string)$encoding) {
  4862. case 'base64':
  4863. $headers=trim($headers).LF.
  4864. 'Mime-Version: 1.0'.LF.
  4865. 'Content-Type: text/plain; charset="'.$charset.'"'.LF.
  4866. 'Content-Transfer-Encoding: base64';
  4867. $message=trim(chunk_split(base64_encode($message.LF))).LF; // Adding LF because I think MS outlook 2002 wants it... may be removed later again.
  4868. break;
  4869. case '8bit':
  4870. $headers=trim($headers).LF.
  4871. 'Mime-Version: 1.0'.LF.
  4872. 'Content-Type: text/plain; charset='.$charset.LF.
  4873. 'Content-Transfer-Encoding: 8bit';
  4874. break;
  4875. case 'quoted-printable':
  4876. default:
  4877. $headers=trim($headers).LF.
  4878. 'Mime-Version: 1.0'.LF.
  4879. 'Content-Type: text/plain; charset='.$charset.LF.
  4880. 'Content-Transfer-Encoding: quoted-printable';
  4881. $message=self::quoted_printable($message);
  4882. break;
  4883. }
  4884. // Headers must be separated by CRLF according to RFC 2822, not just LF.
  4885. // But many servers (Gmail, for example) behave incorectly and want only LF.
  4886. // So we stick to LF in all cases.
  4887. $headers = trim(implode(LF, self::trimExplode(LF, $headers, true))); // Make sure no empty lines are there.
  4888. return t3lib_utility_Mail::mail($email, $subject, $message, $headers);
  4889. }
  4890. /**
  4891. * Implementation of quoted-printable encode.
  4892. * 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!
  4893. * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
  4894. * Usage: 2
  4895. *
  4896. * @param string Content to encode
  4897. * @param integer Length of the lines, default is 76
  4898. * @return string The QP encoded string
  4899. */
  4900. public static function quoted_printable($string,$maxlen=76) {
  4901. // Make sure the string contains only Unix linebreaks
  4902. $string = str_replace(CRLF, LF, $string); // Replace Windows breaks (\r\n)
  4903. $string = str_replace(CR, LF, $string); // Replace Mac breaks (\r)
  4904. $linebreak = LF; // Default line break for Unix systems.
  4905. if (TYPO3_OS=='WIN') {
  4906. $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.
  4907. }
  4908. $newString = '';
  4909. $theLines = explode(LF,$string); // Split lines
  4910. foreach ($theLines as $val) {
  4911. $newVal = '';
  4912. $theValLen = strlen($val);
  4913. $len = 0;
  4914. for ($index=0; $index < $theValLen; $index++) { // Walk through each character of this line
  4915. $char = substr($val,$index,1);
  4916. $ordVal = ord($char);
  4917. if ($len>($maxlen-4) || ($len>($maxlen-14) && $ordVal==32)) {
  4918. $newVal.='='.$linebreak; // Add a line break
  4919. $len=0; // Reset the length counter
  4920. }
  4921. if (($ordVal>=33 && $ordVal<=60) || ($ordVal>=62 && $ordVal<=126) || $ordVal==9 || $ordVal==32) {
  4922. $newVal.=$char; // This character is ok, add it to the message
  4923. $len++;
  4924. } else {
  4925. $newVal.=sprintf('=%02X',$ordVal); // Special character, needs to be encoded
  4926. $len+=3;
  4927. }
  4928. }
  4929. $newVal = preg_replace('/'.chr(32).'$/','=20',$newVal); // Replaces a possible SPACE-character at the end of a line
  4930. $newVal = preg_replace('/'.TAB.'$/','=09',$newVal); // Replaces a possible TAB-character at the end of a line
  4931. $newString.=$newVal.$linebreak;
  4932. }
  4933. return preg_replace('/'.$linebreak.'$/','',$newString); // Remove last newline
  4934. }
  4935. /**
  4936. * Encode header lines
  4937. * Email headers must be ASCII, therefore they will be encoded to quoted_printable (default) or base64.
  4938. *
  4939. * @param string Content to encode
  4940. * @param string Encoding type: "base64" or "quoted-printable". Default value is "quoted-printable".
  4941. * @param string Charset used for encoding
  4942. * @return string The encoded string
  4943. */
  4944. public static function encodeHeader($line,$enc='quoted-printable',$charset='iso-8859-1') {
  4945. // Avoid problems if "###" is found in $line (would conflict with the placeholder which is used below)
  4946. if (strpos($line,'###') !== false) {
  4947. return $line;
  4948. }
  4949. // Check if any non-ASCII characters are found - otherwise encoding is not needed
  4950. if (!preg_match('/[^'.chr(32).'-'.chr(127).']/',$line)) {
  4951. return $line;
  4952. }
  4953. // Wrap email addresses in a special marker
  4954. $line = preg_replace('/([^ ]+@[^ ]+)/', '###$1###', $line);
  4955. $matches = preg_split('/(.?###.+###.?|\(|\))/', $line, -1, PREG_SPLIT_NO_EMPTY);
  4956. foreach ($matches as $part) {
  4957. $oldPart = $part;
  4958. switch ((string)$enc) {
  4959. case 'base64':
  4960. $part = '=?'.$charset.'?B?'.base64_encode($part).'?=';
  4961. break;
  4962. case 'quoted-printable':
  4963. default:
  4964. $qpValue = self::quoted_printable($part,1000);
  4965. if ($part!=$qpValue) {
  4966. // Encoded words in the header should not contain non-encoded:
  4967. // * spaces. "_" is a shortcut for "=20". See RFC 2047 for details.
  4968. // * question mark. See RFC 1342 (http://tools.ietf.org/html/rfc1342)
  4969. $search = array(' ', '?');
  4970. $replace = array('_', '=3F');
  4971. $qpValue = str_replace($search, $replace, $qpValue);
  4972. $part = '=?'.$charset.'?Q?'.$qpValue.'?=';
  4973. }
  4974. break;
  4975. }
  4976. $line = str_replace($oldPart, $part, $line);
  4977. }
  4978. $line = preg_replace('/###(.+?)###/', '$1', $line); // Remove the wrappers
  4979. return $line;
  4980. }
  4981. /**
  4982. * 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.
  4983. * This function is about preserving long links in messages.
  4984. * Usage: 3
  4985. *
  4986. * @param string Message content
  4987. * @param string URL mode; "76" or "all"
  4988. * @param string URL of index script (see makeRedirectUrl())
  4989. * @return string Processed message content
  4990. * @see makeRedirectUrl()
  4991. */
  4992. public static function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
  4993. // Substitute URLs with shorter links:
  4994. foreach (array('http','https') as $protocol) {
  4995. $urlSplit = explode($protocol.'://',$message);
  4996. foreach ($urlSplit as $c => &$v) {
  4997. if ($c) {
  4998. $newParts = preg_split('/\s|[<>"{}|\\\^`()\']/', $v, 2);
  4999. $newURL = $protocol.'://'.$newParts[0];
  5000. switch ((string)$urlmode) {
  5001. case 'all':
  5002. $newURL = self::makeRedirectUrl($newURL,0,$index_script_url);
  5003. break;
  5004. case '76':
  5005. $newURL = self::makeRedirectUrl($newURL,76,$index_script_url);
  5006. break;
  5007. }
  5008. $v = $newURL . substr($v,strlen($newParts[0]));
  5009. }
  5010. }
  5011. $message = implode('',$urlSplit);
  5012. }
  5013. return $message;
  5014. }
  5015. /**
  5016. * Subfunction for substUrlsInPlainText() above.
  5017. * Usage: 2
  5018. *
  5019. * @param string Input URL
  5020. * @param integer URL string length limit
  5021. * @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'
  5022. * @return string Processed URL
  5023. */
  5024. public static function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
  5025. if (strlen($inUrl)>$l) {
  5026. $md5 = substr(md5($inUrl),0,20);
  5027. $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
  5028. '*',
  5029. 'cache_md5params',
  5030. 'md5hash=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params')
  5031. );
  5032. if (!$count) {
  5033. $insertFields = array(
  5034. 'md5hash' => $md5,
  5035. 'tstamp' => $GLOBALS['EXEC_TIME'],
  5036. 'type' => 2,
  5037. 'params' => $inUrl
  5038. );
  5039. $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
  5040. }
  5041. $inUrl=($index_script_url ? $index_script_url : self::getIndpEnv('TYPO3_REQUEST_DIR').'index.php').
  5042. '?RDCT='.$md5;
  5043. }
  5044. return $inUrl;
  5045. }
  5046. /**
  5047. * Function to compensate for FreeType2 96 dpi
  5048. * Usage: 21
  5049. *
  5050. * @param integer Fontsize for freetype function call
  5051. * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
  5052. */
  5053. public static function freetypeDpiComp($font_size) {
  5054. $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
  5055. if ($dpi!=72) $font_size = $font_size/$dpi*72;
  5056. return $font_size;
  5057. }
  5058. /**
  5059. * Initialize the system log.
  5060. *
  5061. * @return void
  5062. * @see sysLog()
  5063. */
  5064. public static function initSysLog() {
  5065. global $TYPO3_CONF_VARS;
  5066. // for CLI logging name is <fqdn-hostname>:<TYPO3-path>
  5067. if (defined('TYPO3_cliMode') && TYPO3_cliMode) {
  5068. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getHostname($requestHost=FALSE).':'.PATH_site;
  5069. }
  5070. // for Web logging name is <protocol>://<request-hostame>/<site-path>
  5071. else {
  5072. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] = self::getIndpEnv('TYPO3_SITE_URL');
  5073. }
  5074. // init custom logging
  5075. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  5076. $params = array('initLog'=>TRUE);
  5077. $fakeThis = FALSE;
  5078. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  5079. self::callUserFunction($hookMethod,$params,$fakeThis);
  5080. }
  5081. }
  5082. // init TYPO3 logging
  5083. foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
  5084. list($type,$destination) = explode(',',$log,3);
  5085. if ($type == 'syslog') {
  5086. if (TYPO3_OS == 'WIN') {
  5087. $facility = LOG_USER;
  5088. } else {
  5089. $facility = constant('LOG_'.strtoupper($destination));
  5090. }
  5091. openlog($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'], LOG_ODELAY, $facility);
  5092. }
  5093. }
  5094. $TYPO3_CONF_VARS['SYS']['systemLogLevel'] = self::intInRange($TYPO3_CONF_VARS['SYS']['systemLogLevel'],0,4);
  5095. $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit'] = TRUE;
  5096. }
  5097. /**
  5098. * Logs message to the system log.
  5099. * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
  5100. * If you want to implement the sysLog in your applications, simply add lines like:
  5101. * t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
  5102. *
  5103. * @param string Message (in English).
  5104. * @param string Extension key (from which extension you are calling the log) or "Core"
  5105. * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
  5106. * @return void
  5107. */
  5108. public static function sysLog($msg, $extKey, $severity=0) {
  5109. global $TYPO3_CONF_VARS;
  5110. $severity = self::intInRange($severity,0,4);
  5111. // is message worth logging?
  5112. if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity) return;
  5113. // initialize logging
  5114. if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
  5115. self::initSysLog();
  5116. }
  5117. // do custom logging
  5118. if (isset($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) &&
  5119. is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
  5120. $params = array('msg'=>$msg, 'extKey'=>$extKey, 'backTrace'=>debug_backtrace(), 'severity'=>$severity);
  5121. $fakeThis = FALSE;
  5122. foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
  5123. self::callUserFunction($hookMethod,$params,$fakeThis);
  5124. }
  5125. }
  5126. // TYPO3 logging enabled?
  5127. if (!$TYPO3_CONF_VARS['SYS']['systemLog']) return;
  5128. $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
  5129. $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
  5130. // use all configured logging options
  5131. foreach (explode(';',$TYPO3_CONF_VARS['SYS']['systemLog'],2) as $log) {
  5132. list($type,$destination,$level) = explode(',',$log,4);
  5133. // is message worth logging for this log type?
  5134. if (intval($level) > $severity) continue;
  5135. $msgLine = ' - '.$extKey.': '.$msg;
  5136. // write message to a file
  5137. if ($type == 'file') {
  5138. $file = fopen($destination, 'a');
  5139. if ($file) {
  5140. flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
  5141. fwrite($file, date($dateFormat.' '.$timeFormat).$msgLine.LF);
  5142. flock($file, LOCK_UN); // release the lock
  5143. fclose($file);
  5144. }
  5145. }
  5146. // send message per mail
  5147. elseif ($type == 'mail') {
  5148. list($to,$from) = explode('/',$destination);
  5149. t3lib_utility_Mail::mail($to, 'Warning - error in TYPO3 installation',
  5150. 'Host: '.$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].LF.
  5151. 'Extension: '.$extKey.LF.
  5152. 'Severity: '.$severity.LF.
  5153. LF.$msg,
  5154. ($from ? 'From: '.$from : '')
  5155. );
  5156. }
  5157. // use the PHP error log
  5158. elseif ($type == 'error_log') {
  5159. error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'].$msgLine, 0);
  5160. }
  5161. // use the system log
  5162. elseif ($type == 'syslog') {
  5163. $priority = array(LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_CRIT);
  5164. syslog($priority[(int)$severity], $msgLine);
  5165. }
  5166. }
  5167. }
  5168. /**
  5169. * Logs message to the development log.
  5170. * 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.
  5171. * The result is meant to make sense to developers during development or debugging of a site.
  5172. * 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.
  5173. * If you want to implement the devLog in your applications, simply add lines like:
  5174. * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
  5175. *
  5176. * @param string Message (in english).
  5177. * @param string Extension key (from which extension you are calling the log)
  5178. * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
  5179. * @param array Additional data you want to pass to the logger.
  5180. * @return void
  5181. */
  5182. public static function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
  5183. global $TYPO3_CONF_VARS;
  5184. if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
  5185. $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
  5186. $fakeThis = FALSE;
  5187. foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
  5188. self::callUserFunction($hookMethod,$params,$fakeThis);
  5189. }
  5190. }
  5191. }
  5192. /**
  5193. * Writes a message to the deprecation log.
  5194. *
  5195. * @param string Message (in English).
  5196. * @return void
  5197. */
  5198. public static function deprecationLog($msg) {
  5199. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5200. return;
  5201. }
  5202. $log = $GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog'];
  5203. $date = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] . ': ');
  5204. // legacy values (no strict comparison, $log can be boolean, string or int)
  5205. if ($log === TRUE || $log == '1') {
  5206. $log = 'file';
  5207. }
  5208. if (stripos($log, 'file') !== FALSE) {
  5209. // write a longer message to the deprecation log
  5210. $destination = self::getDeprecationLogFileName();
  5211. $file = @fopen($destination, 'a');
  5212. if ($file) {
  5213. flock($file, LOCK_EX); // try locking, but ignore if not available (eg. on NFS and FAT)
  5214. @fwrite($file, $date . $msg . LF);
  5215. flock($file, LOCK_UN); // release the lock
  5216. @fclose($file);
  5217. }
  5218. }
  5219. if (stripos($log, 'devlog') !== FALSE) {
  5220. // copy message also to the developer log
  5221. self::devLog($msg, 'Core', self::SYSLOG_SEVERITY_WARNING);
  5222. }
  5223. if (stripos($log, 'console') !== FALSE) {
  5224. self::debug($msg, $date, 'Deprecation Log');
  5225. }
  5226. }
  5227. /**
  5228. * Gets the absolute path to the deprecation log file.
  5229. *
  5230. * @return string absolute path to the deprecation log file
  5231. */
  5232. public static function getDeprecationLogFileName() {
  5233. return PATH_typo3conf .
  5234. 'deprecation_' .
  5235. self::shortMD5(
  5236. PATH_site . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
  5237. ) .
  5238. '.log';
  5239. }
  5240. /**
  5241. * Logs a call to a deprecated function.
  5242. * The log message will be taken from the annotation.
  5243. * @return void
  5244. */
  5245. public static function logDeprecatedFunction() {
  5246. if (!$GLOBALS['TYPO3_CONF_VARS']['SYS']['enableDeprecationLog']) {
  5247. return;
  5248. }
  5249. $trail = debug_backtrace();
  5250. if ($trail[1]['type']) {
  5251. $function = new ReflectionMethod($trail[1]['class'], $trail[1]['function']);
  5252. } else {
  5253. $function = new ReflectionFunction($trail[1]['function']);
  5254. }
  5255. $msg = '';
  5256. if (preg_match('/@deprecated\s+(.*)/', $function->getDocComment(), $match)) {
  5257. $msg = $match[1];
  5258. }
  5259. // trigger PHP error with a short message: <function> is deprecated (called from <source>, defined in <source>)
  5260. $errorMsg = 'Function ' . $trail[1]['function'];
  5261. if ($trail[1]['class']) {
  5262. $errorMsg .= ' of class ' . $trail[1]['class'];
  5263. }
  5264. $errorMsg .= ' is deprecated (called from '.$trail[1]['file'] . '#' . $trail[1]['line'] . ', defined in ' . $function->getFileName() . '#' . $function->getStartLine() . ')';
  5265. // write a longer message to the deprecation log: <function> <annotion> - <trace> (<source>)
  5266. $logMsg = $trail[1]['class'] . $trail[1]['type'] . $trail[1]['function'];
  5267. $logMsg .= '() - ' . $msg.' - ' . self::debug_trail();
  5268. $logMsg .= ' (' . substr($function->getFileName(), strlen(PATH_site)) . '#' . $function->getStartLine() . ')';
  5269. self::deprecationLog($logMsg);
  5270. }
  5271. /**
  5272. * Converts a one dimensional array to a one line string which can be used for logging or debugging output
  5273. * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
  5274. *
  5275. * @param array Data array which should be outputted
  5276. * @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.
  5277. * @param integer Long string values are shortened to this length. Default: 20
  5278. * @return string Output string with key names and their value as string
  5279. */
  5280. public static function arrayToLogString(array $arr, $valueList=array(), $valueLength=20) {
  5281. $str = '';
  5282. if (!is_array($valueList)) {
  5283. $valueList = self::trimExplode(',', $valueList, 1);
  5284. }
  5285. $valListCnt = count($valueList);
  5286. foreach ($arr as $key => $value) {
  5287. if (!$valListCnt || in_array($key, $valueList)) {
  5288. $str .= (string)$key.trim(': '.self::fixed_lgd_cs(str_replace(LF,'|',(string)$value), $valueLength)).'; ';
  5289. }
  5290. }
  5291. return $str;
  5292. }
  5293. /**
  5294. * Compile the command for running ImageMagick/GraphicsMagick.
  5295. *
  5296. * @param string Command to be run: identify, convert or combine/composite
  5297. * @param string The parameters string
  5298. * @param string Override the default path
  5299. * @return string Compiled command that deals with IM6 & GraphicsMagick
  5300. */
  5301. public static function imageMagickCommand($command, $parameters, $path='') {
  5302. $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
  5303. $isExt = (TYPO3_OS=='WIN' ? '.exe' : '');
  5304. $switchCompositeParameters=false;
  5305. if(!$path) { $path = $gfxConf['im_path']; }
  5306. $im_version = strtolower($gfxConf['im_version_5']);
  5307. $combineScript = $gfxConf['im_combine_filename'] ? trim($gfxConf['im_combine_filename']) : 'combine';
  5308. if($command==='combine') { // This is only used internally, has no effect outside
  5309. $command = 'composite';
  5310. }
  5311. // Compile the path & command
  5312. if($im_version==='gm') {
  5313. $switchCompositeParameters=true;
  5314. $path .= 'gm'.$isExt.' '.$command;
  5315. } else {
  5316. if($im_version==='im6') { $switchCompositeParameters=true; }
  5317. $path .= (($command=='composite') ? $combineScript : $command).$isExt;
  5318. }
  5319. // strip profile information for thumbnails and reduce their size
  5320. if ($parameters && $command != 'identify' && $gfxConf['im_useStripProfileByDefault'] && $gfxConf['im_stripProfileCommand'] != '') {
  5321. if (strpos($parameters, $gfxConf['im_stripProfileCommand']) === false) {
  5322. // Determine whether the strip profile action has be disabled by TypoScript:
  5323. if ($parameters !== '-version' && strpos($parameters, '###SkipStripProfile###') === false) {
  5324. $parameters = $gfxConf['im_stripProfileCommand'] . ' ' . $parameters;
  5325. } else {
  5326. $parameters = str_replace('###SkipStripProfile###', '', $parameters);
  5327. }
  5328. }
  5329. }
  5330. $cmdLine = $path.' '.$parameters;
  5331. 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
  5332. $paramsArr = self::unQuoteFilenames($parameters);
  5333. if(count($paramsArr)>5) { // The mask image has been specified => swap the parameters
  5334. $tmp = $paramsArr[count($paramsArr)-3];
  5335. $paramsArr[count($paramsArr)-3] = $paramsArr[count($paramsArr)-4];
  5336. $paramsArr[count($paramsArr)-4] = $tmp;
  5337. }
  5338. $cmdLine = $path.' '.implode(' ', $paramsArr);
  5339. }
  5340. return $cmdLine;
  5341. }
  5342. /**
  5343. * 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.
  5344. *
  5345. * @param string The whole parameters string
  5346. * @param boolean If set, the elements of the resulting array are unquoted.
  5347. * @return array Exploded parameters
  5348. */
  5349. public static function unQuoteFilenames($parameters,$unQuote=FALSE) {
  5350. $paramsArr = explode(' ', trim($parameters));
  5351. $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.
  5352. foreach ($paramsArr as $k => $v) {
  5353. if($quoteActive > -1) {
  5354. $paramsArr[$quoteActive] .= ' '.$v;
  5355. unset($paramsArr[$k]);
  5356. if(preg_match('/"$/', $v)) { $quoteActive = -1; }
  5357. } elseif(!trim($v)) {
  5358. unset($paramsArr[$k]); // Remove empty elements
  5359. } elseif(preg_match('/^"/', $v)) {
  5360. $quoteActive = $k;
  5361. }
  5362. }
  5363. if($unQuote) {
  5364. foreach ($paramsArr as $key => &$val) {
  5365. $val = preg_replace('/(^"|"$)/','',$val);
  5366. }
  5367. }
  5368. // return reindexed array
  5369. return array_values($paramsArr);
  5370. }
  5371. /**
  5372. * Quotes a string for usage as JS parameter. Depends whether the value is
  5373. * used in script tags (it doesn't need/must not get htmlspecialchar'ed in
  5374. * this case).
  5375. *
  5376. * @param string $value the string to encode, may be empty
  5377. * @param boolean $withinCData
  5378. * whether the escaped data is expected to be used as CDATA and thus
  5379. * does not need to be htmlspecialchared
  5380. *
  5381. * @return string the encoded value already quoted (with single quotes),
  5382. * will not be empty
  5383. */
  5384. static public function quoteJSvalue($value, $withinCData = false) {
  5385. $escapedValue = addcslashes(
  5386. $value, '\'' . '"' . '\\' . TAB . LF . CR
  5387. );
  5388. if (!$withinCData) {
  5389. $escapedValue = htmlspecialchars($escapedValue);
  5390. }
  5391. return '\'' . $escapedValue . '\'';
  5392. }
  5393. /**
  5394. * Ends and cleans all output buffers
  5395. *
  5396. * @return void
  5397. */
  5398. public static function cleanOutputBuffers() {
  5399. while (ob_end_clean());
  5400. header('Content-Encoding: None', TRUE);
  5401. }
  5402. /**
  5403. * Ends and flushes all output buffers
  5404. *
  5405. * @return void
  5406. */
  5407. public static function flushOutputBuffers() {
  5408. $obContent = '';
  5409. while ($obContent .= ob_get_clean());
  5410. // if previously a "Content-Encoding: whatever" has been set, we have to unset it
  5411. if (!headers_sent()) {
  5412. $headersList = headers_list();
  5413. foreach ($headersList as $header) {
  5414. // split it up at the :
  5415. list($key, $value) = self::trimExplode(':', $header, TRUE);
  5416. // check if we have a Content-Encoding other than 'None'
  5417. if (strtolower($key) === 'content-encoding' && strtolower($value) !== 'none') {
  5418. header('Content-Encoding: None');
  5419. break;
  5420. }
  5421. }
  5422. }
  5423. echo $obContent;
  5424. }
  5425. }
  5426. ?>