2 /***************************************************************
5 * (c) 1999-2004 Kasper Skaarhoj (kasper@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 <kasper@typo3.com>
38 * [CLASS/FUNCTION INDEX of SCRIPT]
42 * 207: class t3lib_div
44 * SECTION: GET/POST Variables
45 * 237: function _GP($var)
46 * 254: function _GET($var='')
47 * 269: function _POST($var='')
48 * 283: function _GETset($inputGet,$key='')
49 * 306: function GPvar($var,$strip=0)
50 * 322: function setGPvars($list,$strip=0)
51 * 338: function GParrayMerged($var)
53 * SECTION: IMAGE FUNCTIONS
54 * 382: function gif_compress($theFile, $type)
55 * 408: function png_to_gif_by_imagemagick($theFile)
56 * 432: function read_png_gif($theFile,$output_png=0)
58 * SECTION: STRING FUNCTIONS
59 * 481: function fixed_lgd($string,$origChars,$preStr='...')
60 * 506: function fixed_lgd_pre($string,$chars)
61 * 520: function fixed_lgd_cs($string,$chars)
62 * 537: function breakTextForEmail($str,$implChar="\n",$charWidth=76)
63 * 556: function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
64 * 591: function cmpIP($baseIP, $list)
65 * 633: function cmpFQDN($baseIP, $list)
66 * 663: function inList($in_list,$item)
67 * 675: function rmFromList($element,$list)
68 * 693: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
69 * 709: function intval_positive($theInt)
70 * 722: function int_from_ver($verNumberStr)
71 * 734: function md5int($str)
72 * 747: function shortMD5($input, $len=10)
73 * 758: function uniqueList()
74 * 778: function split_fileref($fileref)
75 * 815: function dirname($path)
76 * 831: function modifyHTMLColor($color,$R,$G,$B)
77 * 851: function modifyHTMLColorAll($color,$all)
78 * 862: function rm_endcomma($string)
79 * 875: function danish_strtoupper($string)
80 * 890: function convUmlauts($str)
81 * 903: function testInt($var)
82 * 915: function isFirstPartOfStr($str,$partStr)
83 * 931: function formatSize($sizeInBytes,$labels='')
84 * 966: function convertMicrotime($microtime)
85 * 980: function splitCalc($string,$operators)
86 * 1002: function calcPriority($string)
87 * 1042: function calcParenthesis($string)
88 * 1068: function htmlspecialchars_decode($value)
89 * 1083: function deHSCentities($str)
90 * 1096: function slashJS($string,$extended=0,$char="'")
91 * 1109: function rawUrlEncodeJS($str)
92 * 1121: function rawUrlEncodeFP($str)
93 * 1132: function validEmail($email)
94 * 1147: function formatForTextarea($content)
96 * SECTION: ARRAY FUNCTIONS
97 * 1178: function inArray($in_array,$item)
98 * 1195: function intExplode($delim, $string)
99 * 1214: function revExplode($delim, $string, $count=0)
100 * 1234: function trimExplode($delim, $string, $onlyNonEmptyValues=0)
101 * 1259: function uniqueArray($valueArray)
102 * 1281: function removeArrayEntryByValue($array,$cmpValue)
103 * 1309: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
104 * 1336: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
105 * 1359: function addSlashesOnArray(&$theArray)
106 * 1383: function stripSlashesOnArray(&$theArray)
107 * 1405: function slashArray($arr,$cmd)
108 * 1421: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0)
109 * 1450: function array_merge($arr1,$arr2)
110 * 1463: function csvValues($row,$delim=',',$quote='"')
112 * SECTION: HTML/XML PROCESSING
113 * 1505: function get_tag_attributes($tag)
114 * 1542: function split_tag_attributes($tag)
115 * 1576: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
116 * 1604: function wrapJS($string, $linebreak=TRUE)
117 * 1634: function xml2tree($string,$depth=999)
118 * 1720: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$parentTagName='')
119 * 1803: function xml2array($string,$NSprefix='')
120 * 1891: function xmlRecompileFromStructValArray($vals)
121 * 1935: function xmlGetHeaderAttribs($xmlData)
123 * SECTION: FILES FUNCTIONS
124 * 1967: function getURL($url)
125 * 2009: function writeFile($file,$content)
126 * 2030: function mkdir($theNewFolder)
127 * 2046: function get_dirs($path)
128 * 2071: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
129 * 2125: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
130 * 2148: function removePrefixPathFromList($fileArr,$prefixToRemove)
131 * 2164: function fixWindowsFilePath($theFile)
132 * 2175: function resolveBackPath($pathStr)
133 * 2202: function locationHeaderUrl($path)
135 * SECTION: DEBUG helper FUNCTIONS
136 * 2242: function debug_ordvalue($string,$characters=100)
137 * 2259: function view_array($array_in)
138 * 2287: function print_array($array_in)
139 * 2302: function debug($var="",$brOrHeader=0)
141 * SECTION: SYSTEM INFORMATION
142 * 2371: function getThisUrl()
143 * 2387: function linkThisScript($getParams=array())
144 * 2411: function linkThisUrl($url,$getParams=array())
145 * 2436: function getIndpEnv($getEnvName)
146 * 2626: function milliseconds()
147 * 2638: function clientInfo($useragent='')
149 * SECTION: TYPO3 SPECIFIC FUNCTIONS
150 * 2726: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
151 * 2761: function validPathStr($theFile)
152 * 2772: function isAbsPath($path)
153 * 2783: function isAllowedAbsPath($path)
154 * 2800: function verifyFilenameAgainstDenyPattern($filename)
155 * 2818: function upload_copy_move($source,$destination)
156 * 2847: function upload_to_tempfile($uploadedFileName)
157 * 2865: function unlink_tempfile($uploadedTempFileName)
158 * 2881: function tempnam($filePrefix)
159 * 2894: function stdAuthCode($uid_or_record,$fields='')
160 * 2928: function loadTCA($table)
161 * 2948: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
162 * 2976: function resolveAllSheetsInDS($dataStructArray)
163 * 3005: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
164 * 3103: function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
165 * 3161: function &makeInstance($className)
166 * 3173: function makeInstanceClassName($className)
167 * 3187: function makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys='')
168 * 3232: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)
169 * 3277: function quoted_printable($string,$maxlen=76)
170 * 3319: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
171 * 3353: function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
172 * 3380: function freetypeDpiComp($font_size)
173 * 3399: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
175 * TOTAL FUNCTIONS: 113
176 * (This index is automatically created/updated by the extension "extdeveval")
192 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
193 * Most of the functions does not relate specifically to TYPO3
194 * However a section of functions requires certain TYPO3 features available
195 * See comments in the source.
196 * You are encouraged to use this library in your own scripts!
199 * The class is intended to be used without creating an instance of it.
200 * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
201 * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
203 * @author Kasper Skaarhoj <kasper@typo3.com>
213 /*************************
218 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
219 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
220 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
221 * Eventually TYPO3 should provide this in the global space as well.
222 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
224 *************************/
227 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
228 * Strips slashes from all output, both strings and arrays.
229 * This function substitutes t3lib_div::GPvar()
230 * 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!
233 * @param string GET/POST var to return
234 * @return mixed POST var named $var and if not set, the GET var of the same name.
238 if(empty($var)) return;
239 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
241 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
247 * Returns the global GET array (or value from) normalized to contain un-escaped values.
248 * ALWAYS use this API function to acquire the GET variables!
251 * @param string Optional pointer to value in GET array (basically name of GET var)
252 * @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!*
253 * @see _POST(), _GP(), _GETset()
255 function _GET($var=NULL
) {
256 $value = ($var === NULL
) ?
$_GET : (empty($var) ? NULL
: $_GET[$var]);
257 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
258 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
264 * Returns the global POST array (or value from) normalized to contain un-escaped values.
265 * ALWAYS use this API function to acquire the POST variables!
268 * @param string Optional pointer to value in POST array (basically name of POST var)
269 * @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!*
272 function _POST($var=NULL
) {
273 $value = ($var === NULL
) ?
$_POST : (empty($var) ? NULL
: $_POST[$var]);
274 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
275 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
281 * Writes input value to $_GET
284 * @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).
285 * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
288 function _GETset($inputGet,$key='') {
289 // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
290 if (strcmp($key,'')) {
291 if (is_array($inputGet)) { t3lib_div
::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
292 $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
293 } elseif (is_array($inputGet)){
294 t3lib_div
::addSlashesOnArray($inputGet);
295 $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
301 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
302 * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
305 * @param string GET/POST var to return
306 * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
307 * @return mixed POST var named $var and if not set, the GET var of the same name.
308 * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
311 function GPvar($var,$strip=0) {
312 if(empty($var)) return;
313 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
314 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.
315 if ($strip && isset($value) && is_array($value)) { t3lib_div
::stripSlashesOnArray($value); }
320 * Returns the GET/POST global arrays merged with POST taking precedence.
323 * @param string Key (variable name) from GET or POST vars
324 * @return array Returns the GET vars merged recursively onto the POST vars.
328 function GParrayMerged($var) {
329 $postA = is_array($_POST[$var]) ?
$_POST[$var] : array();
330 $getA = is_array($_GET[$var]) ?
$_GET[$var] : array();
331 $mergedA = t3lib_div
::array_merge_recursive_overrule($getA,$postA);
332 t3lib_div
::stripSlashesOnArray($mergedA);
345 /*************************
349 *************************/
353 * Compressing a GIF file if not already LZW compressed
354 * 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)
356 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
358 * 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!)
359 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
363 * $theFile is expected to be a valid GIF-file!
364 * The function returns a code for the operation.
367 * @param string Filepath
368 * @param string See description of function
369 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
372 function gif_compress($theFile, $type) {
373 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
375 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
376 if (($type=='IM' ||
!$type) && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']) { // IM
377 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$theFile.'"');
379 } elseif (($type=='GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
380 $tempImage = imageCreateFromGif($theFile);
381 imageGif($tempImage, $theFile);
382 imageDestroy($tempImage);
390 * Converts a png file to gif
391 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
394 * @param string $theFile the filename with path
395 * @return string new filename
398 function png_to_gif_by_imagemagick($theFile) {
399 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
400 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
401 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
402 && strtolower(substr($theFile,-4,4))=='.png'
403 && @is_file
($theFile)) { // IM
404 $newFile = substr($theFile,0,-4).'.gif';
405 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'].'convert "'.$theFile.'" "'.$newFile.'"');
407 // 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!!
413 * Returns filename of the png/gif version of the input file (which can be png or gif).
414 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
417 * @param string Filepath of image file
418 * @param boolean If set, then input file is converted to PNG, otherwise to GIF
419 * @return string If the new image file exists, it's filepath is returned
422 function read_png_gif($theFile,$output_png=0) {
423 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file
($theFile)) {
424 $ext = strtolower(substr($theFile,-4,4));
426 ((string)$ext=='.png' && $output_png) ||
427 ((string)$ext=='.gif' && !$output_png)
431 $newFile = PATH_site
.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?
'.png':'.gif');
432 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
433 if (@is_file
($newFile)) return $newFile;
452 /*************************
456 *************************/
460 * Returns a new string of max. $chars length.
461 * If the string is longer, it will be truncated and appended with '...'.
462 * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
465 * @param string $string string to truncate
466 * @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.
467 * @param string String to append to the the output if it is truncated, default is '...'
468 * @return string new string
469 * @see fixed_lgd_pre()
471 function fixed_lgd($string,$origChars,$preStr='...') {
472 $chars = abs($origChars);
474 if(strlen($string)>$chars) {
475 return $origChars < 0 ?
476 $preStr.trim(substr($string, -($chars-3))) :
477 trim(substr($string, 0, $chars-3)).$preStr;
485 * Returns a new string of max. $chars length.
486 * If the string is longer, it will be truncated and prepended with '...'.
487 * This works like fixed_lgd, but is truncated in the start of the string instead of the end
488 * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
491 * @param string $string string to truncate
492 * @param integer $chars must be an integer of at least 4
493 * @return string new string
496 function fixed_lgd_pre($string,$chars) {
497 return strrev(t3lib_div
::fixed_lgd(strrev($string),$chars));
501 * Truncates a string with appended/prepended "..." and takes backend character set into consideration
502 * Use only from backend!
505 * @param string $string string to truncate
506 * @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.
507 * @return string New string
510 function fixed_lgd_cs($string,$chars) {
511 if (is_object($GLOBALS['LANG'])) {
512 return $GLOBALS['LANG']->csConvObj
->crop($GLOBALS['LANG']->charSet
,$string,$chars,'...');
514 return t3lib_div
::fixed_lgd($string, $chars);
519 * Breaks up the text for emails
522 * @param string The string to break up
523 * @param string The string to implode the broken lines with (default/typically \n)
524 * @param integer The line length
527 function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
528 $lines = explode(chr(10),$str);
530 while(list(,$lStr)=each($lines)) {
531 $outArr = array_merge($outArr,t3lib_div
::breakLinesForEmail($lStr,$implChar,$charWidth));
533 return implode(chr(10),$outArr);
537 * Breaks up a single line of text for emails
540 * @param string The string to break up
541 * @param string The string to implode the broken lines with (default/typically \n)
542 * @param integer The line length
544 * @see breakTextForEmail()
546 function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
550 while(strlen($str)>$p) {
551 $substr=substr($str,$p,$l);
552 if (strlen($substr)==$l) {
553 $count = count(explode(' ',trim(strrev($substr))));
554 if ($count>1) { // OK...
555 $parts = explode(' ',strrev($substr),2);
556 $theLine = strrev($parts[1]);
558 $afterParts = explode(' ',substr($str,$l+
$p),2);
559 $theLine = $substr.$afterParts[0];
561 if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
566 $lines[]=trim($theLine);
567 $p+
=strlen($theLine);
568 if (!trim(substr($str,$p,$l))) break; // added...
570 return implode($implChar,$lines);
574 * Match IP number with list of numbers with wildcard
577 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
578 * @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)
579 * @return boolean True if an IP-mask from $list matches $baseIP
581 function cmpIP($baseIP, $list) {
582 $IPpartsReq = explode('.',$baseIP);
583 if (count($IPpartsReq)==4) {
584 $values = t3lib_div
::trimExplode(',',$list,1);
586 foreach($values as $test) {
587 list($test,$mask) = explode('/',$test);
591 $lnet = ip2long($test);
592 $lip = ip2long($baseIP);
593 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
594 $firstpart = substr($binnet,0,$mask);
595 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
596 $firstip = substr($binip,0,$mask);
597 $yes = (strcmp($firstpart,$firstip)==0);
600 $IPparts = explode('.',$test);
603 while(list($index,$val)=each($IPparts)) {
605 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
610 if ($yes) return true
;
617 * Match fully qualified domain name with list of strings with wildcard
619 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
620 * @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)
621 * @return boolean True if a domain name mask from $list matches $baseIP
623 function cmpFQDN($baseIP, $list) {
624 if (count(explode('.',$baseIP))==4) {
625 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
626 $values = t3lib_div
::trimExplode(',',$list,1);
628 foreach($values as $test) {
629 $hostNameParts = explode('.',$test);
632 foreach($hostNameParts as $index => $val) {
634 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
638 if ($yes) return true
;
645 * Check for item in list
646 * Check if an item exists in a comma-separated list of items.
649 * @param string $in_list comma-separated list of items (string)
650 * @param string $item item to check for
651 * @return boolean true if $item is in $in_list
653 function inList($in_list,$item) {
654 return strstr(','.$in_list.',', ','.$item.',');
658 * Removes an item from a comma-separated list of items.
661 * @param string $element element to remove
662 * @param string $list comma-separated list of items (string)
663 * @return string new comma-separated list of items
665 function rmFromList($element,$list) {
666 $items = explode(',',$list);
667 while(list($k,$v)=each($items)) {
668 if ($v==$element) {unset($items[$k]);}
670 return implode(',',$items);
674 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
677 * @param integer Input value
678 * @param integer Lower limit
679 * @param integer Higher limit
680 * @param integer Default value if input is false.
681 * @return integer The input value forced into the boundaries of $min and $max
683 function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
684 // Returns $theInt as an integer in the integerspace from $min to $max
685 $theInt = intval($theInt);
686 if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
687 if ($theInt<$min){$theInt=$min;}
688 if ($theInt>$max){$theInt=$max;}
693 * Returns the $integer if greater than zero, otherwise returns zero.
696 * @param integer Integer string to process
699 function intval_positive($theInt) {
700 $theInt = intval($theInt);
701 if ($theInt<0){$theInt=0;}
706 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
709 * @param string Version number on format x.x.x
710 * @return integer Integer version of version number (where each part can count to 999)
712 function int_from_ver($verNumberStr) {
713 $verParts = explode('.',$verNumberStr);
714 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
));
718 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
721 * @param string String to md5-hash
722 * @return integer Returns 28bit integer-hash
724 function md5int($str) {
725 return hexdec(substr(md5($str),0,7));
729 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
733 * @param string Input string to be md5-hashed
734 * @param integer The string-length of the output
735 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
737 function shortMD5($input, $len=10) {
738 return substr(md5($input),0,$len);
742 * Takes comma-separated lists and arrays and removes all duplicates
745 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
746 * @return string Returns the list without any duplicates of values, space around values are trimmed
748 function uniqueList() {
749 $listArray = array();
751 $arg_list = func_get_args();
752 foreach ($arg_list as $in_list) {
753 if (!is_array($in_list)) {
754 $in_list = explode(',',$in_list);
756 $listArray = array_merge($listArray,$in_list);
758 return implode(',',array_unique($listArray));
762 * Splits a reference to a file in 5 parts
765 * @param string Filename/filepath to be analysed
766 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
768 function split_fileref($fileref) {
769 if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
770 $info['path'] = $reg[1];
771 $info['file'] = $reg[2];
774 $info['file'] = $fileref;
777 if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
778 $info['filebody'] = $reg[1];
779 $info['fileext'] = strtolower($reg[2]);
780 $info['realFileext'] = $reg[2];
782 $info['filebody'] = $info['file'];
783 $info['fileext'] = '';
790 * Returns the directory part of a path without trailing slash
791 * If there is no dir-part, then an empty string is returned.
794 * '/dir1/dir2/script.php' => '/dir1/dir2'
795 * '/dir1/' => '/dir1'
796 * 'dir1/script.php' => 'dir1'
797 * 'd/script.php' => 'd'
798 * '/script.php' => ''
802 * @param string Directory name / path
803 * @return string Processed input value. See function description.
805 function dirname($path) {
806 $p=t3lib_div
::revExplode('/',$path,2);
807 return count($p)==2?
$p[0]:'';
811 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
814 * @param string A hexadecimal color code, #xxxxxx
815 * @param integer Offset value 0-255
816 * @param integer Offset value 0-255
817 * @param integer Offset value 0-255
818 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
819 * @see modifyHTMLColorAll()
821 function modifyHTMLColor($color,$R,$G,$B) {
822 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
823 $nR = t3lib_div
::intInRange(hexdec(substr($color,1,2))+
$R,0,255);
824 $nG = t3lib_div
::intInRange(hexdec(substr($color,3,2))+
$G,0,255);
825 $nB = t3lib_div
::intInRange(hexdec(substr($color,5,2))+
$B,0,255);
827 substr('0'.dechex($nR),-2).
828 substr('0'.dechex($nG),-2).
829 substr('0'.dechex($nB),-2);
833 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
836 * @param string A hexadecimal color code, #xxxxxx
837 * @param integer Offset value 0-255 for all three channels.
838 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
839 * @see modifyHTMLColor()
841 function modifyHTMLColorAll($color,$all) {
842 return t3lib_div
::modifyHTMLColor($color,$all,$all,$all);
846 * Removes comma (if present) in the end of string
849 * @param string String from which the comma in the end (if any) will be removed.
852 function rm_endcomma($string) {
853 return ereg_replace(',$','',$string);
857 * strtoupper which converts danish (and other characters) characters as well
858 * (DEPRECIATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
861 * @param string String to process
865 function danish_strtoupper($string) {
866 $value = strtoupper($string);
867 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
871 * Change umlaut characters to plain ASCII with normally two character target
872 * Only known characters will be converted, so don't expect a result for any character.
873 * (DEPRECIATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!)
877 * @param string String to convert.
880 function convUmlauts($str) {
881 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
882 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
883 return preg_replace($pat,$repl,$str);
887 * Tests if the input is an integer.
890 * @param mixed Any input variable to test.
891 * @return boolean Returns true if string is an integer
893 function testInt($var) {
894 return !strcmp($var,intval($var));
898 * Returns true if the first part of $str matches the string $partStr
901 * @param string Full string to check
902 * @param string Reference string which must be found as the "first part" of the full string
903 * @return boolean True if $partStr was found to be equal to the first part of $str
905 function isFirstPartOfStr($str,$partStr) {
906 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
907 $psLen = strlen($partStr);
909 return substr($str,0,$psLen)==(string)$partStr;
914 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
917 * @param integer Number of bytes to format.
918 * @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)
919 * @return string Formatted representation of the byte number, for output.
921 function formatSize($sizeInBytes,$labels='') {
924 if (strlen($labels) == 0) {
925 $labels = ' | K| M| G';
927 $labels = str_replace('"','',$labels);
929 $labelArr = explode('|',$labels);
932 if ($sizeInBytes>900) {
933 if ($sizeInBytes>900000000) { // GB
934 $val = $sizeInBytes/(1024*1024*1024);
935 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[3];
937 elseif ($sizeInBytes>900000) { // MB
938 $val = $sizeInBytes/(1024*1024);
939 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[2];
941 $val = $sizeInBytes/(1024);
942 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[1];
945 return $sizeInBytes.$labelArr[0];
950 * Returns microtime input to milliseconds
953 * @param string Microtime
954 * @return integer Microtime input string converted to an integer (milliseconds)
956 function convertMicrotime($microtime) {
957 $parts = explode(' ',$microtime);
958 return round(($parts[0]+
$parts[1])*1000);
962 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
965 * @param string Input string, eg "123 + 456 / 789 - 4"
966 * @param string Operators to split by, typically "/+-*"
967 * @return array Array with operators and operands separated.
968 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
970 function splitCalc($string,$operators) {
974 $valueLen=strcspn($string,$operators);
975 $value=substr($string,0,$valueLen);
976 $res[] = Array($sign,trim($value));
977 $sign=substr($string,$valueLen,1);
978 $string=substr($string,$valueLen+
1);
985 * Calculates the input by +,-,*,/,%,^ with priority to + and -
988 * @param string Input string, eg "123 + 456 / 789 - 4"
989 * @return integer Calculated value. Or error string.
990 * @see calcParenthesis()
992 function calcPriority($string) {
993 $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
994 $string='+'.$string; // Ensuring an operator for the first entrance
996 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
997 // split the expression here:
998 preg_match_all('/'.$regex.'/',$string,$reg);
1004 $buffer=doubleval(current($reg[2]));
1005 next($reg[2]); // Advance pointer
1006 while(list($k,$v)=each($reg[2])) {
1008 $sign = $reg[1][$k];
1009 if ($sign=='+' ||
$sign=='-') {
1010 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1014 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
1015 if ($sign=='%') {if ($v) $buffer%
=$v; else $err='dividing by zero';}
1016 if ($sign=='*') {$buffer*=$v;}
1017 if ($sign=='^') {$buffer=pow($buffer,$v);}
1020 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1021 return $err ?
'ERROR: '.$err : $number;
1025 * Calculates the input with parenthesis levels
1028 * @param string Input string, eg "(123 + 456) / 789 - 4"
1029 * @return integer Calculated value. Or error string.
1030 * @see calcPriority(), tslib_cObj::stdWrap()
1032 function calcParenthesis($string) {
1035 $valueLenO=strcspn($string,'(');
1036 $valueLenC=strcspn($string,')');
1037 if ($valueLenC==strlen($string) ||
$valueLenC < $valueLenO) {
1038 $value = t3lib_div
::calcPriority(substr($string,0,$valueLenC));
1039 $string = $value.substr($string,$valueLenC+
1);
1042 $string = substr($string,0,$valueLenO).t3lib_div
::calcParenthesis(substr($string,$valueLenO+
1));
1046 if ($securC<=0) break;
1047 } while($valueLenO<strlen($string));
1052 * Inverse version of htmlspecialchars()
1055 * @param string Value where >, <, " and & should be converted to regular chars.
1056 * @return string Converted result.
1058 function htmlspecialchars_decode($value) {
1059 $value = str_replace('>','>',$value);
1060 $value = str_replace('<','<',$value);
1061 $value = str_replace('"','"',$value);
1062 $value = str_replace('&','&',$value);
1067 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1070 * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1071 * @return string Converted result.
1073 function deHSCentities($str) {
1074 return ereg_replace('&([#[:alnum:]]*;)','&\1',$str);
1078 * This function is used to escape any ' -characters when transferring text to JavaScript!
1081 * @param string String to escape
1082 * @param boolean If set, also backslashes are escaped.
1083 * @param string The character to escape, default is ' (single-quote)
1084 * @return string Processed input string
1086 function slashJS($string,$extended=0,$char="'") {
1087 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
1088 return str_replace ($char, "\\".$char, $string);
1092 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1093 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1096 * @param string String to raw-url-encode with spaces preserved
1097 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1099 function rawUrlEncodeJS($str) {
1100 return str_replace('%20',' ',rawurlencode($str));
1104 * rawurlencode which preserves "/" chars
1105 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1108 * @param string Input string
1109 * @return string Output string
1111 function rawUrlEncodeFP($str) {
1112 return str_replace('%2F','/',rawurlencode($str));
1116 * Checking syntax of input email address
1119 * @param string Input string to evaluate
1120 * @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.
1122 function validEmail($email) {
1123 $email = trim ($email);
1124 if (strstr($email,' ')) return FALSE
;
1125 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE
: FALSE
;
1129 * Formats a string for output between <textarea>-tags
1130 * All content outputted in a textarea form should be passed through this function
1131 * 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!
1134 * @param string Input string to be formatted.
1135 * @return string Formatted for <textarea>-tags
1137 function formatForTextarea($content) {
1138 return chr(10).htmlspecialchars($content);
1152 /*************************
1156 *************************/
1159 * Check if an item exists in an array
1160 * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
1163 * @param array $in_array one-dimensional array of items
1164 * @param string $item item to check for
1165 * @return boolean true if $item is in the one-dimensional array $in_array
1168 function inArray($in_array,$item) {
1169 if (is_array($in_array)) {
1170 while (list(,$val)=each($in_array)) {
1171 if (!is_array($val) && !strcmp($val,$item)) return true
;
1177 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1178 * Corresponds to explode(), but with conversion to integers for all values.
1181 * @param string Delimiter string to explode with
1182 * @param string The string to explode
1183 * @return array Exploded values, all converted to integers
1185 function intExplode($delim, $string) {
1186 $temp = explode($delim,$string);
1187 while(list($key,$val)=each($temp)) {
1188 $temp[$key]=intval($val);
1195 * Reverse explode which explodes the string counting from behind.
1196 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1199 * @param string Delimiter string to explode with
1200 * @param string The string to explode
1201 * @param integer Number of array entries
1202 * @return array Exploded values
1204 function revExplode($delim, $string, $count=0) {
1205 $temp = explode($delim,strrev($string),$count);
1206 while(list($key,$val)=each($temp)) {
1207 $temp[$key]=strrev($val);
1209 $temp=array_reverse($temp);
1215 * Explodes a string and trims all values for whitespace in the ends.
1216 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1219 * @param string Delimiter string to explode with
1220 * @param string The string to explode
1221 * @param boolean If set, all empty values (='') will NOT be set in output
1222 * @return array Exploded values
1224 function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
1225 $temp = explode($delim,$string);
1227 while(list($key,$val)=each($temp)) {
1228 if (!$onlyNonEmptyValues ||
strcmp('',trim($val))) {
1229 $newtemp[]=trim($val);
1237 * Remove duplicate values from an array
1238 * This function is deprecated, use the PHP function array_unique instead
1241 * @param array Array of values to make unique
1246 function uniqueArray($valueArray) {
1247 return array_unique($valueArray);
1251 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1254 * @param array Array containing the values
1255 * @param string Value to search for and if found remove array entry where found.
1256 * @return array Output array with entries removed if search string is found
1258 function removeArrayEntryByValue($array,$cmpValue) {
1259 if (is_array($array)) {
1261 while(list($k,$v)=each($array)) {
1263 $array[$k] = t3lib_div
::removeArrayEntryByValue($v,$cmpValue);
1265 if (!strcmp($v,$cmpValue)) {
1276 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1279 * @param string Name prefix for entries. Set to blank if you wish none.
1280 * @param array The (multidim) array to implode
1281 * @param boolean If set, all values that are blank (='') will NOT be imploded
1282 * @param boolean If set, parameters which were blank strings would be removed.
1283 * @param boolean If set, the param name itselt (for example "param[key][key2]") would be rawurlencoded as well.
1284 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1286 function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
1287 if (is_array($theArray)) {
1288 foreach($theArray as $Akey => $AVal) {
1289 $thisKeyName = $name ?
$name.'['.$Akey.']' : $Akey;
1290 if (is_array($AVal)) {
1291 $str = t3lib_div
::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1293 if (!$skipBlank ||
strcmp($AVal,'')) {
1294 $str.='&'.($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName).
1295 '='.rawurlencode($AVal); // strips slashes because _POST / _GET input is with slashes...
1304 * Returns an array with selected keys from incoming data.
1305 * (Better read source code if you want to find out...)
1308 * @param string List of variable/key names
1309 * @param array Array from where to get values based on the keys in $varList
1310 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1311 * @return array Output array with selected variables.
1313 function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) {
1314 $keys = t3lib_div
::trimExplode(',',$varList,1);
1316 foreach($keys as $v) {
1317 if (isset($getArray[$v])) {
1318 $outArr[$v]=$getArray[$v];
1319 } elseif ($GPvarAlt) {
1320 $outArr[$v]=t3lib_div
::_GP($v);
1328 * This function traverses a multidimentional array and adds slashes to the values.
1329 * NOTE that the input array is and argument by reference.!!
1330 * Twin-function to stripSlashesOnArray
1333 * @param array Multidimensional input array, (REFERENCE!)
1336 function addSlashesOnArray(&$theArray) {
1337 if (is_array($theArray)) {
1339 while(list($Akey,$AVal)=each($theArray)) {
1340 if (is_array($AVal)) {
1341 t3lib_div
::addSlashesOnArray($theArray[$Akey]);
1343 $theArray[$Akey] = addslashes($AVal);
1352 * This function traverses a multidimentional array and strips slashes to the values.
1353 * NOTE that the input array is and argument by reference.!!
1354 * Twin-function to addSlashesOnArray
1357 * @param array Multidimensional input array, (REFERENCE!)
1360 function stripSlashesOnArray(&$theArray) {
1361 if (is_array($theArray)) {
1363 while(list($Akey,$AVal)=each($theArray)) {
1364 if (is_array($AVal)) {
1365 t3lib_div
::stripSlashesOnArray($theArray[$Akey]);
1367 $theArray[$Akey] = stripslashes($AVal);
1375 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1378 * @param array Multidimensional input array
1379 * @param string "add" or "strip", depending on usage you wish.
1382 function slashArray($arr,$cmd) {
1383 if ($cmd=='strip') t3lib_div
::stripSlashesOnArray($arr);
1384 if ($cmd=='add') t3lib_div
::addSlashesOnArray($arr);
1389 * 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)
1390 * In case of identical keys, ie. keeping the values of the second.
1393 * @param array First array
1394 * @param array Second array, overruling the first array
1395 * @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.
1396 * @param boolean If set, values from $arr1 will overrule if they are empty. Default: true
1397 * @return array Resulting array where $arr1 values has overruled $arr0 values
1399 function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true
) {
1401 while(list($key,$val) = each($arr1)) {
1402 if(is_array($arr0[$key])) {
1403 if (is_array($arr1[$key])) {
1404 $arr0[$key] = t3lib_div
::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
1408 if (isset($arr0[$key])) {
1409 if ($includeEmtpyValues OR $val) {
1414 if ($includeEmtpyValues OR $val) {
1425 * 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.
1428 * @param array First array
1429 * @param array Second array
1430 * @return array Merged result.
1432 function array_merge($arr1,$arr2) {
1437 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1440 * @param array Input array of values
1441 * @param string Delimited, default is comman
1442 * @param string Quote-character to wrap around the values.
1443 * @return string A single line of CSV
1445 function csvValues($row,$delim=',',$quote='"') {
1448 while(list(,$value)=each($row)) {
1449 list($valPart) = explode(chr(10),$value);
1450 $valPart = trim($valPart);
1451 $out[]=str_replace($quote,$quote.$quote,$valPart);
1453 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1472 /*************************
1474 * HTML/XML PROCESSING
1476 *************************/
1479 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1480 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1481 * 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()
1484 * @param string HTML-tag string (or attributes only)
1485 * @return array Array with the attribute values.
1487 function get_tag_attributes($tag) {
1488 $components = t3lib_div
::split_tag_attributes($tag);
1489 $name = ''; // attribute name is stored here
1491 if (is_array($components)) {
1492 while (list($key,$val) = each ($components)) {
1493 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
1496 $attributes[$name] = $val;
1500 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1501 $attributes[$key] = '';
1510 if (is_array($attributes)) reset($attributes);
1516 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1517 * Removes tag-name if found
1520 * @param string HTML-tag string (or attributes only)
1521 * @return array Array with the attribute values.
1524 function split_tag_attributes($tag) {
1525 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1526 // Removes any > in the end of the string
1527 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1529 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1530 $firstChar=substr($tag_tmp,0,1);
1531 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
1532 $reg=explode($firstChar,$tag_tmp,3);
1534 $tag_tmp=trim($reg[2]);
1535 } elseif (!strcmp($firstChar,'=')) {
1537 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1539 // There are '' around the value. We look for the next ' ' or '>'
1540 $reg = split('[[:space:]=]',$tag_tmp,2);
1541 $value[] = trim($reg[0]);
1542 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1545 if (is_array($value)) reset($value);
1550 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1553 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1554 * @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!
1555 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1556 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1558 function implodeAttributes($arr,$xhtmlSafe=FALSE
,$dontOmitBlankAttribs=FALSE
) {
1559 if (is_array($arr)) {
1562 foreach($arr as $p => $v) {
1563 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
1568 foreach($arr as $p => $v) {
1569 if (strcmp($v,'') ||
$dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
1571 return implode(' ',$list);
1576 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1578 * @param array See implodeAttributes()
1579 * @param boolean See implodeAttributes()
1580 * @param boolean See implodeAttributes()
1581 * @return string See implodeAttributes()
1582 * @deprecated Name was changed into implodeAttributes
1583 * @see implodeAttributes()
1585 function implodeParams($arr,$xhtmlSafe=FALSE
,$dontOmitBlankAttribs=FALSE
) {
1586 return t3lib_div
::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
1590 * Wraps JavaScript code XHTML ready with <script>-tags
1591 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1592 * This is nice for identing JS code with PHP code on the same level.
1594 * @param string JavaScript code
1595 * @param boolean Wrap script element in linebreaks? Default is TRUE.
1596 * @return string The wrapped JS code, ready to put into a XHTML page
1597 * @author Ingmar Schlecht <ingmars@web.de>
1598 * @author René Fritz <r.fritz@colorcube.de>
1600 function wrapJS($string, $linebreak=TRUE
) {
1602 // <script wrapped in nl?
1603 $cr = $linebreak?
"\n" : '';
1605 // remove nl from the beginning
1606 $string = preg_replace ('/^\n+/', '', $string);
1607 // re-ident to one tab using the first line as reference
1608 if(preg_match('/^(\t+)/',$string,$match)) {
1609 $string = str_replace($match[1],"\t", $string);
1611 $string = $cr.'<script type="text/javascript">
1617 return trim($string);
1622 * Parses XML input into a PHP array with associative keys
1625 * @param string XML data input
1626 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1627 * @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.
1628 * @author bisqwit at iki dot fi dot not dot for dot ads dot invalid / http://dk.php.net/xml_parse_into_struct + kasper@typo3.com
1630 function xml2tree($string,$depth=999) {
1631 $parser = xml_parser_create();
1635 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1636 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1637 xml_parse_into_struct($parser, $string, $vals, $index);
1639 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1640 xml_parser_free($parser);
1642 $stack = array( array() );
1647 foreach($vals as $key => $val) {
1648 $type = $val['type'];
1651 if ($type=='open' ||
$type=='complete') {
1652 $stack[$stacktop++
] = $tagi;
1654 if ($depth==$stacktop) {
1658 $tagi = array('tag' => $val['tag']);
1660 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
1661 if(isset($val['value'])) $tagi['values'][] = $val['value'];
1664 if ($type=='complete' ||
$type=='close') {
1666 $tagi = $stack[--$stacktop];
1667 $oldtag = $oldtagi['tag'];
1668 unset($oldtagi['tag']);
1670 if ($depth==($stacktop+
1)) {
1671 if ($key-$startPoint > 0) {
1672 $partArray = array_slice(
1677 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
1678 $oldtagi['XMLvalue']=t3lib_div
::xmlRecompileFromStructValArray($partArray);
1680 $oldtagi['XMLvalue']=$oldtagi['values'][0];
1684 $tagi['ch'][$oldtag][] = $oldtagi;
1688 if($type=='cdata') {
1689 $tagi['values'][] = $val['value'];
1696 * Converts a PHP array into an XML string.
1697 * The XML output is optimized for readability since associative keys are used as tagnames.
1698 * 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.
1699 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
1700 * 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
1701 * 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.
1702 * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
1703 * 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...
1706 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1707 * @param string tag-prefix, eg. a namespace prefix like "T3:"
1708 * @param integer Current recursion level. Don't change, stay at zero!
1709 * @param string Alternative document tag. Default is "phparray".
1710 * @param integer If set, the number of spaces corresponding to this number is used for indenting, otherwise a single chr(9) (TAB) is used
1711 * @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')
1712 * @param string Parent tag name. Don't touch.
1713 * @return string An XML string made from the input content in the array.
1716 function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$parentTagName='') {
1717 // 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
1718 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
1719 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
1720 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
1722 // Set indenting mode:
1723 $indentChar = $spaceInd ?
' ' : chr(9);
1724 $indentN = $spaceInd>0 ?
$spaceInd : 1;
1726 // Init output variable:
1729 // Traverse the input array
1730 if (is_array($array)) {
1731 foreach($array as $k=>$v) {
1735 // Construct the tag name.
1736 if (!strcmp(intval($tagName),$tagName)) { // If integer...;
1737 if ($options['useNindex']) { // If numeric key, prefix "n"
1738 $tagName = 'n'.$tagName;
1739 } else { // Use special tag for num. keys:
1740 $attr.=' index="'.$tagName.'"';
1741 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
1743 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
1744 $attr.=' index="'.htmlspecialchars($tagName).'"';
1745 $tagName = $options['useIndexTagForAssoc'];
1746 } elseif(isset($options['parentTagMap'][$parentTagName])) { // Use tag based on parent tag name:
1747 $attr.=' index="'.htmlspecialchars($tagName).'"';
1748 $tagName = (string)$options['parentTagMap'][$parentTagName];
1751 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1752 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
1754 // If the value is an array then we will call this function recursively:
1757 $content = chr(10).t3lib_div
::array2xml($v,$NSprefix,$level+
1,'',$spaceInd,$options,$tagName).
1758 str_pad('',($level+
1)*$indentN,$indentChar);
1759 $attr.=' type="array"';
1760 } else { // Just a value:
1762 // Look for binary chars:
1763 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!
1764 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
1765 $content = chr(10).chunk_split(base64_encode($v));
1766 $attr.=' base64="1"';
1768 // Otherwise, just htmlspecialchar the stuff:
1769 $content = htmlspecialchars($v);
1770 $dType = gettype($v);
1771 if ($dType!='string') { $attr.=' type="'.$dType.'"'; }
1775 // Add the element to the output string:
1776 $output.=str_pad('',($level+
1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
1780 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1783 '<'.$docTag.'>'.chr(10).
1792 * Converts an XML string to a PHP array.
1793 * This is the reverse function of array2xml()
1796 * @param string XML content to convert into an array
1797 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
1798 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1801 function xml2array($string,$NSprefix='') {
1802 global $TYPO3_CONF_VARS;
1805 $parser = xml_parser_create();
1809 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1810 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1812 // PHP5 fix of charset awareness:
1813 // 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.
1814 // 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.
1815 // 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.
1816 if ((double)phpversion()>=5) {
1817 unset($ereg_result);
1818 ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
1819 $theCharset = $ereg_result[1] ?
$ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
1820 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
1824 xml_parse_into_struct($parser, $string, $vals, $index);
1826 // If error, return error message:
1827 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1828 xml_parser_free($parser);
1831 $stack = array(array());
1836 // Traverse the parsed XML structure:
1837 foreach($vals as $key => $val) {
1839 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1840 $tagName = $val['tag'];
1842 // Test for name space:
1843 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ?
substr($tagName,strlen($NSprefix)) : $tagName;
1845 // Test for numeric tag, encoded on the form "nXXX":
1846 $testNtag = substr($tagName,1); // Closing tag.
1847 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ?
intval($testNtag) : $tagName;
1849 // Test for alternative index value:
1850 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
1852 // Setting tag-values, manage stack:
1853 switch($val['type']) {
1854 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1855 $current[$tagName] = array(); // Setting blank place holder
1856 $stack[$stacktop++
] = $current;
1859 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1860 $oldCurrent = $current;
1861 $current = $stack[--$stacktop];
1862 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
1863 $current[key($current)] = $oldCurrent;
1866 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1867 if ($val['attributes']['base64']) {
1868 $current[$tagName] = base64_decode($val['value']);
1870 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
1873 switch((string)$val['attributes']['type']) {
1875 $current[$tagName] = (integer)$current[$tagName];
1878 $current[$tagName] = (double)$current[$tagName];
1881 $current[$tagName] = (bool
)$current[$tagName];
1884 $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...
1892 // Finally return the content of the document tag.
1893 return $current[$tagName];
1897 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1900 * @param array A array of XML parts, see xml2tree
1901 * @return string Re-compiled XML data.
1903 function xmlRecompileFromStructValArray($vals) {
1906 foreach($vals as $val) {
1907 $type = $val['type'];
1910 if ($type=='open' ||
$type=='complete') {
1911 $XMLcontent.='<'.$val['tag'];
1912 if(isset($val['attributes'])) {
1913 foreach($val['attributes'] as $k => $v) {
1914 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
1917 if ($type=='complete') {
1918 if(isset($val['value'])) {
1919 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
1920 } else $XMLcontent.='/>';
1921 } else $XMLcontent.='>';
1923 if ($type=='open' && isset($val['value'])) {
1924 $XMLcontent.=htmlspecialchars($val['value']);
1928 if ($type=='close') {
1929 $XMLcontent.='</'.$val['tag'].'>';
1932 if($type=='cdata') {
1933 $XMLcontent.=htmlspecialchars($val['value']);
1941 * Extract the encoding scheme as found in the first line of an XML document (typically)
1944 * @param string XML data
1945 * @return string Encoding scheme (lowercase), if found.
1947 function xmlGetHeaderAttribs($xmlData) {
1948 $xmlHeader = substr(trim($xmlData),0,200);
1950 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg)) {
1951 return t3lib_div
::get_tag_attributes($reg[1]);
1965 /*************************
1969 *************************/
1972 * Reads the file or url $url and returns the content
1973 * 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.
1976 * @param string Filepath/URL to read
1977 * @return string The content from the resource given as input.
1979 function getURL($url) {
1982 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
1983 if((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1')) {
1984 //external URL without error checking.
1986 curl_setopt ($ch,CURLOPT_URL
, $url);
1987 curl_setopt ($ch,CURLOPT_HEADER
, 0);
1988 curl_setopt ($ch,CURLOPT_RETURNTRANSFER
, 1);
1990 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
1991 curl_setopt ($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
1993 // I don't know if it will be needed
1994 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
1995 curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
1997 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
1998 curl_setopt ($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
2001 $content=curl_exec ($ch);
2004 } elseif($fd = fopen($url,'rb')) {
2005 while (!feof($fd)) {
2006 $content.=fread($fd, 5000);
2014 * Writes $content to the file $file
2017 * @param string Filepath to write to
2018 * @param string Content to write
2019 * @return boolean True if the file was successfully opened and written to.
2021 function writeFile($file,$content) {
2022 if($fd = fopen($file,'wb')) {
2023 fwrite( $fd, $content);
2026 // Setting file system mode & group ownership of file:
2027 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2028 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2029 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2030 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2039 * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
2040 * Accepts an additional subdirectory in the file path!
2042 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2043 * @param string Content string to write
2044 * @return string Returns false on success, otherwise an error string telling about the problem.
2046 function writeFileToTypo3tempDir($filepath,$content) {
2048 // Parse filepath into directory and basename:
2049 $fI = pathinfo($filepath);
2050 $fI['dirname'].= '/';
2053 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2054 if (defined('PATH_site')) {
2055 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2056 if (@is_dir
($dirName)) {
2057 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2059 // Checking if the "subdir" is found:
2060 $subdir = substr($fI['dirname'],strlen($dirName));
2062 if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
2064 if (!@is_dir
($dirName)) {
2065 t3lib_div
::mkdir($dirName);
2067 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
2069 // Checking dir-name again (sub-dir might have been created):
2070 if (@is_dir
($dirName)) {
2071 if ($filepath == $dirName.$fI['basename']) {
2072 t3lib_div
::writeFile($filepath, $content);
2073 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2074 } else return 'Calculated filelocation didn\'t match input $filepath!';
2075 } else return '"'.$dirName.'" is not a directory!';
2076 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2077 } else return 'PATH_site + "typo3temp/" was not a directory!';
2078 } else return 'PATH_site constant was NOT defined!';
2079 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2083 * 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']
2086 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2087 * @return boolean TRUE if @mkdir went well!
2089 function mkdir($theNewFolder) {
2090 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
2091 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2092 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2094 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2095 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2102 * Returns an array with the names of folders in a specific path
2103 * Will return 'error' (string) if there were an error with reading directory content.
2106 * @param string Path to list directories from
2107 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2109 function get_dirs($path) {
2112 if (is_object($d)) {
2113 while($entry=$d->read()) {
2114 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2115 $filearray[]=$entry;
2119 } else return 'error';
2125 * Returns an array with the names of files in a specific path
2128 * @param string $path: Is the path to the file
2129 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2130 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2131 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2132 * @return array Array of the files found
2134 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2136 // Initialize variabels:
2137 $filearray = array();
2138 $sortarray = array();
2139 $path = ereg_replace('\/$','',$path);
2141 // Find files+directories:
2142 if (@is_dir
($path)) {
2143 $extensionList = strtolower($extensionList);
2145 if (is_object($d)) {
2146 while($entry=$d->read()) {
2147 if (@is_file
($path.'/'.$entry)) {
2148 $fI = pathinfo($entry);
2149 $key = md5($path.'/'.$entry);
2150 if (!$extensionList || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) {
2151 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2152 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2153 elseif ($order) {$sortarray[$key]=$entry;}
2158 } else return 'error opening path: "'.$path.'"';
2166 while(list($k,$v)=each($sortarray)) {
2167 $newArr[$k]=$filearray[$k];
2178 * Recursively gather all files and folders of a path.
2181 * @param array $fileArr: Empty input array (will have files added to it)
2182 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2183 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2184 * @param boolean $regDirs: If set, directories are also included in output.
2185 * @param integer $recursivityLevels: The number of levels to dig down...
2186 * @return array An array with the found files/directories.
2188 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2189 if ($regDirs) $fileArr[] = $path;
2190 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1));
2192 $dirs = t3lib_div
::get_dirs($path);
2193 if (is_array($dirs) && $recursivityLevels>0) {
2194 foreach ($dirs as $subdirs) {
2195 if ((string)$subdirs!='') {
2196 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2204 * Removes the absolute part of all files/folders in fileArr
2207 * @param array $fileArr: The file array to remove the prefix from
2208 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2209 * @return array The input $fileArr processed.
2211 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2212 foreach($fileArr as $k => $absFileRef) {
2213 if(t3lib_div
::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2214 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2215 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2221 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2224 * @param string File path to process
2227 function fixWindowsFilePath($theFile) {
2228 return str_replace('//','/', str_replace('\\','/', $theFile));
2232 * Resolves "../" sections in the input path string.
2233 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2236 * @param string File path in which "/../" is resolved
2239 function resolveBackPath($pathStr) {
2240 $parts = explode('/',$pathStr);
2242 foreach($parts as $pV) {
2247 } else $output[]=$pV;
2253 return implode('/',$output);
2257 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2258 * - If already having a scheme, nothing is prepended
2259 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2260 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2263 * @param string URL / path to prepend full URL addressing to.
2266 function locationHeaderUrl($path) {
2267 $uI = parse_url($path);
2268 if (substr($path,0,1)=='/') { // relative to HOST
2269 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2270 } elseif (!$uI['scheme']) { // No scheme either
2271 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2291 /*************************
2293 * DEBUG helper FUNCTIONS
2295 *************************/
2298 * Returns a string with a list of ascii-values for the first $characters characters in $string
2301 * @param string String to show ASCII value for
2302 * @param integer Number of characters to show
2303 * @return string The string with ASCII values in separated by a space char.
2306 function debug_ordvalue($string,$characters=100) {
2307 if(strlen($string) < $characters) $characters = strlen($string);
2308 for ($i=0; $i<$characters; $i++
) {
2309 $valuestring.=' '.ord(substr($string,$i,1));
2311 return trim($valuestring);
2315 * Returns HTML-code, which is a visual representation of a multidimensional array
2316 * use t3lib_div::print_array() in order to print an array
2317 * Returns false if $array_in is not an array
2320 * @param array Array to view
2321 * @return string HTML output
2323 function view_array($array_in) {
2324 if (is_array($array_in)) {
2325 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2326 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
2327 while (list($key,$val)=each($array_in)) {
2328 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
2329 if (is_array($array_in[$key])) {
2330 $result.=t3lib_div
::view_array($array_in[$key]);
2332 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
2333 $result.= '</td></tr>';
2335 $result.= '</table>';
2346 * @param array Array to print visually (in a table).
2351 function print_array($array_in) {
2352 echo t3lib_div
::view_array($array_in);
2356 * Makes debug output
2357 * Prints $var in bold between two vertical lines
2358 * If not $var the word 'debug' is printed
2359 * If $var is an array, the array is printed by t3lib_div::print_array()
2362 * @param mixed Variable to print
2363 * @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.
2366 function debug($var="",$brOrHeader=0) {
2367 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2368 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>';
2369 } elseif ($brOrHeader<0) {
2370 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
2373 if (is_array($var)) {
2374 t3lib_div
::print_array($var);
2375 } elseif (is_object($var)) {
2376 echo '<b>|Object:<pre>';
2379 } elseif ((string)$var!='') {
2380 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2382 echo '<b>| debug |</b>';
2385 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2386 echo '</td></tr></table>';
2387 } elseif ($brOrHeader>0) {
2388 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
2423 /*************************
2425 * SYSTEM INFORMATION
2427 *************************/
2430 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2435 function getThisUrl() {
2436 $p=parse_url(t3lib_div
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2437 $dir=t3lib_div
::dirname($p['path']).'/'; // Strip file
2438 $url = str_replace('//','/',$p['host'].($p['port']?
':'.$p['port']:'').$dir);
2443 * Returns the link-url to the current script.
2444 * 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.
2445 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
2448 * @param array Array of GET parameters to include
2451 function linkThisScript($getParams=array()) {
2452 $parts = t3lib_div
::getIndpEnv('SCRIPT_NAME');
2453 $params = t3lib_div
::_GET();
2455 foreach($getParams as $k => $v) {
2456 if (strcmp($v,'')) {
2458 } else unset($params[$k]);
2461 $pString = t3lib_div
::implodeArrayForUrl('',$params);
2463 return $pString ?
$parts.'?'.ereg_replace('^&','',$pString) : $parts;
2467 * 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.
2468 * So basically it adds the parameters in $getParams to an existing URL, $url
2471 * @param string URL string
2472 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2473 * @return string Output URL with added getParams.
2475 function linkThisUrl($url,$getParams=array()) {
2476 $parts = parse_url($url);
2477 if ($parts['query']) {
2478 parse_str($parts['query'],$getP);
2483 $getP = t3lib_div
::array_merge_recursive_overrule($getP,$getParams);
2484 $uP = explode('?',$url);
2486 $params = t3lib_div
::implodeArrayForUrl('',$getP);
2487 $outurl = $uP[0].($params ?
'?'.substr($params, 1) : '');
2493 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2494 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2497 * @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
2498 * @return string Value based on the input key, independent of server/os environment.
2500 function getIndpEnv($getEnvName) {
2503 output from parse_url():
2504 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
2506 [user] => 'username'
2507 [pass] => 'password'
2508 [host] => '192.168.1.4'
2510 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2511 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2512 [fragment] => 'link1'
2514 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2515 [path_dir] = '/typo3/32/temp/phpcheck/'
2516 [path_info] = '/arg1/arg2/arg3/'
2517 [path] = [path_script/path_dir][path_info]
2523 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2524 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2525 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')!
2526 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2527 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2528 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
2529 (Notice: NO username/password + NO fragment)
2532 REMOTE_ADDR = (client IP)
2533 REMOTE_HOST = (client host)
2534 HTTP_USER_AGENT = (client user agent)
2535 HTTP_ACCEPT_LANGUAGE = (client accept language)
2538 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2541 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2542 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2543 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2544 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2545 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2546 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2547 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2548 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2549 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2551 Notice: [fragment] is apparently NEVER available to the script!
2554 Testing suggestions:
2555 - Output all the values.
2556 - 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
2557 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2561 # if ($getEnvName=='HTTP_REFERER') return '';
2562 switch((string)$getEnvName) {
2564 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']);
2566 case 'SCRIPT_FILENAME':
2567 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'])));
2570 // Typical application of REQUEST_URI is return urls, forms submitting to itselt etc. Eg: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2571 if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2572 return '/'.ereg_replace('^/','',t3lib_div
::getIndpEnv('SCRIPT_NAME')).
2573 ($_SERVER['QUERY_STRING']?
'?'.$_SERVER['QUERY_STRING']:'');
2574 } else return $_SERVER['REQUEST_URI'];
2577 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
2578 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2579 // 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)
2580 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
2581 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
2582 return $_SERVER['PATH_INFO'];
2585 // These are let through without modification
2588 case 'HTTP_REFERER':
2590 case 'HTTP_USER_AGENT':
2591 case 'HTTP_ACCEPT_LANGUAGE':
2592 case 'QUERY_STRING':
2593 return $_SERVER[$getEnvName];
2595 case 'TYPO3_DOCUMENT_ROOT':
2596 // 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.
2597 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2598 $SFN = t3lib_div
::getIndpEnv('SCRIPT_FILENAME');
2599 $SN_A = explode('/',strrev(t3lib_div
::getIndpEnv('SCRIPT_NAME')));
2600 $SFN_A = explode('/',strrev($SFN));
2602 while(list($kk,$vv)=each($SN_A)) {
2603 if (!strcmp($SFN_A[$kk],$vv)) {
2607 $commonEnd=strrev(implode('/',$acc));
2608 if (strcmp($commonEnd,'')) $DR = substr($SFN,0,-(strlen($commonEnd)+
1));
2611 case 'TYPO3_HOST_ONLY':
2612 $p = explode(':',$_SERVER['HTTP_HOST']);
2616 $p = explode(':',$_SERVER['HTTP_HOST']);
2619 case 'TYPO3_REQUEST_HOST':
2620 return (t3lib_div
::getIndpEnv('TYPO3_SSL') ?
'https://' : 'http://').
2621 $_SERVER['HTTP_HOST'];
2623 case 'TYPO3_REQUEST_URL':
2624 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('REQUEST_URI');
2626 case 'TYPO3_REQUEST_SCRIPT':
2627 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('SCRIPT_NAME');
2629 case 'TYPO3_REQUEST_DIR':
2630 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::dirname(t3lib_div
::getIndpEnv('SCRIPT_NAME')).'/';
2632 case 'TYPO3_SITE_URL':
2633 if (defined('PATH_thisScript') && defined('PATH_site')) {
2634 $lPath = substr(dirname(PATH_thisScript
),strlen(PATH_site
)).'/';
2635 $url = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR');
2636 $siteUrl = substr($url,0,-strlen($lPath));
2637 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2641 case 'TYPO3_SITE_SCRIPT':
2642 return substr(t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
2645 return $_SERVER['SSL_SESSION_ID'] ||
!strcmp($_SERVER['HTTPS'],'on') ? TRUE
: FALSE
;
2649 // Here, list ALL possible keys to this function for debug display.
2650 $envTestVars = t3lib_div
::trimExplode(',','
2660 TYPO3_REQUEST_SCRIPT,
2666 TYPO3_DOCUMENT_ROOT,
2671 HTTP_ACCEPT_LANGUAGE',1);
2672 reset($envTestVars);
2673 while(list(,$v)=each($envTestVars)) {
2674 $out[$v]=t3lib_div
::getIndpEnv($v);
2684 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2689 function milliseconds() {
2690 $p=explode(' ',microtime());
2691 return round(($p[0]+
$p[1])*1000);
2695 * Client Browser Information
2698 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2699 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2701 function clientInfo($useragent='') {
2702 if (!$useragent) $useragent=t3lib_div
::getIndpEnv('HTTP_USER_AGENT');
2706 if (strstr($useragent,'Konqueror')) {
2707 $bInfo['BROWSER']= 'konqu';
2708 } elseif (strstr($useragent,'Opera')) {
2709 $bInfo['BROWSER']= 'opera';
2710 } elseif (strstr($useragent,'MSIE 4') ||
strstr($useragent,'MSIE 5') ||
strstr($useragent,'MSIE 6')) {
2711 $bInfo['BROWSER']= 'msie';
2712 } elseif (strstr($useragent,'Mozilla/4') ||
strstr($useragent,'Mozilla/5')) {
2713 $bInfo['BROWSER']='net';
2715 if ($bInfo['BROWSER']) {
2717 switch($bInfo['BROWSER']) {
2719 $bInfo['VERSION']= doubleval(substr($useragent,8));
2720 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2721 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2724 $tmp = strstr($useragent,'MSIE');
2725 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
2728 $tmp = strstr($useragent,'Opera');
2729 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
2732 $tmp = strstr($useragent,'Konqueror/');
2733 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2737 if (strstr($useragent,'Win')) {
2738 $bInfo['SYSTEM'] = 'win';
2739 } elseif (strstr($useragent,'Mac')) {
2740 $bInfo['SYSTEM'] = 'mac';
2741 } elseif (strstr($useragent,'Linux') ||
strstr($useragent,'X11') ||
strstr($useragent,'SGI') ||
strstr($useragent,' SunOS ') ||
strstr($useragent,' HP-UX ')) {
2742 $bInfo['SYSTEM'] = 'unix';
2745 // Is true if the browser supports css to format forms, especially the width
2746 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' ||
($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) ||
$bInfo['BROWSER']=='opera' ||
$bInfo['BROWSER']=='konqu');
2773 /*************************
2775 * TYPO3 SPECIFIC FUNCTIONS
2777 *************************/
2780 * 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.
2783 * @param string The input filename/filepath to evaluate
2784 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2785 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2786 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2788 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2789 if (!strcmp($filename,'')) return '';
2791 if ($relToTYPO3_mainDir) {
2792 if (!defined('PATH_typo3')) return '';
2793 $relPathPrefix = PATH_typo3
;
2795 $relPathPrefix = PATH_site
;
2797 if (substr($filename,0,4)=='EXT:') { // extension
2798 list($extKey,$local) = explode('/',substr($filename,4),2);
2800 if (strcmp($extKey,'') && t3lib_extMgm
::isLoaded($extKey) && strcmp($local,'')) {
2801 $filename = t3lib_extMgm
::extPath($extKey).$local;
2803 } elseif (!t3lib_div
::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2804 $filename=$relPathPrefix.$filename;
2805 } elseif ($onlyRelative && !t3lib_div
::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2808 if (strcmp($filename,'') && t3lib_div
::validPathStr($filename)) { // checks backpath.
2814 * Checks for malicious file paths.
2815 * Returns true if no '//', '..' or '\' is in the $theFile
2816 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2817 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2820 * @param string Filepath to evaluate
2821 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2822 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2824 function validPathStr($theFile) {
2825 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true
;
2829 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
2832 * @param string Filepath to evaluate
2835 function isAbsPath($path) {
2836 return TYPO3_OS
=='WIN' ?
substr($path,1,2)==':/' : substr($path,0,1)=='/';
2840 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
2843 * @param string Filepath to evaluate
2846 function isAllowedAbsPath($path) {
2847 if (t3lib_div
::isAbsPath($path) &&
2848 t3lib_div
::validPathStr($path) &&
2849 ( t3lib_div
::isFirstPartOfStr($path,PATH_site
)
2851 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div
::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
2857 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
2860 * @param string Filepath to evaluate
2863 function verifyFilenameAgainstDenyPattern($filename) {
2864 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
2865 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
2866 if ($result) return false
; // so if a matching filename is found, return false;
2872 * Moves $source file to $destination if uploaded, otherwise try to make a copy
2875 * @param string Source file, absolute path
2876 * @param string Destination file, absolute path
2877 * @return boolean Returns true if the file was moved.
2878 * @coauthor Dennis Petersen <fessor@software.dk>
2879 * @see upload_to_tempfile()
2881 function upload_copy_move($source,$destination) {
2882 if (is_uploaded_file($source)) {
2884 // 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:
2885 $uploadedResult = move_uploaded_file($source, $destination);
2888 @copy
($source,$destination);
2891 // Setting file system mode & group ownership of file:
2892 if (@is_file
($destination) && TYPO3_OS
!='WIN') {
2893 chmod($destination, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask']));
2894 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2895 chgrp($destination, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2899 // 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
2900 return $uploaded ?
$uploadedResult : FALSE
;
2904 * 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.
2905 * Use this function to move uploaded files to where you can work on them.
2906 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
2909 * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
2910 * @return string If a new file was successfully created, return its filename, otherwise blank string.
2911 * @see unlink_tempfile(), upload_copy_move()
2913 function upload_to_tempfile($uploadedFileName) {
2914 if (is_uploaded_file($uploadedFileName)) {
2915 $tempFile = t3lib_div
::tempnam('upload_temp_');
2916 move_uploaded_file($uploadedFileName, $tempFile);
2917 return @is_file
($tempFile) ?
$tempFile : '';
2922 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
2923 * 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.
2924 * Use this after upload_to_tempfile() or tempnam() from this class!
2927 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
2928 * @return boolean Returns true if the file was unlink()'ed
2929 * @see upload_to_tempfile(), tempnam()
2931 function unlink_tempfile($uploadedTempFileName) {
2932 if ($uploadedTempFileName && t3lib_div
::validPathStr($uploadedTempFileName) && t3lib_div
::isFirstPartOfStr($uploadedTempFileName,PATH_site
.'typo3temp/') && @is_file
($uploadedTempFileName)) {
2933 if (unlink($uploadedTempFileName)) return TRUE
;
2938 * Create temporary filename (Create file with unique file name)
2939 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
2940 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
2943 * @param string Prefix to temp file (which will have no extension btw)
2944 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
2945 * @see unlink_tempfile(), upload_to_tempfile()
2947 function tempnam($filePrefix) {
2948 return tempnam(PATH_site
.'typo3temp/',$filePrefix);
2952 * standard authentication code - can't remember what it's used for.
2955 * @param mixed Uid (integer) or record (array)
2956 * @param string List of fields from the record if that is given.
2957 * @return string MD5 hash of 8 chars.
2960 function stdAuthCode($uid_or_record,$fields='') {
2961 if (is_array($uid_or_record)) {
2962 $recCopy_temp=array();
2964 $fieldArr = t3lib_div
::trimExplode(',',$fields,1);
2966 while(list($k,$v)=each($fieldArr)) {
2967 $recCopy_temp[$k]=$recCopy[$v];
2970 $recCopy_temp=$recCopy;
2972 $preKey = implode('|',$recCopy_temp);
2974 $preKey = $uid_or_record;
2977 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
2978 $authCode = substr(md5($authCode),0,8);
2983 * Loads the $TCA (Table Configuration Array) for the $table
2986 * 1) must be configured table (the ctrl-section configured),
2987 * 2) columns must not be an array (which it is always if whole table loaded), and
2988 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
2991 * @param string Table name for which to load the full TCA array part into the global $TCA
2994 function loadTCA($table) {
2995 global $TCA,$LANG_GENERAL_LABELS;
2996 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
2997 if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
2998 include(PATH_t3lib
.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
2999 } elseif (t3lib_div
::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file
($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
3000 include($TCA[$table]['ctrl']['dynamicConfigFile']);
3001 } else include(PATH_typo3conf
.$TCA[$table]['ctrl']['dynamicConfigFile']);
3006 * 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).
3007 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
3010 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3011 * @param string The sheet to return, preferably.
3012 * @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!
3014 function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
3015 if (is_array($dataStructArray['sheets'])) {
3016 $singleSheet = FALSE
;
3017 if (!isset($dataStructArray['sheets'][$sheet])) {
3020 $dataStruct = $dataStructArray['sheets'][$sheet];
3022 // If not an array, but still set, then regard it as a relative reference to a file:
3023 if ($dataStruct && !is_array($dataStruct)) {
3024 $file = t3lib_div
::getFileAbsFileName($dataStruct);
3025 if ($file && @is_file
($file)) {
3026 $dataStruct = t3lib_div
::xml2array(t3lib_div
::getUrl($file));
3030 $singleSheet = TRUE
;
3031 $dataStruct = $dataStructArray;
3032 $sheet = 'sDEF'; // Default sheet
3034 return array($dataStruct,$sheet,$singleSheet);
3038 * Resolves ALL sheet definitions in dataStructArray
3039 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
3041 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3042 * @return array Output data structure with all sheets resolved as arrays.
3044 function resolveAllSheetsInDS($dataStructArray) {
3045 if (is_array($dataStructArray['sheets'])) {
3046 $out=array('sheets'=>array());
3047 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
3048 list($ds,$aS) = t3lib_div
::resolveSheetDefInDS($dataStructArray,$sheetId);
3049 if ($sheetId==$aS) {
3050 $out['sheets'][$aS]=$ds;
3054 list($ds) = t3lib_div
::resolveSheetDefInDS($dataStructArray);
3055 $out = array('sheets' => array('sDEF' => $ds));
3061 * Calls a userdefined function/method in class
3062 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
3065 * @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").
3066 * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
3067 * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
3068 * @param string Required prefix of class or function name
3069 * @param boolean If set, no debug() error message is shown if class/function is not present.
3070 * @return mixed Content from method/function call
3073 function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
3074 global $TYPO3_CONF_VARS;
3076 // Check persistent object and if found, call directly and exit.
3077 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
3078 return call_user_method(
3079 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
3080 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
3086 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3087 if (strstr($funcName,':')) {
3088 list($file,$funcRef) = t3lib_div
::revExplode(':',$funcName,2);
3089 $requireFile = t3lib_div
::getFileAbsFileName($file);
3090 if ($requireFile) require_once($requireFile);
3092 $funcRef = $funcName;
3095 // Check for persistent object token, "&"
3096 if (substr($funcRef,0,1)=='&') {
3097 $funcRef = substr($funcRef,1);
3098 $storePersistentObject = TRUE
;
3100 $storePersistentObject = FALSE
;
3103 // Check prefix is valid:
3105 !t3lib_div
::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
3106 !t3lib_div
::isFirstPartOfStr(trim($funcRef),'tx_')
3108 if (!$silent) debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
3112 // Call function or method:
3113 $parts = explode('->',$funcRef);
3114 if (count($parts)==2) { // Class
3116 // Check if class/method exists:
3117 if (class_exists($parts[0])) {
3119 // Get/Create object of class:
3120 if ($storePersistentObject) { // Get reference to current instance of class:
3121 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
3122 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div
::makeInstance($parts[0]);
3124 $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
3125 } else { // Create new object:
3126 $classObj = &t3lib_div
::makeInstance($parts[0]);
3129 if (method_exists($classObj, $parts[1])) {
3131 // If persistent object should be created, set reference:
3132 if ($storePersistentObject) {
3133 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
3134 'method' => $parts[1],
3139 $content = call_user_method(
3146 if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
3149 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
3151 } else { // Function
3152 if (function_exists($funcRef)) {
3153 $content = call_user_func($funcRef, $params, $ref);
3155 if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
3162 * Creates and returns reference to a user defined object.
3163 * 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.
3166 * @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!).
3167 * @param string Required prefix of class name. By default "tx_" is allowed.
3168 * @param boolean If set, no debug() error message is shown if class/function is not present.
3169 * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
3170 * @see callUserFunction()
3172 function &getUserObj($classRef,$checkPrefix='user_',$silent=0) {
3173 global $TYPO3_CONF_VARS;
3174 // Check persistent object and if found, call directly and exit.
3175 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
3176 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
3179 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3180 if (strstr($classRef,':')) {
3181 list($file,$class) = t3lib_div
::revExplode(':',$classRef,2);
3182 $requireFile = t3lib_div
::getFileAbsFileName($file);
3183 if ($requireFile) require_once($requireFile);
3188 // Check for persistent object token, "&"
3189 if (substr($class,0,1)=='&') {
3190 $class = substr($class,1);
3191 $storePersistentObject = TRUE
;
3193 $storePersistentObject = FALSE
;
3196 // Check prefix is valid:
3198 !t3lib_div
::isFirstPartOfStr(trim($class),$checkPrefix) &&
3199 !t3lib_div
::isFirstPartOfStr(trim($class),'tx_')
3201 if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
3205 // Check if class exists:
3206 if (class_exists($class)) {
3207 $classObj = &t3lib_div
::makeInstance($class);
3209 // If persistent object should be created, set reference:
3210 if ($storePersistentObject) {
3211 $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
3216 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$class,1);
3222 * Make instance of class
3223 * Takes the class-extensions API of TYPO3 into account
3224 * Please USE THIS instead of the PHP "new" keyword. Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
3227 * @param string Class name to instantiate
3228 * @return object The object
3230 function &makeInstance($className) {
3231 return class_exists('ux_'.$className) ? t3lib_div
::makeInstance('ux_'.$className) : new $className;
3235 * Return classname for new instance
3236 * Takes the class-extensions API of TYPO3 into account
3239 * @param string Base Class name to evaluate
3240 * @return string Final class name to instantiate with "new [classname]"
3242 function makeInstanceClassName($className) {
3243 return class_exists('ux_'.$className) ? t3lib_div
::makeInstanceClassName('ux_'.$className) : $className;
3247 * Find the best service and check if it works.
3248 * Returns object of the service class.
3250 * @param string Type of service (service key).
3251 * @param string Sub type like file extensions or similar. Defined by the service.
3252 * @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
3253 * @return object The service object or an array with error info's.
3254 * @author René Fritz <r.fritz@colorcube.de>