2 /***************************************************************
5 * (c) 1999-2004 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 * 209: class t3lib_div
44 * SECTION: GET/POST Variables
45 * 239: function _GP($var)
46 * 257: function _GET($var=NULL)
47 * 274: function _POST($var=NULL)
48 * 290: function _GETset($inputGet,$key='')
49 * 313: function GPvar($var,$strip=0)
50 * 330: function GParrayMerged($var)
52 * SECTION: IMAGE FUNCTIONS
53 * 374: function gif_compress($theFile, $type)
54 * 400: function png_to_gif_by_imagemagick($theFile)
55 * 424: function read_png_gif($theFile,$output_png=0)
57 * SECTION: STRING FUNCTIONS
58 * 473: function fixed_lgd($string,$origChars,$preStr='...')
59 * 498: function fixed_lgd_pre($string,$chars)
60 * 512: function fixed_lgd_cs($string,$chars)
61 * 529: function breakTextForEmail($str,$implChar="\n",$charWidth=76)
62 * 548: function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
63 * 583: function cmpIP($baseIP, $list)
64 * 625: function cmpFQDN($baseIP, $list)
65 * 655: function inList($in_list,$item)
66 * 667: function rmFromList($element,$list)
67 * 685: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
68 * 701: function intval_positive($theInt)
69 * 714: function int_from_ver($verNumberStr)
70 * 726: function md5int($str)
71 * 739: function shortMD5($input, $len=10)
72 * 752: function uniqueList($in_list, $secondParameter=NULL)
73 * 766: function split_fileref($fileref)
74 * 803: function dirname($path)
75 * 819: function modifyHTMLColor($color,$R,$G,$B)
76 * 839: function modifyHTMLColorAll($color,$all)
77 * 850: function rm_endcomma($string)
78 * 863: function danish_strtoupper($string)
79 * 878: function convUmlauts($str)
80 * 891: function testInt($var)
81 * 903: function isFirstPartOfStr($str,$partStr)
82 * 919: function formatSize($sizeInBytes,$labels='')
83 * 954: function convertMicrotime($microtime)
84 * 968: function splitCalc($string,$operators)
85 * 990: function calcPriority($string)
86 * 1030: function calcParenthesis($string)
87 * 1056: function htmlspecialchars_decode($value)
88 * 1071: function deHSCentities($str)
89 * 1084: function slashJS($string,$extended=0,$char="'")
90 * 1097: function rawUrlEncodeJS($str)
91 * 1109: function rawUrlEncodeFP($str)
92 * 1120: function validEmail($email)
93 * 1135: function formatForTextarea($content)
95 * SECTION: ARRAY FUNCTIONS
96 * 1166: function inArray($in_array,$item)
97 * 1183: function intExplode($delim, $string)
98 * 1202: function revExplode($delim, $string, $count=0)
99 * 1222: function trimExplode($delim, $string, $onlyNonEmptyValues=0)
100 * 1244: function uniqueArray($valueArray)
101 * 1256: function removeArrayEntryByValue($array,$cmpValue)
102 * 1284: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
103 * 1311: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
104 * 1334: function addSlashesOnArray(&$theArray)
105 * 1358: function stripSlashesOnArray(&$theArray)
106 * 1380: function slashArray($arr,$cmd)
107 * 1397: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
108 * 1430: function array_merge($arr1,$arr2)
109 * 1443: function csvValues($row,$delim=',',$quote='"')
111 * SECTION: HTML/XML PROCESSING
112 * 1485: function get_tag_attributes($tag)
113 * 1522: function split_tag_attributes($tag)
114 * 1556: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
115 * 1583: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
116 * 1598: function wrapJS($string, $linebreak=TRUE)
117 * 1628: function xml2tree($string,$depth=999)
118 * 1714: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$parentTagName='')
119 * 1799: function xml2array($string,$NSprefix='')
120 * 1901: function xmlRecompileFromStructValArray($vals)
121 * 1945: function xmlGetHeaderAttribs($xmlData)
123 * SECTION: FILES FUNCTIONS
124 * 1977: function getURL($url)
125 * 2019: function writeFile($file,$content)
126 * 2044: function writeFileToTypo3tempDir($filepath,$content)
127 * 2087: function mkdir($theNewFolder)
128 * 2107: function get_dirs($path)
129 * 2132: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
130 * 2186: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
131 * 2209: function removePrefixPathFromList($fileArr,$prefixToRemove)
132 * 2225: function fixWindowsFilePath($theFile)
133 * 2237: function resolveBackPath($pathStr)
134 * 2264: function locationHeaderUrl($path)
136 * SECTION: DEBUG helper FUNCTIONS
137 * 2304: function debug_ordvalue($string,$characters=100)
138 * 2321: function view_array($array_in)
139 * 2349: function print_array($array_in)
140 * 2364: function debug($var="",$brOrHeader=0)
142 * SECTION: SYSTEM INFORMATION
143 * 2433: function getThisUrl()
144 * 2449: function linkThisScript($getParams=array())
145 * 2473: function linkThisUrl($url,$getParams=array())
146 * 2498: function getIndpEnv($getEnvName)
147 * 2687: function milliseconds()
148 * 2699: function clientInfo($useragent='')
150 * SECTION: TYPO3 SPECIFIC FUNCTIONS
151 * 2786: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
152 * 2822: function validPathStr($theFile)
153 * 2833: function isAbsPath($path)
154 * 2844: function isAllowedAbsPath($path)
155 * 2861: function verifyFilenameAgainstDenyPattern($filename)
156 * 2879: function upload_copy_move($source,$destination)
157 * 2911: function upload_to_tempfile($uploadedFileName)
158 * 2929: function unlink_tempfile($uploadedTempFileName)
159 * 2945: function tempnam($filePrefix)
160 * 2958: function stdAuthCode($uid_or_record,$fields='')
161 * 2992: function loadTCA($table)
162 * 3012: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
163 * 3042: function resolveAllSheetsInDS($dataStructArray)
164 * 3071: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
165 * 3170: function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
166 * 3228: function &makeInstance($className)
167 * 3240: function makeInstanceClassName($className)
168 * 3254: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
169 * 3315: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)
170 * 3360: function quoted_printable($string,$maxlen=76)
171 * 3402: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
172 * 3436: function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
173 * 3463: function freetypeDpiComp($font_size)
174 * 3482: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
175 * 3503: function arrayToLogString($arr, $valueList=array(), $valueLength=20)
177 * TOTAL FUNCTIONS: 115
178 * (This index is automatically created/updated by the extension "extdeveval")
194 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
195 * Most of the functions does not relate specifically to TYPO3
196 * However a section of functions requires certain TYPO3 features available
197 * See comments in the source.
198 * You are encouraged to use this library in your own scripts!
201 * The class is intended to be used without creating an instance of it.
202 * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
203 * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
205 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
215 /*************************
220 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
221 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
222 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
223 * Eventually TYPO3 should provide this in the global space as well.
224 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
226 *************************/
229 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
230 * Strips slashes from all output, both strings and arrays.
231 * This function substitutes t3lib_div::GPvar()
232 * 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!
235 * @param string GET/POST var to return
236 * @return mixed POST var named $var and if not set, the GET var of the same name.
240 if(empty($var)) return;
241 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
243 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
249 * Returns the global GET array (or value from) normalized to contain un-escaped values.
250 * ALWAYS use this API function to acquire the GET variables!
253 * @param string Optional pointer to value in GET array (basically name of GET var)
254 * @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!*
255 * @see _POST(), _GP(), _GETset()
257 function _GET($var=NULL) {
258 $value = ($var === NULL) ?
$_GET : (empty($var) ?
NULL : $_GET[$var]);
259 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
260 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
266 * Returns the global POST array (or value from) normalized to contain un-escaped values.
267 * ALWAYS use this API function to acquire the POST variables!
270 * @param string Optional pointer to value in POST array (basically name of POST var)
271 * @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!*
274 function _POST($var=NULL) {
275 $value = ($var === NULL) ?
$_POST : (empty($var) ?
NULL : $_POST[$var]);
276 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
277 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
283 * Writes input value to $_GET
286 * @param array Array to write to $_GET. Values should NOT be escaped at input time (but will be escaped before writing according to TYPO3 standards).
287 * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
290 function _GETset($inputGet,$key='') {
291 // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
292 if (strcmp($key,'')) {
293 if (is_array($inputGet)) { t3lib_div
::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
294 $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
295 } elseif (is_array($inputGet)){
296 t3lib_div
::addSlashesOnArray($inputGet);
297 $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
303 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
304 * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
307 * @param string GET/POST var to return
308 * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
309 * @return mixed POST var named $var and if not set, the GET var of the same name.
310 * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
313 function GPvar($var,$strip=0) {
314 if(empty($var)) return;
315 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
316 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.
317 if ($strip && isset($value) && is_array($value)) { t3lib_div
::stripSlashesOnArray($value); }
322 * Returns the GET/POST global arrays merged with POST taking precedence.
325 * @param string Key (variable name) from GET or POST vars
326 * @return array Returns the GET vars merged recursively onto the POST vars.
330 function GParrayMerged($var) {
331 $postA = is_array($_POST[$var]) ?
$_POST[$var] : array();
332 $getA = is_array($_GET[$var]) ?
$_GET[$var] : array();
333 $mergedA = t3lib_div
::array_merge_recursive_overrule($getA,$postA);
334 t3lib_div
::stripSlashesOnArray($mergedA);
347 /*************************
351 *************************/
355 * Compressing a GIF file if not already LZW compressed
356 * 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)
358 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
360 * 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!)
361 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
365 * $theFile is expected to be a valid GIF-file!
366 * The function returns a code for the operation.
369 * @param string Filepath
370 * @param string See description of function
371 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
374 function gif_compress($theFile, $type) {
375 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
377 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
378 if (($type=='IM' ||
!$type) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) { // IM
379 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$theFile.'"');
381 } elseif (($type=='GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
382 $tempImage = imageCreateFromGif($theFile);
383 imageGif($tempImage, $theFile);
384 imageDestroy($tempImage);
392 * Converts a png file to gif
393 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
396 * @param string $theFile the filename with path
397 * @return string new filename
400 function png_to_gif_by_imagemagick($theFile) {
401 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
402 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
403 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
404 && strtolower(substr($theFile,-4,4))=='.png'
405 && @is_file
($theFile)) { // IM
406 $newFile = substr($theFile,0,-4).'.gif';
407 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$newFile.'"');
409 // 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!!
415 * Returns filename of the png/gif version of the input file (which can be png or gif).
416 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
419 * @param string Filepath of image file
420 * @param boolean If set, then input file is converted to PNG, otherwise to GIF
421 * @return string If the new image file exists, it's filepath is returned
424 function read_png_gif($theFile,$output_png=0) {
425 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file
($theFile)) {
426 $ext = strtolower(substr($theFile,-4,4));
428 ((string)$ext=='.png' && $output_png) ||
429 ((string)$ext=='.gif' && !$output_png)
433 $newFile = PATH_site
.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?
'.png':'.gif');
434 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
435 if (@is_file
($newFile)) return $newFile;
454 /*************************
458 *************************/
462 * Returns a new string of max. $chars length.
463 * If the string is longer, it will be truncated and appended with '...'.
464 * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
467 * @param string $string string to truncate
468 * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
469 * @param string String to append to the the output if it is truncated, default is '...'
470 * @return string new string
471 * @see fixed_lgd_pre()
473 function fixed_lgd($string,$origChars,$preStr='...') {
474 $chars = abs($origChars);
476 if(strlen($string)>$chars) {
477 return $origChars < 0 ?
478 $preStr.trim(substr($string, -($chars-3))) :
479 trim(substr($string, 0, $chars-3)).$preStr;
487 * Returns a new string of max. $chars length.
488 * If the string is longer, it will be truncated and prepended with '...'.
489 * This works like fixed_lgd, but is truncated in the start of the string instead of the end
490 * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
493 * @param string $string string to truncate
494 * @param integer $chars must be an integer of at least 4
495 * @return string new string
498 function fixed_lgd_pre($string,$chars) {
499 return strrev(t3lib_div
::fixed_lgd(strrev($string),$chars));
503 * Truncates a string with appended/prepended "..." and takes backend character set into consideration
504 * Use only from backend!
507 * @param string $string string to truncate
508 * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
509 * @return string New string
512 function fixed_lgd_cs($string,$chars) {
513 if (is_object($GLOBALS['LANG'])) {
514 return $GLOBALS['LANG']->csConvObj
->crop($GLOBALS['LANG']->charSet
,$string,$chars,'...');
516 return t3lib_div
::fixed_lgd($string, $chars);
521 * Breaks up the text for emails
524 * @param string The string to break up
525 * @param string The string to implode the broken lines with (default/typically \n)
526 * @param integer The line length
529 function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
530 $lines = explode(chr(10),$str);
532 while(list(,$lStr)=each($lines)) {
533 $outArr = array_merge($outArr,t3lib_div
::breakLinesForEmail($lStr,$implChar,$charWidth));
535 return implode(chr(10),$outArr);
539 * Breaks up a single line of text for emails
542 * @param string The string to break up
543 * @param string The string to implode the broken lines with (default/typically \n)
544 * @param integer The line length
546 * @see breakTextForEmail()
548 function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
552 while(strlen($str)>$p) {
553 $substr=substr($str,$p,$l);
554 if (strlen($substr)==$l) {
555 $count = count(explode(' ',trim(strrev($substr))));
556 if ($count>1) { // OK...
557 $parts = explode(' ',strrev($substr),2);
558 $theLine = strrev($parts[1]);
560 $afterParts = explode(' ',substr($str,$l+
$p),2);
561 $theLine = $substr.$afterParts[0];
563 if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
568 $lines[]=trim($theLine);
569 $p+
=strlen($theLine);
570 if (!trim(substr($str,$p,$l))) break; // added...
572 return implode($implChar,$lines);
576 * Match IP number with list of numbers with wildcard
579 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
580 * @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)
581 * @return boolean True if an IP-mask from $list matches $baseIP
583 function cmpIP($baseIP, $list) {
584 $IPpartsReq = explode('.',$baseIP);
585 if (count($IPpartsReq)==4) {
586 $values = t3lib_div
::trimExplode(',',$list,1);
588 foreach($values as $test) {
589 list($test,$mask) = explode('/',$test);
593 $lnet = ip2long($test);
594 $lip = ip2long($baseIP);
595 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
596 $firstpart = substr($binnet,0,$mask);
597 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
598 $firstip = substr($binip,0,$mask);
599 $yes = (strcmp($firstpart,$firstip)==0);
602 $IPparts = explode('.',$test);
605 while(list($index,$val)=each($IPparts)) {
607 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
612 if ($yes) return true;
619 * Match fully qualified domain name with list of strings with wildcard
621 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
622 * @param string $list is 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)
623 * @return boolean True if a domain name mask from $list matches $baseIP
625 function cmpFQDN($baseIP, $list) {
626 if (count(explode('.',$baseIP))==4) {
627 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
628 $values = t3lib_div
::trimExplode(',',$list,1);
630 foreach($values as $test) {
631 $hostNameParts = explode('.',$test);
634 foreach($hostNameParts as $index => $val) {
636 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
640 if ($yes) return true;
647 * Check for item in list
648 * Check if an item exists in a comma-separated list of items.
651 * @param string $in_list comma-separated list of items (string)
652 * @param string $item item to check for
653 * @return boolean true if $item is in $in_list
655 function inList($in_list,$item) {
656 return strstr(','.$in_list.',', ','.$item.',');
660 * Removes an item from a comma-separated list of items.
663 * @param string $element element to remove
664 * @param string $list comma-separated list of items (string)
665 * @return string new comma-separated list of items
667 function rmFromList($element,$list) {
668 $items = explode(',',$list);
669 while(list($k,$v)=each($items)) {
670 if ($v==$element) {unset($items[$k]);}
672 return implode(',',$items);
676 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
679 * @param integer Input value
680 * @param integer Lower limit
681 * @param integer Higher limit
682 * @param integer Default value if input is false.
683 * @return integer The input value forced into the boundaries of $min and $max
685 function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
686 // Returns $theInt as an integer in the integerspace from $min to $max
687 $theInt = intval($theInt);
688 if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
689 if ($theInt<$min){$theInt=$min;}
690 if ($theInt>$max){$theInt=$max;}
695 * Returns the $integer if greater than zero, otherwise returns zero.
698 * @param integer Integer string to process
701 function intval_positive($theInt) {
702 $theInt = intval($theInt);
703 if ($theInt<0){$theInt=0;}
708 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
711 * @param string Version number on format x.x.x
712 * @return integer Integer version of version number (where each part can count to 999)
714 function int_from_ver($verNumberStr) {
715 $verParts = explode('.',$verNumberStr);
716 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
));
720 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
723 * @param string String to md5-hash
724 * @return integer Returns 28bit integer-hash
726 function md5int($str) {
727 return hexdec(substr(md5($str),0,7));
731 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
735 * @param string Input string to be md5-hashed
736 * @param integer The string-length of the output
737 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
739 function shortMD5($input, $len=10) {
740 return substr(md5($input),0,$len);
744 * Takes comma-separated lists and arrays and removes all duplicates
745 * If a value in the list is trim(empty), the value is ignored.
748 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
749 * @param mixed $secondParameter: ...
750 * @return string Returns the list without any duplicates of values, space around values are trimmed
752 function uniqueList($in_list, $secondParameter=NULL) {
753 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
754 if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
756 return implode(',',array_unique(t3lib_div
::trimExplode(',',$in_list,1)));
760 * Splits a reference to a file in 5 parts
763 * @param string Filename/filepath to be analysed
764 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
766 function split_fileref($fileref) {
767 if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
768 $info['path'] = $reg[1];
769 $info['file'] = $reg[2];
772 $info['file'] = $fileref;
775 if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
776 $info['filebody'] = $reg[1];
777 $info['fileext'] = strtolower($reg[2]);
778 $info['realFileext'] = $reg[2];
780 $info['filebody'] = $info['file'];
781 $info['fileext'] = '';
788 * Returns the directory part of a path without trailing slash
789 * If there is no dir-part, then an empty string is returned.
792 * '/dir1/dir2/script.php' => '/dir1/dir2'
793 * '/dir1/' => '/dir1'
794 * 'dir1/script.php' => 'dir1'
795 * 'd/script.php' => 'd'
796 * '/script.php' => ''
800 * @param string Directory name / path
801 * @return string Processed input value. See function description.
803 function dirname($path) {
804 $p=t3lib_div
::revExplode('/',$path,2);
805 return count($p)==2?
$p[0]:'';
809 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
812 * @param string A hexadecimal color code, #xxxxxx
813 * @param integer Offset value 0-255
814 * @param integer Offset value 0-255
815 * @param integer Offset value 0-255
816 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
817 * @see modifyHTMLColorAll()
819 function modifyHTMLColor($color,$R,$G,$B) {
820 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
821 $nR = t3lib_div
::intInRange(hexdec(substr($color,1,2))+
$R,0,255);
822 $nG = t3lib_div
::intInRange(hexdec(substr($color,3,2))+
$G,0,255);
823 $nB = t3lib_div
::intInRange(hexdec(substr($color,5,2))+
$B,0,255);
825 substr('0'.dechex($nR),-2).
826 substr('0'.dechex($nG),-2).
827 substr('0'.dechex($nB),-2);
831 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
834 * @param string A hexadecimal color code, #xxxxxx
835 * @param integer Offset value 0-255 for all three channels.
836 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
837 * @see modifyHTMLColor()
839 function modifyHTMLColorAll($color,$all) {
840 return t3lib_div
::modifyHTMLColor($color,$all,$all,$all);
844 * Removes comma (if present) in the end of string
847 * @param string String from which the comma in the end (if any) will be removed.
850 function rm_endcomma($string) {
851 return ereg_replace(',$','',$string);
855 * strtoupper which converts danish (and other characters) characters as well
856 * (DEPRECIATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
859 * @param string String to process
863 function danish_strtoupper($string) {
864 $value = strtoupper($string);
865 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
869 * Change umlaut characters to plain ASCII with normally two character target
870 * Only known characters will be converted, so don't expect a result for any character.
871 * (DEPRECIATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!)
875 * @param string String to convert.
878 function convUmlauts($str) {
879 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
880 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
881 return preg_replace($pat,$repl,$str);
885 * Tests if the input is an integer.
888 * @param mixed Any input variable to test.
889 * @return boolean Returns true if string is an integer
891 function testInt($var) {
892 return !strcmp($var,intval($var));
896 * Returns true if the first part of $str matches the string $partStr
899 * @param string Full string to check
900 * @param string Reference string which must be found as the "first part" of the full string
901 * @return boolean True if $partStr was found to be equal to the first part of $str
903 function isFirstPartOfStr($str,$partStr) {
904 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
905 $psLen = strlen($partStr);
907 return substr($str,0,$psLen)==(string)$partStr;
912 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
915 * @param integer Number of bytes to format.
916 * @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)
917 * @return string Formatted representation of the byte number, for output.
919 function formatSize($sizeInBytes,$labels='') {
922 if (strlen($labels) == 0) {
923 $labels = ' | K| M| G';
925 $labels = str_replace('"','',$labels);
927 $labelArr = explode('|',$labels);
930 if ($sizeInBytes>900) {
931 if ($sizeInBytes>900000000) { // GB
932 $val = $sizeInBytes/(1024*1024*1024);
933 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[3];
935 elseif ($sizeInBytes>900000) { // MB
936 $val = $sizeInBytes/(1024*1024);
937 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[2];
939 $val = $sizeInBytes/(1024);
940 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[1];
943 return $sizeInBytes.$labelArr[0];
948 * Returns microtime input to milliseconds
951 * @param string Microtime
952 * @return integer Microtime input string converted to an integer (milliseconds)
954 function convertMicrotime($microtime) {
955 $parts = explode(' ',$microtime);
956 return round(($parts[0]+
$parts[1])*1000);
960 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
963 * @param string Input string, eg "123 + 456 / 789 - 4"
964 * @param string Operators to split by, typically "/+-*"
965 * @return array Array with operators and operands separated.
966 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
968 function splitCalc($string,$operators) {
972 $valueLen=strcspn($string,$operators);
973 $value=substr($string,0,$valueLen);
974 $res[] = Array($sign,trim($value));
975 $sign=substr($string,$valueLen,1);
976 $string=substr($string,$valueLen+
1);
983 * Calculates the input by +,-,*,/,%,^ with priority to + and -
986 * @param string Input string, eg "123 + 456 / 789 - 4"
987 * @return integer Calculated value. Or error string.
988 * @see calcParenthesis()
990 function calcPriority($string) {
991 $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
992 $string='+'.$string; // Ensuring an operator for the first entrance
994 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
995 // split the expression here:
996 preg_match_all('/'.$regex.'/',$string,$reg);
1002 $buffer=doubleval(current($reg[2]));
1003 next($reg[2]); // Advance pointer
1004 while(list($k,$v)=each($reg[2])) {
1006 $sign = $reg[1][$k];
1007 if ($sign=='+' ||
$sign=='-') {
1008 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1012 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
1013 if ($sign=='%') {if ($v) $buffer%
=$v; else $err='dividing by zero';}
1014 if ($sign=='*') {$buffer*=$v;}
1015 if ($sign=='^') {$buffer=pow($buffer,$v);}
1018 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1019 return $err ?
'ERROR: '.$err : $number;
1023 * Calculates the input with parenthesis levels
1026 * @param string Input string, eg "(123 + 456) / 789 - 4"
1027 * @return integer Calculated value. Or error string.
1028 * @see calcPriority(), tslib_cObj::stdWrap()
1030 function calcParenthesis($string) {
1033 $valueLenO=strcspn($string,'(');
1034 $valueLenC=strcspn($string,')');
1035 if ($valueLenC==strlen($string) ||
$valueLenC < $valueLenO) {
1036 $value = t3lib_div
::calcPriority(substr($string,0,$valueLenC));
1037 $string = $value.substr($string,$valueLenC+
1);
1040 $string = substr($string,0,$valueLenO).t3lib_div
::calcParenthesis(substr($string,$valueLenO+
1));
1044 if ($securC<=0) break;
1045 } while($valueLenO<strlen($string));
1050 * Inverse version of htmlspecialchars()
1053 * @param string Value where >, <, " and & should be converted to regular chars.
1054 * @return string Converted result.
1056 function htmlspecialchars_decode($value) {
1057 $value = str_replace('>','>',$value);
1058 $value = str_replace('<','<',$value);
1059 $value = str_replace('"','"',$value);
1060 $value = str_replace('&','&',$value);
1065 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1068 * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1069 * @return string Converted result.
1071 function deHSCentities($str) {
1072 return ereg_replace('&([#[:alnum:]]*;)','&\1',$str);
1076 * This function is used to escape any ' -characters when transferring text to JavaScript!
1079 * @param string String to escape
1080 * @param boolean If set, also backslashes are escaped.
1081 * @param string The character to escape, default is ' (single-quote)
1082 * @return string Processed input string
1084 function slashJS($string,$extended=0,$char="'") {
1085 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
1086 return str_replace ($char, "\\".$char, $string);
1090 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1091 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1094 * @param string String to raw-url-encode with spaces preserved
1095 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1097 function rawUrlEncodeJS($str) {
1098 return str_replace('%20',' ',rawurlencode($str));
1102 * rawurlencode which preserves "/" chars
1103 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1106 * @param string Input string
1107 * @return string Output string
1109 function rawUrlEncodeFP($str) {
1110 return str_replace('%2F','/',rawurlencode($str));
1114 * Checking syntax of input email address
1117 * @param string Input string to evaluate
1118 * @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.
1120 function validEmail($email) {
1121 $email = trim ($email);
1122 if (strstr($email,' ')) return FALSE;
1123 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ?
TRUE : FALSE;
1127 * Formats a string for output between <textarea>-tags
1128 * All content outputted in a textarea form should be passed through this function
1129 * 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!
1132 * @param string Input string to be formatted.
1133 * @return string Formatted for <textarea>-tags
1135 function formatForTextarea($content) {
1136 return chr(10).htmlspecialchars($content);
1150 /*************************
1154 *************************/
1157 * Check if an item exists in an array
1158 * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
1161 * @param array $in_array one-dimensional array of items
1162 * @param string $item item to check for
1163 * @return boolean true if $item is in the one-dimensional array $in_array
1166 function inArray($in_array,$item) {
1167 if (is_array($in_array)) {
1168 while (list(,$val)=each($in_array)) {
1169 if (!is_array($val) && !strcmp($val,$item)) return true;
1175 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1176 * Corresponds to explode(), but with conversion to integers for all values.
1179 * @param string Delimiter string to explode with
1180 * @param string The string to explode
1181 * @return array Exploded values, all converted to integers
1183 function intExplode($delim, $string) {
1184 $temp = explode($delim,$string);
1185 while(list($key,$val)=each($temp)) {
1186 $temp[$key]=intval($val);
1193 * Reverse explode which explodes the string counting from behind.
1194 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1197 * @param string Delimiter string to explode with
1198 * @param string The string to explode
1199 * @param integer Number of array entries
1200 * @return array Exploded values
1202 function revExplode($delim, $string, $count=0) {
1203 $temp = explode($delim,strrev($string),$count);
1204 while(list($key,$val)=each($temp)) {
1205 $temp[$key]=strrev($val);
1207 $temp=array_reverse($temp);
1213 * Explodes a string and trims all values for whitespace in the ends.
1214 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1217 * @param string Delimiter string to explode with
1218 * @param string The string to explode
1219 * @param boolean If set, all empty values (='') will NOT be set in output
1220 * @return array Exploded values
1222 function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
1223 $temp = explode($delim,$string);
1225 while(list($key,$val)=each($temp)) {
1226 if (!$onlyNonEmptyValues ||
strcmp('',trim($val))) {
1227 $newtemp[]=trim($val);
1235 * Remove duplicate values from an array
1236 * This function is deprecated, use the PHP function array_unique instead
1239 * @param array Array of values to make unique
1244 function uniqueArray($valueArray) {
1245 return array_unique($valueArray);
1249 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1252 * @param array Array containing the values
1253 * @param string Value to search for and if found remove array entry where found.
1254 * @return array Output array with entries removed if search string is found
1256 function removeArrayEntryByValue($array,$cmpValue) {
1257 if (is_array($array)) {
1259 while(list($k,$v)=each($array)) {
1261 $array[$k] = t3lib_div
::removeArrayEntryByValue($v,$cmpValue);
1263 if (!strcmp($v,$cmpValue)) {
1274 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1277 * @param string Name prefix for entries. Set to blank if you wish none.
1278 * @param array The (multidim) array to implode
1279 * @param boolean If set, all values that are blank (='') will NOT be imploded
1280 * @param boolean If set, parameters which were blank strings would be removed.
1281 * @param boolean If set, the param name itselt (for example "param[key][key2]") would be rawurlencoded as well.
1282 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1284 function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
1285 if (is_array($theArray)) {
1286 foreach($theArray as $Akey => $AVal) {
1287 $thisKeyName = $name ?
$name.'['.$Akey.']' : $Akey;
1288 if (is_array($AVal)) {
1289 $str = t3lib_div
::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1291 if (!$skipBlank ||
strcmp($AVal,'')) {
1292 $str.='&'.($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName).
1293 '='.rawurlencode($AVal); // strips slashes because _POST / _GET input is with slashes...
1302 * Returns an array with selected keys from incoming data.
1303 * (Better read source code if you want to find out...)
1306 * @param string List of variable/key names
1307 * @param array Array from where to get values based on the keys in $varList
1308 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1309 * @return array Output array with selected variables.
1311 function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) {
1312 $keys = t3lib_div
::trimExplode(',',$varList,1);
1314 foreach($keys as $v) {
1315 if (isset($getArray[$v])) {
1316 $outArr[$v]=$getArray[$v];
1317 } elseif ($GPvarAlt) {
1318 $outArr[$v]=t3lib_div
::_GP($v);
1326 * This function traverses a multidimentional array and adds slashes to the values.
1327 * NOTE that the input array is and argument by reference.!!
1328 * Twin-function to stripSlashesOnArray
1331 * @param array Multidimensional input array, (REFERENCE!)
1334 function addSlashesOnArray(&$theArray) {
1335 if (is_array($theArray)) {
1337 while(list($Akey,$AVal)=each($theArray)) {
1338 if (is_array($AVal)) {
1339 t3lib_div
::addSlashesOnArray($theArray[$Akey]);
1341 $theArray[$Akey] = addslashes($AVal);
1350 * This function traverses a multidimentional array and strips slashes to the values.
1351 * NOTE that the input array is and argument by reference.!!
1352 * Twin-function to addSlashesOnArray
1355 * @param array Multidimensional input array, (REFERENCE!)
1358 function stripSlashesOnArray(&$theArray) {
1359 if (is_array($theArray)) {
1361 while(list($Akey,$AVal)=each($theArray)) {
1362 if (is_array($AVal)) {
1363 t3lib_div
::stripSlashesOnArray($theArray[$Akey]);
1365 $theArray[$Akey] = stripslashes($AVal);
1373 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1376 * @param array Multidimensional input array
1377 * @param string "add" or "strip", depending on usage you wish.
1380 function slashArray($arr,$cmd) {
1381 if ($cmd=='strip') t3lib_div
::stripSlashesOnArray($arr);
1382 if ($cmd=='add') t3lib_div
::addSlashesOnArray($arr);
1387 * Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar the values in the first array ($arr0) with the values of the second array ($arr1)
1388 * In case of identical keys, ie. keeping the values of the second.
1391 * @param array First array
1392 * @param array Second array, overruling the first array
1393 * @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.
1394 * @param boolean If set, values from $arr1 will overrule if they are empty. Default: true
1395 * @return array Resulting array where $arr1 values has overruled $arr0 values
1397 function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
1399 while(list($key,$val) = each($arr1)) {
1400 if(is_array($arr0[$key])) {
1401 if (is_array($arr1[$key])) {
1402 $arr0[$key] = t3lib_div
::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
1406 if (isset($arr0[$key])) {
1407 if ($includeEmtpyValues OR $val) {
1412 if ($includeEmtpyValues OR $val) {
1423 * 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.
1426 * @param array First array
1427 * @param array Second array
1428 * @return array Merged result.
1430 function array_merge($arr1,$arr2) {
1435 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1438 * @param array Input array of values
1439 * @param string Delimited, default is comman
1440 * @param string Quote-character to wrap around the values.
1441 * @return string A single line of CSV
1443 function csvValues($row,$delim=',',$quote='"') {
1446 while(list(,$value)=each($row)) {
1447 list($valPart) = explode(chr(10),$value);
1448 $valPart = trim($valPart);
1449 $out[]=str_replace($quote,$quote.$quote,$valPart);
1451 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1470 /*************************
1472 * HTML/XML PROCESSING
1474 *************************/
1477 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1478 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1479 * If a attribute is empty (I call it 'an option'), then the value for the key is empty. You can check if it existed with isset()
1482 * @param string HTML-tag string (or attributes only)
1483 * @return array Array with the attribute values.
1485 function get_tag_attributes($tag) {
1486 $components = t3lib_div
::split_tag_attributes($tag);
1487 $name = ''; // attribute name is stored here
1489 if (is_array($components)) {
1490 while (list($key,$val) = each ($components)) {
1491 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
1494 $attributes[$name] = $val;
1498 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1499 $attributes[$key] = '';
1508 if (is_array($attributes)) reset($attributes);
1514 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1515 * Removes tag-name if found
1518 * @param string HTML-tag string (or attributes only)
1519 * @return array Array with the attribute values.
1522 function split_tag_attributes($tag) {
1523 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1524 // Removes any > in the end of the string
1525 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1527 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1528 $firstChar=substr($tag_tmp,0,1);
1529 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
1530 $reg=explode($firstChar,$tag_tmp,3);
1532 $tag_tmp=trim($reg[2]);
1533 } elseif (!strcmp($firstChar,'=')) {
1535 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1537 // There are '' around the value. We look for the next ' ' or '>'
1538 $reg = split('[[:space:]=]',$tag_tmp,2);
1539 $value[] = trim($reg[0]);
1540 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1543 if (is_array($value)) reset($value);
1548 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1551 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1552 * @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!
1553 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1554 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1556 function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1557 if (is_array($arr)) {
1560 foreach($arr as $p => $v) {
1561 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
1566 foreach($arr as $p => $v) {
1567 if (strcmp($v,'') ||
$dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
1569 return implode(' ',$list);
1574 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1576 * @param array See implodeAttributes()
1577 * @param boolean See implodeAttributes()
1578 * @param boolean See implodeAttributes()
1579 * @return string See implodeAttributes()
1580 * @deprecated Name was changed into implodeAttributes
1581 * @see implodeAttributes()
1583 function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1584 return t3lib_div
::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
1588 * Wraps JavaScript code XHTML ready with <script>-tags
1589 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1590 * This is nice for identing JS code with PHP code on the same level.
1592 * @param string JavaScript code
1593 * @param boolean Wrap script element in linebreaks? Default is TRUE.
1594 * @return string The wrapped JS code, ready to put into a XHTML page
1595 * @author Ingmar Schlecht <ingmars@web.de>
1596 * @author René Fritz <r.fritz@colorcube.de>
1598 function wrapJS($string, $linebreak=TRUE) {
1600 // <script wrapped in nl?
1601 $cr = $linebreak?
"\n" : '';
1603 // remove nl from the beginning
1604 $string = preg_replace ('/^\n+/', '', $string);
1605 // re-ident to one tab using the first line as reference
1606 if(preg_match('/^(\t+)/',$string,$match)) {
1607 $string = str_replace($match[1],"\t", $string);
1609 $string = $cr.'<script type="text/javascript">
1615 return trim($string);
1620 * Parses XML input into a PHP array with associative keys
1623 * @param string XML data input
1624 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1625 * @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.
1626 * @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
1628 function xml2tree($string,$depth=999) {
1629 $parser = xml_parser_create();
1633 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1634 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1635 xml_parse_into_struct($parser, $string, $vals, $index);
1637 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1638 xml_parser_free($parser);
1640 $stack = array( array() );
1645 foreach($vals as $key => $val) {
1646 $type = $val['type'];
1649 if ($type=='open' ||
$type=='complete') {
1650 $stack[$stacktop++
] = $tagi;
1652 if ($depth==$stacktop) {
1656 $tagi = array('tag' => $val['tag']);
1658 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
1659 if(isset($val['value'])) $tagi['values'][] = $val['value'];
1662 if ($type=='complete' ||
$type=='close') {
1664 $tagi = $stack[--$stacktop];
1665 $oldtag = $oldtagi['tag'];
1666 unset($oldtagi['tag']);
1668 if ($depth==($stacktop+
1)) {
1669 if ($key-$startPoint > 0) {
1670 $partArray = array_slice(
1675 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
1676 $oldtagi['XMLvalue']=t3lib_div
::xmlRecompileFromStructValArray($partArray);
1678 $oldtagi['XMLvalue']=$oldtagi['values'][0];
1682 $tagi['ch'][$oldtag][] = $oldtagi;
1686 if($type=='cdata') {
1687 $tagi['values'][] = $val['value'];
1694 * Converts a PHP array into an XML string.
1695 * The XML output is optimized for readability since associative keys are used as tagnames.
1696 * 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.
1697 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
1698 * 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
1699 * 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.
1700 * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
1701 * 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...
1704 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1705 * @param string tag-prefix, eg. a namespace prefix like "T3:"
1706 * @param integer Current recursion level. Don't change, stay at zero!
1707 * @param string Alternative document tag. Default is "phparray".
1708 * @param integer If set, the number of spaces corresponding to this number is used for indenting, otherwise a single chr(9) (TAB) is used
1709 * @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')
1710 * @param string Stack data. Don't touch.
1711 * @return string An XML string made from the input content in the array.
1714 function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array()) {
1715 // 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
1716 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
1717 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
1718 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
1720 // Set indenting mode:
1721 $indentChar = $spaceInd ?
' ' : chr(9);
1722 $indentN = $spaceInd>0 ?
$spaceInd : 1;
1724 // Init output variable:
1727 // Traverse the input array
1728 if (is_array($array)) {
1729 foreach($array as $k=>$v) {
1733 // Construct the tag name.
1734 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
1735 $attr.=' index="'.htmlspecialchars($tagName).'"';
1736 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
1737 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
1738 $attr.=' index="'.htmlspecialchars($tagName).'"';
1739 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
1740 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
1741 $attr.=' index="'.htmlspecialchars($tagName).'"';
1742 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1743 } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
1744 if ($options['useNindex']) { // If numeric key, prefix "n"
1745 $tagName = 'n'.$tagName;
1746 } else { // Use special tag for num. keys:
1747 $attr.=' index="'.$tagName.'"';
1748 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
1750 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
1751 $attr.=' index="'.htmlspecialchars($tagName).'"';
1752 $tagName = $options['useIndexTagForAssoc'];
1755 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1756 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
1758 // If the value is an array then we will call this function recursively:
1762 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
1763 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
1764 $clearStackPath = $subOptions['clearStackPath'];
1766 $subOptions = $options;
1767 $clearStackPath = FALSE;
1771 t3lib_div
::array2xml(
1779 'parentTagName' => $tagName,
1780 'grandParentTagName' => $stackData['parentTagName'],
1781 'path' => $clearStackPath ?
'' : $stackData['path'].'/'.$tagName,
1784 str_pad('',($level+
1)*$indentN,$indentChar);
1785 $attr.=' type="array"';
1786 } else { // Just a value:
1788 // Look for binary chars:
1789 if (strcspn($v,$binaryChars) != strlen($v)) { // Go for base64 encoding if the initial segment NOT matching any binary char has the same length as the whole string!
1790 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
1791 $content = chr(10).chunk_split(base64_encode($v));
1792 $attr.=' base64="1"';
1794 // Otherwise, just htmlspecialchar the stuff:
1795 $content = htmlspecialchars($v);
1796 $dType = gettype($v);
1797 if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
1801 // Add the element to the output string:
1802 $output.=str_pad('',($level+
1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
1806 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1809 '<'.$docTag.'>'.chr(10).
1818 * Converts an XML string to a PHP array.
1819 * This is the reverse function of array2xml()
1822 * @param string XML content to convert into an array
1823 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
1824 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1825 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1828 function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
1829 global $TYPO3_CONF_VARS;
1832 $parser = xml_parser_create();
1836 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1837 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1839 // PHP5 fix of charset awareness:
1840 // Problem is: PHP5 apparently detects the charset of the XML file (or defaults to utf-8) and will AUTOMATICALLY convert the content to either utf-8, iso-8859-1 or us-ascii. PHP4 just passed the content through without taking action regarding the charset.
1841 // In TYPO3 we expect that the charset of XML content is NOT handled in the parser but internally in TYPO3 instead. Therefore it would be very nice if PHP5 could be configured to NOT process the charset of the files. But this is not possible for now.
1842 // What we do here fixes the problem but ONLY if the charset is utf-8, iso-8859-1 or us-ascii. That should work for most TYPO3 installations, in particular if people use utf-8 which we highly recommend.
1843 if ((double)phpversion()>=5) {
1844 unset($ereg_result);
1845 ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
1846 $theCharset = $ereg_result[1] ?
$ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
1847 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
1851 xml_parse_into_struct($parser, $string, $vals, $index);
1853 // If error, return error message:
1854 if (xml_get_error_code($parser)) {
1855 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1857 xml_parser_free($parser);
1860 $stack = array(array());
1866 // Traverse the parsed XML structure:
1867 foreach($vals as $key => $val) {
1869 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1870 $tagName = $val['tag'];
1871 if (!$documentTag) $documentTag = $tagName;
1873 // Test for name space:
1874 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ?
substr($tagName,strlen($NSprefix)) : $tagName;
1876 // Test for numeric tag, encoded on the form "nXXX":
1877 $testNtag = substr($tagName,1); // Closing tag.
1878 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ?
intval($testNtag) : $tagName;
1880 // Test for alternative index value:
1881 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
1883 // Setting tag-values, manage stack:
1884 switch($val['type']) {
1885 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1886 $current[$tagName] = array(); // Setting blank place holder
1887 $stack[$stacktop++
] = $current;
1890 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1891 $oldCurrent = $current;
1892 $current = $stack[--$stacktop];
1893 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
1894 $current[key($current)] = $oldCurrent;
1897 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1898 if ($val['attributes']['base64']) {
1899 $current[$tagName] = base64_decode($val['value']);
1901 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
1904 switch((string)$val['attributes']['type']) {
1906 $current[$tagName] = (integer)$current[$tagName];
1909 $current[$tagName] = (double)$current[$tagName];
1912 $current[$tagName] = (bool)$current[$tagName];
1915 $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...
1923 if ($reportDocTag) {
1924 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
1927 // Finally return the content of the document tag.
1928 return $current[$tagName];
1932 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1935 * @param array A array of XML parts, see xml2tree
1936 * @return string Re-compiled XML data.
1938 function xmlRecompileFromStructValArray($vals) {
1941 foreach($vals as $val) {
1942 $type = $val['type'];
1945 if ($type=='open' ||
$type=='complete') {
1946 $XMLcontent.='<'.$val['tag'];
1947 if(isset($val['attributes'])) {
1948 foreach($val['attributes'] as $k => $v) {
1949 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
1952 if ($type=='complete') {
1953 if(isset($val['value'])) {
1954 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
1955 } else $XMLcontent.='/>';
1956 } else $XMLcontent.='>';
1958 if ($type=='open' && isset($val['value'])) {
1959 $XMLcontent.=htmlspecialchars($val['value']);
1963 if ($type=='close') {
1964 $XMLcontent.='</'.$val['tag'].'>';
1967 if($type=='cdata') {
1968 $XMLcontent.=htmlspecialchars($val['value']);
1976 * Extract the encoding scheme as found in the first line of an XML document (typically)
1979 * @param string XML data
1980 * @return string Encoding scheme (lowercase), if found.
1982 function xmlGetHeaderAttribs($xmlData) {
1983 $xmlHeader = substr(trim($xmlData),0,200);
1985 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg)) {
1986 return t3lib_div
::get_tag_attributes($reg[1]);
2000 /*************************
2004 *************************/
2007 * Reads the file or url $url and returns the content
2008 * 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.
2011 * @param string Filepath/URL to read
2012 * @return string The content from the resource given as input.
2014 function getURL($url) {
2017 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2018 if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1')) {
2019 //external URL without error checking.
2021 curl_setopt ($ch,CURLOPT_URL
, $url);
2022 curl_setopt ($ch,CURLOPT_HEADER
, 0);
2023 curl_setopt ($ch,CURLOPT_RETURNTRANSFER
, 1);
2025 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2026 curl_setopt ($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2028 // I don't know if it will be needed
2029 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2030 curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
2032 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2033 curl_setopt ($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
2036 $content=curl_exec ($ch);
2039 } elseif($fd = fopen($url,'rb')) {
2040 while (!feof($fd)) {
2041 $content.=fread($fd, 5000);
2049 * Writes $content to the file $file
2052 * @param string Filepath to write to
2053 * @param string Content to write
2054 * @return boolean True if the file was successfully opened and written to.
2056 function writeFile($file,$content) {
2057 if($fd = fopen($file,'wb')) {
2058 fwrite( $fd, $content);
2061 // Setting file system mode & group ownership of file:
2062 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2063 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2064 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2065 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2074 * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
2075 * Accepts an additional subdirectory in the file path!
2077 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2078 * @param string Content string to write
2079 * @return string Returns false on success, otherwise an error string telling about the problem.
2081 function writeFileToTypo3tempDir($filepath,$content) {
2083 // Parse filepath into directory and basename:
2084 $fI = pathinfo($filepath);
2085 $fI['dirname'].= '/';
2088 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2089 if (defined('PATH_site')) {
2090 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2091 if (@is_dir
($dirName)) {
2092 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2094 // Checking if the "subdir" is found:
2095 $subdir = substr($fI['dirname'],strlen($dirName));
2097 if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
2099 if (!@is_dir
($dirName)) {
2100 t3lib_div
::mkdir($dirName);
2102 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
2104 // Checking dir-name again (sub-dir might have been created):
2105 if (@is_dir
($dirName)) {
2106 if ($filepath == $dirName.$fI['basename']) {
2107 t3lib_div
::writeFile($filepath, $content);
2108 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2109 } else return 'Calculated filelocation didn\'t match input $filepath!';
2110 } else return '"'.$dirName.'" is not a directory!';
2111 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2112 } else return 'PATH_site + "typo3temp/" was not a directory!';
2113 } else return 'PATH_site constant was NOT defined!';
2114 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2118 * 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']
2121 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2122 * @return boolean TRUE if @mkdir went well!
2124 function mkdir($theNewFolder) {
2125 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
2126 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2127 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2129 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2130 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2137 * Returns an array with the names of folders in a specific path
2138 * Will return 'error' (string) if there were an error with reading directory content.
2141 * @param string Path to list directories from
2142 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2144 function get_dirs($path) {
2147 if (is_object($d)) {
2148 while($entry=$d->read()) {
2149 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2150 $filearray[]=$entry;
2154 } else return 'error';
2160 * Returns an array with the names of files in a specific path
2163 * @param string $path: Is the path to the file
2164 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2165 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2166 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2167 * @return array Array of the files found
2169 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2171 // Initialize variabels:
2172 $filearray = array();
2173 $sortarray = array();
2174 $path = ereg_replace('\/$','',$path);
2176 // Find files+directories:
2177 if (@is_dir
($path)) {
2178 $extensionList = strtolower($extensionList);
2180 if (is_object($d)) {
2181 while($entry=$d->read()) {
2182 if (@is_file
($path.'/'.$entry)) {
2183 $fI = pathinfo($entry);
2184 $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)
2185 if (!$extensionList || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) {
2186 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2187 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2188 elseif ($order) {$sortarray[$key]=$entry;}
2193 } else return 'error opening path: "'.$path.'"';
2201 while(list($k,$v)=each($sortarray)) {
2202 $newArr[$k]=$filearray[$k];
2213 * Recursively gather all files and folders of a path.
2216 * @param array $fileArr: Empty input array (will have files added to it)
2217 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2218 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2219 * @param boolean $regDirs: If set, directories are also included in output.
2220 * @param integer $recursivityLevels: The number of levels to dig down...
2221 * @return array An array with the found files/directories.
2223 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2224 if ($regDirs) $fileArr[] = $path;
2225 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1));
2227 $dirs = t3lib_div
::get_dirs($path);
2228 if (is_array($dirs) && $recursivityLevels>0) {
2229 foreach ($dirs as $subdirs) {
2230 if ((string)$subdirs!='') {
2231 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2239 * Removes the absolute part of all files/folders in fileArr
2242 * @param array $fileArr: The file array to remove the prefix from
2243 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2244 * @return array The input $fileArr processed.
2246 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2247 foreach($fileArr as $k => $absFileRef) {
2248 if(t3lib_div
::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2249 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2250 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2256 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2259 * @param string File path to process
2262 function fixWindowsFilePath($theFile) {
2263 return str_replace('//','/', str_replace('\\','/', $theFile));
2267 * Resolves "../" sections in the input path string.
2268 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2271 * @param string File path in which "/../" is resolved
2274 function resolveBackPath($pathStr) {
2275 $parts = explode('/',$pathStr);
2277 foreach($parts as $pV) {
2282 } else $output[]=$pV;
2288 return implode('/',$output);
2292 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2293 * - If already having a scheme, nothing is prepended
2294 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2295 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2298 * @param string URL / path to prepend full URL addressing to.
2301 function locationHeaderUrl($path) {
2302 $uI = parse_url($path);
2303 if (substr($path,0,1)=='/') { // relative to HOST
2304 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2305 } elseif (!$uI['scheme']) { // No scheme either
2306 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2326 /*************************
2328 * DEBUG helper FUNCTIONS
2330 *************************/
2333 * Returns a string with a list of ascii-values for the first $characters characters in $string
2336 * @param string String to show ASCII value for
2337 * @param integer Number of characters to show
2338 * @return string The string with ASCII values in separated by a space char.
2341 function debug_ordvalue($string,$characters=100) {
2342 if(strlen($string) < $characters) $characters = strlen($string);
2343 for ($i=0; $i<$characters; $i++
) {
2344 $valuestring.=' '.ord(substr($string,$i,1));
2346 return trim($valuestring);
2350 * Returns HTML-code, which is a visual representation of a multidimensional array
2351 * use t3lib_div::print_array() in order to print an array
2352 * Returns false if $array_in is not an array
2355 * @param array Array to view
2356 * @return string HTML output
2358 function view_array($array_in) {
2359 if (is_array($array_in)) {
2360 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2361 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
2362 while (list($key,$val)=each($array_in)) {
2363 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
2364 if (is_array($array_in[$key])) {
2365 $result.=t3lib_div
::view_array($array_in[$key]);
2367 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
2368 $result.= '</td></tr>';
2370 $result.= '</table>';
2381 * @param array Array to print visually (in a table).
2386 function print_array($array_in) {
2387 echo t3lib_div
::view_array($array_in);
2391 * Makes debug output
2392 * Prints $var in bold between two vertical lines
2393 * If not $var the word 'debug' is printed
2394 * If $var is an array, the array is printed by t3lib_div::print_array()
2397 * @param mixed Variable to print
2398 * @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.
2401 function debug($var="",$brOrHeader=0) {
2402 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2403 echo '<table 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><td>';
2404 } elseif ($brOrHeader<0) {
2405 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
2408 if (is_array($var)) {
2409 t3lib_div
::print_array($var);
2410 } elseif (is_object($var)) {
2411 echo '<b>|Object:<pre>';
2414 } elseif ((string)$var!='') {
2415 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2417 echo '<b>| debug |</b>';
2420 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2421 echo '</td></tr></table>';
2422 } elseif ($brOrHeader>0) {
2423 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
2458 /*************************
2460 * SYSTEM INFORMATION
2462 *************************/
2465 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2470 function getThisUrl() {
2471 $p=parse_url(t3lib_div
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2472 $dir=t3lib_div
::dirname($p['path']).'/'; // Strip file
2473 $url = str_replace('//','/',$p['host'].($p['port']?
':'.$p['port']:'').$dir);
2478 * Returns the link-url to the current script.
2479 * In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL.
2480 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2483 * @param array Array of GET parameters to include
2486 function linkThisScript($getParams=array()) {
2487 $parts = t3lib_div
::getIndpEnv('SCRIPT_NAME');
2488 $params = t3lib_div
::_GET();
2490 foreach($getParams as $k => $v) {
2491 if (strcmp($v,'')) {
2493 } else unset($params[$k]);
2496 $pString = t3lib_div
::implodeArrayForUrl('',$params);
2498 return $pString ?
$parts.'?'.ereg_replace('^&','',$pString) : $parts;
2502 * Takes a full URL, $url, possibly with a querystring and overlays the $getParams arrays values onto the quirystring, packs it all together and returns the URL again.
2503 * So basically it adds the parameters in $getParams to an existing URL, $url
2506 * @param string URL string
2507 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2508 * @return string Output URL with added getParams.
2510 function linkThisUrl($url,$getParams=array()) {
2511 $parts = parse_url($url);
2512 if ($parts['query']) {
2513 parse_str($parts['query'],$getP);
2518 $getP = t3lib_div
::array_merge_recursive_overrule($getP,$getParams);
2519 $uP = explode('?',$url);
2521 $params = t3lib_div
::implodeArrayForUrl('',$getP);
2522 $outurl = $uP[0].($params ?
'?'.substr($params, 1) : '');
2528 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2529 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2532 * @param string Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY
2533 * @return string Value based on the input key, independent of server/os environment.
2535 function getIndpEnv($getEnvName) {
2538 output from parse_url():
2539 URL: http://username:password@192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value#link1
2541 [user] => 'username'
2542 [pass] => 'password'
2543 [host] => '192.168.1.4'
2545 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2546 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2547 [fragment] => 'link1'
2549 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2550 [path_dir] = '/typo3/32/temp/phpcheck/'
2551 [path_info] = '/arg1/arg2/arg3/'
2552 [path] = [path_script/path_dir][path_info]
2558 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2559 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2560 SCRIPT_NAME = [path_script]++ = /typo3/32/temp/phpcheck/index.php // NOTICE THAT SCRIPT_NAME will return the php-script name ALSO. [path_script] may not do that (eg. '/somedir/' may result in SCRIPT_NAME '/somedir/index.php')!
2561 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2562 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2563 HTTP_REFERER = [scheme]://[host][:[port]][path] = http://192.168.1.4:8080/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2564 (Notice: NO username/password + NO fragment)
2567 REMOTE_ADDR = (client IP)
2568 REMOTE_HOST = (client host)
2569 HTTP_USER_AGENT = (client user agent)
2570 HTTP_ACCEPT_LANGUAGE = (client accept language)
2573 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2576 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2577 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2578 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2579 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2580 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2581 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2582 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2583 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2584 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2586 Notice: [fragment] is apparently NEVER available to the script!
2589 Testing suggestions:
2590 - Output all the values.
2591 - In the script, make a link to the script it self, maybe add some parameters and click the link a few times so HTTP_REFERER is seen
2592 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2596 # if ($getEnvName=='HTTP_REFERER') return '';
2597 switch((string)$getEnvName) {
2599 return (php_sapi_name()=='cgi'||
php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_INFO']?
$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) ?
($_SERVER['ORIG_PATH_INFO']?
$_SERVER['ORIG_PATH_INFO']:$_SERVER['PATH_INFO']) : ($_SERVER['ORIG_SCRIPT_NAME']?
$_SERVER['ORIG_SCRIPT_NAME']:$_SERVER['SCRIPT_NAME']);
2601 case 'SCRIPT_FILENAME':
2602 return str_replace('//','/', str_replace('\\','/', (php_sapi_name()=='cgi'||
php_sapi_name()=='isapi' ||
php_sapi_name()=='cgi-fcgi')&&($_SERVER['ORIG_PATH_TRANSLATED']?
$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED'])?
($_SERVER['ORIG_PATH_TRANSLATED']?
$_SERVER['ORIG_PATH_TRANSLATED']:$_SERVER['PATH_TRANSLATED']):($_SERVER['ORIG_SCRIPT_FILENAME']?
$_SERVER['ORIG_SCRIPT_FILENAME']:$_SERVER['SCRIPT_FILENAME'])));
2605 // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2606 if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2607 return '/'.ereg_replace('^/','',t3lib_div
::getIndpEnv('SCRIPT_NAME')).
2608 ($_SERVER['QUERY_STRING']?
'?'.$_SERVER['QUERY_STRING']:'');
2609 } else return $_SERVER['REQUEST_URI'];
2612 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
2613 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2614 // IF 'PATH_INFO' never works for our purpose in TYPO3 with CGI-servers, then 'php_sapi_name()=='cgi'' might be a better check. Right now strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) will always return false for CGI-versions, but that is only as long as SCRIPT_NAME is set equal to PATH_INFO because of php_sapi_name()=='cgi' (see above)
2615 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
2616 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
2617 return $_SERVER['PATH_INFO'];
2620 // These are let through without modification
2623 case 'HTTP_REFERER':
2625 case 'HTTP_USER_AGENT':
2626 case 'HTTP_ACCEPT_LANGUAGE':
2627 case 'QUERY_STRING':
2628 return $_SERVER[$getEnvName];
2630 case 'TYPO3_DOCUMENT_ROOT':
2631 // Some CGI-versions (LA13CGI) and mod-rewrite rules on MODULE versions will deliver a 'wrong' DOCUMENT_ROOT (according to our description). Further various aliases/mod_rewrite rules can disturb this as well.
2632 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2633 $SFN = t3lib_div
::getIndpEnv('SCRIPT_FILENAME');
2634 $SN_A = explode('/',strrev(t3lib_div
::getIndpEnv('SCRIPT_NAME')));
2635 $SFN_A = explode('/',strrev($SFN));
2637 while(list($kk,$vv)=each($SN_A)) {
2638 if (!strcmp($SFN_A[$kk],$vv)) {
2642 $commonEnd=strrev(implode('/',$acc));
2643 if (strcmp($commonEnd,'')) $DR = substr($SFN,0,-(strlen($commonEnd)+
1));
2646 case 'TYPO3_HOST_ONLY':
2647 $p = explode(':',$_SERVER['HTTP_HOST']);
2651 $p = explode(':',$_SERVER['HTTP_HOST']);
2654 case 'TYPO3_REQUEST_HOST':
2655 return (t3lib_div
::getIndpEnv('TYPO3_SSL') ?
'https://' : 'http://').
2656 $_SERVER['HTTP_HOST'];
2658 case 'TYPO3_REQUEST_URL':
2659 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('REQUEST_URI');
2661 case 'TYPO3_REQUEST_SCRIPT':
2662 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('SCRIPT_NAME');
2664 case 'TYPO3_REQUEST_DIR':
2665 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::dirname(t3lib_div
::getIndpEnv('SCRIPT_NAME')).'/';
2667 case 'TYPO3_SITE_URL':
2668 if (defined('PATH_thisScript') && defined('PATH_site')) {
2669 $lPath = substr(dirname(PATH_thisScript
),strlen(PATH_site
)).'/';
2670 $url = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR');
2671 $siteUrl = substr($url,0,-strlen($lPath));
2672 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2676 case 'TYPO3_SITE_SCRIPT':
2677 return substr(t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
2680 return $_SERVER['SSL_SESSION_ID'] ||
!strcmp($_SERVER['HTTPS'],'on') ?
TRUE : FALSE;
2684 // Here, list ALL possible keys to this function for debug display.
2685 $envTestVars = t3lib_div
::trimExplode(',','
2695 TYPO3_REQUEST_SCRIPT,
2701 TYPO3_DOCUMENT_ROOT,
2706 HTTP_ACCEPT_LANGUAGE',1);
2707 reset($envTestVars);
2708 while(list(,$v)=each($envTestVars)) {
2709 $out[$v]=t3lib_div
::getIndpEnv($v);
2719 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2724 function milliseconds() {
2725 $p=explode(' ',microtime());
2726 return round(($p[0]+
$p[1])*1000);
2730 * Client Browser Information
2733 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2734 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2736 function clientInfo($useragent='') {
2737 if (!$useragent) $useragent=t3lib_div
::getIndpEnv('HTTP_USER_AGENT');
2741 if (strstr($useragent,'Konqueror')) {
2742 $bInfo['BROWSER']= 'konqu';
2743 } elseif (strstr($useragent,'Opera')) {
2744 $bInfo['BROWSER']= 'opera';
2745 } elseif (strstr($useragent,'MSIE 4') ||
strstr($useragent,'MSIE 5') ||
strstr($useragent,'MSIE 6')) {
2746 $bInfo['BROWSER']= 'msie';
2747 } elseif (strstr($useragent,'Mozilla/4') ||
strstr($useragent,'Mozilla/5')) {
2748 $bInfo['BROWSER']='net';
2750 if ($bInfo['BROWSER']) {
2752 switch($bInfo['BROWSER']) {
2754 $bInfo['VERSION']= doubleval(substr($useragent,8));
2755 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2756 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2759 $tmp = strstr($useragent,'MSIE');
2760 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
2763 $tmp = strstr($useragent,'Opera');
2764 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
2767 $tmp = strstr($useragent,'Konqueror/');
2768 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2772 if (strstr($useragent,'Win')) {
2773 $bInfo['SYSTEM'] = 'win';
2774 } elseif (strstr($useragent,'Mac')) {
2775 $bInfo['SYSTEM'] = 'mac';
2776 } elseif (strstr($useragent,'Linux') ||
strstr($useragent,'X11') ||
strstr($useragent,'SGI') ||
strstr($useragent,' SunOS ') ||
strstr($useragent,' HP-UX ')) {
2777 $bInfo['SYSTEM'] = 'unix';
2780 // Is true if the browser supports css to format forms, especially the width
2781 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' ||
($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) ||
$bInfo['BROWSER']=='opera' ||
$bInfo['BROWSER']=='konqu');
2808 /*************************
2810 * TYPO3 SPECIFIC FUNCTIONS
2812 *************************/
2815 * Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the PATH_site of the TYPO3 installation and implies a check with t3lib_div::validPathStr(). Returns false if checks failed. Does not check if the file exists.
2818 * @param string The input filename/filepath to evaluate
2819 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2820 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2821 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2823 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2824 if (!strcmp($filename,'')) return '';
2826 if ($relToTYPO3_mainDir) {
2827 if (!defined('PATH_typo3')) return '';
2828 $relPathPrefix = PATH_typo3
;
2830 $relPathPrefix = PATH_site
;
2832 if (substr($filename,0,4)=='EXT:') { // extension
2833 list($extKey,$local) = explode('/',substr($filename,4),2);
2835 if (strcmp($extKey,'') && t3lib_extMgm
::isLoaded($extKey) && strcmp($local,'')) {
2836 $filename = t3lib_extMgm
::extPath($extKey).$local;
2838 } elseif (!t3lib_div
::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2839 $filename=$relPathPrefix.$filename;
2840 } elseif ($onlyRelative && !t3lib_div
::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2843 if (strcmp($filename,'') && t3lib_div
::validPathStr($filename)) { // checks backpath.
2849 * Checks for malicious file paths.
2850 * Returns true if no '//', '..' or '\' is in the $theFile
2851 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2852 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2855 * @param string Filepath to evaluate
2856 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2857 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2859 function validPathStr($theFile) {
2860 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
2864 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
2867 * @param string Filepath to evaluate
2870 function isAbsPath($path) {
2871 return TYPO3_OS
=='WIN' ?
substr($path,1,2)==':/' : substr($path,0,1)=='/';
2875 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
2878 * @param string Filepath to evaluate
2881 function isAllowedAbsPath($path) {
2882 if (t3lib_div
::isAbsPath($path) &&
2883 t3lib_div
::validPathStr($path) &&
2884 ( t3lib_div
::isFirstPartOfStr($path,PATH_site
)
2886 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div
::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
2892 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
2895 * @param string Filepath to evaluate
2898 function verifyFilenameAgainstDenyPattern($filename) {
2899 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
2900 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
2901 if ($result) return false; // so if a matching filename is found, return false;
2907 * Moves $source file to $destination if uploaded, otherwise try to make a copy
2910 * @param string Source file, absolute path
2911 * @param string Destination file, absolute path
2912 * @return boolean Returns true if the file was moved.
2913 * @coauthor Dennis Petersen <fessor@software.dk>
2914 * @see upload_to_tempfile()
2916 function upload_copy_move($source,$destination) {
2917 if (is_uploaded_file($source)) {
2919 // Return the value of move_uploaded_file, and if false the temporary $source is still around so the user can use unlink to delete it:
2920 $uploadedResult = move_uploaded_file($source, $destination);
2923 @copy
($source,$destination);
2926 // Setting file system mode & group ownership of file:
2927 if (@is_file
($destination) && TYPO3_OS
!='WIN') {
2928 chmod($destination, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2929 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2930 chgrp($destination, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2934 // If here the file is copied and the temporary $source is still around, so when returning false the user can try unlink to delete the $source
2935 return $uploaded ?
$uploadedResult : FALSE;
2939 * Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in PATH_site."typo3temp/" from where TYPO3 can use it under safe_mode.
2940 * Use this function to move uploaded files to where you can work on them.
2941 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
2944 * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
2945 * @return string If a new file was successfully created, return its filename, otherwise blank string.
2946 * @see unlink_tempfile(), upload_copy_move()
2948 function upload_to_tempfile($uploadedFileName) {
2949 if (is_uploaded_file($uploadedFileName)) {
2950 $tempFile = t3lib_div
::tempnam('upload_temp_');
2951 move_uploaded_file($uploadedFileName, $tempFile);
2952 return @is_file
($tempFile) ?
$tempFile : '';
2957 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
2958 * The function will check that the file exists, is in PATH_site."typo3temp/" and does not contain back-spaces ("../") so it should be pretty safe.
2959 * Use this after upload_to_tempfile() or tempnam() from this class!
2962 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
2963 * @return boolean Returns true if the file was unlink()'ed
2964 * @see upload_to_tempfile(), tempnam()
2966 function unlink_tempfile($uploadedTempFileName) {
2967 if ($uploadedTempFileName && t3lib_div
::validPathStr($uploadedTempFileName) && t3lib_div
::isFirstPartOfStr($uploadedTempFileName,PATH_site
.'typo3temp/') && @is_file
($uploadedTempFileName)) {
2968 if (unlink($uploadedTempFileName)) return TRUE;
2973 * Create temporary filename (Create file with unique file name)
2974 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
2975 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
2978 * @param string Prefix to temp file (which will have no extension btw)
2979 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
2980 * @see unlink_tempfile(), upload_to_tempfile()
2982 function tempnam($filePrefix) {
2983 return tempnam(PATH_site
.'typo3temp/',$filePrefix);
2987 * standard authentication code - can't remember what it's used for.
2990 * @param mixed Uid (integer) or record (array)
2991 * @param string List of fields from the record if that is given.
2992 * @return string MD5 hash of 8 chars.
2995 function stdAuthCode($uid_or_record,$fields='') {
2996 if (is_array($uid_or_record)) {
2997 $recCopy_temp=array();
2999 $fieldArr = t3lib_div
::trimExplode(',',$fields,1);
3001 while(list($k,$v)=each($fieldArr)) {
3002 $recCopy_temp[$k]=$recCopy[$v];
3005 $recCopy_temp=$recCopy;
3007 $preKey = implode('|',$recCopy_temp);
3009 $preKey = $uid_or_record;
3012 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3013 $authCode = substr(md5($authCode),0,8);
3018 * Loads the $TCA (Table Configuration Array) for the $table
3021 * 1) must be configured table (the ctrl-section configured),
3022 * 2) columns must not be an array (which it is always if whole table loaded), and
3023 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
3026 * @param string Table name for which to load the full TCA array part into the global $TCA
3029 function loadTCA($table) {
3030 global $TCA,$LANG_GENERAL_LABELS;
3031 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
3032 if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
3033 include(PATH_t3lib
.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
3034 } elseif (t3lib_div
::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file
($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
3035 include($TCA[$table]['ctrl']['dynamicConfigFile']);
3036 } else include(PATH_typo3conf
.$TCA[$table]['ctrl']['dynamicConfigFile']);
3041 * Looks for a sheet-definition in the input data structure array. If found it will return the data structure for the sheet given as $sheet (if found).
3042 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
3045 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3046 * @param string The sheet to return, preferably.
3047 * @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error happend in which case an error string is returned (string). key1: The used sheet key value!
3049 function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
3050 if (is_array($dataStructArray['sheets'])) {
3051 $singleSheet = FALSE;
3052 if (!isset($dataStructArray['sheets'][$sheet])) {
3055 $dataStruct = $dataStructArray['sheets'][$sheet];
3057 // If not an array, but still set, then regard it as a relative reference to a file:
3058 if ($dataStruct && !is_array($dataStruct)) {
3059 $file = t3lib_div
::getFileAbsFileName($dataStruct);
3060 if ($file && @is_file
($file)) {
3061 $dataStruct = t3lib_div
::xml2array(t3lib_div
::getUrl($file));
3065 $singleSheet = TRUE;
3066 $dataStruct = $dataStructArray;
3067 $sheet = 'sDEF'; // Default sheet
3069 return array($dataStruct,$sheet,$singleSheet);
3073 * Resolves ALL sheet definitions in dataStructArray
3074 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
3076 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3077 * @return array Output data structure with all sheets resolved as arrays.
3079 function resolveAllSheetsInDS($dataStructArray) {
3080 if (is_array($dataStructArray['sheets'])) {
3081 $out=array('sheets'=>array());
3082 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
3083 list($ds,$aS) = t3lib_div
::resolveSheetDefInDS($dataStructArray,$sheetId);
3084 if ($sheetId==$aS) {
3085 $out['sheets'][$aS]=$ds;
3089 list($ds) = t3lib_div
::resolveSheetDefInDS($dataStructArray);
3090 $out = array('sheets' => array('sDEF' => $ds));
3096 * Calls a userdefined function/method in class
3097 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
3100 * @param string Function/Method reference, '[file-reference":"]["&"]class/function["->"method-name]'. You can prefix this reference with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl->encodeSpURL". Finally; you can prefix the class name with "&" if you want to reuse a former instance of the same object call ("singleton").
3101 * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
3102 * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
3103 * @param string Required prefix of class or function name
3104 * @param boolean If set, no debug() error message is shown if class/function is not present.
3105 * @return mixed Content from method/function call
3108 function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
3109 global $TYPO3_CONF_VARS;
3111 // Check persistent object and if found, call directly and exit.
3112 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
3113 return call_user_method(
3114 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
3115 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
3121 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3122 if (strstr($funcName,':')) {
3123 list($file,$funcRef) = t3lib_div
::revExplode(':',$funcName,2);
3124 $requireFile = t3lib_div
::getFileAbsFileName($file);
3125 if ($requireFile) require_once($requireFile);
3127 $funcRef = $funcName;
3130 // Check for persistent object token, "&"
3131 if (substr($funcRef,0,1)=='&') {
3132 $funcRef = substr($funcRef,1);
3133 $storePersistentObject = TRUE;
3135 $storePersistentObject = FALSE;
3138 // Check prefix is valid:
3140 !t3lib_div
::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
3141 !t3lib_div
::isFirstPartOfStr(trim($funcRef),'tx_')
3143 if (!$silent) debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
3147 // Call function or method:
3148 $parts = explode('->',$funcRef);
3149 if (count($parts)==2) { // Class
3151 // Check if class/method exists:
3152 if (class_exists($parts[0])) {
3154 // Get/Create object of class:
3155 if ($storePersistentObject) { // Get reference to current instance of class:
3156 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
3157 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div
::makeInstance($parts[0]);
3159 $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
3160 } else { // Create new object:
3161 $classObj = &t3lib_div
::makeInstance($parts[0]);
3164 if (method_exists($classObj, $parts[1])) {
3166 // If persistent object should be created, set reference:
3167 if ($storePersistentObject) {
3168 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
3169 'method' => $parts[1],
3174 $content = call_user_method(
3181 if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
3184 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
3186 } else { // Function
3187 if (function_exists($funcRef)) {
3188 $content = call_user_func($funcRef, $params, $ref);
3190 if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
3197 * Creates and returns reference to a user defined object.
3198 * This function can return an object reference if you like. Just prefix the function call with "&": "$objRef = &t3lib_div::getUserObj('EXT:myext/class.tx_myext_myclass.php:&tx_myext_myclass');". This will work ONLY if you prefix the class name with "&" as well. See description of function arguments.
3201 * @param string Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
3202 * @param string Required prefix of class name. By default "tx_" is allowed.
3203 * @param boolean If set, no debug() error message is shown if class/function is not present.
3204 * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
3205 * @see callUserFunction()
3207 function &getUserObj($classRef,$checkPrefix='user_',$silent=0) {
3208 global $TYPO3_CONF_VARS;
3209 // Check persistent object and if found, call directly and exit.
3210 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
3211 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
3214 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3215 if (strstr($classRef,':'