2 /***************************************************************
5 * (c) 1999-2005 Kasper Skaarhoj (kasperYYYY@typo3.com)
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
28 * Contains the reknown class "t3lib_div" with general purpose functions
31 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
33 * Usage counts are based on search 22/2 2003 through whole source including tslib/
35 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
38 * [CLASS/FUNCTION INDEX of SCRIPT]
42 * 211: class t3lib_div
44 * SECTION: GET/POST Variables
45 * 241: function _GP($var)
46 * 259: function _GET($var=NULL)
47 * 276: function _POST($var=NULL)
48 * 292: function _GETset($inputGet,$key='')
49 * 315: function GPvar($var,$strip=0)
50 * 332: function GParrayMerged($var)
52 * SECTION: IMAGE FUNCTIONS
53 * 376: function gif_compress($theFile, $type)
54 * 402: function png_to_gif_by_imagemagick($theFile)
55 * 426: function read_png_gif($theFile,$output_png=0)
57 * SECTION: STRING FUNCTIONS
58 * 475: function fixed_lgd($string,$origChars,$preStr='...')
59 * 500: function fixed_lgd_pre($string,$chars)
60 * 514: function fixed_lgd_cs($string,$chars)
61 * 531: function breakTextForEmail($str,$implChar="\n",$charWidth=76)
62 * 550: function breakLinesForEmail($str,$implChar="\n",$charWidth=76)
63 * 585: function cmpIP($baseIP, $list)
64 * 627: function cmpFQDN($baseIP, $list)
65 * 657: function inList($list,$item)
66 * 669: function rmFromList($element,$list)
67 * 687: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0)
68 * 703: function intval_positive($theInt)
69 * 716: function int_from_ver($verNumberStr)
70 * 728: function md5int($str)
71 * 741: function shortMD5($input, $len=10)
72 * 754: function uniqueList($in_list, $secondParameter=NULL)
73 * 768: function split_fileref($fileref)
74 * 805: function dirname($path)
75 * 821: function modifyHTMLColor($color,$R,$G,$B)
76 * 841: function modifyHTMLColorAll($color,$all)
77 * 852: function rm_endcomma($string)
78 * 865: function danish_strtoupper($string)
79 * 880: function convUmlauts($str)
80 * 893: function testInt($var)
81 * 905: function isFirstPartOfStr($str,$partStr)
82 * 921: function formatSize($sizeInBytes,$labels='')
83 * 956: function convertMicrotime($microtime)
84 * 970: function splitCalc($string,$operators)
85 * 992: function calcPriority($string)
86 * 1032: function calcParenthesis($string)
87 * 1058: function htmlspecialchars_decode($value)
88 * 1073: function deHSCentities($str)
89 * 1086: function slashJS($string,$extended=0,$char="'")
90 * 1099: function rawUrlEncodeJS($str)
91 * 1111: function rawUrlEncodeFP($str)
92 * 1122: function validEmail($email)
93 * 1137: function formatForTextarea($content)
95 * SECTION: ARRAY FUNCTIONS
96 * 1168: function inArray($in_array,$item)
97 * 1185: function intExplode($delim, $string)
98 * 1204: function revExplode($delim, $string, $count=0)
99 * 1224: function trimExplode($delim, $string, $onlyNonEmptyValues=0)
100 * 1246: function uniqueArray($valueArray)
101 * 1258: function removeArrayEntryByValue($array,$cmpValue)
102 * 1286: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0)
103 * 1313: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1)
104 * 1336: function addSlashesOnArray(&$theArray)
105 * 1360: function stripSlashesOnArray(&$theArray)
106 * 1382: function slashArray($arr,$cmd)
107 * 1399: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true)
108 * 1432: function array_merge($arr1,$arr2)
109 * 1445: function csvValues($row,$delim=',',$quote='"')
111 * SECTION: HTML/XML PROCESSING
112 * 1487: function get_tag_attributes($tag)
113 * 1524: function split_tag_attributes($tag)
114 * 1558: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
115 * 1585: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE)
116 * 1600: function wrapJS($string, $linebreak=TRUE)
117 * 1630: function xml2tree($string,$depth=999)
118 * 1716: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array())
119 * 1830: function xml2array($string,$NSprefix='',$reportDocTag=FALSE)
120 * 1940: function xmlRecompileFromStructValArray($vals)
121 * 1984: function xmlGetHeaderAttribs($xmlData)
123 * SECTION: FILES FUNCTIONS
124 * 2016: function getURL($url)
125 * 2058: function writeFile($file,$content)
126 * 2075: function fixPermissions($file)
127 * 2092: function writeFileToTypo3tempDir($filepath,$content)
128 * 2135: function mkdir($theNewFolder)
129 * 2155: function get_dirs($path)
130 * 2180: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='')
131 * 2234: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99)
132 * 2257: function removePrefixPathFromList($fileArr,$prefixToRemove)
133 * 2273: function fixWindowsFilePath($theFile)
134 * 2285: function resolveBackPath($pathStr)
135 * 2312: function locationHeaderUrl($path)
137 * SECTION: DEBUG helper FUNCTIONS
138 * 2352: function debug_ordvalue($string,$characters=100)
139 * 2369: function view_array($array_in)
140 * 2397: function print_array($array_in)
141 * 2412: function debug($var="",$brOrHeader=0)
143 * SECTION: SYSTEM INFORMATION
144 * 2481: function getThisUrl()
145 * 2497: function linkThisScript($getParams=array())
146 * 2521: function linkThisUrl($url,$getParams=array())
147 * 2546: function getIndpEnv($getEnvName)
148 * 2735: function milliseconds()
149 * 2747: function clientInfo($useragent='')
151 * SECTION: TYPO3 SPECIFIC FUNCTIONS
152 * 2834: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0)
153 * 2870: function validPathStr($theFile)
154 * 2881: function isAbsPath($path)
155 * 2892: function isAllowedAbsPath($path)
156 * 2909: function verifyFilenameAgainstDenyPattern($filename)
157 * 2927: function upload_copy_move($source,$destination)
158 * 2953: function upload_to_tempfile($uploadedFileName)
159 * 2971: function unlink_tempfile($uploadedTempFileName)
160 * 2987: function tempnam($filePrefix)
161 * 3000: function stdAuthCode($uid_or_record,$fields='')
162 * 3030: function cHashParams($addQueryParams)
163 * 3059: function loadTCA($table)
164 * 3079: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF')
165 * 3109: function resolveAllSheetsInDS($dataStructArray)
166 * 3138: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0)
167 * 3237: function &getUserObj($classRef,$checkPrefix='user_',$silent=0)
168 * 3295: function &makeInstance($className)
169 * 3307: function makeInstanceClassName($className)
170 * 3321: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array())
171 * 3382: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0)
172 * 3427: function quoted_printable($string,$maxlen=76)
173 * 3471: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='')
174 * 3505: function makeRedirectUrl($inUrl,$l=0,$index_script_url='')
175 * 3532: function freetypeDpiComp($font_size)
176 * 3551: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE)
177 * 3572: function arrayToLogString($arr, $valueList=array(), $valueLength=20)
179 * TOTAL FUNCTIONS: 117
180 * (This index is automatically created/updated by the extension "extdeveval")
196 * The legendary "t3lib_div" class - Miscellaneous functions for general purpose.
197 * Most of the functions does not relate specifically to TYPO3
198 * However a section of functions requires certain TYPO3 features available
199 * See comments in the source.
200 * You are encouraged to use this library in your own scripts!
203 * The class is intended to be used without creating an instance of it.
204 * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name.
205 * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()'
207 * @author Kasper Skaarhoj <kasperYYYY@typo3.com>
217 /*************************
222 * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration.
223 * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so.
224 * But the clean solution is that quotes are never escaped and that is what the functions below offers.
225 * Eventually TYPO3 should provide this in the global space as well.
226 * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below.
228 *************************/
231 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
232 * Strips slashes from all output, both strings and arrays.
233 * This function substitutes t3lib_div::GPvar()
234 * 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!
237 * @param string GET/POST var to return
238 * @return mixed POST var named $var and if not set, the GET var of the same name.
242 if(empty($var)) return;
243 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
245 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
251 * Returns the global GET array (or value from) normalized to contain un-escaped values.
252 * ALWAYS use this API function to acquire the GET variables!
255 * @param string Optional pointer to value in GET array (basically name of GET var)
256 * @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!*
257 * @see _POST(), _GP(), _GETset()
259 function _GET($var=NULL) {
260 $value = ($var === NULL) ?
$_GET : (empty($var) ?
NULL : $_GET[$var]);
261 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
262 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
268 * Returns the global POST array (or value from) normalized to contain un-escaped values.
269 * ALWAYS use this API function to acquire the POST variables!
272 * @param string Optional pointer to value in POST array (basically name of POST var)
273 * @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!*
276 function _POST($var=NULL) {
277 $value = ($var === NULL) ?
$_POST : (empty($var) ?
NULL : $_POST[$var]);
278 if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting.
279 if (is_array($value)) { t3lib_div
::stripSlashesOnArray($value); } else { $value = stripslashes($value); }
285 * Writes input value to $_GET
288 * @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).
289 * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value!
292 function _GETset($inputGet,$key='') {
293 // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting).
294 if (strcmp($key,'')) {
295 if (is_array($inputGet)) { t3lib_div
::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); }
296 $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet;
297 } elseif (is_array($inputGet)){
298 t3lib_div
::addSlashesOnArray($inputGet);
299 $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet;
305 * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order)
306 * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped.
309 * @param string GET/POST var to return
310 * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed()
311 * @return mixed POST var named $var and if not set, the GET var of the same name.
312 * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!)
315 function GPvar($var,$strip=0) {
316 if(empty($var)) return;
317 $value = isset($_POST[$var]) ?
$_POST[$var] : $_GET[$var];
318 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.
319 if ($strip && isset($value) && is_array($value)) { t3lib_div
::stripSlashesOnArray($value); }
324 * Returns the GET/POST global arrays merged with POST taking precedence.
327 * @param string Key (variable name) from GET or POST vars
328 * @return array Returns the GET vars merged recursively onto the POST vars.
332 function GParrayMerged($var) {
333 $postA = is_array($_POST[$var]) ?
$_POST[$var] : array();
334 $getA = is_array($_GET[$var]) ?
$_GET[$var] : array();
335 $mergedA = t3lib_div
::array_merge_recursive_overrule($getA,$postA);
336 t3lib_div
::stripSlashesOnArray($mergedA);
349 /*************************
353 *************************/
357 * Compressing a GIF file if not already LZW compressed
358 * 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)
360 * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file
362 * 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!)
363 * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively
367 * $theFile is expected to be a valid GIF-file!
368 * The function returns a code for the operation.
371 * @param string Filepath
372 * @param string See description of function
373 * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string.
376 function gif_compress($theFile, $type) {
377 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
379 if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF...
380 if (($type=='IM' ||
!$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM
381 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']);
385 } elseif (($type=='GD' ||
!$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD
386 $tempImage = imageCreateFromGif($theFile);
387 imageGif($tempImage, $theFile);
388 imageDestroy($tempImage);
396 * Converts a png file to gif
397 * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true.
400 * @param string $theFile the filename with path
401 * @return string new filename
404 function png_to_gif_by_imagemagick($theFile) {
405 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif']
406 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im']
407 && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw']
408 && strtolower(substr($theFile,-4,4))=='.png'
409 && @is_file
($theFile)) { // IM
410 $newFile = substr($theFile,0,-4).'.gif';
411 $cmd = t3lib_div
::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $gfxConf['im_path_lzw']);
414 // 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!!
420 * Returns filename of the png/gif version of the input file (which can be png or gif).
421 * If input file type does not match the wanted output type a conversion is made and temp-filename returned.
424 * @param string Filepath of image file
425 * @param boolean If set, then input file is converted to PNG, otherwise to GIF
426 * @return string If the new image file exists, it's filepath is returned
429 function read_png_gif($theFile,$output_png=0) {
430 if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file
($theFile)) {
431 $ext = strtolower(substr($theFile,-4,4));
433 ((string)$ext=='.png' && $output_png) ||
434 ((string)$ext=='.gif' && !$output_png)
438 $newFile = PATH_site
.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?
'.png':'.gif');
439 exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"');
440 if (@is_file
($newFile)) return $newFile;
459 /*************************
463 *************************/
467 * Returns a new string of max. $chars length.
468 * If the string is longer, it will be truncated and appended with '...'.
469 * DEPRECATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
472 * @param string string to truncate
473 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
474 * @param string String to append to the output if it is truncated, default is '...'
475 * @return string new string
476 * @see fixed_lgd_pre()
478 function fixed_lgd($string,$origChars,$preStr='...') {
479 $chars = abs($origChars);
481 if(strlen($string)>$chars) {
482 return $origChars < 0 ?
483 $preStr.trim(substr($string, -($chars-3))) :
484 trim(substr($string, 0, $chars-3)).$preStr;
492 * Returns a new string of max. $chars length.
493 * If the string is longer, it will be truncated and prepended with '...'.
494 * This works like fixed_lgd, but is truncated in the start of the string instead of the end
495 * DEPRECATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
498 * @param string string to truncate
499 * @param integer must be an integer of at least 4
500 * @return string new string
503 function fixed_lgd_pre($string,$chars) {
504 return strrev(t3lib_div
::fixed_lgd(strrev($string),$chars));
508 * Truncates a string with appended/prepended "..." and takes backend character set into consideration
509 * Use only from backend!
512 * @param string string to truncate
513 * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
514 * @return string New string
517 function fixed_lgd_cs($string,$chars) {
518 if (is_object($GLOBALS['LANG'])) {
519 return $GLOBALS['LANG']->csConvObj
->crop($GLOBALS['LANG']->charSet
,$string,$chars,'...');
521 return t3lib_div
::fixed_lgd($string, $chars);
526 * Breaks up the text for emails
529 * @param string The string to break up
530 * @param string The string to implode the broken lines with (default/typically \n)
531 * @param integer The line length
534 function breakTextForEmail($str,$implChar="\n",$charWidth=76) {
535 $lines = explode(chr(10),$str);
537 while(list(,$lStr)=each($lines)) {
538 $outArr = array_merge($outArr,t3lib_div
::breakLinesForEmail($lStr,$implChar,$charWidth));
540 return implode(chr(10),$outArr);
544 * Breaks up a single line of text for emails
547 * @param string The string to break up
548 * @param string The string to implode the broken lines with (default/typically \n)
549 * @param integer The line length
551 * @see breakTextForEmail()
553 function breakLinesForEmail($str,$implChar="\n",$charWidth=76) {
557 while(strlen($str)>$p) {
558 $substr=substr($str,$p,$l);
559 if (strlen($substr)==$l) {
560 $count = count(explode(' ',trim(strrev($substr))));
561 if ($count>1) { // OK...
562 $parts = explode(' ',strrev($substr),2);
563 $theLine = strrev($parts[1]);
565 $afterParts = explode(' ',substr($str,$l+
$p),2);
566 $theLine = $substr.$afterParts[0];
568 if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop.
573 $lines[]=trim($theLine);
574 $p+
=strlen($theLine);
575 if (!trim(substr($str,$p,$l))) break; // added...
577 return implode($implChar,$lines);
581 * Match IP number with list of numbers with wildcard
584 * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
585 * @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)
586 * @return boolean True if an IP-mask from $list matches $baseIP
588 function cmpIP($baseIP, $list) {
589 $IPpartsReq = explode('.',$baseIP);
590 if (count($IPpartsReq)==4) {
591 $values = t3lib_div
::trimExplode(',',$list,1);
593 foreach($values as $test) {
594 list($test,$mask) = explode('/',$test);
598 $lnet = ip2long($test);
599 $lip = ip2long($baseIP);
600 $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT');
601 $firstpart = substr($binnet,0,$mask);
602 $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT');
603 $firstip = substr($binip,0,$mask);
604 $yes = (strcmp($firstpart,$firstip)==0);
607 $IPparts = explode('.',$test);
610 while(list($index,$val)=each($IPparts)) {
612 if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) {
617 if ($yes) return true;
624 * Match fully qualified domain name with list of strings with wildcard
626 * @param string The current remote IP address for instance, typ. REMOTE_ADDR
627 * @param string A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
628 * @return boolean True if a domain name mask from $list matches $baseIP
630 function cmpFQDN($baseIP, $list) {
631 if (count(explode('.',$baseIP))==4) {
632 $resolvedHostName = explode('.', gethostbyaddr($baseIP));
633 $values = t3lib_div
::trimExplode(',',$list,1);
635 foreach($values as $test) {
636 $hostNameParts = explode('.',$test);
639 foreach($hostNameParts as $index => $val) {
641 if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) {
645 if ($yes) return true;
652 * Check for item in list
653 * Check if an item exists in a comma-separated list of items.
656 * @param string comma-separated list of items (string)
657 * @param string item to check for
658 * @return boolean true if $item is in $list
660 function inList($list,$item) {
661 return strstr(','.$list.',', ','.$item.',') ?
true : false;
665 * Removes an item from a comma-separated list of items.
668 * @param string element to remove
669 * @param string comma-separated list of items (string)
670 * @return string new comma-separated list of items
672 function rmFromList($element,$list) {
673 $items = explode(',',$list);
674 while(list($k,$v)=each($items)) {
675 if ($v==$element) {unset($items[$k]);}
677 return implode(',',$items);
681 * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
682 * Ranges are limited to 1000 values per range.
684 * @param string comma-separated list of integers with ranges (string)
685 * @return string new comma-separated list of items
686 * @author Martin Kutschker <martin.kutschker@activesolution.at>
688 function expandList($list) {
689 $items = explode(',',$list);
691 while(list(,$item)=each($items)) {
692 $range = explode('-',$item);
693 if (isset($range[1])) {
694 $runAwayBrake = 1000;
695 for ($n=$range[0]; $n<=$range[1]; $n++
) {
699 if ($runAwayBrake<=0) break;
706 return implode(',',$list);
710 * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied.
713 * @param integer Input value
714 * @param integer Lower limit
715 * @param integer Higher limit
716 * @param integer Default value if input is false.
717 * @return integer The input value forced into the boundaries of $min and $max
719 function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) {
720 // Returns $theInt as an integer in the integerspace from $min to $max
721 $theInt = intval($theInt);
722 if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it.
723 if ($theInt<$min){$theInt=$min;}
724 if ($theInt>$max){$theInt=$max;}
729 * Returns the $integer if greater than zero, otherwise returns zero.
732 * @param integer Integer string to process
735 function intval_positive($theInt) {
736 $theInt = intval($theInt);
737 if ($theInt<0){$theInt=0;}
742 * Returns an integer from a three part version number, eg '4.12.3' -> 4012003
745 * @param string Version number on format x.x.x
746 * @return integer Integer version of version number (where each part can count to 999)
748 function int_from_ver($verNumberStr) {
749 $verParts = explode('.',$verNumberStr);
750 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
));
754 * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
757 * @param string String to md5-hash
758 * @return integer Returns 28bit integer-hash
760 function md5int($str) {
761 return hexdec(substr(md5($str),0,7));
765 * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently)
769 * @param string Input string to be md5-hashed
770 * @param integer The string-length of the output
771 * @return string Substring of the resulting md5-hash, being $len chars long (from beginning)
773 function shortMD5($input, $len=10) {
774 return substr(md5($input),0,$len);
778 * Takes comma-separated lists and arrays and removes all duplicates
779 * If a value in the list is trim(empty), the value is ignored.
782 * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays.
783 * @param mixed $secondParameter: Dummy field, which if set will show a warning!
784 * @return string Returns the list without any duplicates of values, space around values are trimmed
786 function uniqueList($in_list, $secondParameter=NULL) {
787 if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!');
788 if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.');
790 return implode(',',array_unique(t3lib_div
::trimExplode(',',$in_list,1)));
794 * Splits a reference to a file in 5 parts
797 * @param string Filename/filepath to be analysed
798 * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext]
800 function split_fileref($fileref) {
801 if ( ereg('(.*/)(.*)$',$fileref,$reg) ) {
802 $info['path'] = $reg[1];
803 $info['file'] = $reg[2];
806 $info['file'] = $fileref;
809 if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) {
810 $info['filebody'] = $reg[1];
811 $info['fileext'] = strtolower($reg[2]);
812 $info['realFileext'] = $reg[2];
814 $info['filebody'] = $info['file'];
815 $info['fileext'] = '';
822 * Returns the directory part of a path without trailing slash
823 * If there is no dir-part, then an empty string is returned.
826 * '/dir1/dir2/script.php' => '/dir1/dir2'
827 * '/dir1/' => '/dir1'
828 * 'dir1/script.php' => 'dir1'
829 * 'd/script.php' => 'd'
830 * '/script.php' => ''
834 * @param string Directory name / path
835 * @return string Processed input value. See function description.
837 function dirname($path) {
838 $p=t3lib_div
::revExplode('/',$path,2);
839 return count($p)==2?
$p[0]:'';
843 * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers
846 * @param string A hexadecimal color code, #xxxxxx
847 * @param integer Offset value 0-255
848 * @param integer Offset value 0-255
849 * @param integer Offset value 0-255
850 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
851 * @see modifyHTMLColorAll()
853 function modifyHTMLColor($color,$R,$G,$B) {
854 // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color
855 $nR = t3lib_div
::intInRange(hexdec(substr($color,1,2))+
$R,0,255);
856 $nG = t3lib_div
::intInRange(hexdec(substr($color,3,2))+
$G,0,255);
857 $nB = t3lib_div
::intInRange(hexdec(substr($color,5,2))+
$B,0,255);
859 substr('0'.dechex($nR),-2).
860 substr('0'.dechex($nG),-2).
861 substr('0'.dechex($nB),-2);
865 * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels
868 * @param string A hexadecimal color code, #xxxxxx
869 * @param integer Offset value 0-255 for all three channels.
870 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars
871 * @see modifyHTMLColor()
873 function modifyHTMLColorAll($color,$all) {
874 return t3lib_div
::modifyHTMLColor($color,$all,$all,$all);
878 * Removes comma (if present) in the end of string
881 * @param string String from which the comma in the end (if any) will be removed.
884 function rm_endcomma($string) {
885 return ereg_replace(',$','',$string);
889 * strtoupper which converts danish (and other characters) characters as well
890 * (DEPRECATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in <span class="uppercase">...</span>)
893 * @param string String to process
897 function danish_strtoupper($string) {
898 $value = strtoupper($string);
899 return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ');
903 * Change umlaut characters to plain ASCII with normally two character target
904 * Only known characters will be converted, so don't expect a result for any character.
905 * (DEPRECATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!)
909 * @param string String to convert.
912 function convUmlauts($str) {
913 $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' );
914 $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' );
915 return preg_replace($pat,$repl,$str);
919 * Tests if the input is an integer.
922 * @param mixed Any input variable to test.
923 * @return boolean Returns true if string is an integer
925 function testInt($var) {
926 return !strcmp($var,intval($var));
930 * Returns true if the first part of $str matches the string $partStr
933 * @param string Full string to check
934 * @param string Reference string which must be found as the "first part" of the full string
935 * @return boolean True if $partStr was found to be equal to the first part of $str
937 function isFirstPartOfStr($str,$partStr) {
938 // Returns true, if the first part of a $str equals $partStr and $partStr is not ''
939 $psLen = strlen($partStr);
941 return substr($str,0,$psLen)==(string)$partStr;
946 * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
949 * @param integer Number of bytes to format.
950 * @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)
951 * @return string Formatted representation of the byte number, for output.
953 function formatSize($sizeInBytes,$labels='') {
956 if (strlen($labels) == 0) {
957 $labels = ' | K| M| G';
959 $labels = str_replace('"','',$labels);
961 $labelArr = explode('|',$labels);
964 if ($sizeInBytes>900) {
965 if ($sizeInBytes>900000000) { // GB
966 $val = $sizeInBytes/(1024*1024*1024);
967 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[3];
969 elseif ($sizeInBytes>900000) { // MB
970 $val = $sizeInBytes/(1024*1024);
971 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[2];
973 $val = $sizeInBytes/(1024);
974 return number_format($val, (($val<20)?
1:0), '.', '').$labelArr[1];
977 return $sizeInBytes.$labelArr[0];
982 * Returns microtime input to milliseconds
985 * @param string Microtime
986 * @return integer Microtime input string converted to an integer (milliseconds)
988 function convertMicrotime($microtime) {
989 $parts = explode(' ',$microtime);
990 return round(($parts[0]+
$parts[1])*1000);
994 * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
997 * @param string Input string, eg "123 + 456 / 789 - 4"
998 * @param string Operators to split by, typically "/+-*"
999 * @return array Array with operators and operands separated.
1000 * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset()
1002 function splitCalc($string,$operators) {
1006 $valueLen=strcspn($string,$operators);
1007 $value=substr($string,0,$valueLen);
1008 $res[] = Array($sign,trim($value));
1009 $sign=substr($string,$valueLen,1);
1010 $string=substr($string,$valueLen+
1);
1017 * Calculates the input by +,-,*,/,%,^ with priority to + and -
1020 * @param string Input string, eg "123 + 456 / 789 - 4"
1021 * @return integer Calculated value. Or error string.
1022 * @see calcParenthesis()
1024 function calcPriority($string) {
1025 $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace
1026 $string='+'.$string; // Ensuring an operator for the first entrance
1028 $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)';
1029 // split the expression here:
1030 preg_match_all('/'.$regex.'/',$string,$reg);
1036 $buffer=doubleval(current($reg[2]));
1037 next($reg[2]); // Advance pointer
1038 while(list($k,$v)=each($reg[2])) {
1040 $sign = $reg[1][$k];
1041 if ($sign=='+' ||
$sign=='-') {
1042 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1046 if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';}
1047 if ($sign=='%') {if ($v) $buffer%
=$v; else $err='dividing by zero';}
1048 if ($sign=='*') {$buffer*=$v;}
1049 if ($sign=='^') {$buffer=pow($buffer,$v);}
1052 $number = $Msign=='-' ?
$number-=$buffer : $number+
=$buffer;
1053 return $err ?
'ERROR: '.$err : $number;
1057 * Calculates the input with parenthesis levels
1060 * @param string Input string, eg "(123 + 456) / 789 - 4"
1061 * @return integer Calculated value. Or error string.
1062 * @see calcPriority(), tslib_cObj::stdWrap()
1064 function calcParenthesis($string) {
1067 $valueLenO=strcspn($string,'(');
1068 $valueLenC=strcspn($string,')');
1069 if ($valueLenC==strlen($string) ||
$valueLenC < $valueLenO) {
1070 $value = t3lib_div
::calcPriority(substr($string,0,$valueLenC));
1071 $string = $value.substr($string,$valueLenC+
1);
1074 $string = substr($string,0,$valueLenO).t3lib_div
::calcParenthesis(substr($string,$valueLenO+
1));
1078 if ($securC<=0) break;
1079 } while($valueLenO<strlen($string));
1084 * Inverse version of htmlspecialchars()
1087 * @param string Value where >, <, " and & should be converted to regular chars.
1088 * @return string Converted result.
1090 function htmlspecialchars_decode($value) {
1091 $value = str_replace('>','>',$value);
1092 $value = str_replace('<','<',$value);
1093 $value = str_replace('"','"',$value);
1094 $value = str_replace('&','&',$value);
1099 * Re-converts HTML entities if they have been converted by htmlspecialchars()
1102 * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to ""
1103 * @return string Converted result.
1105 function deHSCentities($str) {
1106 return ereg_replace('&([#[:alnum:]]*;)','&\1',$str);
1110 * This function is used to escape any ' -characters when transferring text to JavaScript!
1113 * @param string String to escape
1114 * @param boolean If set, also backslashes are escaped.
1115 * @param string The character to escape, default is ' (single-quote)
1116 * @return string Processed input string
1118 function slashJS($string,$extended=0,$char="'") {
1119 if ($extended) {$string = str_replace ("\\", "\\\\", $string);}
1120 return str_replace ($char, "\\".$char, $string);
1124 * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters.
1125 * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc.
1128 * @param string String to raw-url-encode with spaces preserved
1129 * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces.
1131 function rawUrlEncodeJS($str) {
1132 return str_replace('%20',' ',rawurlencode($str));
1136 * rawurlencode which preserves "/" chars
1137 * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded.
1140 * @param string Input string
1141 * @return string Output string
1143 function rawUrlEncodeFP($str) {
1144 return str_replace('%2F','/',rawurlencode($str));
1148 * Checking syntax of input email address
1151 * @param string Input string to evaluate
1152 * @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.
1154 function validEmail($email) {
1155 $email = trim ($email);
1156 if (strstr($email,' ')) return FALSE;
1157 return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ?
TRUE : FALSE;
1161 * Formats a string for output between <textarea>-tags
1162 * All content outputted in a textarea form should be passed through this function
1163 * 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!
1166 * @param string Input string to be formatted.
1167 * @return string Formatted for <textarea>-tags
1169 function formatForTextarea($content) {
1170 return chr(10).htmlspecialchars($content);
1184 /*************************
1188 *************************/
1191 * Check if an item exists in an array
1192 * Please note that the order of parameters is reverse compared to the php4-function in_array()!!!
1195 * @param array one-dimensional array of items
1196 * @param string item to check for
1197 * @return boolean true if $item is in the one-dimensional array $in_array
1200 function inArray($in_array,$item) {
1201 if (is_array($in_array)) {
1202 while (list(,$val)=each($in_array)) {
1203 if (!is_array($val) && !strcmp($val,$item)) return true;
1209 * Explodes a $string delimited by $delim and passes each item in the array through intval().
1210 * Corresponds to explode(), but with conversion to integers for all values.
1213 * @param string Delimiter string to explode with
1214 * @param string The string to explode
1215 * @return array Exploded values, all converted to integers
1217 function intExplode($delim, $string) {
1218 $temp = explode($delim,$string);
1219 while(list($key,$val)=each($temp)) {
1220 $temp[$key]=intval($val);
1227 * Reverse explode which explodes the string counting from behind.
1228 * Thus t3lib_div::revExplode(':','my:words:here',2) will return array('my:words','here')
1231 * @param string Delimiter string to explode with
1232 * @param string The string to explode
1233 * @param integer Number of array entries
1234 * @return array Exploded values
1236 function revExplode($delim, $string, $count=0) {
1237 $temp = explode($delim,strrev($string),$count);
1238 while(list($key,$val)=each($temp)) {
1239 $temp[$key]=strrev($val);
1241 $temp=array_reverse($temp);
1247 * Explodes a string and trims all values for whitespace in the ends.
1248 * If $onlyNonEmptyValues is set, then all blank ('') values are removed.
1251 * @param string Delimiter string to explode with
1252 * @param string The string to explode
1253 * @param boolean If set, all empty values (='') will NOT be set in output
1254 * @return array Exploded values
1256 function trimExplode($delim, $string, $onlyNonEmptyValues=0) {
1257 $temp = explode($delim,$string);
1259 while(list($key,$val)=each($temp)) {
1260 if (!$onlyNonEmptyValues ||
strcmp('',trim($val))) {
1261 $newtemp[]=trim($val);
1269 * Remove duplicate values from an array
1270 * This function is deprecated, use the PHP function array_unique instead
1273 * @param array Array of values to make unique
1278 function uniqueArray($valueArray) {
1279 return array_unique($valueArray);
1283 * Removes the value $cmpValue from the $array if found there. Returns the modified array
1286 * @param array Array containing the values
1287 * @param string Value to search for and if found remove array entry where found.
1288 * @return array Output array with entries removed if search string is found
1290 function removeArrayEntryByValue($array,$cmpValue) {
1291 if (is_array($array)) {
1293 while(list($k,$v)=each($array)) {
1295 $array[$k] = t3lib_div
::removeArrayEntryByValue($v,$cmpValue);
1297 if (!strcmp($v,$cmpValue)) {
1308 * Implodes a multidim-array into GET-parameters (eg. ¶m[key][key2]=value2¶m[key][key3]=value3)
1311 * @param string Name prefix for entries. Set to blank if you wish none.
1312 * @param array The (multidim) array to implode
1313 * @param string (keep blank)
1314 * @param boolean If set, parameters which were blank strings would be removed.
1315 * @param boolean If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.
1316 * @return string Imploded result, fx. ¶m[key][key2]=value2¶m[key][key3]=value3
1317 * @see explodeUrl2Array()
1319 function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) {
1320 if (is_array($theArray)) {
1321 foreach($theArray as $Akey => $AVal) {
1322 $thisKeyName = $name ?
$name.'['.$Akey.']' : $Akey;
1323 if (is_array($AVal)) {
1324 $str = t3lib_div
::implodeArrayForUrl($thisKeyName,$AVal,$str,$skipBlank,$rawurlencodeParamName);
1326 if (!$skipBlank ||
strcmp($AVal,'')) {
1327 $str.='&'.($rawurlencodeParamName ?
rawurlencode($thisKeyName) : $thisKeyName).
1328 '='.rawurlencode($AVal);
1337 * Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array
1339 * @param string GETvars string
1340 * @param boolean If set, the string will be parsed into a multidimensional array if square brackets are used in variable names (using PHP function parse_str())
1341 * @return array Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!
1342 * @see implodeArrayForUrl()
1344 function explodeUrl2Array($string,$multidim=FALSE) {
1346 parse_str($string,$tempGetVars);
1347 return $tempGetVars;
1350 $p = explode('&',$string);
1353 list($pK,$pV) = explode('=',$v,2);
1354 $output[rawurldecode($pK)] = rawurldecode($pV);
1362 * Returns an array with selected keys from incoming data.
1363 * (Better read source code if you want to find out...)
1366 * @param string List of variable/key names
1367 * @param array Array from where to get values based on the keys in $varList
1368 * @param boolean If set, then t3lib_div::_GP() is used to fetch the value if not found (isset) in the $getArray
1369 * @return array Output array with selected variables.
1371 function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) {
1372 $keys = t3lib_div
::trimExplode(',',$varList,1);
1374 foreach($keys as $v) {
1375 if (isset($getArray[$v])) {
1376 $outArr[$v]=$getArray[$v];
1377 } elseif ($GPvarAlt) {
1378 $outArr[$v]=t3lib_div
::_GP($v);
1386 * This function traverses a multidimentional array and adds slashes to the values.
1387 * NOTE that the input array is and argument by reference.!!
1388 * Twin-function to stripSlashesOnArray
1391 * @param array Multidimensional input array, (REFERENCE!)
1394 function addSlashesOnArray(&$theArray) {
1395 if (is_array($theArray)) {
1397 while(list($Akey,$AVal)=each($theArray)) {
1398 if (is_array($AVal)) {
1399 t3lib_div
::addSlashesOnArray($theArray[$Akey]);
1401 $theArray[$Akey] = addslashes($AVal);
1410 * This function traverses a multidimentional array and strips slashes to the values.
1411 * NOTE that the input array is and argument by reference.!!
1412 * Twin-function to addSlashesOnArray
1415 * @param array Multidimensional input array, (REFERENCE!)
1418 function stripSlashesOnArray(&$theArray) {
1419 if (is_array($theArray)) {
1421 while(list($Akey,$AVal)=each($theArray)) {
1422 if (is_array($AVal)) {
1423 t3lib_div
::stripSlashesOnArray($theArray[$Akey]);
1425 $theArray[$Akey] = stripslashes($AVal);
1433 * Either slashes ($cmd=add) or strips ($cmd=strip) array $arr depending on $cmd
1436 * @param array Multidimensional input array
1437 * @param string "add" or "strip", depending on usage you wish.
1440 function slashArray($arr,$cmd) {
1441 if ($cmd=='strip') t3lib_div
::stripSlashesOnArray($arr);
1442 if ($cmd=='add') t3lib_div
::addSlashesOnArray($arr);
1447 * Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the first array ($arr0) with the values of the second array ($arr1)
1448 * In case of identical keys, ie. keeping the values of the second.
1451 * @param array First array
1452 * @param array Second array, overruling the first array
1453 * @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.
1454 * @param boolean If set, values from $arr1 will overrule if they are empty. Default: true
1455 * @return array Resulting array where $arr1 values has overruled $arr0 values
1457 function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) {
1459 while(list($key,$val) = each($arr1)) {
1460 if(is_array($arr0[$key])) {
1461 if (is_array($arr1[$key])) {
1462 $arr0[$key] = t3lib_div
::array_merge_recursive_overrule($arr0[$key],$arr1[$key],$notAddKeys);
1466 if (isset($arr0[$key])) {
1467 if ($includeEmtpyValues OR $val) {
1472 if ($includeEmtpyValues OR $val) {
1483 * 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.
1486 * @param array First array
1487 * @param array Second array
1488 * @return array Merged result.
1490 function array_merge($arr1,$arr2) {
1495 * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
1498 * @param array Input array of values
1499 * @param string Delimited, default is comman
1500 * @param string Quote-character to wrap around the values.
1501 * @return string A single line of CSV
1503 function csvValues($row,$delim=',',$quote='"') {
1506 while(list(,$value)=each($row)) {
1507 list($valPart) = explode(chr(10),$value);
1508 $valPart = trim($valPart);
1509 $out[]=str_replace($quote,$quote.$quote,$valPart);
1511 $str = $quote.implode($quote.$delim.$quote,$out).$quote;
1530 /*************************
1532 * HTML/XML PROCESSING
1534 *************************/
1537 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
1538 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
1539 * 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()
1542 * @param string HTML-tag string (or attributes only)
1543 * @return array Array with the attribute values.
1545 function get_tag_attributes($tag) {
1546 $components = t3lib_div
::split_tag_attributes($tag);
1547 $name = ''; // attribute name is stored here
1549 if (is_array($components)) {
1550 while (list($key,$val) = each ($components)) {
1551 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
1554 $attributes[$name] = $val;
1558 if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val))) {
1559 $attributes[$key] = '';
1568 if (is_array($attributes)) reset($attributes);
1574 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
1575 * Removes tag-name if found
1578 * @param string HTML-tag string (or attributes only)
1579 * @return array Array with the attribute values.
1582 function split_tag_attributes($tag) {
1583 $tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
1584 // Removes any > in the end of the string
1585 $tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));
1587 while (strcmp($tag_tmp,'')) { // Compared with empty string instead , 030102
1588 $firstChar=substr($tag_tmp,0,1);
1589 if (!strcmp($firstChar,'"') ||
!strcmp($firstChar,"'")) {
1590 $reg=explode($firstChar,$tag_tmp,3);
1592 $tag_tmp=trim($reg[2]);
1593 } elseif (!strcmp($firstChar,'=')) {
1595 $tag_tmp = trim(substr($tag_tmp,1)); // Removes = chars.
1597 // There are '' around the value. We look for the next ' ' or '>'
1598 $reg = split('[[:space:]=]',$tag_tmp,2);
1599 $value[] = trim($reg[0]);
1600 $tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
1603 if (is_array($value)) reset($value);
1608 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1611 * @param array Array with attribute key/value pairs, eg. "bgcolor"=>"red", "border"=>0
1612 * @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!
1613 * @param boolean If true, don't check if values are blank. Default is to omit attributes with blank values.
1614 * @return string Imploded attributes, eg. 'bgcolor="red" border="0"'
1616 function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1617 if (is_array($arr)) {
1620 foreach($arr as $p => $v) {
1621 if (!isset($newArr[strtolower($p)])) $newArr[strtolower($p)] = htmlspecialchars($v);
1626 foreach($arr as $p => $v) {
1627 if (strcmp($v,'') ||
$dontOmitBlankAttribs) {$list[]=$p.'="'.$v.'"';}
1629 return implode(' ',$list);
1634 * Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
1636 * @param array See implodeAttributes()
1637 * @param boolean See implodeAttributes()
1638 * @param boolean See implodeAttributes()
1639 * @return string See implodeAttributes()
1640 * @deprecated Name was changed into implodeAttributes
1641 * @see implodeAttributes()
1643 function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) {
1644 return t3lib_div
::implodeAttributes($arr,$xhtmlSafe,$dontOmitBlankAttribs);
1648 * Wraps JavaScript code XHTML ready with <script>-tags
1649 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1650 * This is nice for identing JS code with PHP code on the same level.
1652 * @param string JavaScript code
1653 * @param boolean Wrap script element in linebreaks? Default is TRUE.
1654 * @return string The wrapped JS code, ready to put into a XHTML page
1655 * @author Ingmar Schlecht <ingmars@web.de>
1656 * @author René Fritz <r.fritz@colorcube.de>
1658 function wrapJS($string, $linebreak=TRUE) {
1660 // <script wrapped in nl?
1661 $cr = $linebreak?
"\n" : '';
1663 // remove nl from the beginning
1664 $string = preg_replace ('/^\n+/', '', $string);
1665 // re-ident to one tab using the first line as reference
1666 if(preg_match('/^(\t+)/',$string,$match)) {
1667 $string = str_replace($match[1],"\t", $string);
1669 $string = $cr.'<script type="text/javascript">
1675 return trim($string);
1680 * Parses XML input into a PHP array with associative keys
1683 * @param string XML data input
1684 * @param integer Number of element levels to resolve the XML into an array. Any further structure will be set as XML.
1685 * @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.
1686 * @author bisqwit at iki dot fi dot not dot for dot ads dot invalid / http://dk.php.net/xml_parse_into_struct + kasperYYYY@typo3.com
1688 function xml2tree($string,$depth=999) {
1689 $parser = xml_parser_create();
1693 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1694 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1695 xml_parse_into_struct($parser, $string, $vals, $index);
1697 if (xml_get_error_code($parser)) return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1698 xml_parser_free($parser);
1700 $stack = array( array() );
1705 foreach($vals as $key => $val) {
1706 $type = $val['type'];
1709 if ($type=='open' ||
$type=='complete') {
1710 $stack[$stacktop++
] = $tagi;
1712 if ($depth==$stacktop) {
1716 $tagi = array('tag' => $val['tag']);
1718 if(isset($val['attributes'])) $tagi['attrs'] = $val['attributes'];
1719 if(isset($val['value'])) $tagi['values'][] = $val['value'];
1722 if ($type=='complete' ||
$type=='close') {
1724 $tagi = $stack[--$stacktop];
1725 $oldtag = $oldtagi['tag'];
1726 unset($oldtagi['tag']);
1728 if ($depth==($stacktop+
1)) {
1729 if ($key-$startPoint > 0) {
1730 $partArray = array_slice(
1735 #$oldtagi=array('XMLvalue'=>t3lib_div::xmlRecompileFromStructValArray($partArray));
1736 $oldtagi['XMLvalue']=t3lib_div
::xmlRecompileFromStructValArray($partArray);
1738 $oldtagi['XMLvalue']=$oldtagi['values'][0];
1742 $tagi['ch'][$oldtag][] = $oldtagi;
1746 if($type=='cdata') {
1747 $tagi['values'][] = $val['value'];
1754 * Converts a PHP array into an XML string.
1755 * The XML output is optimized for readability since associative keys are used as tagnames.
1756 * 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.
1757 * Numeric keys are stored with the default tagname "numIndex" but can be overridden to other formats)
1758 * 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
1759 * 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.
1760 * The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances.
1761 * 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...
1764 * @param array The input PHP array with any kind of data; text, binary, integers. Not objects though.
1765 * @param string tag-prefix, eg. a namespace prefix like "T3:"
1766 * @param integer Current recursion level. Don't change, stay at zero!
1767 * @param string Alternative document tag. Default is "phparray".
1768 * @param integer If set, the number of spaces corresponding to this number is used for indenting, otherwise a single chr(9) (TAB) is used
1769 * @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')
1770 * @param string Stack data. Don't touch.
1771 * @return string An XML string made from the input content in the array.
1774 function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array()) {
1775 // 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
1776 $binaryChars = chr(0).chr(1).chr(2).chr(3).chr(4).chr(5).chr(6).chr(7).chr(8).
1777 chr(11).chr(12).chr(14).chr(15).chr(16).chr(17).chr(18).chr(19).
1778 chr(20).chr(21).chr(22).chr(23).chr(24).chr(25).chr(26).chr(27).chr(28).chr(29).
1780 // Set indenting mode:
1781 $indentChar = $spaceInd ?
' ' : chr(9);
1782 $indentN = $spaceInd>0 ?
$spaceInd : 1;
1784 // Init output variable:
1787 // Traverse the input array
1788 if (is_array($array)) {
1789 foreach($array as $k=>$v) {
1793 // Construct the tag name.
1794 if(isset($options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']])) { // Use tag based on grand-parent + parent tag name
1795 $attr.=' index="'.htmlspecialchars($tagName).'"';
1796 $tagName = (string)$options['grandParentTagMap'][$stackData['grandParentTagName'].'/'.$stackData['parentTagName']];
1797 }elseif(isset($options['parentTagMap'][$stackData['parentTagName'].':'.$tagName])) { // Use tag based on parent tag name + current tag
1798 $attr.=' index="'.htmlspecialchars($tagName).'"';
1799 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName'].':'.$tagName];
1800 } elseif(isset($options['parentTagMap'][$stackData['parentTagName']])) { // Use tag based on parent tag name:
1801 $attr.=' index="'.htmlspecialchars($tagName).'"';
1802 $tagName = (string)$options['parentTagMap'][$stackData['parentTagName']];
1803 } elseif (!strcmp(intval($tagName),$tagName)) { // If integer...;
1804 if ($options['useNindex']) { // If numeric key, prefix "n"
1805 $tagName = 'n'.$tagName;
1806 } else { // Use special tag for num. keys:
1807 $attr.=' index="'.$tagName.'"';
1808 $tagName = $options['useIndexTagForNum'] ?
$options['useIndexTagForNum'] : 'numIndex';
1810 } elseif($options['useIndexTagForAssoc']) { // Use tag for all associative keys:
1811 $attr.=' index="'.htmlspecialchars($tagName).'"';
1812 $tagName = $options['useIndexTagForAssoc'];
1815 // The tag name is cleaned up so only alphanumeric chars (plus - and _) are in there and not longer than 100 chars either.
1816 $tagName = substr(ereg_replace('[^[:alnum:]_-]','',$tagName),0,100);
1818 // If the value is an array then we will call this function recursively:
1822 if ($options['alt_options'][$stackData['path'].'/'.$tagName]) {
1823 $subOptions = $options['alt_options'][$stackData['path'].'/'.$tagName];
1824 $clearStackPath = $subOptions['clearStackPath'];
1826 $subOptions = $options;
1827 $clearStackPath = FALSE;
1831 t3lib_div
::array2xml(
1839 'parentTagName' => $tagName,
1840 'grandParentTagName' => $stackData['parentTagName'],
1841 'path' => $clearStackPath ?
'' : $stackData['path'].'/'.$tagName,
1844 str_pad('',($level+
1)*$indentN,$indentChar);
1845 $attr.=' type="array"';
1846 } else { // Just a value:
1848 // Look for binary chars:
1849 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!
1850 // If the value contained binary chars then we base64-encode it an set an attribute to notify this situation:
1851 $content = chr(10).chunk_split(base64_encode($v));
1852 $attr.=' base64="1"';
1854 // Otherwise, just htmlspecialchar the stuff:
1855 $content = htmlspecialchars($v);
1856 $dType = gettype($v);
1857 if ($dType!='string' && !$options['disableTypeAttrib']) { $attr.=' type="'.$dType.'"'; }
1861 // Add the element to the output string:
1862 $output.=str_pad('',($level+
1)*$indentN,$indentChar).'<'.$NSprefix.$tagName.$attr.'>'.$content.'</'.$NSprefix.$tagName.'>'.chr(10);
1866 // If we are at the outer-most level, then we finally wrap it all in the document tags and return that as the value:
1869 '<'.$docTag.'>'.chr(10).
1878 * Converts an XML string to a PHP array.
1879 * This is the reverse function of array2xml()
1882 * @param string XML content to convert into an array
1883 * @param string The tag-prefix resolve, eg. a namespace like "T3:"
1884 * @param boolean If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array
1885 * @return mixed If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.
1888 function xml2array($string,$NSprefix='',$reportDocTag=FALSE) {
1889 global $TYPO3_CONF_VARS;
1892 $parser = xml_parser_create();
1896 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
1897 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
1899 // PHP5 fix of charset awareness:
1900 // 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.
1901 // 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.
1902 // 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.
1903 if ((double)phpversion()>=5) {
1904 unset($ereg_result);
1905 ereg('^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"',substr($string,0,200),$ereg_result);
1906 $theCharset = $ereg_result[1] ?
$ereg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
1907 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
1911 xml_parse_into_struct($parser, $string, $vals, $index);
1913 // If error, return error message:
1914 if (xml_get_error_code($parser)) {
1915 return 'Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
1917 xml_parser_free($parser);
1920 $stack = array(array());
1926 // Traverse the parsed XML structure:
1927 foreach($vals as $key => $val) {
1929 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
1930 $tagName = $val['tag'];
1931 if (!$documentTag) $documentTag = $tagName;
1933 // Test for name space:
1934 $tagName = ($NSprefix && substr($tagName,0,strlen($NSprefix))==$NSprefix) ?
substr($tagName,strlen($NSprefix)) : $tagName;
1936 // Test for numeric tag, encoded on the form "nXXX":
1937 $testNtag = substr($tagName,1); // Closing tag.
1938 $tagName = (substr($tagName,0,1)=='n' && !strcmp(intval($testNtag),$testNtag)) ?
intval($testNtag) : $tagName;
1940 // Test for alternative index value:
1941 if (strlen($val['attributes']['index'])) { $tagName = $val['attributes']['index']; }
1943 // Setting tag-values, manage stack:
1944 switch($val['type']) {
1945 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
1946 $current[$tagName] = array(); // Setting blank place holder
1947 $stack[$stacktop++
] = $current;
1950 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
1951 $oldCurrent = $current;
1952 $current = $stack[--$stacktop];
1953 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
1954 $current[key($current)] = $oldCurrent;
1957 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
1958 if ($val['attributes']['base64']) {
1959 $current[$tagName] = base64_decode($val['value']);
1961 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
1964 switch((string)$val['attributes']['type']) {
1966 $current[$tagName] = (integer)$current[$tagName];
1969 $current[$tagName] = (double)$current[$tagName];
1972 $current[$tagName] = (bool)$current[$tagName];
1975 $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...
1983 if ($reportDocTag) {
1984 $current[$tagName]['_DOCUMENT_TAG'] = $documentTag;
1987 // Finally return the content of the document tag.
1988 return $current[$tagName];
1992 * This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
1995 * @param array A array of XML parts, see xml2tree
1996 * @return string Re-compiled XML data.
1998 function xmlRecompileFromStructValArray($vals) {
2001 foreach($vals as $val) {
2002 $type = $val['type'];
2005 if ($type=='open' ||
$type=='complete') {
2006 $XMLcontent.='<'.$val['tag'];
2007 if(isset($val['attributes'])) {
2008 foreach($val['attributes'] as $k => $v) {
2009 $XMLcontent.=' '.$k.'="'.htmlspecialchars($v).'"';
2012 if ($type=='complete') {
2013 if(isset($val['value'])) {
2014 $XMLcontent.='>'.htmlspecialchars($val['value']).'</'.$val['tag'].'>';
2015 } else $XMLcontent.='/>';
2016 } else $XMLcontent.='>';
2018 if ($type=='open' && isset($val['value'])) {
2019 $XMLcontent.=htmlspecialchars($val['value']);
2023 if ($type=='close') {
2024 $XMLcontent.='</'.$val['tag'].'>';
2027 if($type=='cdata') {
2028 $XMLcontent.=htmlspecialchars($val['value']);
2036 * Extract the encoding scheme as found in the first line of an XML document (typically)
2039 * @param string XML data
2040 * @return string Encoding scheme (lowercase), if found.
2042 function xmlGetHeaderAttribs($xmlData) {
2043 $xmlHeader = substr(trim($xmlData),0,200);
2045 if (eregi('^<\?xml([^>]*)\?\>',$xmlHeader,$reg)) {
2046 return t3lib_div
::get_tag_attributes($reg[1]);
2060 /*************************
2064 *************************/
2067 * Reads the file or url $url and returns the content
2068 * 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.
2071 * @param string Filepath/URL to read
2072 * @return string The content from the resource given as input.
2074 function getURL($url) {
2077 // (Proxy support implemented by Arco <arco@appeltaart.mine.nu>)
2078 if ((substr($url,0,7)=='http://') && ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse']=='1')) {
2079 //external URL without error checking.
2081 curl_setopt ($ch,CURLOPT_URL
, $url);
2082 curl_setopt ($ch,CURLOPT_HEADER
, 0);
2083 curl_setopt ($ch,CURLOPT_RETURNTRANSFER
, 1);
2085 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']) {
2086 curl_setopt ($ch, CURLOPT_PROXY
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyServer']);
2088 // I don't know if it will be needed
2089 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel']) {
2090 curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyTunnel'] );
2092 if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass']) {
2093 curl_setopt ($ch, CURLOPT_PROXYUSERPWD
, $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlProxyUserPass'] );
2096 $content=curl_exec ($ch);
2099 } elseif (function_exists('file_get_contents')) {
2100 return file_get_contents($url);
2101 } elseif ($fd = fopen($url,'rb')) {
2102 while (!feof($fd)) {
2103 $content.=fread($fd, 4096);
2113 * Writes $content to the file $file
2116 * @param string Filepath to write to
2117 * @param string Content to write
2118 * @return boolean True if the file was successfully opened and written to.
2120 function writeFile($file,$content) {
2121 if (!@is_file
($file)) { $changePermissions=true; }
2123 if ($fd = fopen($file,'wb')) {
2124 $res = fwrite($fd,$content);
2130 if ($changePermissions) { // Change the permissions only if the file has just been created
2131 t3lib_div
::fixPermissions($file);
2141 * Setting file system mode & group ownership of file
2143 * @param string Filepath of newly created file
2146 function fixPermissions($file) {
2147 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2148 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2149 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2150 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2156 * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
2157 * Accepts an additional subdirectory in the file path!
2159 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2160 * @param string Content string to write
2161 * @return string Returns false on success, otherwise an error string telling about the problem.
2163 function writeFileToTypo3tempDir($filepath,$content) {
2165 // Parse filepath into directory and basename:
2166 $fI = pathinfo($filepath);
2167 $fI['dirname'].= '/';
2170 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2171 if (defined('PATH_site')) {
2172 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2173 if (@is_dir
($dirName)) {
2174 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2176 // Checking if the "subdir" is found:
2177 $subdir = substr($fI['dirname'],strlen($dirName));
2179 if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
2181 if (!@is_dir
($dirName)) {
2182 t3lib_div
::mkdir($dirName);
2184 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
2186 // Checking dir-name again (sub-dir might have been created):
2187 if (@is_dir
($dirName)) {
2188 if ($filepath == $dirName.$fI['basename']) {
2189 t3lib_div
::writeFile($filepath, $content);
2190 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2191 } else return 'Calculated filelocation didn\'t match input $filepath!';
2192 } else return '"'.$dirName.'" is not a directory!';
2193 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2194 } else return 'PATH_site + "typo3temp/" was not a directory!';
2195 } else return 'PATH_site constant was NOT defined!';
2196 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2200 * 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']
2203 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2204 * @return boolean TRUE if @mkdir went well!
2206 function mkdir($theNewFolder) {
2207 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
2208 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2209 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2211 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2212 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2219 * Returns an array with the names of folders in a specific path
2220 * Will return 'error' (string) if there were an error with reading directory content.
2223 * @param string Path to list directories from
2224 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2226 function get_dirs($path) {
2229 if (is_object($d)) {
2230 while($entry=$d->read()) {
2231 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2232 $filearray[]=$entry;
2236 } else return 'error';
2242 * Returns an array with the names of files in a specific path
2245 * @param string $path: Is the path to the file
2246 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2247 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2248 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2249 * @return array Array of the files found
2251 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2253 // Initialize variabels:
2254 $filearray = array();
2255 $sortarray = array();
2256 $path = ereg_replace('\/$','',$path);
2258 // Find files+directories:
2259 if (@is_dir
($path)) {
2260 $extensionList = strtolower($extensionList);
2262 if (is_object($d)) {
2263 while($entry=$d->read()) {
2264 if (@is_file
($path.'/'.$entry)) {
2265 $fI = pathinfo($entry);
2266 $key = md5($path.'/'.$entry); // Don't change this ever - extensions may depend on the fact that the hash is an md5 of the path! (import/export extension)
2267 if (!$extensionList || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) {
2268 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2269 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2270 elseif ($order) {$sortarray[$key]=$entry;}
2275 } else return 'error opening path: "'.$path.'"';
2283 while(list($k,$v)=each($sortarray)) {
2284 $newArr[$k]=$filearray[$k];
2295 * Recursively gather all files and folders of a path.
2298 * @param array $fileArr: Empty input array (will have files added to it)
2299 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2300 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2301 * @param boolean $regDirs: If set, directories are also included in output.
2302 * @param integer $recursivityLevels: The number of levels to dig down...
2303 * @return array An array with the found files/directories.
2305 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2306 if ($regDirs) $fileArr[] = $path;
2307 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1));
2309 $dirs = t3lib_div
::get_dirs($path);
2310 if (is_array($dirs) && $recursivityLevels>0) {
2311 foreach ($dirs as $subdirs) {
2312 if ((string)$subdirs!='') {
2313 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2321 * Removes the absolute part of all files/folders in fileArr
2324 * @param array $fileArr: The file array to remove the prefix from
2325 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2326 * @return array The input $fileArr processed.
2328 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2329 foreach($fileArr as $k => $absFileRef) {
2330 if(t3lib_div
::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2331 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2332 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2338 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2341 * @param string File path to process
2344 function fixWindowsFilePath($theFile) {
2345 return str_replace('//','/', str_replace('\\','/', $theFile));
2349 * Resolves "../" sections in the input path string.
2350 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2353 * @param string File path in which "/../" is resolved
2356 function resolveBackPath($pathStr) {
2357 $parts = explode('/',$pathStr);
2359 foreach($parts as $pV) {
2364 } else $output[]=$pV;
2370 return implode('/',$output);
2374 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2375 * - If already having a scheme, nothing is prepended
2376 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2377 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2380 * @param string URL / path to prepend full URL addressing to.
2383 function locationHeaderUrl($path) {
2384 $uI = parse_url($path);
2385 if (substr($path,0,1)=='/') { // relative to HOST
2386 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2387 } elseif (!$uI['scheme']) { // No scheme either
2388 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2408 /*************************
2410 * DEBUG helper FUNCTIONS
2412 *************************/
2415 * Returns a string with a list of ascii-values for the first $characters characters in $string
2418 * @param string String to show ASCII value for
2419 * @param integer Number of characters to show
2420 * @return string The string with ASCII values in separated by a space char.
2423 function debug_ordvalue($string,$characters=100) {
2424 if(strlen($string) < $characters) $characters = strlen($string);
2425 for ($i=0; $i<$characters; $i++
) {
2426 $valuestring.=' '.ord(substr($string,$i,1));
2428 return trim($valuestring);
2432 * Returns HTML-code, which is a visual representation of a multidimensional array
2433 * use t3lib_div::print_array() in order to print an array
2434 * Returns false if $array_in is not an array
2437 * @param array Array to view
2438 * @return string HTML output
2440 function view_array($array_in) {
2441 if (is_array($array_in)) {
2442 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2443 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
2444 while (list($key,$val)=each($array_in)) {
2445 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
2446 if (is_array($array_in[$key])) {
2447 $result.=t3lib_div
::view_array($array_in[$key]);
2449 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
2450 $result.= '</td></tr>';
2452 $result.= '</table>';
2463 * @param array Array to print visually (in a table).
2468 function print_array($array_in) {
2469 echo t3lib_div
::view_array($array_in);
2473 * Makes debug output
2474 * Prints $var in bold between two vertical lines
2475 * If not $var the word 'debug' is printed
2476 * If $var is an array, the array is printed by t3lib_div::print_array()
2479 * @param mixed Variable to print
2480 * @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.
2483 function debug($var="",$brOrHeader=0) {
2484 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2485 echo '<table class="typo3-debug" border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><tr><td>';
2486 } elseif ($brOrHeader<0) {
2487 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
2490 if (is_array($var)) {
2491 t3lib_div
::print_array($var);
2492 } elseif (is_object($var)) {
2493 echo '<b>|Object:<pre>';
2496 } elseif ((string)$var!='') {
2497 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2499 echo '<b>| debug |</b>';
2502 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2503 echo '</td></tr></table>';
2504 } elseif ($brOrHeader>0) {
2505 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
2512 function debug_trail() {
2513 if (function_exists('debug_backtrace')) {
2514 $trail = debug_backtrace();
2515 $trail = array_reverse($trail);
2519 foreach($trail as $dat) {
2520 $path[] = $dat['class'].$dat['type'].$dat['function'];
2523 return implode(' // ',$path);
2524 } else return 'N/A';
2527 function debugRows($rows,$header) {
2528 if (is_array($rows)) {
2530 $firstEl = current($rows);
2531 if (is_array($firstEl)) {
2532 $headerColumns = array_keys($firstEl);
2536 $tRows[] = '<tr><td colspan="'.count($headerColumns).'" style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;"><strong>'.htmlspecialchars($header).'</strong></td></tr>';
2538 foreach($headerColumns as $key) {
2540 <td><font face="Verdana,Arial" size="1"><strong>'.htmlspecialchars($key).'</strong></font></td>';
2543 <tr>'.implode('',$tCells).'
2547 foreach($rows as $singleRow) {
2549 foreach($headerColumns as $key) {
2551 <td><font face="Verdana,Arial" size="1">'.htmlspecialchars($singleRow[$key]).'</font></td>';
2554 <tr>'.implode('',$tCells).'
2559 <table border="1" cellpadding="1" cellspacing="0" bgcolor="white">'.implode('',$tRows).'
2562 } else debug('Empty array of rows',$header);
2563 } else debug('No array of rows',$header);
2593 /*************************
2595 * SYSTEM INFORMATION
2597 *************************/
2600 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2605 function getThisUrl() {
2606 $p=parse_url(t3lib_div
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2607 $dir=t3lib_div
::dirname($p['path']).'/'; // Strip file
2608 $url = str_replace('//','/',$p['host'].($p['port']?
':'.$p['port']:'').$dir);
2613 * Returns the link-url to the current script.
2614 * 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.
2615 * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
2618 * @param array Array of GET parameters to include
2621 function linkThisScript($getParams=array()) {
2622 $parts = t3lib_div
::getIndpEnv('SCRIPT_NAME');
2623 $params = t3lib_div
::_GET();
2625 foreach($getParams as $k => $v) {
2626 if (strcmp($v,'')) {
2628 } else unset($params[$k]);
2631 $pString = t3lib_div
::implodeArrayForUrl('',$params);
2633 return $pString ?
$parts.'?'.ereg_replace('^&','',$pString) : $parts;
2637 * 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.
2638 * So basically it adds the parameters in $getParams to an existing URL, $url
2641 * @param string URL string
2642 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2643 * @return string Output URL with added getParams.
2645 function linkThisUrl($url,$getParams=array()) {
2646 $parts = parse_url($url);
2647 if ($parts['query']) {
2648 parse_str($parts['query'],$getP);
2653 $getP = t3lib_div
::array_merge_recursive_overrule($getP,$getParams);
2654 $uP = explode('?',$url);
2656 $params = t3lib_div
::implodeArrayForUrl('',$getP);
2657 $outurl = $uP[0].($params ?
'?'.substr($params, 1) : '');
2663 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2664 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2667 * @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
2668 * @return string Value based on the input key, independent of server/os environment.
2670 function getIndpEnv($getEnvName) {
2673 output from parse_url():
2674 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
2676 [user] => 'username'
2677 [pass] => 'password'
2678 [host] => '192.168.1.4'
2680 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2681 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2682 [fragment] => 'link1'
2684 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2685 [path_dir] = '/typo3/32/temp/phpcheck/'
2686 [path_info] = '/arg1/arg2/arg3/'
2687 [path] = [path_script/path_dir][path_info]
2693 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2694 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2695 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')!
2696 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2697 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2698 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
2699 (Notice: NO username/password + NO fragment)
2702 REMOTE_ADDR = (client IP)
2703 REMOTE_HOST = (client host)
2704 HTTP_USER_AGENT = (client user agent)
2705 HTTP_ACCEPT_LANGUAGE = (client accept language)
2708 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2711 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2712 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2713 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2714 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2715 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2716 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2717 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2718 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2719 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2721 Notice: [fragment] is apparently NEVER available to the script!
2724 Testing suggestions:
2725 - Output all the values.
2726 - 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
2727 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2731 # if ($getEnvName=='HTTP_REFERER') return '';
2732 switch((string)$getEnvName) {
2734 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']);
2736 case 'SCRIPT_FILENAME':
2737 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'])));
2740 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2741 if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2742 return '/'.ereg_replace('^/','',t3lib_div
::getIndpEnv('SCRIPT_NAME')).
2743 ($_SERVER['QUERY_STRING']?
'?'.$_SERVER['QUERY_STRING']:'');
2744 } else return $_SERVER['REQUEST_URI'];
2747 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
2748 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2749 // 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)
2750 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
2751 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
2752 return $_SERVER['PATH_INFO'];
2755 // These are let through without modification
2758 case 'HTTP_REFERER':
2760 case 'HTTP_USER_AGENT':
2761 case 'HTTP_ACCEPT_LANGUAGE':
2762 case 'QUERY_STRING':
2763 return $_SERVER[$getEnvName];
2765 case 'TYPO3_DOCUMENT_ROOT':
2766 // 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.
2767 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2768 $SFN = t3lib_div
::getIndpEnv('SCRIPT_FILENAME');
2769 $SN_A = explode('/',strrev(t3lib_div
::getIndpEnv('SCRIPT_NAME')));
2770 $SFN_A = explode('/',strrev($SFN));
2772 while(list($kk,$vv)=each($SN_A)) {
2773 if (!strcmp($SFN_A[$kk],$vv)) {
2777 $commonEnd=strrev(implode('/',$acc));
2778 if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+
1)); }
2781 case 'TYPO3_HOST_ONLY':
2782 $p = explode(':',$_SERVER['HTTP_HOST']);
2786 $p = explode(':',$_SERVER['HTTP_HOST']);
2789 case 'TYPO3_REQUEST_HOST':
2790 return (t3lib_div
::getIndpEnv('TYPO3_SSL') ?
'https://' : 'http://').
2791 $_SERVER['HTTP_HOST'];
2793 case 'TYPO3_REQUEST_URL':
2794 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('REQUEST_URI');
2796 case 'TYPO3_REQUEST_SCRIPT':
2797 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('SCRIPT_NAME');
2799 case 'TYPO3_REQUEST_DIR':
2800 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::dirname(t3lib_div
::getIndpEnv('SCRIPT_NAME')).'/';
2802 case 'TYPO3_SITE_URL':
2803 if (defined('PATH_thisScript') && defined('PATH_site')) {
2804 $lPath = substr(dirname(PATH_thisScript
),strlen(PATH_site
)).'/';
2805 $url = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR');
2806 $siteUrl = substr($url,0,-strlen($lPath));
2807 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2811 case 'TYPO3_SITE_SCRIPT':
2812 return substr(t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
2815 return $_SERVER['SSL_SESSION_ID'] ||
!strcmp($_SERVER['HTTPS'],'on') ?
TRUE : FALSE;
2819 // Here, list ALL possible keys to this function for debug display.
2820 $envTestVars = t3lib_div
::trimExplode(',','
2830 TYPO3_REQUEST_SCRIPT,
2836 TYPO3_DOCUMENT_ROOT,
2841 HTTP_ACCEPT_LANGUAGE',1);
2842 reset($envTestVars);
2843 while(list(,$v)=each($envTestVars)) {
2844 $out[$v]=t3lib_div
::getIndpEnv($v);
2854 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2859 function milliseconds() {
2860 $p=explode(' ',microtime());
2861 return round(($p[0]+
$p[1])*1000);
2865 * Client Browser Information
2868 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2869 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2871 function clientInfo($useragent='') {
2872 if (!$useragent) $useragent=t3lib_div
::getIndpEnv('HTTP_USER_AGENT');
2876 if (strstr($useragent,'Konqueror')) {
2877 $bInfo['BROWSER']= 'konqu';
2878 } elseif (strstr($useragent,'Opera')) {
2879 $bInfo['BROWSER']= 'opera';
2880 } elseif (strstr($useragent,'MSIE 4') ||
strstr($useragent,'MSIE 5') ||
strstr($useragent,'MSIE 6')) {
2881 $bInfo['BROWSER']= 'msie';
2882 } elseif (strstr($useragent,'Mozilla/4') ||
strstr($useragent,'Mozilla/5')) {
2883 $bInfo['BROWSER']='net';
2885 if ($bInfo['BROWSER']) {
2887 switch($bInfo['BROWSER']) {
2889 $bInfo['VERSION']= doubleval(substr($useragent,8));
2890 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2891 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2894 $tmp = strstr($useragent,'MSIE');
2895 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
2898 $tmp = strstr($useragent,'Opera');
2899 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
2902 $tmp = strstr($useragent,'Konqueror/');
2903 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2907 if (strstr($useragent,'Win')) {
2908 $bInfo['SYSTEM'] = 'win';
2909 } elseif (strstr($useragent,'Mac')) {
2910 $bInfo['SYSTEM'] = 'mac';
2911 } elseif (strstr($useragent,'Linux') ||
strstr($useragent,'X11') ||
strstr($useragent,'SGI') ||
strstr($useragent,' SunOS ') ||
strstr($useragent,' HP-UX ')) {
2912 $bInfo['SYSTEM'] = 'unix';
2915 // Is true if the browser supports css to format forms, especially the width
2916 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' ||
($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) ||
$bInfo['BROWSER']=='opera' ||
$bInfo['BROWSER']=='konqu');
2943 /*************************
2945 * TYPO3 SPECIFIC FUNCTIONS
2947 *************************/
2950 * 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.
2953 * @param string The input filename/filepath to evaluate
2954 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2955 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2956 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2958 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2959 if (!strcmp($filename,'')) return '';
2961 if ($relToTYPO3_mainDir) {
2962 if (!defined('PATH_typo3')) return '';
2963 $relPathPrefix = PATH_typo3
;
2965 $relPathPrefix = PATH_site
;
2967 if (substr($filename,0,4)=='EXT:') { // extension
2968 list($extKey,$local) = explode('/',substr($filename,4),2);
2970 if (strcmp($extKey,'') && t3lib_extMgm
::isLoaded($extKey) && strcmp($local,'')) {
2971 $filename = t3lib_extMgm
::extPath($extKey).$local;
2973 } elseif (!t3lib_div
::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2974 $filename=$relPathPrefix.$filename;
2975 } elseif ($onlyRelative && !t3lib_div
::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2978 if (strcmp($filename,'') && t3lib_div
::validPathStr($filename)) { // checks backpath.
2984 * Checks for malicious file paths.
2985 * Returns true if no '//', '..' or '\' is in the $theFile
2986 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2987 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2990 * @param string Filepath to evaluate
2991 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2992 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2994 function validPathStr($theFile) {
2995 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
2999 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
3002 * @param string Filepath to evaluate
3005 function isAbsPath($path) {
3006 return TYPO3_OS
=='WIN' ?
substr($path,1,2)==':/' : substr($path,0,1)=='/';
3010 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
3013 * @param string Filepath to evaluate
3016 function isAllowedAbsPath($path) {
3017 if (t3lib_div
::isAbsPath($path) &&
3018 t3lib_div
::validPathStr($path) &&
3019 ( t3lib_div
::isFirstPartOfStr($path,PATH_site
)
3021 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div
::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
3027 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
3030 * @param string Filepath to evaluate
3033 function verifyFilenameAgainstDenyPattern($filename) {
3034 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
3035 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
3036 if ($result) return false; // so if a matching filename is found, return false;
3042 * Moves $source file to $destination if uploaded, otherwise try to make a copy
3045 * @param string Source file, absolute path
3046 * @param string Destination file, absolute path
3047 * @return boolean Returns true if the file was moved.
3048 * @coauthor Dennis Petersen <fessor@software.dk>
3049 * @see upload_to_tempfile()
3051 function upload_copy_move($source,$destination) {
3052 if (is_uploaded_file($source)) {
3054 // 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:
3055 $uploadedResult = move_uploaded_file($source, $destination);
3058 @copy
($source,$destination);
3061 t3lib_div
::fixPermissions($destination); // Change the permissions of the file
3063 // 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
3064 return $uploaded ?
$uploadedResult : FALSE;
3068 * 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.
3069 * Use this function to move uploaded files to where you can work on them.
3070 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
3073 * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
3074 * @return string If a new file was successfully created, return its filename, otherwise blank string.
3075 * @see unlink_tempfile(), upload_copy_move()
3077 function upload_to_tempfile($uploadedFileName) {
3078 if (is_uploaded_file($uploadedFileName)) {
3079 $tempFile = t3lib_div
::tempnam('upload_temp_');
3080 move_uploaded_file($uploadedFileName, $tempFile);
3081 return @is_file
($tempFile) ?
$tempFile : '';
3086 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
3087 * 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.
3088 * Use this after upload_to_tempfile() or tempnam() from this class!
3091 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
3092 * @return boolean Returns true if the file was unlink()'ed
3093 * @see upload_to_tempfile(), tempnam()
3095 function unlink_tempfile($uploadedTempFileName) {
3096 if ($uploadedTempFileName && t3lib_div
::validPathStr($uploadedTempFileName) && t3lib_div
::isFirstPartOfStr($uploadedTempFileName,PATH_site
.'typo3temp/') && @is_file
($uploadedTempFileName)) {
3097 if (unlink($uploadedTempFileName)) return TRUE;
3102 * Create temporary filename (Create file with unique file name)
3103 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
3104 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
3107 * @param string Prefix to temp file (which will have no extension btw)
3108 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
3109 * @see unlink_tempfile(), upload_to_tempfile()
3111 function tempnam($filePrefix) {
3112 return tempnam(PATH_site
.'typo3temp/',$filePrefix);
3116 * standard authentication code - can't remember what it's used for.
3119 * @param mixed Uid (integer) or record (array)
3120 * @param string List of fields from the record if that is given.
3121 * @return string MD5 hash of 8 chars.
3124 function stdAuthCode($uid_or_record,$fields='') {
3125 if (is_array($uid_or_record)) {
3126 $recCopy_temp=array();
3128 $fieldArr = t3lib_div
::trimExplode(',',$fields,1);
3130 while(list($k,$v)=each($fieldArr)) {
3131 $recCopy_temp[$k]=$recCopy[$v];
3134 $recCopy_temp=$recCopy;
3136 $preKey = implode('|',$recCopy_temp);
3138 $preKey = $uid_or_record;
3141 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3142 $authCode = substr(md5($authCode),0,8);
3147 * Splits the input query-parameters into an array with certain parameters filtered out.
3148 * Used to create the cHash value
3150 * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
3151 * @return array Array with key/value pairs of query-parameters WITHOUT a certain list of variable names (like id, type, no_cache etc) and WITH a variable, encryptionKey, specific for this server/installation
3152 * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink()
3154 function cHashParams($addQueryParams) {
3155 $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
3159 foreach($params as $theP) {
3160 $pKV = explode('=', $theP); // Splitting single param by '=' sign
3161 if (!t3lib_div
::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0])) {
3162 $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
3165 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3172 * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
3174 * @param integer Value from "l18n_cfg" field of a page record
3175 * @return boolean True if the page should be hidden
3177 function hideIfNotTranslated($l18n_cfg_fieldValue) {
3178 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
3179 return $l18n_cfg_fieldValue&2 ?
FALSE : TRUE;
3181 return $l18n_cfg_fieldValue&2 ?
TRUE : FALSE;
3186 * Includes a locallang file and returns the $LOCAL_LANG array found inside.
3188 * @param string Input is a file-reference (see t3lib_div::getFileAbsFileName) which, if exists, is included. That file is expected to be a 'local_lang' file containing a $LOCAL_LANG array.
3189 * @param string Language key
3190 * @return array Value of $LOCAL_LANG found in the included file. If that array is found it's returned. Otherwise an empty array
3192 function readLLfile($fileRef,$langKey) {
3194 $file = t3lib_div
::getFileAbsFileName($fileRef);
3196 $baseFile = ereg_replace('\.(php|xml)$', '', $file);
3198 if (@is_file
($baseFile.'.xml')) {
3199 $LOCAL_LANG = t3lib_div
::readLLXMLfile($baseFile.'.xml', $langKey);
3200 } elseif (@is_file
($baseFile.'.php')) {
3201 include($baseFile.'.php');
3202 } else die('Filereference, "'.$file.'", not found!');
3205 return is_array($LOCAL_LANG)?
$LOCAL_LANG:array();
3209 * Includes a locallang-xml file and returns the $LOCAL_LANG array
3210 * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
3212 * @param string Absolute reference to locallang-XML file
3213 * @param string TYPO3 language key, eg. "dk" or "de" or "default"
3214 * @return array LOCAL_LANG array in return.
3216 function readLLXMLfile($fileRef,$langKey) {
3218 if (is_object($GLOBALS['LANG'])) {
3219 $csConvObj = &$GLOBALS['LANG']->csConvObj
;
3220 } elseif (is_object($GLOBALS['TSFE'])) {
3221 $csConvObj = &$GLOBALS['TSFE']->csConvObj
;
3222 } else $csConvObj = NULL;
3224 if (@is_file
($fileRef) && $langKey && is_object($csConvObj)) {
3227 $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray
[$langKey] ?
$csConvObj->charSetArray
[$langKey] : 'iso-8859-1');
3230 $hashSource = substr($fileRef,strlen(PATH_site
)).'|'.date('d-m-Y H:i:s',filemtime($fileRef));
3231 $cacheFileName = PATH_site
.'typo3temp/llxml/'.
3232 #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
3233 #'_'.basename($fileRef).
3234 substr(basename($fileRef),10,15).
3235 '_'.t3lib_div
::shortMD5($hashSource).'.'.