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>
238 /*************************
243 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
244 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
245 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
246 * Eventually TYPO3 should provide this in the global space as well.
247 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
249 *************************/
252 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
253 * Strips slashes from all output, both strings and arrays.
254 * This function substitutes t3lib_div::GPvar()
255 * 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!
258 * @param string GET/POST var to return
259 * @return mixed POST var named $var and if not set, the GET var of the same name.
262 public static function _GP($var) {
263 if(empty($var)) return;
264 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
266 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
272 * Returns the global GET array (or value from) normalized to contain un-escaped values.
273 * ALWAYS use this API function to acquire the GET variables!
276 * @param string Optional pointer to value in GET array (basically name of GET var)
277 * @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!*
278 * @see _POST(), _GP(), _GETset()
280 public static function _GET($var=NULL) {
281 $value = ($var === NULL) ?
$_GET : (empty($var) ?
NULL : $_GET[$var]);
282 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
283 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
289 * Returns the global POST array (or value from) normalized to contain un-escaped values.
290 * ALWAYS use this API function to acquire the POST variables!
293 * @param string Optional pointer to value in POST array (basically name of POST var)
294 * @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!*
297 public static function _POST($var=NULL) {
298 $value = ($var === NULL) ?
$_POST : (empty($var) ?
NULL : $_POST[$var]);
299 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
300 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
306 * Writes input value to $_GET
309 * @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).
310 * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
313 public static function _GETset($inputGet,$key='') {
314 // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
315 if (strcmp($key,'')) {
316 if (is_array($inputGet)) {
317 t3lib_div
::addSlashesOnArray($inputGet);
319 $inputGet = addslashes($inputGet);
321 $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
322 } elseif (is_array($inputGet)) {
323 t3lib_div
::addSlashesOnArray($inputGet);
324 $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
330 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
331 * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
334 * @param string GET/POST var to return
335 * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
336 * @return mixed POST var named $var and if not set, the GET var of the same name.
337 * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
340 public static function GPvar($var,$strip=0) {
341 if(empty($var)) return;
342 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
343 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.
344 if ($strip && isset($value) && is_array($value)) { t3lib_div
::stripSlashesOnArray($value); }
349 * Returns the GET/POST global arrays merged with POST taking precedence.
352 * @param string Key (variable name) from GET or POST vars
353 * @return array Returns the GET vars merged recursively onto the POST vars.
357 public static function GParrayMerged($var) {
358 $postA = is_array($_POST[$var]) ?
$_POST[$var] : array();
359 $getA = is_array($_GET[$var]) ?
$_GET[$var] : array();
360 $mergedA = t3lib_div
::array_merge_recursive_overrule($getA,$postA);
361 t3lib_div
::stripSlashesOnArray($mergedA);
366 * Wrapper for the RemoveXSS function.
367 * Removes potential XSS code from an input string.
369 * Using an external class by Travis Puderbaugh <kallahar@quickwired.com>
371 * @param string Input string
372 * @return string Input string with potential XSS code removed
374 public function removeXSS($string) {
375 require_once(PATH_typo3
.'contrib/RemoveXSS/RemoveXSS.php');
376 $string = RemoveXSS
::RemoveXSS($string);
389 /*************************
393 *************************/
397 * Compressing a GIF file if not already LZW compressed
398 * 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)
400 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
402 * 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!)
403 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
407 * $theFile is expected to be a valid GIF-file!
408 * The function returns a code for the operation.
411 * @param string Filepath
412 * @param string See description of function
413 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
416 public static function gif_compress($theFile, $type) {
417 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
419 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
420 if (($type=='IM' ||
!$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
421 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
425 } elseif (($type=='GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
426 $tempImage = imageCreateFromGif($theFile);
427 imageGif($tempImage, $theFile);
428 imageDestroy($tempImage);
436 * Converts a png file to gif
437 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
440 * @param string $theFile the filename with path
441 * @return string new filename
444 public static function png_to_gif_by_imagemagick($theFile) {
445 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
446 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
447 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
448 && strtolower(substr($theFile,-4,4))=='.png'
449 && @is_file
($theFile)) { // IM
450 $newFile = substr($theFile,0,-4).'.gif';
451 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']);
454 // 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!!
460 * Returns filename of the png/gif version of the input file (which can be png or gif).
461 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
464 * @param string Filepath of image file
465 * @param boolean If set, then input file is converted to PNG, otherwise to GIF
466 * @return string If the new image file exists, it's filepath is returned
469 public static function read_png_gif($theFile,$output_png=0) {
470 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file
($theFile)) {
471 $ext = strtolower(substr($theFile,-4,4));
473 ((string)$ext=='.png' && $output_png) ||
474 ((string)$ext=='.gif' && !$output_png)
478 $newFile = PATH_site
.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?
'.png':'.gif');
479 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']);
481 if (@is_file
($newFile)) return $newFile;
500 /*************************
504 *************************/
508 * Returns a new string of max. $chars length.
509 * If the string is longer, it will be truncated and appended with '...'.
512 * @param string string to truncate
513 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
514 * @param string String to append to the output if it is truncated, default is '...'
515 * @return string new string
516 * @deprecated Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
517 * @see fixed_lgd_pre()
519 public static function fixed_lgd($string,$origChars,$preStr='...') {
520 $chars = abs($origChars);
522 if(strlen($string)>$chars) {
523 return $origChars < 0 ?
524 $preStr.trim(substr($string, -($chars-3))) :
525 trim(substr($string, 0, $chars-3)).$preStr;
533 * Returns a new string of max. $chars length.
534 * If the string is longer, it will be truncated and prepended with '...'.
535 * This works like fixed_lgd, but is truncated in the start of the string instead of the end
538 * @param string string to truncate
539 * @param integer must be an integer of at least 4
540 * @return string new string
541 * @deprecated Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
544 public static function fixed_lgd_pre($string,$chars) {
545 return strrev(t3lib_div
::fixed_lgd(strrev($string),$chars));
549 * Truncates a string with appended/prepended "..." and takes backend character set into consideration
550 * Use only from backend!
553 * @param string string to truncate
554 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
555 * @return string New string
558 public static function fixed_lgd_cs($string,$chars) {
559 if (is_object($GLOBALS['LANG'])) {
560 return $GLOBALS['LANG']->csConvObj
->crop($GLOBALS['LANG']->charSet
,$string,$chars,'...');
562 return t3lib_div
::fixed_lgd($string, $chars);
567 * Breaks up the text for emails
570 * @param string The string to break up
571 * @param string The string to implode the broken lines with (default/typically \n)
572 * @param integer The line length
573 * @deprecated Use PHP function wordwrap()
576 public static function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
577 $lines = explode(chr(10),$str);
579 foreach ($lines as $lStr) {
580 $outArr[] = t3lib_div
::breakLinesForEmail($lStr,$implChar,$charWidth);
582 return implode(chr(10),$outArr);
586 * Breaks up a single line of text for emails
589 * @param string The string to break up
590 * @param string The string to implode the broken lines with (default/typically \n)
591 * @param integer The line length
593 * @see breakTextForEmail()
595 public static function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
599 while(strlen($str)>$p) {
600 $substr=substr($str,$p,$l);
601 if (strlen($substr)==$l) {
602 $count = count(explode(' ',trim(strrev($substr))));
603 if ($count>1) { // OK...
604 $parts = explode(' ',strrev($substr),2);
605 $theLine = strrev($parts[1]);
607 $afterParts = explode(' ',substr($str,$l+
$p),2);
608 $theLine = $substr.$afterParts[0];
610 if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
615 $lines[]=trim($theLine);
616 $p+
=strlen($theLine);
617 if (!trim(substr($str,$p,$l))) break; // added...
619 return implode($implChar,$lines);
623 * Match IP number with list of numbers with wildcard
624 * Dispatcher method for switching into specialised IPv4 and IPv6 methods.
627 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
628 * @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.
629 * @return boolean True if an IP-mask from $list matches $baseIP
631 public static function cmpIP($baseIP, $list) {
635 } elseif ($list === '*') {
638 if (strpos($baseIP, ':') !== false && t3lib_div
::validIPv6($baseIP)) {
639 return t3lib_div
::cmpIPv6($baseIP, $list);
641 return t3lib_div
::cmpIPv4($baseIP, $list);
646 * Match IPv4 number with list of numbers with wildcard
648 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
649 * @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)
650 * @return boolean True if an IP-mask from $list matches $baseIP
652 public static function cmpIPv4($baseIP, $list) {
653 $IPpartsReq = explode('.',$baseIP);
654 if (count($IPpartsReq)==4) {
655 $values = t3lib_div
::trimExplode(',',$list,1);
657 foreach($values as $test) {
658 list($test,$mask) = explode('/',$test);
662 $lnet = ip2long($test);
663 $lip = ip2long($baseIP);
664 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
665 $firstpart = substr($binnet,0,$mask);
666 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
667 $firstip = substr($binip,0,$mask);
668 $yes = (strcmp($firstpart,$firstip)==0);
671 $IPparts = explode('.',$test);
673 foreach ($IPparts as $index => $val) {
675 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
680 if ($yes) return true;
687 * Match IPv6 address with a list of IPv6 prefixes
689 * @param string $baseIP is the current remote IP address for instance
690 * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses
691 * @return boolean True if an baseIP matches any prefix
693 public static function cmpIPv6($baseIP, $list) {
694 $success = false; // Policy default: Deny connection
695 $baseIP = t3lib_div
::normalizeIPv6($baseIP);
697 $values = t3lib_div
::trimExplode(',',$list,1);
698 foreach ($values as $test) {
699 list($test,$mask) = explode('/',$test);
700 if (t3lib_div
::validIPv6($test)) {
701 $test = t3lib_div
::normalizeIPv6($test);
703 switch ($mask) { // test on /48 /64
705 $testBin = substr(t3lib_div
::IPv6Hex2Bin($test), 0, 48);
706 $baseIPBin = substr(t3lib_div
::IPv6Hex2Bin($baseIP), 0, 48);
707 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
710 $testBin = substr(t3lib_div
::IPv6Hex2Bin($test), 0, 64);
711 $baseIPBin = substr(t3lib_div
::IPv6Hex2Bin($baseIP), 0, 64);
712 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
718 if (t3lib_div
::validIPv6($test)) { // test on full ip address 128 bits
719 $testBin = t3lib_div
::IPv6Hex2Bin($test);
720 $baseIPBin = t3lib_div
::IPv6Hex2Bin($baseIP);
721 $success = strcmp($testBin, $baseIPBin)==0 ?
true : false;
725 if ($success) return true;
731 * [Describe function...]
733 * @param [type] $hex: ...
736 public static function IPv6Hex2Bin ($hex) {
738 $hex = str_replace(':', '', $hex); // Replace colon to nothing
739 for ($i=0; $i<strlen($hex); $i=$i+
2) {
740 $bin.= chr(hexdec(substr($hex, $i, 2)));
746 * Normalize an IPv6 address to full length
748 * @param string Given IPv6 address
749 * @return string Normalized address
751 public static function normalizeIPv6($address) {
752 $normalizedAddress = '';
753 $stageOneAddress = '';
755 $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks
756 if (count($chunks)==2) {
757 $chunksLeft = explode(':', $chunks[0]);
758 $chunksRight = explode(':', $chunks[1]);
759 $left = count($chunksLeft);
760 $right = count($chunksRight);
762 // Special case: leading zero-only blocks count to 1, should be 0
763 if ($left==1 && strlen($chunksLeft[0])==0) $left=0;
765 $hiddenBlocks = 8 - ($left +
$right);
767 while ($h<$hiddenBlocks) {
768 $hiddenPart .= '0000:';
773 $stageOneAddress = $hiddenPart . $chunks[1];
775 $stageOneAddress = $chunks[0] . ':' . $hiddenPart . $chunks[1];
777 } else $stageOneAddress = $address;
779 // normalize the blocks:
780 $blocks = explode(':', $stageOneAddress);
782 foreach ($blocks as $block) {
785 $hiddenZeros = 4 - strlen($block);
786 while ($i < $hiddenZeros) {
790 $normalizedAddress .= $tmpBlock . $block;
791 if ($divCounter < 7) {
792 $normalizedAddress .= ':';
796 return $normalizedAddress;
800 * Validate a given IP address.
802 * Possible format are IPv4 and IPv6.
804 * @param string IP address to be tested
805 * @return boolean True if $ip is either of IPv4 or IPv6 format.
807 public static function validIP($ip) {
808 if (strpos($ip, ':') === false) {
809 return t3lib_div
::validIPv4($ip);
811 return t3lib_div
::validIPv6($ip);
816 * Validate a given IP address to the IPv4 address format.
818 * Example for possible format: 10.0.45.99
820 * @param string IP address to be tested
821 * @return boolean True if $ip is of IPv4 format.
823 public static function validIPv4($ip) {
824 $parts = explode('.', $ip);
825 if (count($parts)==4 &&
826 t3lib_div
::testInt($parts[0]) && $parts[0]>=1 && $parts[0]<256 &&
827 t3lib_div
::testInt($parts[1]) && $parts[0]>=0 && $parts[0]<256 &&
828 t3lib_div
::testInt($parts[2]) && $parts[0]>=0 && $parts[0]<256 &&
829 t3lib_div
::testInt($parts[3]) && $parts[0]>=0 && $parts[0]<256) {
837 * Validate a given IP address to the IPv6 address format.
839 * Example for possible format: 43FB::BB3F:A0A0:0 | ::1
841 * @param string IP address to be tested
842 * @return boolean True if $ip is of IPv6 format.
844 public static function validIPv6($ip) {
845 $uppercaseIP = strtoupper($ip);
848 $regex.= '(([\dA-F]{1,4}:){7}[\dA-F]{1,4})|';
849 $regex.= '(([\dA-F]{1,4}){1}::([\dA-F]{1,4}:){1,5}[\dA-F]{1,4})|';
850 $regex.= '(([\dA-F]{1,4}:){2}:([\dA-F]{1,4}:){1,4}[\dA-F]{1,4})|';
851 $regex.= '(([\dA-F]{1,4}:){3}:([\dA-F]{1,4}:){1,3}[\dA-F]{1,4})|';
852 $regex.= '(([\dA-F]{1,4}:){4}:([\dA-F]{1,4}:){1,2}[\dA-F]{1,4})|';
853 $regex.= '(([\dA-F]{1,4}:){5}:([\dA-F]{1,4}:){0,1}[\dA-F]{1,4})|';
854 $regex.= '(::([\dA-F]{1,4}:){0,6}[\dA-F]{1,4})';
857 return preg_match($regex, $uppercaseIP) ?
true : false;
861 * Match fully qualified domain name with list of strings with wildcard
863 * @param string The current remote IP address for instance, typ. REMOTE_ADDR
864 * @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)
865 * @return boolean True if a domain name mask from $list matches $baseIP
867 public static function cmpFQDN($baseIP, $list) {
868 if (count(explode('.',$baseIP))==4) {
869 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
870 $values = t3lib_div
::trimExplode(',',$list,1);
872 foreach($values as $test) {
873 $hostNameParts = explode('.',$test);
876 foreach($hostNameParts as $index => $val) {
878 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
882 if ($yes) return true;
889 * Check for item in list
890 * Check if an item exists in a comma-separated list of items.
893 * @param string comma-separated list of items (string)
894 * @param string item to check for
895 * @return boolean true if $item is in $list
897 public static function inList($list, $item) {
898 return (strpos(','.$list.',', ','.$item.',')!==false ?
true : false);
902 * Removes an item from a comma-separated list of items.
905 * @param string element to remove
906 * @param string comma-separated list of items (string)
907 * @return string new comma-separated list of items
909 public static function rmFromList($element,$list) {
910 $items = explode(',',$list);
911 foreach ($items as $k => $v) {
916 return implode(',',$items);
920 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
921 * Ranges are limited to 1000 values per range.
923 * @param string comma-separated list of integers with ranges (string)
924 * @return string new comma-separated list of items
925 * @author Martin Kutschker <martin.kutschker@activesolution.at>
927 public static function expandList($list) {
928 $items = explode(',',$list);
930 foreach ($items as $item) {
931 $range = explode('-',$item);
932 if (isset($range[1])) {
933 $runAwayBrake = 1000;
934 for ($n=$range[0]; $n<=$range[1]; $n++
) {
938 if ($runAwayBrake<=0) break;
944 return implode(',',$list);
948 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
951 * @param integer Input value
952 * @param integer Lower limit
953 * @param integer Higher limit
954 * @param integer Default value if input is false.
955 * @return integer The input value forced into the boundaries of $min and $max
957 public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
958 // Returns $theInt as an integer in the integerspace from $min to $max
959 $theInt = intval($theInt);
960 if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
961 if ($theInt<$min){$theInt=$min;}
962 if ($theInt>$max){$theInt=$max;}
967 * Returns the $integer if greater than zero, otherwise returns zero.
970 * @param integer Integer string to process
973 public static function intval_positive($theInt) {
974 $theInt = intval($theInt);
975 if ($theInt<0){$theInt=0;}
980 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
983 * @param string Version number on format x.x.x
984 * @return integer Integer version of version number (where each part can count to 999)
986 public static function int_from_ver($verNumberStr) {
987 $verParts = explode('.',$verNumberStr);
988 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
));
992 * Returns true if the current TYPO3 version (or compatibility version) is compatible to the input version
993 * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version)
995 * @param string Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!)
996 * @return boolean Returns true if this setup is compatible with the provided version number
997 * @todo Still needs a function to convert versions to branches
999 public static function compat_version($verNumberStr) {
1000 global $TYPO3_CONF_VARS;
1001 $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ?
$TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch
;
1003 if (t3lib_div
::int_from_ver($currVersionStr) < t3lib_div
::int_from_ver($verNumberStr)) {
1011 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
1014 * @param string String to md5-hash
1015 * @return integer Returns 28bit integer-hash
1017 public static function md5int($str) {
1018 return hexdec(substr(md5($str),0,7));
1022 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
1026 * @param string Input string to be md5-hashed
1027 * @param integer The string-length of the output
1028 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
1030 public static function shortMD5($input, $len=10) {
1031 return substr(md5($input),0,$len);
1035 * Takes comma-separated lists and arrays and removes all duplicates
1036 * If a value in the list is trim(empty), the value is ignored.
1039 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
1040 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
1041 * @return string Returns the list without any duplicates of values, space around values are trimmed
1043 public static function uniqueList($in_list, $secondParameter=NULL) {
1044 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
1045 if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
1047 return implode(',',array_unique(t3lib_div
::trimExplode(',',$in_list,1)));
1051 * Splits a reference to a file in 5 parts
1054 * @param string Filename/filepath to be analysed
1055 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
1057 public static function split_fileref($fileref) {
1059 if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
1060 $info['path'] = $reg[1];
1061 $info['file'] = $reg[2];
1064 $info['file'] = $fileref;
1067 if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
1068 $info['filebody'] = $reg[1];
1069 $info['fileext'] = strtolower($reg[2]);
1070 $info['realFileext'] = $reg[2];
1072 $info['filebody'] = $info['file'];
1073 $info['fileext'] = '';
1080 * Returns the directory part of a path without trailing slash
1081 * If there is no dir-part, then an empty string is returned.
1084 * '/dir1/dir2/script.php' => '/dir1/dir2'
1085 * '/dir1/' => '/dir1'
1086 * 'dir1/script.php' => 'dir1'
1087 * 'd/script.php' => 'd'
1088 * '/script.php' => ''
1092 * @param string Directory name / path
1093 * @return string Processed input value. See function description.
1095 public static function dirname($path) {
1096 $p = t3lib_div
::revExplode('/',$path,2);
1097 return count($p)==2 ?
$p[0] : '';
1101 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
1104 * @param string A hexadecimal color code, #xxxxxx
1105 * @param integer Offset value 0-255
1106 * @param integer Offset value 0-255
1107 * @param integer Offset value 0-255
1108 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1109 * @see modifyHTMLColorAll()
1111 public static function modifyHTMLColor($color,$R,$G,$B) {
1112 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
1113 $nR = t3lib_div
::intInRange(hexdec(substr($color,1,2))+
$R,0,255);
1114 $nG = t3lib_div
::intInRange(hexdec(substr($color,3,2))+
$G,0,255);
1115 $nB = t3lib_div
::intInRange(hexdec(substr($color,5,2))+
$B,0,255);
1117 substr('0'.dechex($nR),-2).
1118 substr('0'.dechex($nG),-2).
1119 substr('0'.dechex($nB),-2);
1123 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
1126 * @param string A hexadecimal color code, #xxxxxx
1127 * @param integer Offset value 0-255 for all three channels.
1128 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
1129 * @see modifyHTMLColor()
1131 public static function modifyHTMLColorAll($color,$all) {
1132 return t3lib_div
::modifyHTMLColor($color,$all,$all,$all);
1136 * Removes comma (if present) in the end of string
1139 * @param string String from which the comma in the end (if any) will be removed.
1142 public static function rm_endcomma($string) {
1143 return ereg_replace(',$','',$string);
1147 * strtoupper which converts danish (and other characters) characters as well
1150 * @param string String to process
1152 * @deprecated Use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
1155 public static function danish_strtoupper($string) {
1156 $value = strtoupper($string);
1157 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
1161 * Change umlaut characters to plain ASCII with normally two character target
1162 * Only known characters will be converted, so don't expect a result for any character.
1166 * @param string String to convert.
1167 * @deprecated Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!
1170 public static function convUmlauts($str) {
1171 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
1172 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
1173 return preg_replace($pat,$repl,$str);
1177 * Tests if the input is an integer.
1180 * @param mixed Any input variable to test.
1181 * @return boolean Returns true if string is an integer
1183 public static function testInt($var) {
1184 return !strcmp($var,intval($var));
1188 * Returns true if the first part of $str matches the string $partStr
1191 * @param string Full string to check
1192 * @param string Reference string which must be found as the "first part" of the full string
1193 * @return boolean True if $partStr was found to be equal to the first part of $str
1195 public static function isFirstPartOfStr($str,$partStr) {
1196 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
1197 $psLen = strlen($partStr);
1199 return substr($str,0,$psLen)==(string)$partStr;
1200 } else return false;
1204 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
1207 * @param integer Number of bytes to format.
1208 * @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)
1209 * @return string Formatted representation of the byte number, for output.
1211 public static function formatSize($sizeInBytes,$labels='') {
1214 if (strlen($labels) == 0) {
1215 $labels = ' | K| M| G';
1217 $labels = str_replace('"','',$labels);
1219 $labelArr = explode('|',$labels);
1222 if ($sizeInBytes>900) {
1223 if ($sizeInBytes>900000000) { // GB
1224 $val = $sizeInBytes/(1024*1024*1024);
1225 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[3];
1227 elseif ($sizeInBytes>900000) { // MB
1228 $val = $sizeInBytes/(1024*1024);
1229 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[2];
1231 $val = $sizeInBytes/(1024);
1232 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[1];
1235 return $sizeInBytes.$labelArr[0];
1240 * Returns microtime input to milliseconds
1243 * @param string Microtime
1244 * @return integer Microtime input string converted to an integer (milliseconds)
1246 public static function convertMicrotime($microtime) {
1247 $parts = explode(' ',$microtime);
1248 return round(($parts[0]+
$parts[1])*1000);
1252 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
1255 * @param string Input string, eg "123 + 456 / 789 - 4"
1256 * @param string Operators to split by, typically "/+-*"
1257 * @return array Array with operators and operands separated.
1258 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1260 public static function splitCalc($string,$operators) {
1264 $valueLen=strcspn($string,$operators);
1265 $value=substr($string,0,$valueLen);
1266 $res[] = Array($sign,trim($value));
1267 $sign=substr($string,$valueLen,1);
1268 $string=substr($string,$valueLen+
1);
1275 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1278 * @param string Input string, eg "123 + 456 / 789 - 4"
1279 * @return integer Calculated value. Or error string.
1280 * @see calcParenthesis()
1282 public static function calcPriority($string) {
1283 $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
1284 $string='+'.$string; // Ensuring an operator for the first entrance
1286 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
1287 // split the expression here:
1289 preg_match_all('/'.$regex.'/',$string,$reg);
1295 $buffer=doubleval(array_shift($reg[2]));
1297 foreach ($reg[2] as $k => $v) {
1299 $sign = $reg[1][$k];
1300 if ($sign=='+' ||
$sign=='-') {
1301 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1305 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
1306 if ($sign=='%') {if ($v) $buffer%
=$v; else $err='dividing by zero';}
1307 if ($sign=='*') {$buffer*=$v;}
1308 if ($sign=='^') {$buffer=pow($buffer,$v);}
1311 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1312 return $err ?
'ERROR: '.$err : $number;
1316 * Calculates the input with parenthesis levels
1319 * @param string Input string, eg "(123 + 456) / 789 - 4"
1320 * @return integer Calculated value. Or error string.
1321 * @see calcPriority(), tslib_cObj::stdWrap()
1323 public static function calcParenthesis($string) {
1326 $valueLenO=strcspn($string,'(');
1327 $valueLenC=strcspn($string,')');
1328 if ($valueLenC==strlen($string) ||
$valueLenC < $valueLenO) {
1329 $value = t3lib_div
::calcPriority(substr($string,0,$valueLenC));
1330 $string = $value.substr($string,$valueLenC+
1);
1333 $string = substr($string,0,$valueLenO).t3lib_div
::calcParenthesis(substr($string,$valueLenO+
1));
1337 if ($securC<=0) break;
1338 } while($valueLenO<strlen($string));
1343 * Inverse version of htmlspecialchars()
1346 * @param string Value where >, <, " and & should be converted to regular chars.
1347 * @return string Converted result.
1349 public static function htmlspecialchars_decode($value) {
1350 $value = str_replace('>','>',$value);
1351 $value = str_replace('<','<',$value);
1352 $value = str_replace('"','"',$value);
1353 $value = str_replace('&','&',$value);
1358 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1361 * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1362 * @return string Converted result.
1364 public static function deHSCentities($str) {
1365 return ereg_replace('&([#[:alnum:]]*;)','&\1',$str);
1369 * This function is used to escape any ' -characters when transferring text to JavaScript!
1372 * @param string String to escape
1373 * @param boolean If set, also backslashes are escaped.
1374 * @param string The character to escape, default is ' (single-quote)
1375 * @return string Processed input string
1377 public static function slashJS($string,$extended=0,$char="'") {
1378 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
1379 return str_replace ($char, "\\".$char, $string);
1383 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1384 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1387 * @param string String to raw-url-encode with spaces preserved
1388 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1390 public static function rawUrlEncodeJS($str) {
1391 return str_replace('%20',' ',rawurlencode($str));
1395 * rawurlencode which preserves "/" chars
1396 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1399 * @param string Input string
1400 * @return string Output string
1402 public static function rawUrlEncodeFP($str) {
1403 return str_replace('%2F','/',rawurlencode($str));
1407 * Checking syntax of input email address
1410 * @param string Input string to evaluate
1411 * @return boolean Returns true if the $email address (input string) is valid; Has a "@", domain name with at least one period and only allowed a-z characters.
1413 public static function validEmail($email) {
1414 $email = trim ($email);
1415 if (strpos($email,' ') !== false) {
1418 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ?
TRUE : FALSE;
1422 * Formats a string for output between <textarea>-tags
1423 * All content outputted in a textarea form should be passed through this function
1424 * 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!
1427 * @param string Input string to be formatted.
1428 * @return string Formatted for <textarea>-tags
1430 public static function formatForTextarea($content) {
1431 return chr(10).htmlspecialchars($content);
1435 * Converts string to uppercase
1436 * The function converts all Latin characters (a-z, but no accents, etc) to
1437 * uppercase. It is safe for all supported character sets (incl. utf-8).
1438 * Unlike strtoupper() it does not honour the locale.
1440 * @param string Input string
1441 * @return string Uppercase String
1443 public static function strtoupper($str) {
1444 return strtr((string)$str, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
1448 * Converts string to lowercase
1449 * The function converts all Latin characters (A-Z, but no accents, etc) to
1450 * lowercase. It is safe for all supported character sets (incl. utf-8).
1451 * Unlike strtolower() it does not honour the locale.
1453 * @param string Input string
1454 * @return string Lowercase String
1456 public static function strtolower($str) {
1457 return strtr((string)$str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
1471 /*************************
1475 *************************/
1478 * Check if an string item exists in an array.
1479 * Please note that the order of function parameters is reverse compared to the PHP function in_array()!!!
1481 * Comparison to PHP in_array():
1482 * -> $array = array(0, 1, 2, 3);
1483 * -> variant_a := t3lib_div::inArray($array, $needle)
1484 * -> variant_b := in_array($needle, $array)
1485 * -> variant_c := in_array($needle, $array, true)
1486 * +---------+-----------+-----------+-----------+
1487 * | $needle | variant_a | variant_b | variant_c |
1488 * +---------+-----------+-----------+-----------+
1489 * | '1a' | false | true | false |
1490 * | '' | false | true | false |
1491 * | '0' | true | true | false |
1492 * | 0 | true | true | true |
1493 * +---------+-----------+-----------+-----------+
1496 * @param array one-dimensional array of items
1497 * @param string item to check for
1498 * @return boolean true if $item is in the one-dimensional array $in_array
1501 public static function inArray(array $in_array, $item) {
1502 foreach ($in_array as $val) {
1503 if (!is_array($val) && !strcmp($val, $item)) {
1511 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1512 * Corresponds to explode(), but with conversion to integers for all values.
1515 * @param string Delimiter string to explode with
1516 * @param string The string to explode
1517 * @return array Exploded values, all converted to integers
1519 public static function intExplode($delim, $string) {
1520 $temp = explode($delim,$string);
1521 foreach ($temp as &$val) {
1522 $val = intval($val);
1529 * Reverse explode which explodes the string counting from behind.
1530 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1533 * @param string Delimiter string to explode with
1534 * @param string The string to explode
1535 * @param integer Number of array entries
1536 * @return array Exploded values
1538 public static function revExplode($delim, $string, $count=0) {
1539 $temp = explode($delim,strrev($string),$count);
1540 foreach ($temp as &$val) {
1541 $val = strrev($val);
1543 $temp = array_reverse($temp);
1549 * Explodes a string and trims all values for whitespace in the ends.
1550 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1553 * @param string Delimiter string to explode with
1554 * @param string The string to explode
1555 * @param boolean If set, all empty values (='') will NOT be set in output
1556 * @return array Exploded values
1558 public static function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
1559 $array = explode($delim, $string);
1560 // for two perfomance reasons the loop is duplicated
1561 // a) avoid check for $onlyNonEmptyValues in foreach loop
1562 // b) avoid unnecessary code when $onlyNonEmptyValues is not set
1563 if ($onlyNonEmptyValues) {
1564 $new_array = array();
1565 foreach($array as $value) {
1566 $value = trim($value);
1568 $new_array[] = $value;
1571 // direct return for perfomance reasons
1575 foreach($array as &$value) {
1576 $value = trim($value);
1583 * Remove duplicate values from an array
1586 * @param array Array of values to make unique
1589 * @deprecated Use the PHP function array_unique instead
1591 public static function uniqueArray(array $valueArray) {
1592 return array_unique($valueArray);
1596 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1599 * @param array Array containing the values
1600 * @param string Value to search for and if found remove array entry where found.
1601 * @return array Output array with entries removed if search string is found
1603 public static function removeArrayEntryByValue(array $array, $cmpValue) {
1604 foreach ($array as $k => $v) {
1606 $array[$k] = t3lib_div
::removeArrayEntryByValue($v, $cmpValue);
1607 } elseif (!strcmp($v, $cmpValue)) {
1616 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1619 * @param string Name prefix for entries. Set to blank if you wish none.
1620 * @param array The (multidim) array to implode
1621 * @param string (keep blank)
1622 * @param boolean If set, parameters which were blank strings would be removed.
1623 * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1624 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1625 * @see explodeUrl2Array()
1627 public static function implodeArrayForUrl($name,array $theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
1628 foreach($theArray as $Akey => $AVal) {
1629 $thisKeyName = $name ?
$name.'['.$Akey.']' : $Akey;
1630 if (is_array($AVal)) {
1631 $str = t3lib_div
::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1633 if (!$skipBlank ||
strcmp($AVal,'')) {
1634 $str.='&'.($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName).
1635 '='.rawurlencode($AVal);
1643 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1645 * @param string GETvars string
1646 * @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())
1647 * @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!
1648 * @see implodeArrayForUrl()
1650 public static function explodeUrl2Array($string,$multidim=FALSE) {
1653 parse_str($string,$output);
1655 $p = explode('&',$string);
1658 list($pK,$pV) = explode('=',$v,2);
1659 $output[rawurldecode($pK)] = rawurldecode($pV);
1667 * Returns an array with selected keys from incoming data.
1668 * (Better read source code if you want to find out...)
1671 * @param string List of variable/key names
1672 * @param array Array from where to get values based on the keys in $varList
1673 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1674 * @return array Output array with selected variables.
1676 public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) {
1677 $keys = t3lib_div
::trimExplode(',',$varList,1);
1679 foreach($keys as $v) {
1680 if (isset($getArray[$v])) {
1681 $outArr[$v] = $getArray[$v];
1682 } elseif ($GPvarAlt) {
1683 $outArr[$v] = t3lib_div
::_GP($v);
1691 * This function traverses a multidimentional array and adds slashes to the values.
1692 * NOTE that the input array is and argument by reference.!!
1693 * Twin-function to stripSlashesOnArray
1696 * @param array Multidimensional input array, (REFERENCE!)
1699 public static function addSlashesOnArray(array &$theArray) {
1700 foreach ($theArray as &$value) {
1701 if (is_array($value)) {
1702 t3lib_div
::addSlashesOnArray($value);
1704 $value = addslashes($value);
1712 * This function traverses a multidimentional array and strips slashes to the values.
1713 * NOTE that the input array is and argument by reference.!!
1714 * Twin-function to addSlashesOnArray
1717 * @param array Multidimensional input array, (REFERENCE!)
1720 public static function stripSlashesOnArray(array &$theArray) {
1721 foreach ($theArray as &$value) {
1722 if (is_array($value)) {
1723 t3lib_div
::stripSlashesOnArray($value);
1725 $value = stripslashes($value);
1732 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1735 * @param array Multidimensional input array
1736 * @param string "add" or "strip", depending on usage you wish.
1739 public static function slashArray(array $arr,$cmd) {
1740 if ($cmd=='strip') t3lib_div
::stripSlashesOnArray($arr);
1741 if ($cmd=='add') t3lib_div
::addSlashesOnArray($arr);
1746 * Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1)
1747 * In case of identical keys, ie. keeping the values of the second.
1750 * @param array First array
1751 * @param array Second array, overruling the first array
1752 * @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.
1753 * @param boolean If set, values from $arr1 will overrule if they are empty or zero. Default: true
1754 * @return array Resulting array where $arr1 values has overruled $arr0 values
1756 public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) {
1757 foreach ($arr1 as $key => $val) {
1758 if(is_array($arr0[$key])) {
1759 if (is_array($arr1[$key])) {
1760 $arr0[$key] = t3lib_div
::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys,$includeEmtpyValues);
1764 if (isset($arr0[$key])) {
1765 if ($includeEmtpyValues ||
$val) {
1770 if ($includeEmtpyValues ||
$val) {
1781 * 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.
1784 * @param array First array
1785 * @param array Second array
1786 * @return array Merged result.
1788 public static function array_merge(array $arr1,array $arr2) {
1793 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1796 * @param array Input array of values
1797 * @param string Delimited, default is comman
1798 * @param string Quote-character to wrap around the values.
1799 * @return string A single line of CSV
1801 public static function csvValues(array $row,$delim=',',$quote='"') {
1804 foreach ($row as $value) {
1805 $out[] = str_replace($quote, $quote.$quote, $value);
1807 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1812 * Creates recursively a JSON literal from a mulidimensional associative array.
1813 * Uses Services_JSON (http://mike.teczno.com/JSON/doc/)
1815 * @param array $jsonArray: The array to be transformed to JSON
1816 * @return string JSON string
1818 public static function array2json(array $jsonArray) {
1819 if (!$GLOBALS['JSON']) {
1820 require_once(PATH_typo3
.'contrib/json/json.php');
1821 $GLOBALS['JSON'] = t3lib_div
::makeInstance('Services_JSON');
1823 return $GLOBALS['JSON']->encode($jsonArray);
1827 * Removes dots "." from end of a key identifier of TypoScript styled array.
1828 * array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))
1830 * @param array $ts: TypoScript configuration array
1831 * @return array TypoScript configuration array without dots at the end of all keys
1833 public static function removeDotsFromTS(array $ts) {
1835 if (is_array($ts)) {
1836 foreach ($ts as $key => $value) {
1837 if (is_array($value)) {
1838 $key = rtrim($key, '.');
1839 $out[$key] = t3lib_div
::removeDotsFromTS($value);
1841 $out[$key] = $value;
1863 /*************************
1865 * HTML/XML PROCESSING
1867 *************************/
1870 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1871 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1872 * If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
1875 * @param string HTML-tag string (or attributes only)
1876 * @return array Array with the attribute values.
1878 public static function get_tag_attributes($tag) {
1879 $components = t3lib_div
::split_tag_attributes($tag);
1880 $name = ''; // attribute name is stored here
1882 $attributes = array();
1883 foreach ($components as $key => $val) {
1884 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
1887 $attributes[$name] = $val;
1891 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1892 $attributes[$key] = '';
1905 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1906 * Removes tag-name if found
1909 * @param string HTML-tag string (or attributes only)
1910 * @return array Array with the attribute values.
1913 public static function split_tag_attributes($tag) {
1914 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1915 // Removes any > in the end of the string
1916 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1919 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1920 $firstChar=substr($tag_tmp,0,1);
1921 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
1922 $reg=explode($firstChar,$tag_tmp,3);
1924 $tag_tmp=trim($reg[2]);
1925 } elseif (!strcmp($firstChar,'=')) {
1927 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1929 // There are '' around the value. We look for the next ' ' or '>'
1930 $reg = split('[[:space:]=]',$tag_tmp,2);
1931 $value[] = trim($reg[0]);
1932 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1940 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1943 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1944 * @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!
1945 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1946 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1948 public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1951 foreach($arr as $p => $v) {
1952 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
1957 foreach($arr as $p => $v) {
1958 if (strcmp($v,'') ||
$dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
1960 return implode(' ',$list);
1964 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1966 * @param array See implodeAttributes()
1967 * @param boolean See implodeAttributes()
1968 * @param boolean See implodeAttributes()
1969 * @return string See implodeAttributes()
1970 * @deprecated Name was changed into implodeAttributes
1971 * @see implodeAttributes()
1973 public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1974 return t3lib_div
::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
1978 * Wraps JavaScript code XHTML ready with <script>-tags
1979 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1980 * This is nice for identing JS code with PHP code on the same level.
1982 * @param string JavaScript code
1983 * @param boolean Wrap script element in linebreaks? Default is TRUE.
1984 * @return string The wrapped JS code, ready to put into a XHTML page
1985 * @author Ingmar Schlecht <ingmars@web.de>
1986 * @author René Fritz <r.fritz@colorcube.de>
1988 public static function wrapJS($string, $linebreak=TRUE) {
1990 // <script wrapped in nl?
1991 $cr = $linebreak?
"\n" : '';
1993 // remove nl from the beginning
1994 $string = preg_replace ('/^\n+/', '', $string);
1995 // re-ident to one tab using the first line as reference
1997 if(preg_match('/^(\t+)/',$string,$match)) {
1998 $string = str_replace($match[1],"\t", $string);
2000 $string = $cr.'<script type="text/javascript">
2006 return trim($string);
2011 * Parses XML input into a PHP array with associative keys
2014 * @param string XML data input
2015 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
2016 * @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.
2017 * @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
2019 public static function xml2tree($string,$depth=999) {
2020 $parser = xml_parser_create();
2024 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2025 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2026 xml_parse_into_struct($parser, $string, $vals, $index);
2028 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
2029 xml_parser_free($parser);
2031 $stack = array( array() );
2035 // FIXME don't use unset() - what does that mean? Use NULL or similar.
2037 foreach($vals as $key => $val) {
2038 $type = $val['type'];
2041 if ($type=='open' ||
$type=='complete') {
2042 $stack[$stacktop++
] = $tagi;
2044 if ($depth==$stacktop) {
2048 $tagi = array('tag' => $val['tag']);
2050 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
2051 if(isset($val['value'])) $tagi['values'][] = $val['value'];
2054 if ($type=='complete' ||
$type=='close') {
2056 $tagi = $stack[--$stacktop];
2057 $oldtag = $oldtagi['tag'];
2058 unset($oldtagi['tag']);
2060 if ($depth==($stacktop+
1)) {
2061 if ($key-$startPoint > 0) {
2062 $partArray = array_slice(
2067 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
2068 $oldtagi['XMLvalue']=t3lib_div
::xmlRecompileFromStructValArray($partArray);
2070 $oldtagi['XMLvalue']=$oldtagi['values'][0];
2074 $tagi['ch'][$oldtag][] = $oldtagi;
2078 if($type=='cdata') {
2079 $tagi['values'][] = $val['value'];
2086 * Turns PHP array into XML. See array2xml()
2088 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2089 * @param string Alternative document tag. Default is "phparray".
2090 * @param array Options for the compilation. See array2xml() for description.
2091 * @param string Forced charset to prologue
2092 * @return string An XML string made from the input content in the array.
2093 * @see xml2array(),array2xml()
2095 public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') {
2097 // Figure out charset if not given explicitly:
2099 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset']) { // First priority: forceCharset! If set, this will be authoritative!
2100 $charset = $GLOBALS['TYPO3_CONF_VARS']['BE']['forceCharset'];
2101 } elseif (is_object($GLOBALS['LANG'])) {
2102 $charset = $GLOBALS['LANG']->charSet
; // If "LANG" is around, that will hold the current charset
2104 $charset = 'iso-8859-1'; // THIS is just a hopeful guess!
2109 return '<?xml version="1.0" encoding="'.htmlspecialchars($charset).'" standalone="yes" ?>'.chr(10).
2110 t3lib_div
::array2xml($array,'',0,$docTag,0, $options);
2114 * Deprecated to call directly (unless you are aware of using XML prologues)! Use "array2xml_cs" instead (which adds an XML-prologue)
2116 * Converts a PHP array into an XML string.
2117 * The XML output is optimized for readability since associative keys are used as tagnames.
2118 * 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.
2119 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
2120 * 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
2121 * 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.
2122 * 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!
2123 * 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...
2126 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
2127 * @param string tag-prefix, eg. a namespace prefix like "T3:"
2128 * @param integer Current recursion level. Don't change, stay at zero!
2129 * @param string Alternative document tag. Default is "phparray".
2130 * @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
2131 * @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')
2132 * @param string Stack data. Don't touch.
2133 * @return string An XML string made from the input content in the array.
2136 public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) {
2137 // 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
2138 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
2139 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
2140 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
2142 // Set indenting mode:
2143 $indentChar = $spaceInd ?
' ' : chr(9);
2144 $indentN = $spaceInd>0 ?
$spaceInd : 1;
2145 $nl = ($spaceInd >= 0 ?
chr(10) : '');
2147 // Init output variable:
2150 // Traverse the input array
2151 foreach($array as $k=>$v) {
2155 // Construct the tag name.
2156 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
2157 $attr.=' index="'.htmlspecialchars($tagName).'"';
2158 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
2159 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM']) && t3lib_div
::testInt($tagName)) { // Use tag based on parent tag name + if current tag is numeric
2160 $attr.=' index="'.htmlspecialchars($tagName).'"';
2161 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':_IS_NUM'];
2162 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
2163 $attr.=' index="'.htmlspecialchars($tagName).'"';
2164 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
2165 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
2166 $attr.=' index="'.htmlspecialchars($tagName).'"';
2167 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
2168 } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
2169 if ($options['useNindex']) { // If numeric key, prefix "n"
2170 $tagName = 'n'.$tagName;
2171 } else { // Use special tag for num. keys:
2172 $attr.=' index="'.$tagName.'"';
2173 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
2175 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
2176 $attr.=' index="'.htmlspecialchars($tagName).'"';
2177 $tagName = $options['useIndexTagForAssoc'];
2180 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
2181 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
2183 // If the value is an array then we will call this function recursively:
2187 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
2188 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
2189 $clearStackPath = $subOptions['clearStackPath'];
2191 $subOptions = $options;
2192 $clearStackPath = FALSE;
2196 t3lib_div
::array2xml(
2204 'parentTagName' => $tagName,
2205 'grandParentTagName' => $stackData['parentTagName'],
2206 'path' => $clearStackPath ?
'' : $stackData['path'].'/'.$tagName,
2209 ($spaceInd >= 0 ?
str_pad('',($level+
1)*$indentN,$indentChar) : '');
2210 if ((int)$options['disableTypeAttrib']!=2) { // Do not set "type = array". Makes prettier XML but means that empty arrays are not restored with xml2array
2211 $attr.=' type="array"';
2213 } else { // Just a value:
2215 // Look for binary chars:
2216 $vLen = strlen($v); // check for length, because PHP 5.2.0 may crash when first argument of strcspn is empty
2217 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!
2218 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
2219 $content = $nl.chunk_split(base64_encode($v));
2220 $attr.=' base64="1"';
2222 // Otherwise, just htmlspecialchar the stuff:
2223 $content = htmlspecialchars($v);
2224 $dType = gettype($v);
2225 if ($dType == 'string') {
2226 if ($options['useCDATA'] && $content != $v) {
2227 $content = '<![CDATA[' . $v . ']]>';
2229 } elseif (!$options['disableTypeAttrib']) {
2230 $attr.= ' type="'.$dType.'"';
2235 // Add the element to the output string:
2236 $output.=($spaceInd >= 0 ?
str_pad('',($level+
1)*$indentN,$indentChar) : '').'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.$nl;
2239 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
2242 '<'.$docTag.'>'.$nl.
2251 * Converts an XML string to a PHP array.
2252 * This is the reverse function of array2xml()
2255 * @param string XML content to convert into an array
2256 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
2257 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
2258 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
2261 public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
2262 global $TYPO3_CONF_VARS;
2265 $parser = xml_parser_create();
2269 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
2270 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
2272 // default output charset is UTF-8, only ASCII, ISO-8859-1 and UTF-8 are supported!!!
2274 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$match);
2275 $theCharset = $match[1] ?
$match[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
2276 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
2279 xml_parse_into_struct($parser, $string, $vals, $index);
2281 // If error, return error message:
2282 if (xml_get_error_code($parser)) {
2283 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
2285 xml_parser_free($parser);
2288 $stack = array(array());
2294 // Traverse the parsed XML structure:
2295 foreach($vals as $key => $val) {
2297 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
2298 $tagName = $val['tag'];
2299 if (!$documentTag) $documentTag = $tagName;
2301 // Test for name space:
2302 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ?
substr($tagName,strlen($NSprefix)) : $tagName;
2304 // Test for numeric tag, encoded on the form "nXXX":
2305 $testNtag = substr($tagName,1); // Closing tag.
2306 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ?
intval($testNtag) : $tagName;
2308 // Test for alternative index value:
2309 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
2311 // Setting tag-values, manage stack:
2312 switch($val['type']) {
2313 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
2314 $current[$tagName] = array(); // Setting blank place holder
2315 $stack[$stacktop++
] = $current;
2318 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
2319 $oldCurrent = $current;
2320 $current = $stack[--$stacktop];
2321 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
2322 $current[key($current)] = $oldCurrent;
2325 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
2326 if ($val['attributes']['base64']) {
2327 $current[$tagName] = base64_decode($val['value']);
2329 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
2332 switch((string)$val['attributes']['type']) {
2334 $current[$tagName] = (integer)$current[$tagName];
2337 $current[$tagName] = (double)$current[$tagName];
2340 $current[$tagName] = (bool)$current[$tagName];
2343 $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...
2351 if ($reportDocTag) {
2352 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
2355 // Finally return the content of the document tag.
2356 return $current[$tagName];
2360 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
2363 * @param array A array of XML parts, see xml2tree
2364 * @return string Re-compiled XML data.
2366 public static function xmlRecompileFromStructValArray(array $vals) {
2369 foreach($vals as $val) {
2370 $type = $val['type'];
2373 if ($type=='open' ||
$type=='complete') {
2374 $XMLcontent.='<'.$val['tag'];
2375 if(isset($val['attributes'])) {
2376 foreach($val['attributes'] as $k => $v) {
2377 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
2380 if ($type=='complete') {
2381 if(isset($val['value'])) {
2382 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
2383 } else $XMLcontent.='/>';
2384 } else $XMLcontent.='>';
2386 if ($type=='open' && isset($val['value'])) {
2387 $XMLcontent.=htmlspecialchars($val['value']);
2391 if ($type=='close') {
2392 $XMLcontent.='</'.$val['tag'].'>';
2395 if($type=='cdata') {
2396 $XMLcontent.=htmlspecialchars($val['value']);
2404 * Extracts the attributes (typically encoding and version) of an XML prologue (header).
2407 * @param string XML data
2408 * @return array Attributes of the xml prologue (header)
2410 public static function xmlGetHeaderAttribs($xmlData) {
2412 if (preg_match('/^\s*<\?xml([^>]*)\?\>/', $xmlData, $match)) {
2413 return t3lib_div
::get_tag_attributes($match[1]);
2418 * Minifies JavaScript
2420 * @param string $script Script to minify
2421 * @param string $error Error message (if any)
2422 * @return string Minified script or source string if error happened
2424 public static function minifyJavaScript($script, &$error = '') {
2425 require_once(PATH_typo3
. 'contrib/jsmin/jsmin.php');
2428 $script = trim(JSMin
::minify(str_replace(chr(13), '', $script)));
2430 catch(JSMinException
$e) {
2431 $error = 'Error while minifying JavaScript: ' . $e->getMessage();
2432 t3lib_div
::devLog($error, 't3lib_div', 2,
2433 array('JavaScript' => $script, 'Stack trace' => $e->getTrace()));
2445 /*************************
2449 *************************/
2452 * Reads the file or url $url and returns the content
2453 * 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.
2456 * @param string File/URL to read
2457 * @param integer Whether the HTTP header should be fetched or not. 0=disable, 1=fetch header+content, 2=fetch header only
2458 * @param array HTTP headers to be used in the request
2459 * @param array Error code/message and, if $includeHeader is 1, response meta data (HTTP status and content type)
2460 * @return string The content from the resource given as input. FALSE if an error has occured.
2462 public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) {
2465 if (isset($report)) {
2466 $report['error'] = 0;
2467 $report['message'] = '';
2470 // use cURL for: http, https, ftp, ftps, sftp and scp
2471 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] == '1' && preg_match('/^(?:http|ftp)s?|s(?:ftp|cp):/', $url)) {
2472 if (isset($report)) {
2473 $report['lib'] = 'cURL';
2476 // External URL without error checking.
2479 if (isset($report)) {
2480 $report['error'] = -1;
2481 $report['message'] = 'Couldn\'t initialize cURL.';
2486 curl_setopt($ch, CURLOPT_URL
, $url);
2487 curl_setopt($ch, CURLOPT_HEADER
, $includeHeader ?
1 : 0);
2488 curl_setopt($ch, CURLOPT_NOBODY
, $includeHeader == 2 ?
1 : 0);
2489 curl_setopt($ch, CURLOPT_HTTPGET
, $includeHeader == 2 ?
'HEAD' : 'GET');
2490 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, 1);
2491 curl_setopt($ch, CURLOPT_FAILONERROR
, 1);
2493 // may fail (PHP 5.2.0+ and 5.1.5+) when open_basedir or safe_mode are enabled
2494 $followLocation = @curl_setopt
($ch, CURLOPT_FOLLOWLOCATION
, 1);
2496 if (is_array($requestHeaders)) {
2497 curl_setopt($ch, CURLOPT_HTTPHEADER
, $requestHeaders);
2500 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2501 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2502 curl_setopt($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2504 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2505 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']);
2507 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2508 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']);
2511 $content = curl_exec($ch);
2512 if (isset($report)) {
2513 if ($content===FALSE) {
2514 $report['error'] = curl_errno($ch);
2515 $report['message'] = curl_error($ch);
2517 $curlInfo = curl_getinfo($ch);
2518 // We hit a redirection but we couldn't follow it
2519 if (!$followLocation && $curlInfo['status'] >= 300 && $curlInfo['status'] < 400) {
2520 $report['error'] = -1;
2521 $report['message'] = 'Couldn\'t follow location redirect (either PHP configuration option safe_mode or open_basedir is in effect).';
2522 } elseif($includeHeader) {
2523 // Set only for $includeHeader to work exactly like PHP variant
2524 $report['http_code'] = $curlInfo['http_code'];
2525 $report['content_type'] = $curlInfo['content_type'];
2531 } elseif ($includeHeader) {
2532 if (isset($report)) {
2533 $report['lib'] = 'socket';
2535 $parsedURL = parse_url($url);
2536 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2537 if (isset($report)) {
2538 $report['error'] = -1;
2539 $report['message'] = 'Reading headers is not allowed for this protocol.';
2543 $port = intval($parsedURL['port']);
2545 if ($parsedURL['scheme'] == 'http') {
2546 $port = ($port>0 ?
$port : 80);
2549 $port = ($port>0 ?
$port : 443);
2555 $fp = @fsockopen
($scheme.$parsedURL['host'], $port, $errno, $errstr, 2.0);
2556 if (!$fp ||
$errno > 0) {
2557 if (isset($report)) {
2558 $report['error'] = $errno ?
$errno : -1;
2559 $report['message'] = $errno ?
($errstr ?
$errstr : 'Socket error.') : 'Socket initialization error.';
2563 $method = ($includeHeader == 2) ?
'HEAD' : 'GET';
2564 $msg = $method . ' ' . $parsedURL['path'] .
2565 ($parsedURL['query'] ?
'?' . $parsedURL['query'] : '') .
2566 ' HTTP/1.0' . "\r\n" . 'Host: ' .
2567 $parsedURL['host'] . "\r\nConnection: close\r\n";
2568 if (is_array($requestHeaders)) {
2569 $msg .= implode("\r\n", $requestHeaders) . "\r\n";
2574 while (!feof($fp)) {
2575 $line = fgets($fp, 2048);
2576 if (isset($report)) {
2577 if (preg_match('|^HTTP/\d\.\d +(\d+)|', $line, $status)) {
2578 $report['http_code'] = $status[1];
2580 elseif (preg_match('/^Content-Type: *(.*)/i', $line, $type)) {
2581 $report['content_type'] = $type[1];
2585 if (!strlen(trim($line))) {
2586 break; // Stop at the first empty line (= end of header)
2589 if ($includeHeader != 2) {
2590 $content .= stream_get_contents($fp);
2594 } elseif (is_array($requestHeaders)) {
2595 if (isset($report)) {
2596 $report['lib'] = 'file/context';
2598 $parsedURL = parse_url($url);
2599 if (!preg_match('/^https?/', $parsedURL['scheme'])) {
2600 if (isset($report)) {
2601 $report['error'] = -1;
2602 $report['message'] = 'Sending request headers is not allowed for this protocol.';
2606 $ctx = stream_context_create(array(
2608 'header' => implode("\r\n", $requestHeaders)
2612 $content = @file_get_contents
($url, false, $ctx);
2613 if ($content === false && isset($report)) {
2614 // TODO: Remove this once PHP 5.1 support is dropped completely
2615 if (function_exists('error_get_last')) {
2616 $phpError = error_get_last();
2617 $report['error'] = $phpError['type'];
2618 $report['message'] = $phpError['message'];
2620 $report['error'] = -1;
2621 $report['message'] = 'Couldn\'t get URL.';
2625 if (isset($report)) {
2626 $report['lib'] = 'file';
2628 $content = @file_get_contents
($url);
2629 if ($content === false && isset($report)) {
2630 if (function_exists('error_get_last')) {
2631 $phpError = error_get_last();
2632 $report['error'] = $phpError['type'];
2633 $report['message'] = $phpError['message'];
2635 $report['error'] = -1;
2636 $report['message'] = 'Couldn\'t get URL.';
2645 * Writes $content to the file $file
2648 * @param string Filepath to write to
2649 * @param string Content to write
2650 * @return boolean True if the file was successfully opened and written to.
2652 public static function writeFile($file,$content) {
2653 if (!@is_file
($file)) $changePermissions = true;
2655 if ($fd = fopen($file,'wb')) {
2656 $res = fwrite($fd,$content);
2659 if ($res===false) return false;
2661 if ($changePermissions) { // Change the permissions only if the file has just been created
2662 t3lib_div
::fixPermissions($file);
2672 * Setting file system mode & group ownership of file
2674 * @param string Filepath of newly created file
2677 public static function fixPermissions($file) {
2678 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2679 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2680 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2681 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2687 * Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...)
2688 * Accepts an additional subdirectory in the file path!
2690 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2691 * @param string Content string to write
2692 * @return string Returns false on success, otherwise an error string telling about the problem.
2694 public static function writeFileToTypo3tempDir($filepath,$content) {
2696 // Parse filepath into directory and basename:
2697 $fI = pathinfo($filepath);
2698 $fI['dirname'].= '/';
2701 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2702 if (defined('PATH_site')) {
2703 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2704 if (@is_dir
($dirName)) {
2705 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2707 // Checking if the "subdir" is found:
2708 $subdir = substr($fI['dirname'],strlen($dirName));
2710 if (ereg('^[[:alnum:]_]+\/$',$subdir) ||
ereg('^[[:alnum:]_]+\/[[:alnum:]_]+\/$',$subdir)) {
2712 if (!@is_dir
($dirName)) {
2713 t3lib_div
::mkdir_deep(PATH_site
.'typo3temp/', $subdir);
2715 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[[:alnum:]_]/" or "[[:alnum:]_]/[[:alnum:]_]/"';
2717 // Checking dir-name again (sub-dir might have been created):
2718 if (@is_dir
($dirName)) {
2719 if ($filepath == $dirName.$fI['basename']) {
2720 t3lib_div
::writeFile($filepath, $content);
2721 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2722 } else return 'Calculated filelocation didn\'t match input $filepath!';
2723 } else return '"'.$dirName.'" is not a directory!';
2724 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2725 } else return 'PATH_site + "typo3temp/" was not a directory!';
2726 } else return 'PATH_site constant was NOT defined!';
2727 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2731 * 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']
2734 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2735 * @return boolean TRUE if @mkdir went well!
2737 public static function mkdir($theNewFolder) {
2738 $theNewFolder = preg_replace('|/$|','',$theNewFolder);
2739 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2740 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2742 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2743 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2750 * Creates a directory - including parent directories if necessary - in the file system
2752 * @param string Base folder. This must exist! Must have trailing slash! Example "/root/typo3site/"
2753 * @param string Deep directory to create, eg. "xx/yy/" which creates "/root/typo3site/xx/yy/" if $destination is "/root/typo3site/"
2754 * @return string If error, returns error string.
2756 public static function mkdir_deep($destination,$deepDir) {
2757 $allParts = t3lib_div
::trimExplode('/',$deepDir,1);
2759 foreach($allParts as $part) {
2761 if (!is_dir($destination.$root)) {
2762 t3lib_div
::mkdir($destination.$root);
2763 if (!@is_dir
($destination.$root)) {
2764 return 'Error: The directory "'.$destination.$root.'" could not be created...';
2771 * Wrapper function for rmdir, allowing recursive deletion of folders and files
2773 * @param string Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
2774 * @param boolean Allow deletion of non-empty directories
2775 * @return boolean true if @rmdir went well!
2777 public static function rmdir($path,$removeNonEmpty=false) {
2779 $path = preg_replace('|/$|','',$path); // Remove trailing slash
2781 if (file_exists($path)) {
2784 if (is_dir($path)) {
2785 if ($removeNonEmpty==true && $handle = opendir($path)) {
2786 while ($OK && false !== ($file = readdir($handle))) {
2787 if ($file=='.' ||
$file=='..') continue;
2788 $OK = t3lib_div
::rmdir($path.'/'.$file,$removeNonEmpty);
2792 if ($OK) { $OK = rmdir($path); }
2794 } else { // If $dirname is a file, simply remove it
2795 $OK = unlink($path);
2805 * Returns an array with the names of folders in a specific path
2806 * Will return 'error' (string) if there were an error with reading directory content.
2809 * @param string Path to list directories from
2810 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2812 public static function get_dirs($path) {
2815 if (is_object($d)) {
2816 while($entry=$d->read()) {
2817 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2818 $filearray[]=$entry;
2822 } else return 'error';
2828 * Returns an array with the names of files in a specific path
2831 * @param string $path: Is the path to the file
2832 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2833 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2834 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2835 * @param string A comma seperated list of filenames to exclude, no wildcards
2836 * @return array Array of the files found
2838 public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') {
2840 // Initialize variabels:
2841 $filearray = array();
2842 $sortarray = array();
2843 $path = ereg_replace('\/$','',$path);
2845 // Find files+directories:
2846 if (@is_dir
($path)) {
2847 $extensionList = strtolower($extensionList);
2849 if (is_object($d)) {
2850 while($entry=$d->read()) {
2851 if (@is_file
($path.'/'.$entry)) {
2852 $fI = pathinfo($entry);
2853 $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)
2854 if ((!strlen($extensionList) || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) && (!strlen($excludePattern) ||
!preg_match('/^'.$excludePattern.'$/',$entry))) {
2855 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2856 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2857 elseif ($order) {$sortarray[$key]=$entry;}
2862 } else return 'error opening path: "'.$path.'"';
2869 foreach ($sortarray as $k => $v) {
2870 $newArr[$k]=$filearray[$k];
2881 * Recursively gather all files and folders of a path.
2884 * @param array $fileArr: Empty input array (will have files added to it)
2885 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2886 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2887 * @param boolean $regDirs: If set, directories are also included in output.
2888 * @param integer $recursivityLevels: The number of levels to dig down...
2889 * @param string $excludePattern: regex pattern of files/directories to exclude
2890 * @return array An array with the found files/directories.
2892 public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') {
2893 if ($regDirs) $fileArr[] = $path;
2894 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1,$excludePattern));
2896 $dirs = t3lib_div
::get_dirs($path);
2897 if (is_array($dirs) && $recursivityLevels>0) {
2898 foreach ($dirs as $subdirs) {
2899 if ((string)$subdirs!='' && (!strlen($excludePattern) ||
!preg_match('/^'.$excludePattern.'$/',$subdirs))) {
2900 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1,$excludePattern);
2908 * Removes the absolute part of all files/folders in fileArr
2911 * @param array $fileArr: The file array to remove the prefix from
2912 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2913 * @return array The input $fileArr processed.
2915 public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) {
2916 foreach ($fileArr as $k => &$absFileRef) {
2917 if (t3lib_div
::isFirstPartOfStr($absFileRef, $prefixToRemove)) {
2918 $absFileRef = substr($absFileRef, strlen($prefixToRemove));
2920 return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2927 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2930 * @param string File path to process
2933 public static function fixWindowsFilePath($theFile) {
2934 return str_replace('//','/', str_replace('\\','/', $theFile));
2938 * Resolves "../" sections in the input path string.
2939 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2942 * @param string File path in which "/../" is resolved
2945 public static function resolveBackPath($pathStr) {
2946 $parts = explode('/',$pathStr);
2949 foreach($parts as $pV) {
2954 } else $output[]=$pV;
2960 return implode('/',$output);
2964 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2965 * - If already having a scheme, nothing is prepended
2966 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2967 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2970 * @param string URL / path to prepend full URL addressing to.
2973 public static function locationHeaderUrl($path) {
2974 $uI = parse_url($path);
2975 if (substr($path,0,1)=='/') { // relative to HOST
2976 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2977 } elseif (!$uI['scheme']) { // No scheme either
2978 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2998 /*************************
3000 * DEBUG helper FUNCTIONS
3002 *************************/
3005 * Returns a string with a list of ascii-values for the first $characters characters in $string
3008 * @param string String to show ASCII value for
3009 * @param integer Number of characters to show
3010 * @return string The string with ASCII values in separated by a space char.
3013 public static function debug_ordvalue($string,$characters=100) {
3014 if(strlen($string) < $characters) $characters = strlen($string);
3015 for ($i=0; $i<$characters; $i++
) {
3016 $valuestring.=' '.ord(substr($string,$i,1));
3018 return trim($valuestring);
3022 * Returns HTML-code, which is a visual representation of a multidimensional array
3023 * use t3lib_div::print_array() in order to print an array
3024 * Returns false if $array_in is not an array
3027 * @param mixed Array to view
3028 * @return string HTML output
3030 public static function view_array($array_in) {
3031 if (is_array($array_in)) {
3033 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
3034 if (count($array_in) == 0) {
3035 $result.= '<tr><td><font face="Verdana,Arial" size="1"><b>EMPTY!</b></font></td></tr>';
3037 foreach ($array_in as $key => $val) {
3039 <td valign="top"><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td>
3041 if (is_array($val)) {
3042 $result.=t3lib_div
::view_array($val);
3043 } elseif (is_object($val)) {
3044 $string = get_class($val);
3045 if (method_exists($val, '__toString')) {
3046 $string .= ': '.(string)$val;
3048 $result .= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
3050 if (gettype($val) == 'object') {
3051 $string = 'Unknown object';
3053 $string = (string)$val;
3055 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars($string)).'<br /></font>';
3061 $result.= '</table>';
3063 $result = '<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">
3065 <td><font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$array_in)).'<br /></font></td>
3067 </table>'; // Output it as a string.
3076 * @param mixed Array to print visually (in a table).
3081 public static function print_array($array_in) {
3082 echo t3lib_div
::view_array($array_in);
3086 * Makes debug output
3087 * Prints $var in bold between two vertical lines
3088 * If not $var the word 'debug' is printed
3089 * If $var is an array, the array is printed by t3lib_div::print_array()
3092 * @param mixed Variable to print
3093 * @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.
3096 public static function debug($var='',$brOrHeader=0) {
3097 // buffer the output of debug if no buffering started before
3098 if (ob_get_level()==0) {
3102 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
3103 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>';
3104 } elseif ($brOrHeader<0) {
3105 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
3108 if (is_array($var)) {
3109 t3lib_div
::print_array($var);
3110 } elseif (is_object($var)) {
3111 echo '<b>|Object:<pre>';
3114 } elseif ((string)$var!='') {
3115 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
3117 echo '<b>| debug |</b>';
3120 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
3121 echo '</td></tr></table>';
3122 } elseif ($brOrHeader>0) {
3123 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
3128 * Displays the "path" of the function call stack in a string, using debug_backtrace
3132 public static function debug_trail() {
3133 $trail = debug_backtrace();
3134 $trail = array_reverse($trail);
3138 foreach($trail as $dat) {
3139 $path[] = $dat['class'].$dat['type'].$dat['function'];
3142 return implode(' // ',$path);
3146 * Displays an array as rows in a table. Useful to debug output like an array of database records.
3148 * @param mixed Array of arrays with similar keys
3149 * @param string Table header
3150 * @param boolean If TRUE, will return content instead of echo'ing out.
3151 * @return void Outputs to browser.
3153 public static function debugRows($rows,$header='',$returnHTML=FALSE) {
3154 if (is_array($rows)) {
3156 $firstEl = current($rows);
3157 if (is_array($firstEl)) {
3158 $headerColumns = array_keys($firstEl);
3162 $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>';
3164 foreach($headerColumns as $key) {
3166 <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
3169 <tr>'.implode('',$tCells).'
3173 foreach($rows as $singleRow) {
3175 foreach($headerColumns as $key) {
3177 <td><font face="Verdana,Arial" size="1">'.(is_array($singleRow[$key]) ? t3lib_div
::debugRows($singleRow[$key],'',TRUE) : htmlspecialchars($singleRow[$key])).'</font></td>';
3180 <tr>'.implode('',$tCells).'
3185 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
3187 if ($returnHTML) return $table; else echo $table;
3188 } else debug('Empty array of rows',$header);
3190 debug('No array of rows',$header);
3221 /*************************
3223 * SYSTEM INFORMATION
3225 *************************/
3228 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
3233 public static function getThisUrl() {
3234 $p=parse_url(t3lib_div
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
3235 $dir=t3lib_div
::dirname($p['path']).