PageRenderTime 77ms CodeModel.GetById 32ms RepoModel.GetById 1ms 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

Large files files are truncated, but you can click here to view the full file

  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];…

Large files files are truncated, but you can click here to view the full file