2 /***************************************************************
5 * (c) 1999-2008 Kasper Skaarhoj (kasperYYYY@typo3.com)
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains the reknown class "t3lib_div" with general purpose functions
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
33 * Usage counts are based on search 22/2 2003 through whole source including tslib/
35 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
38 * [CLASS/FUNCTION INDEX of SCRIPT]
42 * 232: class t3lib_div
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)
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)
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="\n",$charWidth=76)
62 * 574: function breakLinesForEmail($str,$implChar="\n",$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)
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='"')
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)
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)
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='')
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='')
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)
200 * TOTAL FUNCTIONS: 138
201 * (This index is automatically created/updated by the extension "extdeveval")
217 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
218 * Most of the functions does not relate specifically to TYPO3
219 * However a section of functions requires certain TYPO3 features available
220 * See comments in the source.
221 * You are encouraged to use this library in your own scripts!
224 * The class is intended to be used without creating an instance of it.
225 * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
226 * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
228 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
232 final class t3lib_div
{
234 // Severity constants used by t3lib_div::sysLog()
235 const SYSLOG_SEVERITY_INFO
= 0;
236 const SYSLOG_SEVERITY_NOTICE
= 1;
237 const SYSLOG_SEVERITY_WARNING
= 2;
238 const SYSLOG_SEVERITY_ERROR
= 3;
239 const SYSLOG_SEVERITY_FATAL
= 4;
241 // HTTP Headers, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for Details
242 const HTTP_STATUS_100
= 'HTTP/1.1 100 Continue';
243 const HTTP_STATUS_101
= 'HTTP/1.1 101 Switching Protocols';
245 const HTTP_STATUS_200
= 'HTTP/1.1 200 OK';
246 const HTTP_STATUS_201
= 'HTTP/1.1 201 Created';
247 const HTTP_STATUS_202
= 'HTTP/1.1 202 Accepted';
248 const HTTP_STATUS_203
= 'HTTP/1.1 203 Non-Authoritative Information';
249 const HTTP_STATUS_204
= 'HTTP/1.1 204 No Content';
250 const HTTP_STATUS_205
= 'HTTP/1.1 205 Reset Content';
251 const HTTP_STATUS_206
= 'HTTP/1.1 206 Partial Content';
253 const HTTP_STATUS_300
= 'HTTP/1.1 300 Multiple Choices';
254 const HTTP_STATUS_301
= 'HTTP/1.1 301 Moved Permanently';
255 const HTTP_STATUS_302
= 'HTTP/1.1 302 Found';
256 const HTTP_STATUS_303
= 'HTTP/1.1 303 See Other';
257 const HTTP_STATUS_304
= 'HTTP/1.1 304 Not Modified';
258 const HTTP_STATUS_305
= 'HTTP/1.1 305 Use Proxy';
259 const HTTP_STATUS_307
= 'HTTP/1.1 307 Temporary Redirect';
261 const HTTP_STATUS_400
= 'HTTP/1.1 400 Bad Request';
262 const HTTP_STATUS_401
= 'HTTP/1.1 401 Unauthorized';
263 const HTTP_STATUS_402
= 'HTTP/1.1 402 Payment Required';
264 const HTTP_STATUS_403
= 'HTTP/1.1 403 Forbidden';
265 const HTTP_STATUS_404
= 'HTTP/1.1 404 Not Found';
266 const HTTP_STATUS_405
= 'HTTP/1.1 405 Method Not Allowed';
267 const HTTP_STATUS_406
= 'HTTP/1.1 406 Not Acceptable';
268 const HTTP_STATUS_407
= 'HTTP/1.1 407 Proxy Authentication Required';
269 const HTTP_STATUS_408
= 'HTTP/1.1 408 Request Timeout';
270 const HTTP_STATUS_409
= 'HTTP/1.1 409 Conflict';
271 const HTTP_STATUS_410
= 'HTTP/1.1 410 Gone';
272 const HTTP_STATUS_411
= 'HTTP/1.1 411 Length Required';
273 const HTTP_STATUS_412
= 'HTTP/1.1 412 Precondition Failed';
274 const HTTP_STATUS_413
= 'HTTP/1.1 413 Request Entity Too Large';
275 const HTTP_STATUS_414
= 'HTTP/1.1 414 Request-URI Too Long';
276 const HTTP_STATUS_415
= 'HTTP/1.1 415 Unsupported Media Type';
277 const HTTP_STATUS_416
= 'HTTP/1.1 416 Requested Range Not Satisfiable';
278 const HTTP_STATUS_417
= 'HTTP/1.1 417 Expectation Failed';
280 const HTTP_STATUS_500
= 'HTTP/1.1 500 Internal Server Error';
281 const HTTP_STATUS_501
= 'HTTP/1.1 501 Not Implemented';
282 const HTTP_STATUS_502
= 'HTTP/1.1 502 Bad Gateway';
283 const HTTP_STATUS_503
= 'HTTP/1.1 503 Service Unavailable';
284 const HTTP_STATUS_504
= 'HTTP/1.1 504 Gateway Timeout';
285 const HTTP_STATUS_505
= 'HTTP/1.1 505 Version Not Supported';
289 /*************************
294 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
295 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
296 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
297 * Eventually TYPO3 should provide this in the global space as well.
298 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
300 *************************/
303 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
304 * Strips slashes from all output, both strings and arrays.
305 * This function substitutes t3lib_div::GPvar()
306 * 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!
309 * @param string GET/POST var to return
310 * @return mixed POST var named $var and if not set, the GET var of the same name.
313 public static function _GP($var) {
314 if(empty($var)) return;
315 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
317 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
323 * Returns the global GET array (or value from) normalized to contain un-escaped values.
324 * ALWAYS use this API function to acquire the GET variables!
327 * @param string Optional pointer to value in GET array (basically name of GET var)
328 * @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!*
329 * @see _POST(), _GP(), _GETset()
331 public static function _GET($var=NULL) {
332 $value = ($var === NULL) ?
$_GET : (empty($var) ?
NULL : $_GET[$var]);
333 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
334 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
340 * Returns the global POST array (or value from) normalized to contain un-escaped values.
341 * ALWAYS use this API function to acquire the POST variables!
344 * @param string Optional pointer to value in POST array (basically name of POST var)
345 * @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!*
348 public static function _POST($var=NULL) {
349 $value = ($var === NULL) ?
$_POST : (empty($var) ?
NULL : $_POST[$var]);
350 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
351 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
357 * Writes input value to $_GET
360 * @param mixed Array to write to $_GET. Values should NOT be escaped at input time (but will be escaped before writing according to TYPO3 standards).
361 * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
364 public static function _GETset($inputGet,$key='') {
365 // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
366 if (strcmp($key,'')) {
367 if (is_array($inputGet)) {
368 t3lib_div
::addSlashesOnArray($inputGet);
370 $inputGet = addslashes($inputGet);
372 $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
373 } elseif (is_array($inputGet)) {
374 t3lib_div
::addSlashesOnArray($inputGet);
375 $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
381 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
382 * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
385 * @param string GET/POST var to return
386 * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
387 * @return mixed POST var named $var and if not set, the GET var of the same name.
388 * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
391 public static function GPvar($var,$strip=0) {
392 if(empty($var)) return;
393 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
394 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.
395 if ($strip && isset($value) && is_array($value)) { t3lib_div
::stripSlashesOnArray($value); }
400 * Returns the GET/POST global arrays merged with POST taking precedence.
403 * @param string Key (variable name) from GET or POST vars
404 * @return array Returns the GET vars merged recursively onto the POST vars.
408 public static function GParrayMerged($var) {
409 $postA = is_array($_POST[$var]) ?
$_POST[$var] : array();
410 $getA = is_array($_GET[$var]) ?
$_GET[$var] : array();
411 $mergedA = t3lib_div
::array_merge_recursive_overrule($getA,$postA);
412 t3lib_div
::stripSlashesOnArray($mergedA);
417 * Wrapper for the RemoveXSS function.
418 * Removes potential XSS code from an input string.
420 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
422 * @param string Input string
423 * @return string Input string with potential XSS code removed
425 public static function removeXSS($string) {
426 require_once(PATH_typo3
.'contrib/RemoveXSS/RemoveXSS.php');
427 $string = RemoveXSS
::RemoveXSS($string);
440 /*************************
444 *************************/
448 * Compressing a GIF file if not already LZW compressed
449 * 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)
451 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
453 * 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!)
454 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
458 * $theFile is expected to be a valid GIF-file!
459 * The function returns a code for the operation.
462 * @param string Filepath
463 * @param string See description of function
464 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
466 public static function gif_compress($theFile, $type) {
467 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
469 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
470 if (($type=='IM' ||
!$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
471 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
475 } elseif (($type=='GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
476 $tempImage = imageCreateFromGif($theFile);
477 imageGif($tempImage, $theFile);
478 imageDestroy($tempImage);
486 * Converts a png file to gif
487 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
490 * @param string $theFile the filename with path
491 * @return string new filename
493 public static function png_to_gif_by_imagemagick($theFile) {
494 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
495 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
496 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
497 && strtolower(substr($theFile,-4,4))=='.png'
498 && @is_file
($theFile)) { // IM
499 $newFile = substr($theFile,0,-4).'.gif';
500 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
503 // 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!!
509 * Returns filename of the png/gif version of the input file (which can be png or gif).
510 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
513 * @param string Filepath of image file
514 * @param boolean If set, then input file is converted to PNG, otherwise to GIF
515 * @return string If the new image file exists, it's filepath is returned
517 public static function read_png_gif($theFile,$output_png=0) {
518 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file
($theFile)) {
519 $ext = strtolower(substr($theFile,-4,4));
521 ((string)$ext=='.png' && $output_png) ||
522 ((string)$ext=='.gif' && !$output_png)
526 $newFile = PATH_site
.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?
'.png':'.gif');
527 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
529 if (@is_file
($newFile)) return $newFile;
548 /*************************
552 *************************/
556 * Returns a new string of max. $chars length.
557 * If the string is longer, it will be truncated and appended with '...'.
560 * @param string string to truncate
561 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
562 * @param string String to append to the output if it is truncated, default is '...'
563 * @return string new string
564 * @deprecated Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
565 * @see fixed_lgd_pre()
567 public static function fixed_lgd($string,$origChars,$preStr='...') {
568 $chars = abs($origChars);
570 if(strlen($string)>$chars) {
571 return $origChars < 0 ?
572 $preStr.trim(substr($string, -($chars-3))) :
573 trim(substr($string, 0, $chars-3)).$preStr;
581 * Returns a new string of max. $chars length.
582 * If the string is longer, it will be truncated and prepended with '...'.
583 * This works like fixed_lgd, but is truncated in the start of the string instead of the end
586 * @param string string to truncate
587 * @param integer must be an integer of at least 4
588 * @return string new string
589 * @deprecated Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
592 public static function fixed_lgd_pre($string,$chars) {
593 return strrev(t3lib_div
::fixed_lgd(strrev($string),$chars));
597 * Truncates a string with appended/prepended "..." and takes backend character set into consideration
598 * Use only from backend!
601 * @param string string to truncate
602 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
603 * @return string New string
606 public static function fixed_lgd_cs($string,$chars) {
607 if (is_object($GLOBALS['LANG'])) {
608 return $GLOBALS['LANG']->csConvObj
->crop($GLOBALS['LANG']->charSet
,$string,$chars,'...');
610 return t3lib_div
::fixed_lgd($string, $chars);
615 * Breaks up the text for emails
618 * @param string The string to break up
619 * @param string The string to implode the broken lines with (default/typically \n)
620 * @param integer The line length
621 * @deprecated Use PHP function wordwrap()
624 public static function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
625 $lines = explode(chr(10),$str);
627 foreach ($lines as $lStr) {
628 $outArr[] = t3lib_div
::breakLinesForEmail($lStr,$implChar,$charWidth);
630 return implode(chr(10),$outArr);
634 * Breaks up a single line of text for emails
637 * @param string The string to break up
638 * @param string The string to implode the broken lines with (default/typically \n)
639 * @param integer The line length
641 * @see breakTextForEmail()
643 public static function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
647 while(strlen($str)>$p) {
648 $substr=substr($str,$p,$l);
649 if (strlen($substr)==$l) {
650 $count = count(explode(' ',trim(strrev($substr))));
651 if ($count>1) { // OK...
652 $parts = explode(' ',strrev($substr),2);
653 $theLine = strrev($parts[1]);
655 $afterParts = explode(' ',substr($str,$l+
$p),2);
656 $theLine = $substr.$afterParts[0];
658 if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
663 $lines[]=trim($theLine);
664 $p+
=strlen($theLine);
665 if (!trim(substr($str,$p,$l))) break; // added...
667 return implode($implChar,$lines);
671 * Match IP number with list of numbers with wildcard
672 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
675 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
676 * @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.
677 * @return boolean True if an IP-mask from $list matches $baseIP
679 public static function cmpIP($baseIP, $list) {
683 } elseif ($list === '*') {
686 if (strpos($baseIP, ':') !== false && t3lib_div
::validIPv6($baseIP)) {
687 return t3lib_div
::cmpIPv6($baseIP, $list);
689 return t3lib_div
::cmpIPv4($baseIP, $list);
694 * Match IPv4 number with list of numbers with wildcard
696 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
697 * @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)
698 * @return boolean True if an IP-mask from $list matches $baseIP
700 public static function cmpIPv4($baseIP, $list) {
701 $IPpartsReq = explode('.',$baseIP);
702 if (count($IPpartsReq)==4) {
703 $values = t3lib_div
::trimExplode(',',$list,1);
705 foreach($values as $test) {
706 list($test,$mask) = explode('/',$test);
710 $lnet = ip2long($test);
711 $lip = ip2long($baseIP);
712 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
713 $firstpart = substr($binnet,0,$mask);
714 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
715 $firstip = substr($binip,0,$mask);
716 $yes = (strcmp($firstpart,$firstip)==0);
719 $IPparts = explode('.',$test);
721 foreach ($IPparts as $index => $val) {
723 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
728 if ($yes) return true;
735 * Match IPv6 address with a list of IPv6 prefixes
737 * @param string $baseIP is the current remote IP address for instance
738 * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
739 * @return boolean True if an baseIP matches any prefix
741 public static function cmpIPv6($baseIP, $list) {
742 $success = false; // Policy default: Deny connection
743 $baseIP = t3lib_div
::normalizeIPv6($baseIP);
745 $values = t3lib_div
::trimExplode(',',$list,1);
746 foreach ($values as $test) {
747 list($test,$mask) = explode('/',$test);
748 if (t3lib_div
::validIPv6($test)) {
749 $test = t3lib_div
::normalizeIPv6($test);
751 switch ($mask) { // test on /48 /64
753 $testBin = substr(t3lib_div
::IPv6Hex2Bin($test), 0, 48);
754 $baseIPBin = substr(t3lib_div
::IPv6Hex2Bin($baseIP), 0, 48);
755 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
758 $testBin = substr(t3lib_div
::IPv6Hex2Bin($test), 0, 64);
759 $baseIPBin = substr(t3lib_div
::IPv6Hex2Bin($baseIP), 0, 64);
760 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
766 if (t3lib_div
::validIPv6($test)) { // test on full ip address 128 bits
767 $testBin = t3lib_div
::IPv6Hex2Bin($test);
768 $baseIPBin = t3lib_div
::IPv6Hex2Bin($baseIP);
769 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
773 if ($success) return true;
779 * [Describe function...]
781 * @param [type] $hex: ...
784 public static function IPv6Hex2Bin ($hex) {
786 $hex = str_replace(':', '', $hex); // Replace colon to nothing
787 for ($i=0; $i<strlen($hex); $i=$i+
2) {
788 $bin.= chr(hexdec(substr($hex, $i, 2)));
794 * Normalize an IPv6 address to full length
796 * @param string Given IPv6 address
797 * @return string Normalized address
799 public static function normalizeIPv6($address) {
800 $normalizedAddress = '';
801 $stageOneAddress = '';
803 $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
804 if (count($chunks)==2) {
805 $chunksLeft = explode(':', $chunks[0]);
806 $chunksRight = explode(':', $chunks[1]);
807 $left = count($chunksLeft);
808 $right = count($chunksRight);
810 // Special case: leading zero-only blocks count to 1, should be 0
811 if ($left==1 && strlen($chunksLeft[0])==0) $left=0;
813 $hiddenBlocks = 8 - ($left +
$right);
815 while ($h<$hiddenBlocks) {
816 $hiddenPart .= '0000:';
821 $stageOneAddress = $hiddenPart . $chunks[1];
823 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
825 } else $stageOneAddress = $address;
827 // normalize the blocks:
828 $blocks = explode(':', $stageOneAddress);
830 foreach ($blocks as $block) {
833 $hiddenZeros = 4 - strlen($block);
834 while ($i < $hiddenZeros) {
838 $normalizedAddress .= $tmpBlock . $block;
839 if ($divCounter < 7) {
840 $normalizedAddress .= ':';
844 return $normalizedAddress;
848 * Validate a given IP address.
850 * Possible format are IPv4 and IPv6.
852 * @param string IP address to be tested
853 * @return boolean True if $ip is either of IPv4 or IPv6 format.
855 public static function validIP($ip) {
856 return (filter_var($ip, FILTER_VALIDATE_IP
) !== false);
860 * Validate a given IP address to the IPv4 address format.
862 * Example for possible format: 10.0.45.99
864 * @param string IP address to be tested
865 * @return boolean True if $ip is of IPv4 format.
867 public static function validIPv4($ip) {
868 return (filter_var($ip, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV4
) !== false);
872 * Validate a given IP address to the IPv6 address format.
874 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
876 * @param string IP address to be tested
877 * @return boolean True if $ip is of IPv6 format.
879 public static function validIPv6($ip) {
880 return (filter_var($ip, FILTER_VALIDATE_IP
, FILTER_FLAG_IPV6
) !== false);
884 * Match fully qualified domain name with list of strings with wildcard
886 * @param string The current remote IP address for instance, typ. REMOTE_ADDR
887 * @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)
888 * @return boolean True if a domain name mask from $list matches $baseIP
890 public static function cmpFQDN($baseIP, $list) {
891 if (count(explode('.',$baseIP))==4) {
892 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
893 $values = t3lib_div
::trimExplode(',',$list,1);
895 foreach($values as $test) {
896 $hostNameParts = explode('.',$test);
899 foreach($hostNameParts as $index => $val) {
901 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
905 if ($yes) return true;
912 * Check for item in list
913 * Check if an item exists in a comma-separated list of items.
916 * @param string comma-separated list of items (string)
917 * @param string item to check for
918 * @return boolean true if $item is in $list
920 public static function inList($list, $item) {
921 return (strpos(','.$list.',', ','.$item.',')!==false ?
true : false);
925 * Removes an item from a comma-separated list of items.
928 * @param string element to remove
929 * @param string comma-separated list of items (string)
930 * @return string new comma-separated list of items
932 public static function rmFromList($element,$list) {
933 $items = explode(',',$list);
934 foreach ($items as $k => $v) {
939 return implode(',',$items);
943 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
944 * Ranges are limited to 1000 values per range.
946 * @param string comma-separated list of integers with ranges (string)
947 * @return string new comma-separated list of items
948 * @author Martin Kutschker <martin.kutschker@activesolution.at>
950 public static function expandList($list) {
951 $items = explode(',',$list);
953 foreach ($items as $item) {
954 $range = explode('-',$item);
955 if (isset($range[1])) {
956 $runAwayBrake = 1000;
957 for ($n=$range[0]; $n<=$range[1]; $n++
) {
961 if ($runAwayBrake<=0) break;
967 return implode(',',$list);
971 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
974 * @param integer Input value
975 * @param integer Lower limit
976 * @param integer Higher limit
977 * @param integer Default value if input is false.
978 * @return integer The input value forced into the boundaries of $min and $max
980 public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
981 // Returns $theInt as an integer in the integerspace from $min to $max
982 $theInt = intval($theInt);
983 if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
984 if ($theInt<$min){$theInt=$min;}
985 if ($theInt>$max){$theInt=$max;}
990 * Returns the $integer if greater than zero, otherwise returns zero.
993 * @param integer Integer string to process
996 public static function intval_positive($theInt) {
997 $theInt = intval($theInt);
998 if ($theInt<0){$theInt=0;}
1003 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
1006 * @param string Version number on format x.x.x
1007 * @return integer Integer version of version number (where each part can count to 999)
1009 public static function int_from_ver($verNumberStr) {
1010 $verParts = explode('.',$verNumberStr);
1011 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
));
1015 * Returns true if the current TYPO3 version (or compatibility version) is compatible to the input version
1016 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
1018 * @param string Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
1019 * @return boolean Returns true if this setup is compatible with the provided version number
1020 * @todo Still needs a function to convert versions to branches
1022 public static function compat_version($verNumberStr) {
1023 global $TYPO3_CONF_VARS;
1024 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ?
$TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch
;
1026 if (t3lib_div
::int_from_ver($currVersionStr) < t3lib_div
::int_from_ver($verNumberStr)) {
1034 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
1037 * @param string String to md5-hash
1038 * @return integer Returns 28bit integer-hash
1040 public static function md5int($str) {
1041 return hexdec(substr(md5($str),0,7));
1045 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
1049 * @param string Input string to be md5-hashed
1050 * @param integer The string-length of the output
1051 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
1053 public static function shortMD5($input, $len=10) {
1054 return substr(md5($input),0,$len);
1058 * Takes comma-separated lists and arrays and removes all duplicates
1059 * If a value in the list is trim(empty), the value is ignored.
1062 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
1063 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
1064 * @return string Returns the list without any duplicates of values, space around values are trimmed
1066 public static function uniqueList($in_list, $secondParameter=NULL) {
1067 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
1068 if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
1070 return implode(',',array_unique(t3lib_div
::trimExplode(',',$in_list,1)));
1074 * Splits a reference to a file in 5 parts
1077 * @param string Filename/filepath to be analysed
1078 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
1080 public static function split_fileref($fileref) {
1082 if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
1083 $info['path'] = $reg[1];
1084 $info['file'] = $reg[2];
1087 $info['file'] = $fileref;
1090 if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
1091 $info['filebody'] = $reg[1];
1092 $info['fileext'] = strtolower($reg[2]);
1093 $info['realFileext'] = $reg[2];
1095 $info['filebody'] = $info['file'];
1096 $info['fileext'] = '';
1103 * Returns the directory part of a path without trailing slash
1104 * If there is no dir-part, then an empty string is returned.
1107 * '/dir1/dir2/script.php' => '/dir1/dir2'
1108 * '/dir1/' => '/dir1'
1109 * 'dir1/script.php' => 'dir1'
1110 * 'd/script.php' => 'd'
1111 * '/script.php' => ''
1115 * @param string Directory name / path
1116 * @return string Processed input value. See function description.
1118 public static function dirname($path) {
1119 $p = t3lib_div
::revExplode('/',$path,2);
1120 return count($p)==2 ?
$p[0] : '';
1124 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1127 * @param string A hexadecimal color code, #xxxxxx
1128 * @param integer Offset value 0-255
1129 * @param integer Offset value 0-255
1130 * @param integer Offset value 0-255
1131 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1132 * @see modifyHTMLColorAll()
1134 public static function modifyHTMLColor($color,$R,$G,$B) {
1135 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1136 $nR = t3lib_div
::intInRange(hexdec(substr($color,1,2))+
$R,0,255);
1137 $nG = t3lib_div
::intInRange(hexdec(substr($color,3,2))+
$G,0,255);
1138 $nB = t3lib_div
::intInRange(hexdec(substr($color,5,2))+
$B,0,255);
1140 substr('0'.dechex($nR),-2).
1141 substr('0'.dechex($nG),-2).
1142 substr('0'.dechex($nB),-2);
1146 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1149 * @param string A hexadecimal color code, #xxxxxx
1150 * @param integer Offset value 0-255 for all three channels.
1151 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1152 * @see modifyHTMLColor()
1154 public static function modifyHTMLColorAll($color,$all) {
1155 return t3lib_div
::modifyHTMLColor($color,$all,$all,$all);
1159 * Removes comma (if present) in the end of string
1162 * @param string String from which the comma in the end (if any) will be removed.
1165 public static function rm_endcomma($string) {
1166 return ereg_replace(',$','',$string);
1170 * strtoupper which converts danish (and other characters) characters as well
1173 * @param string String to process
1175 * @deprecated Use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
1178 public static function danish_strtoupper($string) {
1179 $value = strtoupper($string);
1180 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
1184 * Change umlaut characters to plain ASCII with normally two character target
1185 * Only known characters will be converted, so don't expect a result for any character.
1189 * @param string String to convert.
1190 * @deprecated Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
1193 public static function convUmlauts($str) {
1194 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
1195 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
1196 return preg_replace($pat,$repl,$str);
1200 * Tests if the input is an integer.
1203 * @param mixed Any input variable to test.
1204 * @return boolean Returns true if string is an integer
1206 public static function testInt($var) {
1207 return !strcmp($var,intval($var));
1211 * Returns true if the first part of $str matches the string $partStr
1214 * @param string Full string to check
1215 * @param string Reference string which must be found as the "first part" of the full string
1216 * @return boolean True if $partStr was found to be equal to the first part of $str
1218 public static function isFirstPartOfStr($str,$partStr) {
1219 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
1220 $psLen = strlen($partStr);
1222 return substr($str,0,$psLen)==(string)$partStr;
1223 } else return false;
1227 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1230 * @param integer Number of bytes to format.
1231 * @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)
1232 * @return string Formatted representation of the byte number, for output.
1234 public static function formatSize($sizeInBytes,$labels='') {
1237 if (strlen($labels) == 0) {
1238 $labels = ' | K| M| G';
1240 $labels = str_replace('"','',$labels);
1242 $labelArr = explode('|',$labels);
1245 if ($sizeInBytes>900) {
1246 if ($sizeInBytes>900000000) { // GB
1247 $val = $sizeInBytes/(1024*1024*1024);
1248 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[3];
1250 elseif ($sizeInBytes>900000) { // MB
1251 $val = $sizeInBytes/(1024*1024);
1252 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[2];
1254 $val = $sizeInBytes/(1024);
1255 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[1];
1258 return $sizeInBytes.$labelArr[0];
1263 * Returns microtime input to milliseconds
1266 * @param string Microtime
1267 * @return integer Microtime input string converted to an integer (milliseconds)
1269 public static function convertMicrotime($microtime) {
1270 $parts = explode(' ',$microtime);
1271 return round(($parts[0]+
$parts[1])*1000);
1275 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1278 * @param string Input string, eg "123 + 456 / 789 - 4"
1279 * @param string Operators to split by, typically "/+-*"
1280 * @return array Array with operators and operands separated.
1281 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1283 public static function splitCalc($string,$operators) {
1287 $valueLen=strcspn($string,$operators);
1288 $value=substr($string,0,$valueLen);
1289 $res[] = Array($sign,trim($value));
1290 $sign=substr($string,$valueLen,1);
1291 $string=substr($string,$valueLen+
1);
1298 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1301 * @param string Input string, eg "123 + 456 / 789 - 4"
1302 * @return integer Calculated value. Or error string.
1303 * @see calcParenthesis()
1305 public static function calcPriority($string) {
1306 $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
1307 $string='+'.$string; // Ensuring an operator for the first entrance
1309 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
1310 // split the expression here:
1312 preg_match_all('/'.$regex.'/',$string,$reg);
1318 $buffer=doubleval(current($reg[2]));
1319 next($reg[2]); // Advance pointer
1321 while(list($k,$v)=each($reg[2])) {
1323 $sign = $reg[1][$k];
1324 if ($sign=='+' ||
$sign=='-') {
1325 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1329 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
1330 if ($sign=='%') {if ($v) $buffer%
=$v; else $err='dividing by zero';}
1331 if ($sign=='*') {$buffer*=$v;}
1332 if ($sign=='^') {$buffer=pow($buffer,$v);}
1335 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1336 return $err ?
'ERROR: '.$err : $number;
1340 * Calculates the input with parenthesis levels
1343 * @param string Input string, eg "(123 + 456) / 789 - 4"
1344 * @return integer Calculated value. Or error string.
1345 * @see calcPriority(), tslib_cObj::stdWrap()
1347 public static function calcParenthesis($string) {
1350 $valueLenO=strcspn($string,'(');
1351 $valueLenC=strcspn($string,')');
1352 if ($valueLenC==strlen($string) ||
$valueLenC < $valueLenO) {
1353 $value = t3lib_div
::calcPriority(substr($string,0,$valueLenC));
1354 $string = $value.substr($string,$valueLenC+
1);
1357 $string = substr($string,0,$valueLenO).t3lib_div
::calcParenthesis(substr($string,$valueLenO+
1));
1361 if ($securC<=0) break;
1362 } while($valueLenO<strlen($string));
1367 * Inverse version of htmlspecialchars()
1370 * @param string Value where >, <, " and & should be converted to regular chars.
1371 * @return string Converted result.
1373 public static function htmlspecialchars_decode($value) {
1374 $value = str_replace('>','>',$value);
1375 $value = str_replace('<','<',$value);
1376 $value = str_replace('"','"',$value);
1377 $value = str_replace('&','&',$value);
1382 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1385 * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1386 * @return string Converted result.
1388 public static function deHSCentities($str) {
1389 return ereg_replace('&([#[:alnum:]]*;)','&\1',$str);
1393 * This function is used to escape any ' -characters when transferring text to JavaScript!
1396 * @param string String to escape
1397 * @param boolean If set, also backslashes are escaped.
1398 * @param string The character to escape, default is ' (single-quote)
1399 * @return string Processed input string
1401 public static function slashJS($string,$extended=0,$char="'") {
1402 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
1403 return str_replace ($char, "\\".$char, $string);
1407 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1408 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1411 * @param string String to raw-url-encode with spaces preserved
1412 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1414 public static function rawUrlEncodeJS($str) {
1415 return str_replace('%20',' ',rawurlencode($str));
1419 * rawurlencode which preserves "/" chars
1420 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1423 * @param string Input string
1424 * @return string Output string
1426 public static function rawUrlEncodeFP($str) {
1427 return str_replace('%2F','/',rawurlencode($str));
1431 * Checking syntax of input email address
1434 * @param string Input string to evaluate
1435 * @return boolean Returns true if the $email address (input string) is valid
1437 public static function validEmail($email) {
1438 return (filter_var($email, FILTER_VALIDATE_EMAIL
) !== false);
1442 * Checks if current e-mail sending method does not accept recipient/sender name
1443 * in a call to PHP mail() function. Windows version of mail() and mini_sendmail
1444 * program are known not to process such input correctly and they cause SMTP
1445 * errors. This function will return true if current mail sending method has
1446 * problem with recipient name in recipient/sender argument for mail().
1448 * TODO: 4.3 should have additional configuration variable, which is combined
1449 * by || with the rest in this function.
1451 * @return boolean true if mail() does not accept recipient name
1453 public static function isBrokenEmailEnvironment() {
1454 return TYPO3_OS
== 'WIN' ||
(false !== strpos(ini_get('sendmail_path'), 'mini_sendmail'));
1458 * Changes from/to arguments for mail() function to work in any environment.
1460 * @param string $address Address to adjust
1461 * @return string Adjusted address
1462 * @see t3lib_::isBrokenEmailEnvironment()
1464 public static function normalizeMailAddress($address) {
1465 if (self
::isBrokenEmailEnvironment() && false !== ($pos1 = strrpos($address, '<'))) {
1466 $pos2 = strpos($address, '>', $pos1);
1467 $address = substr($address, $pos1 +
1, ($pos2 ?
$pos2 : strlen($address)) - $pos1 - 1);
1473 * Formats a string for output between <textarea>-tags
1474 * All content outputted in a textarea form should be passed through this function
1475 * 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!
1478 * @param string Input string to be formatted.
1479 * @return string Formatted for <textarea>-tags
1481 public static function formatForTextarea($content) {
1482 return chr(10).htmlspecialchars($content);
1486 * Converts string to uppercase
1487 * The function converts all Latin characters (a-z, but no accents, etc) to
1488 * uppercase. It is safe for all supported character sets (incl. utf-8).
1489 * Unlike strtoupper() it does not honour the locale.
1491 * @param string Input string
1492 * @return string Uppercase String
1494 public static function strtoupper($str) {
1495 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1499 * Converts string to lowercase
1500 * The function converts all Latin characters (A-Z, but no accents, etc) to
1501 * lowercase. It is safe for all supported character sets (incl. utf-8).
1502 * Unlike strtolower() it does not honour the locale.
1504 * @param string Input string
1505 * @return string Lowercase String
1507 public static function strtolower($str) {
1508 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1522 /*************************
1526 *************************/
1529 * Check if an string item exists in an array.
1530 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1532 * Comparison to PHP in_array():
1533 * -> $array = array(0, 1, 2, 3);
1534 * -> variant_a := t3lib_div::inArray($array, $needle)
1535 * -> variant_b := in_array($needle, $array)
1536 * -> variant_c := in_array($needle, $array, true)
1537 * +---------+-----------+-----------+-----------+
1538 * | $needle | variant_a | variant_b | variant_c |
1539 * +---------+-----------+-----------+-----------+
1540 * | '1a' | false | true | false |
1541 * | '' | false | true | false |
1542 * | '0' | true | true | false |
1543 * | 0 | true | true | true |
1544 * +---------+-----------+-----------+-----------+
1547 * @param array one-dimensional array of items
1548 * @param string item to check for
1549 * @return boolean true if $item is in the one-dimensional array $in_array
1551 public static function inArray(array $in_array, $item) {
1552 foreach ($in_array as $val) {
1553 if (!is_array($val) && !strcmp($val, $item)) {
1561 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1562 * Corresponds to explode(), but with conversion to integers for all values.
1565 * @param string Delimiter string to explode with
1566 * @param string The string to explode
1567 * @return array Exploded values, all converted to integers
1569 public static function intExplode($delim, $string) {
1570 $temp = explode($delim,$string);
1571 foreach ($temp as &$val) {
1572 $val = intval($val);
1579 * Reverse explode which explodes the string counting from behind.
1580 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1583 * @param string Delimiter string to explode with
1584 * @param string The string to explode
1585 * @param integer Number of array entries
1586 * @return array Exploded values
1588 public static function revExplode($delim, $string, $count=0) {
1589 $temp = explode($delim,strrev($string),$count);
1590 foreach ($temp as &$val) {
1591 $val = strrev($val);
1593 $temp = array_reverse($temp);
1599 * Explodes a string and trims all values for whitespace in the ends.
1600 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1603 * @param string Delimiter string to explode with
1604 * @param string The string to explode
1605 * @param boolean If set, all empty values (='') will NOT be set in output
1606 * @param integer If positive, the result will contain a maximum of limit elements,
1607 * if negative, all components except the last -limit are returned,
1608 * if zero (default), the result is not limited at all
1609 * @return array Exploded values
1611 public static function trimExplode($delim, $string, $onlyNonEmptyValues = false, $limit = 0) {
1612 $array = (!$limit ?
explode($delim, $string) : explode($delim, $string, $limit));
1613 // for two perfomance reasons the loop is duplicated
1614 // a) avoid check for $onlyNonEmptyValues in foreach loop
1615 // b) avoid unnecessary code when $onlyNonEmptyValues is not set
1616 if ($onlyNonEmptyValues) {
1617 $new_array = array();
1618 foreach($array as $value) {
1619 $value = trim($value);
1621 $new_array[] = $value;
1624 // direct return for perfomance reasons
1628 foreach($array as &$value) {
1629 $value = trim($value);
1636 * Remove duplicate values from an array
1639 * @param array Array of values to make unique
1642 * @deprecated Use the PHP function array_unique instead
1644 public static function uniqueArray(array $valueArray) {
1645 return array_unique($valueArray);
1649 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1652 * @param array Array containing the values
1653 * @param string Value to search for and if found remove array entry where found.
1654 * @return array Output array with entries removed if search string is found
1656 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1657 foreach ($array as $k => $v) {
1659 $array[$k] = t3lib_div
::removeArrayEntryByValue($v, $cmpValue);
1660 } elseif (!strcmp($v, $cmpValue)) {
1669 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1672 * @param string Name prefix for entries. Set to blank if you wish none.
1673 * @param array The (multidim) array to implode
1674 * @param string (keep blank)
1675 * @param boolean If set, parameters which were blank strings would be removed.
1676 * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1677 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1678 * @see explodeUrl2Array()
1680 public static function implodeArrayForUrl($name, array $theArray, $str = '', $skipBlank = false, $rawurlencodeParamName = false) {
1681 foreach($theArray as $Akey => $AVal) {
1682 $thisKeyName = $name ?
$name.'['.$Akey.']' : $Akey;
1683 if (is_array($AVal)) {
1684 $str = t3lib_div
::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1686 if (!$skipBlank ||
strcmp($AVal,'')) {
1687 $str.='&'.($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName).
1688 '='.rawurlencode($AVal);
1696 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1698 * @param string GETvars string
1699 * @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())
1700 * @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!
1701 * @see implodeArrayForUrl()
1703 public static function explodeUrl2Array($string,$multidim=FALSE) {
1706 parse_str($string,$output);
1708 $p = explode('&',$string);
1711 list($pK,$pV) = explode('=',$v,2);
1712 $output[rawurldecode($pK)] = rawurldecode($pV);
1720 * Returns an array with selected keys from incoming data.
1721 * (Better read source code if you want to find out...)
1724 * @param string List of variable/key names
1725 * @param array Array from where to get values based on the keys in $varList
1726 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1727 * @return array Output array with selected variables.
1729 public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
1730 $keys = t3lib_div
::trimExplode(',',$varList,1);
1732 foreach($keys as $v) {
1733 if (isset($getArray[$v])) {
1734 $outArr[$v] = $getArray[$v];
1735 } elseif ($GPvarAlt) {
1736 $outArr[$v] = t3lib_div
::_GP($v);
1744 * This function traverses a multidimentional array and adds slashes to the values.
1745 * NOTE that the input array is and argument by reference.!!
1746 * Twin-function to stripSlashesOnArray
1749 * @param array Multidimensional input array, (REFERENCE!)
1752 public static function addSlashesOnArray(array &$theArray) {
1753 foreach ($theArray as &$value) {
1754 if (is_array($value)) {
1755 t3lib_div
::addSlashesOnArray($value);
1757 $value = addslashes($value);
1765 * This function traverses a multidimentional array and strips slashes to the values.
1766 * NOTE that the input array is and argument by reference.!!
1767 * Twin-function to addSlashesOnArray
1770 * @param array Multidimensional input array, (REFERENCE!)
1773 public static function stripSlashesOnArray(array &$theArray) {
1774 foreach ($theArray as &$value) {
1775 if (is_array($value)) {
1776 t3lib_div
::stripSlashesOnArray($value);
1778 $value = stripslashes($value);
1785 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1788 * @param array Multidimensional input array
1789 * @param string "add" or "strip", depending on usage you wish.
1792 public static function slashArray(array $arr,$cmd) {
1793 if ($cmd=='strip') t3lib_div
::stripSlashesOnArray($arr);
1794 if ($cmd=='add') t3lib_div
::addSlashesOnArray($arr);
1799 * Merges two arrays recursively and "binary safe" (integer keys are
1800 * overridden as well), overruling similar values in the first array
1801 * ($arr0) with the values of the second array ($arr1)
1802 * In case of identical keys, ie. keeping the values of the second.
1805 * @param array First array
1806 * @param array Second array, overruling the first array
1807 * @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.
1808 * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: true
1809 * @return array Resulting array where $arr1 values has overruled $arr0 values
1811 public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
1812 foreach ($arr1 as $key => $val) {
1813 if(is_array($arr0[$key])) {
1814 if (is_array($arr1[$key])) {
1815 $arr0[$key] = t3lib_div
::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
1819 if (isset($arr0[$key])) {
1820 if ($includeEmtpyValues ||
$val) {
1825 if ($includeEmtpyValues ||
$val) {
1836 * 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.
1839 * @param array First array
1840 * @param array Second array
1841 * @return array Merged result.
1843 public static function array_merge(array $arr1,array $arr2) {
1848 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1851 * @param array Input array of values
1852 * @param string Delimited, default is comman
1853 * @param string Quote-character to wrap around the values.
1854 * @return string A single line of CSV
1856 public static function csvValues(array $row,$delim=',',$quote='"') {
1859 foreach ($row as $value) {
1860 $out[] = str_replace($quote, $quote.$quote, $value);
1862 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1867 * Creates recursively a JSON literal from a multidimensional associative array.
1868 * Uses native function of PHP >= 5.2.0
1870 * @param array $jsonArray: The array to be transformed to JSON
1871 * @return string JSON string
1872 * @deprecated since TYPO3 4.3, use PHP native function json_encode() instead, will be removed in TYPO3 4.5
1874 public static function array2json(array $jsonArray) {
1875 return json_encode($jsonArray);
1879 * Removes dots "." from end of a key identifier of TypoScript styled array.
1880 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1882 * @param array $ts: TypoScript configuration array
1883 * @return array TypoScript configuration array without dots at the end of all keys
1885 public static function removeDotsFromTS(array $ts) {
1887 foreach ($ts as $key => $value) {
1888 if (is_array($value)) {
1889 $key = rtrim($key, '.');
1890 $out[$key] = t3lib_div
::removeDotsFromTS($value);
1892 $out[$key] = $value;
1913 /*************************
1915 * HTML/XML PROCESSING
1917 *************************/
1920 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1921 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1922 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1925 * @param string HTML-tag string (or attributes only)
1926 * @return array Array with the attribute values.
1928 public static function get_tag_attributes($tag) {
1929 $components = t3lib_div
::split_tag_attributes($tag);
1930 $name = ''; // attribute name is stored here
1932 $attributes = array();
1933 foreach ($components as $key => $val) {
1934 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
1937 $attributes[$name] = $val;
1941 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1942 $attributes[$key] = '';
1955 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1956 * Removes tag-name if found
1959 * @param string HTML-tag string (or attributes only)
1960 * @return array Array with the attribute values.
1962 public static function split_tag_attributes($tag) {
1963 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1964 // Removes any > in the end of the string
1965 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1968 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1969 $firstChar=substr($tag_tmp,0,1);
1970 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
1971 $reg=explode($firstChar,$tag_tmp,3);
1973 $tag_tmp=trim($reg[2]);
1974 } elseif (!strcmp($firstChar,'=')) {
1976 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1978 // There are '' around the value. We look for the next ' ' or '>'
1979 $reg = split('[[:space:]=]',$tag_tmp,2);
1980 $value[] = trim($reg[0]);
1981 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1989 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1992 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1993 * @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!
1994 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1995 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1997 public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
2000 foreach($arr as $p => $v) {
2001 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
2006 foreach($arr as $p => $v) {
2007 if (strcmp($v,'') ||
$dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
2009 return implode(' ',$list);
2013 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
2015 * @param array See implodeAttributes()
2016 * @param boolean See implodeAttributes()
2017 * @param boolean See implodeAttributes()
2018 * @return string See implodeAttributes()
2019 * @deprecated Name was changed into implodeAttributes
2020 * @see implodeAttributes()
2022 public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
2023 return t3lib_div
::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
2027 * Wraps JavaScript code XHTML ready with <script>-tags
2028 * Automatic re-identing of the JS code is done by using the first line as ident reference.
2029 * This is nice for identing JS code with PHP code on the same level.
2031 * @param string JavaScript code
2032 * @param boolean Wrap script element in linebreaks? Default is TRUE.
2033 * @return string The wrapped JS code, ready to put into a XHTML page
2034 * @author Ingmar Schlecht <ingmars@web.de>
2035 * @author René Fritz <r.fritz@colorcube.de>
2037 public static function wrapJS($string, $linebreak=TRUE) {
2039 // <script wrapped in nl?
2040 $cr = $linebreak?
"\n" : '';
2042 // remove nl from the beginning
2043 $string = preg_replace ('/^\n+/', '', $string);
2044 // re-ident to one tab using the first line as reference
2046 if(preg_match('/^(\t+)/',$string,$match)) {
2047 $string = str_replace($match[1],"\t", $string);
2049 $string = $cr.'<script type="text/javascript">
2055 return trim($string);
2060 * Parses XML input into a PHP array with associative keys
2063 * @param string XML data input
2064 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2065 * @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.
2066 * @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
2068 public static function xml2tree($string,$depth=999) {
2069 $parser = xml_parser_create();
2073 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2074 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2075 xml_parse_into_struct($parser, $string, $vals, $index);
2077 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
2078 xml_parser_free($parser);
2080 $stack = array( array() );
2084 // FIXME don't use unset() - what does that mean? Use NULL or similar.
2086 foreach($vals as $key => $val) {
2087 $type = $val['type'];
2090 if ($type=='open' ||
$type=='complete') {
2091 $stack[$stacktop++
] = $tagi;
2093 if ($depth==$stacktop) {
2097 $tagi = array('tag' => $val['tag']);
2099 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
2100 if(isset($val['value'])) $tagi['values'][] = $val['value'];
2103 if ($type=='complete' ||
$type=='close') {
2105 $tagi = $stack[--$stacktop];
2106 $oldtag = $oldtagi['tag'];
2107 unset($oldtagi['tag']);
2109 if ($depth==($stacktop+
1)) {
2110 if ($key-$startPoint > 0) {
2111 $partArray = array_slice(
2116 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
2117 $oldtagi['XMLvalue']=t3lib_div
::xmlRecompileFromStructValArray($partArray);
2119 $oldtagi['XMLvalue']=$oldtagi['values'][0];
2123 $tagi['ch'][$oldtag][] = $oldtagi;
2127 if($type=='cdata') {
2128 $tagi['values'][] = $val['value'];
2135 * Turns PHP array into XML. See array2xml()
2137 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2138 * @param string Alternative document tag. Default is "phparray".
2139 * @param array Options for the compilation. See array2xml() for description.
2140 * @param string Forced charset to prologue
2141 * @return string An XML string made from the input content in the array.
2142 * @see xml2array(),array2xml()
2144 public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
2146 // Figure out charset if not given explicitly:
2148 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
2149 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
2150 } elseif (is_object($GLOBALS['LANG'])) {
2151 $charset = $GLOBALS['LANG']->charSet
; // If "LANG" is around, that will hold the current charset
2153 $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
2158 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
2159 t3lib_div
::array2xml($array,'',0,$docTag,0, $options);
2163 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2165 * Converts a PHP array into an XML string.
2166 * The XML output is optimized for readability since associative keys are used as tagnames.
2167 * 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.
2168 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
2169 * 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
2170 * 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.
2171 * 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!
2172 * 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...
2175 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2176 * @param string tag-prefix, eg. a namespace prefix like "T3:"
2177 * @param integer Current recursion level. Don't change, stay at zero!
2178 * @param string Alternative document tag. Default is "phparray".
2179 * @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 chr(9) (TAB) is used
2180 * @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')
2181 * @param string Stack data. Don't touch.
2182 * @return string An XML string made from the input content in the array.
2185 public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
2186 // 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
2187 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
2188 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
2189 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
2191 // Set indenting mode:
2192 $indentChar = $spaceInd ?
' ' : chr(9);
2193 $indentN = $spaceInd>0 ?
$spaceInd : 1;
2194 $nl = ($spaceInd >= 0 ?
chr(10) : '');
2196 // Init output variable:
2199 // Traverse the input array
2200 foreach($array as $k=>$v) {
2204 // Construct the tag name.
2205 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2206 $attr.=' index="'.htmlspecialchars($tagName).'"';
2207 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
2208 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div
::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2209 $attr.=' index="'.htmlspecialchars($tagName).'"';
2210 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
2211 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
2212 $attr.=' index="'.htmlspecialchars($tagName).'"';
2213 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
2214 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2215 $attr.=' index="'.htmlspecialchars($tagName).'"';
2216 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2217 } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
2218 if ($options['useNindex']) { // If numeric key, prefix "n"
2219 $tagName = 'n'.$tagName;
2220 } else { // Use special tag for num. keys:
2221 $attr.=' index="'.$tagName.'"';
2222 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
2224 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2225 $attr.=' index="'.htmlspecialchars($tagName).'"';
2226 $tagName = $options['useIndexTagForAssoc'];
2229 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2230 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
2232 // If the value is an array then we will call this function recursively:
2236 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
2237 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
2238 $clearStackPath = $subOptions['clearStackPath'];
2240 $subOptions = $options;
2241 $clearStackPath = FALSE;
2245 t3lib_div
::array2xml(
2253 'parentTagName' => $tagName,
2254 'grandParentTagName' => $stackData['parentTagName'],
2255 'path' => $clearStackPath ?
'' : $stackData['path'].'/'.$tagName,
2258 ($spaceInd >= 0 ?
str_pad('',($level+
1)*$indentN,$indentChar) : '');
2259 if ((int)$options['disableTypeAttrib']!=2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2260 $attr.=' type="array"';
2262 } else { // Just a value:
2264 // Look for binary chars:
2265 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2266 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!
2267 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2268 $content = $nl.chunk_split(base64_encode($v));
2269 $attr.=' base64="1"';
2271 // Otherwise, just htmlspecialchar the stuff:
2272 $content = htmlspecialchars($v);
2273 $dType = gettype($v);
2274 if ($dType == 'string') {
2275 if ($options['useCDATA'] && $content != $v) {
2276 $content = '<![CDATA[' . $v . ']]>';
2278 } elseif (!$options['disableTypeAttrib']) {
2279 $attr.= ' type="'.$dType.'"';
2284 // Add the element to the output string:
2285 $output.=($spaceInd >= 0 ?
str_pad('',($level+
1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
2288 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2291 '<'.$docTag.'>'.$nl.
2300 * Converts an XML string to a PHP array.
2301 * This is the reverse function of array2xml()
2304 * @param string XML content to convert into an array
2305 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
2306 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2307 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2310 public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
2311 global $TYPO3_CONF_VARS;
2314 $parser = xml_parser_create();
2318 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2319 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2321 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2323 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
2324 $theCharset = $match[1] ?
$match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
2325 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
2328 xml_parse_into_struct($parser, $string, $vals, $index);
2330 // If error, return error message:
2331 if (xml_get_error_code($parser)) {
2332 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
2334 xml_parser_free($parser);
2337 $stack = array(array());
2343 // Traverse the parsed XML structure:
2344 foreach($vals as $key => $val) {
2346 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2347 $tagName = $val['tag'];
2348 if (!$documentTag) $documentTag = $tagName;
2350 // Test for name space:
2351 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ?
substr($tagName,strlen($NSprefix)) : $tagName;
2353 // Test for numeric tag, encoded on the form "nXXX":
2354 $testNtag = substr($tagName,1); // Closing tag.
2355 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ?
intval($testNtag) : $tagName;
2357 // Test for alternative index value:
2358 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
2360 // Setting tag-values, manage stack:
2361 switch($val['type']) {
2362 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2363 $current[$tagName] = array(); // Setting blank place holder
2364 $stack[$stacktop++
] = $current;
2367 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2368 $oldCurrent = $current;
2369 $current = $stack[--$stacktop];
2370 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2371 $current[key($current)] = $oldCurrent;
2374 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2375 if ($val['attributes']['base64']) {
2376 $current[$tagName] = base64_decode($val['value']);
2378 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
2381 switch((string)$val['attributes']['type']) {
2383 $current[$tagName] = (integer)$current[$tagName];
2386 $current[$tagName] = (double)$current[$tagName];
2389 $current[$tagName] = (bool)$current[$tagName];
2392 $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...
2400 if ($reportDocTag) {
2401 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2404 // Finally return the content of the document tag.
2405 return $current[$tagName];
2409 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2412 * @param array A array of XML parts, see xml2tree
2413 * @return string Re-compiled XML data.
2415 public static function xmlRecompileFromStructValArray(array $vals) {
2418 foreach($vals as $val) {
2419 $type = $val['type'];
2422 if ($type=='open' ||
$type=='complete') {
2423 $XMLcontent.='<'.$val['tag'];
2424 if(isset($val['attributes'])) {
2425 foreach($val['attributes'] as $k => $v) {
2426 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
2429 if ($type=='complete') {
2430 if(isset($val['value'])) {
2431 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
2432 } else $XMLcontent.='/>';
2433 } else $XMLcontent.='>';
2435 if ($type=='open' && isset($val['value'])) {
2436 $XMLcontent.=htmlspecialchars($val['value']);
2440 if ($type=='close') {
2441 $XMLcontent.='</'.$val['tag'].'>';
2444 if($type=='cdata') {
2445 $XMLcontent.=htmlspecialchars($val['value']);
2453 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2456 * @param string XML data
2457 * @return array Attributes of the xml prologue (header)
2459 public static function xmlGetHeaderAttribs($xmlData) {
2461 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2462 return t3lib_div
::get_tag_attributes($match[1]);
2467 * Minifies JavaScript
2469 * @param string $script Script to minify
2470 * @param string $error Error message (if any)
2471 * @return string Minified script or source string if error happened
2473 public static function minifyJavaScript($script, &$error = '') {
2474 require_once(PATH_typo3
. 'contrib/jsmin/jsmin.php');
2477 $script = trim(JSMin
::minify(str_replace(chr(13), '', $script)));
2479 catch(JSMinException
$e) {
2480 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2481 t3lib_div
::devLog($error, 't3lib_div', 2,
2482 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2494 /*************************
2498 *************************/
2501 * Reads the file or url $url and returns the content
2502 * 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.
2505 * @param string File/URL to read
2506 * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2507 * @param array HTTP headers to be used in the request
2508 * @param array Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2509 * @return string The content from the resource given as input. FALSE if an error has occured.
2511 public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) {
2514 if (isset($report)) {
2515 $report['error'] = 0;
2516 $report['message'] = '';
2519 // use cURL for: http, https, ftp, ftps, sftp and scp
2520 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2521 if (isset($report)) {
2522 $report['lib'] = 'cURL';
2525 // External URL without error checking.
2528 if (isset($report)) {
2529 $report['error'] = -1;
2530 $report['message'] = 'Couldn\'t initialize cURL.';
2535 curl_setopt($ch, CURLOPT_URL
, $url);
2536 curl_setopt($ch, CURLOPT_HEADER
, $includeHeader ?
1 : 0);
2537 curl_setopt($ch, CURLOPT_NOBODY
, $includeHeader == 2 ?
1 : 0);
2538 curl_setopt($ch, CURLOPT_HTTPGET
, $includeHeader == 2 ?
'HEAD' : 'GET');
2539 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
2540 curl_setopt($ch, CURLOPT_FAILONERROR
, 1);
2542 // may fail (PHP 5.2.0+ and 5.1.5+) when open_basedir or safe_mode are enabled
2543 $followLocation = @curl_setopt
($ch, CURLOPT_FOLLOWLOCATION
, 1);
2545 if (is_array($requestHeaders)) {
2546 curl_setopt($ch, CURLOPT_HTTPHEADER
, $requestHeaders);
2549 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2550 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2551 curl_setopt($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2553 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2554 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2556 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2557 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2560 $content = curl_exec($ch);
2561 if (isset($report)) {
2562 if ($content===FALSE) {
2563 $report['error'] = curl_errno($ch);
2564 $report['message'] = curl_error($ch);
2566 $curlInfo = curl_getinfo($ch);
2567 // We hit a redirection but we couldn't follow it
2568 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2569 $report['error'] = -1;
2570 $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
2571 } elseif($includeHeader) {
2572 // Set only for $includeHeader to work exactly like PHP variant
2573 $report['http_code'] = $curlInfo['http_code'];
2574 $report['content_type'] = $curlInfo['content_type'];
2580 } elseif ($includeHeader) {
2581 if (isset($report)) {
2582 $report['lib'] = 'socket';
2584 $parsedURL = parse_url($url);
2585 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2586 if (isset($report)) {
2587 $report['error'] = -1;
2588 $report['message'] = 'Reading headers is not allowed for this protocol.';
2592 $port = intval($parsedURL['port']);
2594 if ($parsedURL['scheme'] == 'http') {
2595 $port = ($port>0 ?
$port : 80);
2598 $port = ($port>0 ?
$port : 443);
2604 $fp = @fsockopen
($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
2605 if (!$fp ||
$errno > 0) {
2606 if (isset($report)) {
2607 $report['error'] = $errno ?
$errno : -1;
2608 $report['message'] = $errno ?
($errstr ?
$errstr : 'Socket error.') : 'Socket initialization error.';
2612 $method = ($includeHeader == 2) ?
'HEAD' : 'GET';
2613 $msg = $method . ' ' . $parsedURL['path'] .
2614 ($parsedURL['query'] ?
'?' . $parsedURL['query'] : '') .
2615 ' HTTP/1.0' . "\r\n" . 'Host: ' .
2616 $parsedURL['host'] . "\r\nConnection: close\r\n";
2617 if (is_array($requestHeaders)) {
2618 $msg .= implode("\r\n", $requestHeaders) . "\r\n";
2623 while (!feof($fp)) {
2624 $line = fgets($fp, 2048);
2625 if (isset($report)) {
2626 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2627 $report['http_code'] = $status[1];
2629 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2630 $report['content_type'] = $type[1];
2634 if (!strlen(trim($line))) {
2635 break; // Stop at the first empty line (= end of header)
2638 if ($includeHeader != 2) {
2639 $content .= stream_get_contents($fp);
2643 } elseif (is_array($requestHeaders)) {
2644 if (isset($report)) {
2645 $report['lib'] = 'file/context';
2647 $parsedURL = parse_url($url);
2648 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2649 if (isset($report)) {
2650 $report['error'] = -1;
2651 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2655 $ctx = stream_context_create(array(
2657 'header' => implode("\r\n", $requestHeaders)
2661 $content = @file_get_contents
($url, false, $ctx);
2662 if ($content === false && isset($report)) {
2663 $phpError = error_get_last();
2664 $report['error'] = $phpError['type'];
2665 $report['message'] = $phpError['message'];
2668 if (isset($report)) {
2669 $report['lib'] = 'file';
2671 $content = @file_get_contents
($url);
2672 if ($content === false && isset($report)) {
2673 if (function_exists('error_get_last')) {
2674 $phpError = error_get_last();
2675 $report['error'] = $phpError['type'];
2676 $report['message'] = $phpError['message'];
2678 $report['error'] = -1;
2679 $report['message'] = 'Couldn\'t get URL.';
2688 * Writes $content to the file $file
2691 * @param string Filepath to write to
2692 * @param string Content to write
2693 * @return boolean True if the file was successfully opened and written to.
2695 public static function writeFile($file,$content) {
2696 if (!@is_file
($file)) $changePermissions = true;
2698 if ($fd = fopen($file,'wb')) {
2699 $res = fwrite($fd,$content);
2702 if ($res===false) return false;
2704 if ($changePermissions) { // Change the permissions only if the file has just been created
2705 t3lib_div
::fixPermissions($file);
2715 * Setting file system mode & group ownership of file
2717 * @param string Filepath of newly created file
2720 public static function fixPermissions($file) {
2721 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2722 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2723 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2724 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2730 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2731 * Accepts an additional subdirectory in the file path!
2733 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2734 * @param string Content string to write
2735 * @return string Returns false on success, otherwise an error string telling about the problem.
2737 public static function writeFileToTypo3tempDir($filepath,$content) {
2739 // Parse filepath into directory and basename:
2740 $fI = pathinfo($filepath);
2741 $fI['dirname'].= '/';
2744 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2745 if (defined('PATH_site')) {
2746 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2747 if (@is_dir
($dirName)) {
2748 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2750 // Checking if the "subdir" is found:
2751 $subdir = substr($fI['dirname'],strlen($dirName));
2753 if (ereg('^[[:alnum:]_]+\/$',$subdir) ||
ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir)) {
2755 if (!@is_dir
($dirName)) {
2756 t3lib_div
::mkdir_deep(PATH_site
.'typo3temp/', $subdir);
2758 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2760 // Checking dir-name again (sub-dir might have been created):
2761 if (@is_dir
($dirName)) {
2762 if ($filepath == $dirName.$fI['basename']) {
2763 t3lib_div
::writeFile($filepath, $content);
2764 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2765 } else return 'Calculated filelocation didn\'t match input $filepath!';
2766 } else return '"'.$dirName.'" is not a directory!';
2767 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2768 } else return 'PATH_site + "typo3temp/" was not a directory!';
2769 } else return 'PATH_site constant was NOT defined!';
2770 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2774 * Wrapper function for mkdir, setting folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']
2777 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2778 * @return boolean TRUE if @mkdir went well!
2780 public static function mkdir($theNewFolder) {
2781 $theNewFolder = preg_replace('|/$|','',$theNewFolder);
2782 if (@mkdir
($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2783 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2785 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2786 @chgrp
($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2795 * Creates a directory - including parent directories if necessary - in the file system
2797 * @param string Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
2798 * @param string Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
2799 * @return string If error, returns error string.
2801 public static function mkdir_deep($destination,$deepDir) {
2802 $allParts = t3lib_div
::trimExplode('/',$deepDir,1);
2804 foreach($allParts as $part) {
2806 if (!is_dir($destination.$root)) {
2807 t3lib_div
::mkdir($destination.$root);
2808 if (!@is_dir
($destination.$root)) {
2809 return 'Error: The directory "'.$destination.$root.'" could not be created...';
2816 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2818 * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2819 * @param boolean Allow deletion of non-empty directories
2820 * @return boolean true if @rmdir went well!
2822 public static function rmdir($path,$removeNonEmpty=false) {
2824 $path = preg_replace('|/$|','',$path); // Remove trailing slash
2826 if (file_exists($path)) {
2829 if (is_dir($path)) {
2830 if ($removeNonEmpty==true && $handle = opendir($path)) {
2831 while ($OK && false !== ($file = readdir($handle))) {
2832 if ($file=='.' ||
$file=='..') continue;
2833 $OK = t3lib_div
::rmdir($path.'/'.$file,$removeNonEmpty);
2837 if ($OK) { $OK = rmdir($path); }
2839 } else { // If $dirname is a file, simply remove it
2840 $OK = unlink($path);
2850 * Returns an array with the names of folders in a specific path
2851 * Will return 'error' (string) if there were an error with reading directory content.
2854 * @param string Path to list directories from
2855 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2857 public static function get_dirs($path) {
2860 if (is_object($d)) {
2861 while(false !== ($entry=$d->read())) {
2862 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2863 $filearray[]=$entry;
2867 } else return 'error';
2873 * Returns an array with the names of files in a specific path
2876 * @param string $path: Is the path to the file
2877 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2878 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2879 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2880 * @param string A comma seperated list of filenames to exclude, no wildcards
2881 * @return array Array of the files found
2883 public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
2885 // Initialize variabels:
2886 $filearray = array();
2887 $sortarray = array();
2888 $path = ereg_replace('\/$','',$path);
2890 // Find files+directories:
2891 if (@is_dir
($path)) {
2892 $extensionList = strtolower($extensionList);
2894 if (is_object($d)) {
2895 while($entry=$d->read()) {
2896 if (@is_file
($path.'/'.$entry)) {
2897 $fI = pathinfo($entry);
2898 $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)
2899 if ((!strlen($extensionList) || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) ||
!preg_match('/^'.$excludePattern.'$/',$entry))) {
2900 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2901 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2902 elseif ($order) {$sortarray[$key]=$entry;}
2907 } else return 'error opening path: "'.$path.'"';
2914 foreach ($sortarray as $k => $v) {
2915 $newArr[$k]=$filearray[$k];
2926 * Recursively gather all files and folders of a path.
2929 * @param array $fileArr: Empty input array (will have files added to it)
2930 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2931 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2932 * @param boolean $regDirs: If set, directories are also included in output.
2933 * @param integer $recursivityLevels: The number of levels to dig down...
2934 * @param string $excludePattern: regex pattern of files/directories to exclude
2935 * @return array An array with the found files/directories.
2937 public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
2938 if ($regDirs) $fileArr[] = $path;
2939 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1,$excludePattern));
2941 $dirs = t3lib_div
::get_dirs($path);
2942 if (is_array($dirs) && $recursivityLevels>0) {
2943 foreach ($dirs as $subdirs) {
2944 if ((string)$subdirs!='' && (!strlen($excludePattern) ||
!preg_match('/^'.$excludePattern.'$/',$subdirs))) {
2945 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
2953 * Removes the absolute part of all files/folders in fileArr
2956 * @param array $fileArr: The file array to remove the prefix from
2957 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2958 * @return array The input $fileArr processed.
2960 public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
2961 foreach ($fileArr as $k => &$absFileRef) {
2962 if (t3lib_div
::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2963 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2965 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2972 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2975 * @param string File path to process
2978 public static function fixWindowsFilePath($theFile) {
2979 return str_replace('//','/', str_replace('\\','/', $theFile));
2983 * Resolves "../" sections in the input path string.
2984 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2987 * @param string File path in which "/../" is resolved
2990 public static function resolveBackPath($pathStr) {
2991 $parts = explode('/',$pathStr);
2994 foreach($parts as $pV) {
2999 } else $output[]=$pV;
3005 return implode('/',$output);
3009 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
3010 * - If already having a scheme, nothing is prepended
3011 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
3012 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
3015 * @param string URL / path to prepend full URL addressing to.
3018 public static function locationHeaderUrl($path) {
3019 $uI = parse_url($path);
3020 if (substr($path,0,1)=='/') { // relative to HOST
3021 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
3022 } elseif (!$uI['scheme']) { // No scheme either
3023 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
3043 /*************************
3045 * DEBUG helper FUNCTIONS
3047 *************************/
3050 * Returns a string with a list of ascii-values for the first $characters characters in $string
3053 * @param string String to show ASCII value for
3054 * @param integer Number of characters to show
3055 * @return string The string with ASCII values in separated by a space char.
3057 public static function debug_ordvalue($string,$characters=100) {
3058 if(strlen($string) < $characters) $characters = strlen($string);
3059 for ($i=0; $i<$characters; $i++
) {
3060 $valuestring.=' '.ord(substr($string,$i,1));
3062 return trim($valuestring);
3066 * Returns HTML-code, which is a visual representation of a multidimensional array
3067 * use t3lib_div::print_array() in order to print an array
3068 * Returns false if $array_in is not an array
3071 * @param mixed Array to view
3072 * @return string HTML output
3074 public static function view_array($array_in) {
3075 if (is_array($array_in)) {
3077 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
3078 if (count($array_in) == 0) {
3079 $result.= '<tr><td><font face="Verdana,Arial" size="1"><b>EMPTY!</b></font></td></tr>';
3081 foreach ($array_in as $key => $val) {
3083 <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
3085 if (is_array($val)) {
3086 $result.=t3lib_div
::view_array($val);
3087 } elseif (is_object($val)) {
3088 $string = get_class($val);
3089 if (method_exists($val, '__toString')) {
3090 $string .= ': '.(string)$val;
3092 $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
3094 if (gettype($val) == 'object') {
3095 $string = 'Unknown object';
3097 $string = (string)$val;
3099 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
3105 $result.= '</table>';
3107 $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
3109 <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
3111 </table>'; // Output it as a string.
3120 * @param mixed Array to print visually (in a table).
3124 public static function print_array($array_in) {
3125 echo t3lib_div
::view_array($array_in);
3129 * Makes debug output
3130 * Prints $var in bold between two vertical lines
3131 * If not $var the word 'debug' is printed
3132 * If $var is an array, the array is printed by t3lib_div::print_array()
3135 * @param mixed Variable to print
3136 * @param mixed If the parameter is a string it will be used as header. Otherwise number of break tags to apply after (positive integer) or before (negative integer) the output.
3139 public static function debug($var='',$brOrHeader=0) {
3140 // buffer the output of debug if no buffering started before
3141 if (ob_get_level()==0) {
3145 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
3146 echo '<table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><tr><td>';
3147 } elseif ($brOrHeader<0) {
3148 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
3151 if (is_array($var)) {
3152 t3lib_div
::print_array($var);
3153 } elseif (is_object($var)) {
3154 echo '<b>|Object:<pre>';
3157 } elseif ((string)$var!='') {
3158 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
3160 echo '<b>| debug |</b>';
3163 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
3164 echo '</td></tr></table>';
3165 } elseif ($brOrHeader>0) {
3166 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
3171 * Displays the "path" of the function call stack in a string, using debug_backtrace
3175 public static function debug_trail() {
3176 $trail = debug_backtrace();
3177 $trail = array_reverse($trail);
3181 foreach($trail as $dat) {
3182 $path[] = $dat['class'].$dat['type'].$dat['function'].'#'.$dat['line'];
3185 return implode(' // ',$path);
3189 * Displays an array as rows in a table. Useful to debug output like an array of database records.
3191 * @param mixed Array of arrays with similar keys
3192 * @param string Table header
3193 * @param boolean If TRUE, will return content instead of echo'ing out.
3194 * @return void Outputs to browser.
3196 public static function debugRows($rows,$header='',$returnHTML=FALSE) {
3197 if (is_array($rows)) {
3199 $firstEl = current($rows);
3200 if (is_array($firstEl)) {
3201 $headerColumns = array_keys($firstEl);
3205 $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>';
3207 foreach($headerColumns as $key) {
3209 <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
3212 <tr>'.implode('',$tCells).'
3216 foreach($rows as $singleRow) {
3218 foreach($headerColumns as $key) {
3220 <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? t3lib_div
::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
3223 <tr>'.implode('',$tCells).'
3228 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
3230 if ($returnHTML) return $table; else echo $table;