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 * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead
472 * @param string $string string to truncate
473 * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
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 * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars)
498 * @param string $string string to truncate
499 * @param integer $chars 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 string to truncate
513 * @param integer $chars must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.
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 $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR
627 * @param string $list is a comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong)
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 element to remove
669 * @param string $list 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 $list 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 is 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 * (DEPRECIATED, 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 * (DEPRECIATED: 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 $in_array one-dimensional array of items
1196 * @param string $item 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($fd = fopen($url,'rb')) {
2100 while (!feof($fd)) {
2101 $content.=fread($fd, 5000);
2109 * Writes $content to the file $file
2112 * @param string Filepath to write to
2113 * @param string Content to write
2114 * @return boolean True if the file was successfully opened and written to.
2116 function writeFile($file,$content) {
2117 if($fd = fopen($file,'wb')) {
2118 fwrite( $fd, $content);
2121 t3lib_div
::fixPermissions($file); // Change the permissions of the file
2128 * Setting file system mode & group ownership of file
2130 * @param string Filepath of newly created file
2133 function fixPermissions($file) {
2134 if (@is_file
($file) && TYPO3_OS
!='WIN') {
2135 @chmod
($file, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'])); // "@" is there because file is not necessarily OWNED by the user
2136 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2137 @chgrp
($file, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']); // "@" is there because file is not necessarily OWNED by the user
2143 * Writes $content to a filename in the typo3temp/ folder (and possibly a subfolder...)
2144 * Accepts an additional subdirectory in the file path!
2146 * @param string Absolute filepath to write to inside "typo3temp/". First part of this string must match PATH_site."typo3temp/"
2147 * @param string Content string to write
2148 * @return string Returns false on success, otherwise an error string telling about the problem.
2150 function writeFileToTypo3tempDir($filepath,$content) {
2152 // Parse filepath into directory and basename:
2153 $fI = pathinfo($filepath);
2154 $fI['dirname'].= '/';
2157 if (t3lib_div
::validPathStr($filepath) && $fI['basename'] && strlen($fI['basename'])<60) {
2158 if (defined('PATH_site')) {
2159 $dirName = PATH_site
.'typo3temp/'; // Setting main temporary directory name (standard)
2160 if (@is_dir
($dirName)) {
2161 if (t3lib_div
::isFirstPartOfStr($fI['dirname'],$dirName)) {
2163 // Checking if the "subdir" is found:
2164 $subdir = substr($fI['dirname'],strlen($dirName));
2166 if (ereg('^[[:alnum:]_]+\/$',$subdir)) {
2168 if (!@is_dir
($dirName)) {
2169 t3lib_div
::mkdir($dirName);
2171 } else return 'Subdir, "'.$subdir.'", was NOT on the form "[a-z]/"';
2173 // Checking dir-name again (sub-dir might have been created):
2174 if (@is_dir
($dirName)) {
2175 if ($filepath == $dirName.$fI['basename']) {
2176 t3lib_div
::writeFile($filepath, $content);
2177 if (!@is_file
($filepath)) return 'File not written to disk! Write permission error in filesystem?';
2178 } else return 'Calculated filelocation didn\'t match input $filepath!';
2179 } else return '"'.$dirName.'" is not a directory!';
2180 } else return '"'.$fI['dirname'].'" was not within directory PATH_site + "typo3temp/"';
2181 } else return 'PATH_site + "typo3temp/" was not a directory!';
2182 } else return 'PATH_site constant was NOT defined!';
2183 } else return 'Input filepath "'.$filepath.'" was generally invalid!';
2187 * 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']
2190 * @param string Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.
2191 * @return boolean TRUE if @mkdir went well!
2193 function mkdir($theNewFolder) {
2194 $theNewFolder = ereg_replace('\/$','',$theNewFolder);
2195 if (mkdir($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask']))){
2196 chmod($theNewFolder, octdec($GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'])); //added this line, because the mode at 'mkdir' has a strange behaviour sometimes
2198 if($GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']) { // skip this if createGroup is empty
2199 chgrp($theNewFolder, $GLOBALS['TYPO3_CONF_VARS']['BE']['createGroup']);
2206 * Returns an array with the names of folders in a specific path
2207 * Will return 'error' (string) if there were an error with reading directory content.
2210 * @param string Path to list directories from
2211 * @return array Returns an array with the directory entries as values. If no path, the return value is nothing.
2213 function get_dirs($path) {
2216 if (is_object($d)) {
2217 while($entry=$d->read()) {
2218 if (@is_dir
($path.'/'.$entry) && $entry!= '..' && $entry!= '.') {
2219 $filearray[]=$entry;
2223 } else return 'error';
2229 * Returns an array with the names of files in a specific path
2232 * @param string $path: Is the path to the file
2233 * @param string $extensionList is the comma list of extensions to read only (blank = all)
2234 * @param boolean If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
2235 * @param string $order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
2236 * @return array Array of the files found
2238 function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') {
2240 // Initialize variabels:
2241 $filearray = array();
2242 $sortarray = array();
2243 $path = ereg_replace('\/$','',$path);
2245 // Find files+directories:
2246 if (@is_dir
($path)) {
2247 $extensionList = strtolower($extensionList);
2249 if (is_object($d)) {
2250 while($entry=$d->read()) {
2251 if (@is_file
($path.'/'.$entry)) {
2252 $fI = pathinfo($entry);
2253 $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)
2254 if (!$extensionList || t3lib_div
::inList($extensionList,strtolower($fI['extension']))) {
2255 $filearray[$key]=($prependPath?
$path.'/':'').$entry;
2256 if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
2257 elseif ($order) {$sortarray[$key]=$entry;}
2262 } else return 'error opening path: "'.$path.'"';
2270 while(list($k,$v)=each($sortarray)) {
2271 $newArr[$k]=$filearray[$k];
2282 * Recursively gather all files and folders of a path.
2285 * @param array $fileArr: Empty input array (will have files added to it)
2286 * @param string $path: The path to read recursively from (absolute) (include trailing slash!)
2287 * @param string $extList: Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.
2288 * @param boolean $regDirs: If set, directories are also included in output.
2289 * @param integer $recursivityLevels: The number of levels to dig down...
2290 * @return array An array with the found files/directories.
2292 function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) {
2293 if ($regDirs) $fileArr[] = $path;
2294 $fileArr = array_merge($fileArr, t3lib_div
::getFilesInDir($path,$extList,1,1));
2296 $dirs = t3lib_div
::get_dirs($path);
2297 if (is_array($dirs) && $recursivityLevels>0) {
2298 foreach ($dirs as $subdirs) {
2299 if ((string)$subdirs!='') {
2300 $fileArr = t3lib_div
::getAllFilesAndFoldersInPath($fileArr,$path.$subdirs.'/',$extList,$regDirs,$recursivityLevels-1);
2308 * Removes the absolute part of all files/folders in fileArr
2311 * @param array $fileArr: The file array to remove the prefix from
2312 * @param string $prefixToRemove: The prefix path to remove (if found as first part of string!)
2313 * @return array The input $fileArr processed.
2315 function removePrefixPathFromList($fileArr,$prefixToRemove) {
2316 foreach($fileArr as $k => $absFileRef) {
2317 if(t3lib_div
::isFirstPartOfStr($absFileRef,$prefixToRemove)) {
2318 $fileArr[$k] = substr($absFileRef,strlen($prefixToRemove));
2319 } else return 'ERROR: One or more of the files was NOT prefixed with the prefix-path!';
2325 * Fixes a path for windows-backslashes and reduces double-slashes to single slashes
2328 * @param string File path to process
2331 function fixWindowsFilePath($theFile) {
2332 return str_replace('//','/', str_replace('\\','/', $theFile));
2336 * Resolves "../" sections in the input path string.
2337 * For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"
2340 * @param string File path in which "/../" is resolved
2343 function resolveBackPath($pathStr) {
2344 $parts = explode('/',$pathStr);
2346 foreach($parts as $pV) {
2351 } else $output[]=$pV;
2357 return implode('/',$output);
2361 * Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
2362 * - If already having a scheme, nothing is prepended
2363 * - If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
2364 * - Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
2367 * @param string URL / path to prepend full URL addressing to.
2370 function locationHeaderUrl($path) {
2371 $uI = parse_url($path);
2372 if (substr($path,0,1)=='/') { // relative to HOST
2373 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').$path;
2374 } elseif (!$uI['scheme']) { // No scheme either
2375 $path = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR').$path;
2395 /*************************
2397 * DEBUG helper FUNCTIONS
2399 *************************/
2402 * Returns a string with a list of ascii-values for the first $characters characters in $string
2405 * @param string String to show ASCII value for
2406 * @param integer Number of characters to show
2407 * @return string The string with ASCII values in separated by a space char.
2410 function debug_ordvalue($string,$characters=100) {
2411 if(strlen($string) < $characters) $characters = strlen($string);
2412 for ($i=0; $i<$characters; $i++
) {
2413 $valuestring.=' '.ord(substr($string,$i,1));
2415 return trim($valuestring);
2419 * Returns HTML-code, which is a visual representation of a multidimensional array
2420 * use t3lib_div::print_array() in order to print an array
2421 * Returns false if $array_in is not an array
2424 * @param array Array to view
2425 * @return string HTML output
2427 function view_array($array_in) {
2428 if (is_array($array_in)) {
2429 $result='<table border="1" cellpadding="1" cellspacing="0" bgcolor="white">';
2430 if (!count($array_in)) {$result.= '<tr><td><font face="Verdana,Arial" size="1"><b>'.htmlspecialchars("EMPTY!").'</b></font></td></tr>';}
2431 while (list($key,$val)=each($array_in)) {
2432 $result.= '<tr><td><font face="Verdana,Arial" size="1">'.htmlspecialchars((string)$key).'</font></td><td>';
2433 if (is_array($array_in[$key])) {
2434 $result.=t3lib_div
::view_array($array_in[$key]);
2436 $result.= '<font face="Verdana,Arial" size="1" color="red">'.nl2br(htmlspecialchars((string)$val)).'<br /></font>';
2437 $result.= '</td></tr>';
2439 $result.= '</table>';
2450 * @param array Array to print visually (in a table).
2455 function print_array($array_in) {
2456 echo t3lib_div
::view_array($array_in);
2460 * Makes debug output
2461 * Prints $var in bold between two vertical lines
2462 * If not $var the word 'debug' is printed
2463 * If $var is an array, the array is printed by t3lib_div::print_array()
2466 * @param mixed Variable to print
2467 * @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.
2470 function debug($var="",$brOrHeader=0) {
2471 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2472 echo '<table border="0" cellpadding="0" cellspacing="0" bgcolor="white" style="border:0px; margin-top:3px; margin-bottom:3px;"><tr><td style="background-color:#bbbbbb; font-family: verdana,arial; font-weight: bold; font-size: 10px;">'.htmlspecialchars((string)$brOrHeader).'</td></tr><td>';
2473 } elseif ($brOrHeader<0) {
2474 for($a=0;$a<abs(intval($brOrHeader));$a++
){echo '<br />';}
2477 if (is_array($var)) {
2478 t3lib_div
::print_array($var);
2479 } elseif (is_object($var)) {
2480 echo '<b>|Object:<pre>';
2483 } elseif ((string)$var!='') {
2484 echo '<b>|'.htmlspecialchars((string)$var).'|</b>';
2486 echo '<b>| debug |</b>';
2489 if ($brOrHeader && !t3lib_div
::testInt($brOrHeader)) {
2490 echo '</td></tr></table>';
2491 } elseif ($brOrHeader>0) {
2492 for($a=0;$a<intval($brOrHeader);$a++
){echo '<br />';}
2527 /*************************
2529 * SYSTEM INFORMATION
2531 *************************/
2534 * Returns the HOST+DIR-PATH of the current script (The URL, but without 'http://' and without script-filename)
2539 function getThisUrl() {
2540 $p=parse_url(t3lib_div
::getIndpEnv('TYPO3_REQUEST_SCRIPT')); // Url of this script
2541 $dir=t3lib_div
::dirname($p['path']).'/'; // Strip file
2542 $url = str_replace('//','/',$p['host'].($p['port']?
':'.$p['port']:'').$dir);
2547 * Returns the link-url to the current script.
2548 * 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.
2549 * REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)
2552 * @param array Array of GET parameters to include
2555 function linkThisScript($getParams=array()) {
2556 $parts = t3lib_div
::getIndpEnv('SCRIPT_NAME');
2557 $params = t3lib_div
::_GET();
2559 foreach($getParams as $k => $v) {
2560 if (strcmp($v,'')) {
2562 } else unset($params[$k]);
2565 $pString = t3lib_div
::implodeArrayForUrl('',$params);
2567 return $pString ?
$parts.'?'.ereg_replace('^&','',$pString) : $parts;
2571 * 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.
2572 * So basically it adds the parameters in $getParams to an existing URL, $url
2575 * @param string URL string
2576 * @param array Array of key/value pairs for get parameters to add/overrule with. Can be multidimensional.
2577 * @return string Output URL with added getParams.
2579 function linkThisUrl($url,$getParams=array()) {
2580 $parts = parse_url($url);
2581 if ($parts['query']) {
2582 parse_str($parts['query'],$getP);
2587 $getP = t3lib_div
::array_merge_recursive_overrule($getP,$getParams);
2588 $uP = explode('?',$url);
2590 $params = t3lib_div
::implodeArrayForUrl('',$getP);
2591 $outurl = $uP[0].($params ?
'?'.substr($params, 1) : '');
2597 * Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
2598 * This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.
2601 * @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
2602 * @return string Value based on the input key, independent of server/os environment.
2604 function getIndpEnv($getEnvName) {
2607 output from parse_url():
2608 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
2610 [user] => 'username'
2611 [pass] => 'password'
2612 [host] => '192.168.1.4'
2614 [path] => '/typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/'
2615 [query] => 'arg1,arg2,arg3&p1=parameter1&p2[key]=value'
2616 [fragment] => 'link1'
2618 Further definition: [path_script] = '/typo3/32/temp/phpcheck/index.php'
2619 [path_dir] = '/typo3/32/temp/phpcheck/'
2620 [path_info] = '/arg1/arg2/arg3/'
2621 [path] = [path_script/path_dir][path_info]
2627 REQUEST_URI = [path]?[query] = /typo3/32/temp/phpcheck/index.php/arg1/arg2/arg3/?arg1,arg2,arg3&p1=parameter1&p2[key]=value
2628 HTTP_HOST = [host][:[port]] = 192.168.1.4:8080
2629 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')!
2630 PATH_INFO = [path_info] = /arg1/arg2/arg3/
2631 QUERY_STRING = [query] = arg1,arg2,arg3&p1=parameter1&p2[key]=value
2632 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
2633 (Notice: NO username/password + NO fragment)
2636 REMOTE_ADDR = (client IP)
2637 REMOTE_HOST = (client host)
2638 HTTP_USER_AGENT = (client user agent)
2639 HTTP_ACCEPT_LANGUAGE = (client accept language)
2642 SCRIPT_FILENAME = Absolute filename of script (Differs between windows/unix). On windows 'C:\\blabla\\blabl\\' will be converted to 'C:/blabla/blabl/'
2645 TYPO3_HOST_ONLY = [host] = 192.168.1.4
2646 TYPO3_PORT = [port] = 8080 (blank if 80, taken from host value)
2647 TYPO3_REQUEST_HOST = [scheme]://[host][:[port]]
2648 TYPO3_REQUEST_URL = [scheme]://[host][:[port]][path]?[query] (sheme will by default be 'http' until we can detect if it's https -
2649 TYPO3_REQUEST_SCRIPT = [scheme]://[host][:[port]][path_script]
2650 TYPO3_REQUEST_DIR = [scheme]://[host][:[port]][path_dir]
2651 TYPO3_SITE_URL = [scheme]://[host][:[port]][path_dir] of the TYPO3 website frontend
2652 TYPO3_SITE_SCRIPT = [script / Speaking URL] of the TYPO3 website
2653 TYPO3_DOCUMENT_ROOT = Absolute path of root of documents: TYPO3_DOCUMENT_ROOT.SCRIPT_NAME = SCRIPT_FILENAME (typically)
2655 Notice: [fragment] is apparently NEVER available to the script!
2658 Testing suggestions:
2659 - Output all the values.
2660 - 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
2661 - ALSO TRY the script from the ROOT of a site (like 'http://www.mytest.com/' and not 'http://www.mytest.com/test/' !!)
2665 # if ($getEnvName=='HTTP_REFERER') return '';
2666 switch((string)$getEnvName) {
2668 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']);
2670 case 'SCRIPT_FILENAME':
2671 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'])));
2674 // Typical application of REQUEST_URI is return urls, forms submitting to itself etc. Example: returnUrl='.rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'))
2675 if (!$_SERVER['REQUEST_URI']) { // This is for ISS/CGI which does not have the REQUEST_URI available.
2676 return '/'.ereg_replace('^/','',t3lib_div
::getIndpEnv('SCRIPT_NAME')).
2677 ($_SERVER['QUERY_STRING']?
'?'.$_SERVER['QUERY_STRING']:'');
2678 } else return $_SERVER['REQUEST_URI'];
2681 // $_SERVER['PATH_INFO']!=$_SERVER['SCRIPT_NAME'] is necessary because some servers (Windows/CGI) are seen to set PATH_INFO equal to script_name
2682 // Further, there must be at least one '/' in the path - else the PATH_INFO value does not make sense.
2683 // 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)
2684 // if (strcmp($_SERVER['PATH_INFO'],t3lib_div::getIndpEnv('SCRIPT_NAME')) && count(explode('/',$_SERVER['PATH_INFO']))>1) {
2685 if (php_sapi_name()!='cgi'&&php_sapi_name()!='cgi-fcgi') {
2686 return $_SERVER['PATH_INFO'];
2689 // These are let through without modification
2692 case 'HTTP_REFERER':
2694 case 'HTTP_USER_AGENT':
2695 case 'HTTP_ACCEPT_LANGUAGE':
2696 case 'QUERY_STRING':
2697 return $_SERVER[$getEnvName];
2699 case 'TYPO3_DOCUMENT_ROOT':
2700 // 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.
2701 // Therefore the DOCUMENT_ROOT is now always calculated as the SCRIPT_FILENAME minus the end part shared with SCRIPT_NAME.
2702 $SFN = t3lib_div
::getIndpEnv('SCRIPT_FILENAME');
2703 $SN_A = explode('/',strrev(t3lib_div
::getIndpEnv('SCRIPT_NAME')));
2704 $SFN_A = explode('/',strrev($SFN));
2706 while(list($kk,$vv)=each($SN_A)) {
2707 if (!strcmp($SFN_A[$kk],$vv)) {
2711 $commonEnd=strrev(implode('/',$acc));
2712 if (strcmp($commonEnd,'')) { $DR = substr($SFN,0,-(strlen($commonEnd)+
1)); }
2715 case 'TYPO3_HOST_ONLY':
2716 $p = explode(':',$_SERVER['HTTP_HOST']);
2720 $p = explode(':',$_SERVER['HTTP_HOST']);
2723 case 'TYPO3_REQUEST_HOST':
2724 return (t3lib_div
::getIndpEnv('TYPO3_SSL') ?
'https://' : 'http://').
2725 $_SERVER['HTTP_HOST'];
2727 case 'TYPO3_REQUEST_URL':
2728 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('REQUEST_URI');
2730 case 'TYPO3_REQUEST_SCRIPT':
2731 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::getIndpEnv('SCRIPT_NAME');
2733 case 'TYPO3_REQUEST_DIR':
2734 return t3lib_div
::getIndpEnv('TYPO3_REQUEST_HOST').t3lib_div
::dirname(t3lib_div
::getIndpEnv('SCRIPT_NAME')).'/';
2736 case 'TYPO3_SITE_URL':
2737 if (defined('PATH_thisScript') && defined('PATH_site')) {
2738 $lPath = substr(dirname(PATH_thisScript
),strlen(PATH_site
)).'/';
2739 $url = t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR');
2740 $siteUrl = substr($url,0,-strlen($lPath));
2741 if (substr($siteUrl,-1)!='/') $siteUrl.='/';
2745 case 'TYPO3_SITE_SCRIPT':
2746 return substr(t3lib_div
::getIndpEnv('TYPO3_REQUEST_URL'),strlen(t3lib_div
::getIndpEnv('TYPO3_SITE_URL')));
2749 return $_SERVER['SSL_SESSION_ID'] ||
!strcmp($_SERVER['HTTPS'],'on') ?
TRUE : FALSE;
2753 // Here, list ALL possible keys to this function for debug display.
2754 $envTestVars = t3lib_div
::trimExplode(',','
2764 TYPO3_REQUEST_SCRIPT,
2770 TYPO3_DOCUMENT_ROOT,
2775 HTTP_ACCEPT_LANGUAGE',1);
2776 reset($envTestVars);
2777 while(list(,$v)=each($envTestVars)) {
2778 $out[$v]=t3lib_div
::getIndpEnv($v);
2788 * microtime recalculated to t3lib_div::milliseconds(1/1000 sec)
2793 function milliseconds() {
2794 $p=explode(' ',microtime());
2795 return round(($p[0]+
$p[1])*1000);
2799 * Client Browser Information
2802 * @param string Alternative User Agent string (if empty, t3lib_div::getIndpEnv('HTTP_USER_AGENT') is used)
2803 * @return array Parsed information about the HTTP_USER_AGENT in categories BROWSER, VERSION, SYSTEM and FORMSTYLE
2805 function clientInfo($useragent='') {
2806 if (!$useragent) $useragent=t3lib_div
::getIndpEnv('HTTP_USER_AGENT');
2810 if (strstr($useragent,'Konqueror')) {
2811 $bInfo['BROWSER']= 'konqu';
2812 } elseif (strstr($useragent,'Opera')) {
2813 $bInfo['BROWSER']= 'opera';
2814 } elseif (strstr($useragent,'MSIE 4') ||
strstr($useragent,'MSIE 5') ||
strstr($useragent,'MSIE 6')) {
2815 $bInfo['BROWSER']= 'msie';
2816 } elseif (strstr($useragent,'Mozilla/4') ||
strstr($useragent,'Mozilla/5')) {
2817 $bInfo['BROWSER']='net';
2819 if ($bInfo['BROWSER']) {
2821 switch($bInfo['BROWSER']) {
2823 $bInfo['VERSION']= doubleval(substr($useragent,8));
2824 if (strstr($useragent,'Netscape6/')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape6/'),10));}
2825 if (strstr($useragent,'Netscape/7')) {$bInfo['VERSION']=doubleval(substr(strstr($useragent,'Netscape/7'),9));}
2828 $tmp = strstr($useragent,'MSIE');
2829 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,4)));
2832 $tmp = strstr($useragent,'Opera');
2833 $bInfo['VERSION'] = doubleval(ereg_replace('^[^0-9]*','',substr($tmp,5)));
2836 $tmp = strstr($useragent,'Konqueror/');
2837 $bInfo['VERSION'] = doubleval(substr($tmp,10));
2841 if (strstr($useragent,'Win')) {
2842 $bInfo['SYSTEM'] = 'win';
2843 } elseif (strstr($useragent,'Mac')) {
2844 $bInfo['SYSTEM'] = 'mac';
2845 } elseif (strstr($useragent,'Linux') ||
strstr($useragent,'X11') ||
strstr($useragent,'SGI') ||
strstr($useragent,' SunOS ') ||
strstr($useragent,' HP-UX ')) {
2846 $bInfo['SYSTEM'] = 'unix';
2849 // Is true if the browser supports css to format forms, especially the width
2850 $bInfo['FORMSTYLE']=($bInfo['BROWSER']=='msie' ||
($bInfo['BROWSER']=='net'&&$bInfo['VERSION']>=5) ||
$bInfo['BROWSER']=='opera' ||
$bInfo['BROWSER']=='konqu');
2877 /*************************
2879 * TYPO3 SPECIFIC FUNCTIONS
2881 *************************/
2884 * 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.
2887 * @param string The input filename/filepath to evaluate
2888 * @param boolean If $onlyRelative is set (which it is by default), then only return values relative to the current PATH_site is accepted.
2889 * @param boolean If $relToTYPO3_mainDir is set, then relative paths are relative to PATH_typo3 constant - otherwise (default) they are relative to PATH_site
2890 * @return string Returns the absolute filename of $filename IF valid, otherwise blank string.
2892 function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) {
2893 if (!strcmp($filename,'')) return '';
2895 if ($relToTYPO3_mainDir) {
2896 if (!defined('PATH_typo3')) return '';
2897 $relPathPrefix = PATH_typo3
;
2899 $relPathPrefix = PATH_site
;
2901 if (substr($filename,0,4)=='EXT:') { // extension
2902 list($extKey,$local) = explode('/',substr($filename,4),2);
2904 if (strcmp($extKey,'') && t3lib_extMgm
::isLoaded($extKey) && strcmp($local,'')) {
2905 $filename = t3lib_extMgm
::extPath($extKey).$local;
2907 } elseif (!t3lib_div
::isAbsPath($filename)) { // relative. Prepended with $relPathPrefix
2908 $filename=$relPathPrefix.$filename;
2909 } elseif ($onlyRelative && !t3lib_div
::isFirstPartOfStr($filename,$relPathPrefix)) { // absolute, but set to blank if not allowed
2912 if (strcmp($filename,'') && t3lib_div
::validPathStr($filename)) { // checks backpath.
2918 * Checks for malicious file paths.
2919 * Returns true if no '//', '..' or '\' is in the $theFile
2920 * This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes.
2921 * So it's compatible with the UNIX style path strings valid for TYPO3 internally.
2924 * @param string Filepath to evaluate
2925 * @return boolean True, if no '//', '..' or '\' is in the $theFile
2926 * @todo Possible improvement: Should it rawurldecode the string first to check if any of these characters is encoded ?
2928 function validPathStr($theFile) {
2929 if (!strstr($theFile,'//') && !strstr($theFile,'..') && !strstr($theFile,'\\')) return true;
2933 * Checks if the $path is absolute or relative (detecting either '/' or 'x:/' as first part of string) and returns true if so.
2936 * @param string Filepath to evaluate
2939 function isAbsPath($path) {
2940 return TYPO3_OS
=='WIN' ?
substr($path,1,2)==':/' : substr($path,0,1)=='/';
2944 * Returns true if the path is absolute, without backpath '..' and within the PATH_site OR within the lockRootPath
2947 * @param string Filepath to evaluate
2950 function isAllowedAbsPath($path) {
2951 if (t3lib_div
::isAbsPath($path) &&
2952 t3lib_div
::validPathStr($path) &&
2953 ( t3lib_div
::isFirstPartOfStr($path,PATH_site
)
2955 ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div
::isFirstPartOfStr($path,$GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath']))
2961 * Verifies the input filename againts the 'fileDenyPattern'. Returns true if OK.
2964 * @param string Filepath to evaluate
2967 function verifyFilenameAgainstDenyPattern($filename) {
2968 if (strcmp($filename,'') && strcmp($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],'')) {
2969 $result = eregi($GLOBALS['TYPO3_CONF_VARS']['BE']['fileDenyPattern'],$filename);
2970 if ($result) return false; // so if a matching filename is found, return false;
2976 * Moves $source file to $destination if uploaded, otherwise try to make a copy
2979 * @param string Source file, absolute path
2980 * @param string Destination file, absolute path
2981 * @return boolean Returns true if the file was moved.
2982 * @coauthor Dennis Petersen <fessor@software.dk>
2983 * @see upload_to_tempfile()
2985 function upload_copy_move($source,$destination) {
2986 if (is_uploaded_file($source)) {
2988 // 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:
2989 $uploadedResult = move_uploaded_file($source, $destination);
2992 @copy
($source,$destination);
2995 t3lib_div
::fixPermissions($destination); // Change the permissions of the file
2997 // 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
2998 return $uploaded ?
$uploadedResult : FALSE;
3002 * 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.
3003 * Use this function to move uploaded files to where you can work on them.
3004 * REMEMBER to use t3lib_div::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in PATH_site."typo3temp/"!
3007 * @param string The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']
3008 * @return string If a new file was successfully created, return its filename, otherwise blank string.
3009 * @see unlink_tempfile(), upload_copy_move()
3011 function upload_to_tempfile($uploadedFileName) {
3012 if (is_uploaded_file($uploadedFileName)) {
3013 $tempFile = t3lib_div
::tempnam('upload_temp_');
3014 move_uploaded_file($uploadedFileName, $tempFile);
3015 return @is_file
($tempFile) ?
$tempFile : '';
3020 * Deletes (unlink) a temporary filename in 'PATH_site."typo3temp/"' given as input.
3021 * 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.
3022 * Use this after upload_to_tempfile() or tempnam() from this class!
3025 * @param string Filepath for a file in PATH_site."typo3temp/". Must be absolute.
3026 * @return boolean Returns true if the file was unlink()'ed
3027 * @see upload_to_tempfile(), tempnam()
3029 function unlink_tempfile($uploadedTempFileName) {
3030 if ($uploadedTempFileName && t3lib_div
::validPathStr($uploadedTempFileName) && t3lib_div
::isFirstPartOfStr($uploadedTempFileName,PATH_site
.'typo3temp/') && @is_file
($uploadedTempFileName)) {
3031 if (unlink($uploadedTempFileName)) return TRUE;
3036 * Create temporary filename (Create file with unique file name)
3037 * This function should be used for getting temporary filenames - will make your applications safe for open_basedir = on
3038 * REMEMBER to delete the temporary files after use! This is done by t3lib_div::unlink_tempfile()
3041 * @param string Prefix to temp file (which will have no extension btw)
3042 * @return string result from PHP function tempnam() with PATH_site.'typo3temp/' set for temp path.
3043 * @see unlink_tempfile(), upload_to_tempfile()
3045 function tempnam($filePrefix) {
3046 return tempnam(PATH_site
.'typo3temp/',$filePrefix);
3050 * standard authentication code - can't remember what it's used for.
3053 * @param mixed Uid (integer) or record (array)
3054 * @param string List of fields from the record if that is given.
3055 * @return string MD5 hash of 8 chars.
3058 function stdAuthCode($uid_or_record,$fields='') {
3059 if (is_array($uid_or_record)) {
3060 $recCopy_temp=array();
3062 $fieldArr = t3lib_div
::trimExplode(',',$fields,1);
3064 while(list($k,$v)=each($fieldArr)) {
3065 $recCopy_temp[$k]=$recCopy[$v];
3068 $recCopy_temp=$recCopy;
3070 $preKey = implode('|',$recCopy_temp);
3072 $preKey = $uid_or_record;
3075 $authCode = $preKey.'||'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3076 $authCode = substr(md5($authCode),0,8);
3081 * Splits the input query-parameters into an array with certain parameters filtered out.
3082 * Used to create the cHash value
3084 * @param string Query-parameters: "&xxx=yyy&zzz=uuu"
3085 * @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
3086 * @see tslib_fe::makeCacheHash(), tslib_cObj::typoLink()
3088 function cHashParams($addQueryParams) {
3089 $params = explode('&',substr($addQueryParams,1)); // Splitting parameters up
3093 foreach($params as $theP) {
3094 $pKV = explode('=', $theP); // Splitting single param by '=' sign
3095 if (!t3lib_div
::inList('id,type,no_cache,cHash,MP,ftu',$pKV[0])) {
3096 $pA[$pKV[0]] = (string)rawurldecode($pKV[1]);
3099 $pA['encryptionKey'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
3106 * Responds on input localization setting value whether the page it comes from should be hidden if no translation exists or not.
3108 * @param integer Value from "l18n_cfg" field of a page record
3109 * @return boolean True if the page should be hidden
3111 function hideIfNotTranslated($l18n_cfg_fieldValue) {
3112 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['hidePagesIfNotTranslatedByDefault']) {
3113 return $l18n_cfg_fieldValue&2 ?
FALSE : TRUE;
3115 return $l18n_cfg_fieldValue&2 ?
TRUE : FALSE;
3120 * Includes a locallang file and returns the $LOCAL_LANG array found inside.
3122 * @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.
3123 * @param string Language key
3124 * @return array Value of $LOCAL_LANG found in the included file. If that array is found it's returned. Otherwise an empty array
3126 function readLLfile($fileRef,$langKey) {
3127 $file = t3lib_div
::getFileAbsFileName($fileRef);
3129 $baseFile = ereg_replace('\.(php|xml)$', '', $file);
3131 if (@is_file
($baseFile.'.xml')) {
3132 $LOCAL_LANG = t3lib_div
::readLLXMLfile($baseFile.'.xml', $langKey);
3133 } elseif (@is_file
($baseFile.'.php')) {
3134 include($baseFile.'.php');
3135 } else die('Filereference, "'.$file.'", not found!');
3138 return is_array($LOCAL_LANG)?
$LOCAL_LANG:array();
3142 * Includes a locallang-xml file and returns the $LOCAL_LANG array
3143 * Works only when the frontend or backend has been initialized with a charset conversion object. See first code lines.
3145 * @param string Absolute reference to locallang-XML file
3146 * @param string TYPO3 language key, eg. "dk" or "de" or "default"
3147 * @return array LOCAL_LANG array in return.
3149 function readLLXMLfile($fileRef,$langKey) {
3151 if (is_object($GLOBALS['LANG'])) {
3152 $csConvObj = &$GLOBALS['LANG']->csConvObj
;
3153 } elseif (is_object($GLOBALS['TSFE'])) {
3154 $csConvObj = &$GLOBALS['TSFE']->csConvObj
;
3155 } else $csConvObj = NULL;
3157 if (@is_file
($fileRef) && $langKey && is_object($csConvObj)) {
3160 $origCharset = $csConvObj->parse_charset($csConvObj->charSetArray
[$langKey] ?
$csConvObj->charSetArray
[$langKey] : 'iso-8859-1');
3163 $hashSource = substr($fileRef,strlen(PATH_site
)).'|'.date('d-m-Y H:i:s',filemtime($fileRef));
3164 $cacheFileName = PATH_site
.'typo3temp/llxml/'.
3165 #str_replace('_','',ereg_replace('^.*\/','',dirname($fileRef))).
3166 #'_'.basename($fileRef).
3167 substr(basename($fileRef),10,15).
3168 '_'.t3lib_div
::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
3170 // Check if cache file exists...
3171 if (!@is_file
($cacheFileName)) { // ... if it doesn't, create content and write it:
3173 // Read XML, parse it.
3174 $xmlString = t3lib_div
::getUrl($fileRef);
3175 $xmlContent = t3lib_div
::xml2array($xmlString);
3177 // Set default LOCAL_LANG array content:
3178 $LOCAL_LANG = array();
3179 $LOCAL_LANG['default'] = $xmlContent['data']['default'];
3181 // Specific language, convert from utf-8 to backend language charset:
3182 // NOTICE: Converting from utf-8 back to "native" language may be a temporary solution until we can totally discard "locallang.php" files altogether (and use utf-8 for everything). But doing this conversion is the quickest way to migrate now and the source is in utf-8 anyway which is the main point.
3183 if ($langKey!='default') {
3184 $LOCAL_LANG[$langKey] = $xmlContent['data'][$langKey];
3186 // Checking if charset should be converted.
3187 if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8') {
3188 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
3189 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
3194 // Cache the content now:
3195 $serContent = array('origFile'=>$hashSource, 'LOCAL_LANG'=>$LOCAL_LANG);
3196 $res = t3lib_div
::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
3197 if ($res) die('ERROR: '.$res);
3199 // Get content from cache:
3200 $serContent = unserialize(t3lib_div
::getUrl($cacheFileName));
3201 $LOCAL_LANG = $serContent['LOCAL_LANG'];
3204 // Checking for EXTERNAL file for non-default language:
3205 if ($langKey!='default' && is_string($LOCAL_LANG[$langKey]) && strlen($LOCAL_LANG[$langKey])) {
3207 // Look for localized file:
3208 $localized_file = t3lib_div
::getFileAbsFileName($LOCAL_LANG[$langKey]);
3209 if ($localized_file && @is_file
($localized_file)) {
3212 $hashSource = substr($localized_file,strlen(PATH_site
)).'|'.date('d-m-Y H:i:s',filemtime($localized_file));
3213 $cacheFileName = PATH_site
.'typo3temp/llxml/ext_'.
3214 substr(basename($localized_file),10,15).
3215 '_'.t3lib_div
::shortMD5($hashSource).'.'.$langKey.'.'.$origCharset.'.cache';
3217 // Check if cache file exists...
3218 if (!@is_file
($cacheFileName)) { // ... if it doesn't, create content and write it:
3220 // Read and parse XML content:
3221 $local_xmlString = t3lib_div
::getUrl($localized_file);
3222 $local_xmlContent = t3lib_div
::xml2array($local_xmlString);
3223 $LOCAL_LANG[$langKey] = is_array($local_xmlContent['data'][$langKey]) ?
$local_xmlContent['data'][$langKey] : array();
3225 // Checking if charset should be converted.
3226 if (is_array($LOCAL_LANG[$langKey]) && $origCharset!='utf-8') {
3227 foreach($LOCAL_LANG[$langKey] as $labelKey => $labelValue) {
3228 $LOCAL_LANG[$langKey][$labelKey] = $csConvObj->utf8_decode($labelValue,$origCharset);
3232 // Cache the content now:
3233 $serContent = array('extlang'=>$langKey, 'origFile'=>$LOCAL_LANG[$langKey], 'EXT_DATA'=>$LOCAL_LANG[$langKey]);
3234 $res = t3lib_div
::writeFileToTypo3tempDir($cacheFileName, serialize($serContent));
3235 if ($res) die('ERROR: '.$res);
3237 // Get content from cache:
3238 $serContent = unserialize(t3lib_div
::getUrl($cacheFileName));
3239 $LOCAL_LANG[$langKey] = $serContent['EXT_DATA'];
3242 $LOCAL_LANG[$langKey] = array();
3251 * Loads the $TCA (Table Configuration Array) for the $table
3254 * 1) must be configured table (the ctrl-section configured),
3255 * 2) columns must not be an array (which it is always if whole table loaded), and
3256 * 3) there is a value for dynamicConfigFile (filename in typo3conf)
3259 * @param string Table name for which to load the full TCA array part into the global $TCA
3262 function loadTCA($table) {
3263 global $TCA,$LANG_GENERAL_LABELS;
3264 if (isset($TCA[$table]) && !is_array($TCA[$table]['columns']) && $TCA[$table]['ctrl']['dynamicConfigFile']) {
3265 if (!strcmp(substr($TCA[$table]['ctrl']['dynamicConfigFile'],0,6),'T3LIB:')) {
3266 include(PATH_t3lib
.'stddb/'.substr($TCA[$table]['ctrl']['dynamicConfigFile'],6));
3267 } elseif (t3lib_div
::isAbsPath($TCA[$table]['ctrl']['dynamicConfigFile']) && @is_file
($TCA[$table]['ctrl']['dynamicConfigFile'])) { // Absolute path...
3268 include($TCA[$table]['ctrl']['dynamicConfigFile']);
3269 } else include(PATH_typo3conf
.$TCA[$table]['ctrl']['dynamicConfigFile']);
3274 * Looks for a sheet-definition in the input data structure array. If found it will return the data structure for the sheet given as $sheet (if found).
3275 * If the sheet definition is in an external file that file is parsed and the data structure inside of that is returned.
3278 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3279 * @param string The sheet to return, preferably.
3280 * @return array An array with two num. keys: key0: The data structure is returned in this key (array) UNLESS an error happend in which case an error string is returned (string). key1: The used sheet key value!
3282 function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') {
3283 if (is_array($dataStructArray['sheets'])) {
3284 $singleSheet = FALSE;
3285 if (!isset($dataStructArray['sheets'][$sheet])) {
3288 $dataStruct = $dataStructArray['sheets'][$sheet];
3290 // If not an array, but still set, then regard it as a relative reference to a file:
3291 if ($dataStruct && !is_array($dataStruct)) {
3292 $file = t3lib_div
::getFileAbsFileName($dataStruct);
3293 if ($file && @is_file
($file)) {
3294 $dataStruct = t3lib_div
::xml2array(t3lib_div
::getUrl($file));
3298 $singleSheet = TRUE;
3299 $dataStruct = $dataStructArray;
3300 unset($dataStruct['meta']); // Meta data should not appear there.
3301 $sheet = 'sDEF'; // Default sheet
3303 return array($dataStruct,$sheet,$singleSheet);
3307 * Resolves ALL sheet definitions in dataStructArray
3308 * If no sheet is found, then the default "sDEF" will be created with the dataStructure inside.
3310 * @param array Input data structure, possibly with a sheet-definition and references to external data source files.
3311 * @return array Output data structure with all sheets resolved as arrays.
3313 function resolveAllSheetsInDS($dataStructArray) {
3314 if (is_array($dataStructArray['sheets'])) {
3315 $out=array('sheets'=>array());
3316 foreach($dataStructArray['sheets'] as $sheetId => $sDat) {
3317 list($ds,$aS) = t3lib_div
::resolveSheetDefInDS($dataStructArray,$sheetId);
3318 if ($sheetId==$aS) {
3319 $out['sheets'][$aS]=$ds;
3323 list($ds) = t3lib_div
::resolveSheetDefInDS($dataStructArray);
3324 $out = array('sheets' => array('sDEF' => $ds));
3330 * Calls a userdefined function/method in class
3331 * Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
3334 * @param string Function/Method reference, '[file-reference":"]["&"]class/function["->"method-name]'. You can prefix this reference with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl->encodeSpURL". Finally; you can prefix the class name with "&" if you want to reuse a former instance of the same object call ("singleton").
3335 * @param mixed Parameters to be pass along (typically an array) (REFERENCE!)
3336 * @param mixed Reference to be passed along (typically "$this" - being a reference to the calling object) (REFERENCE!)
3337 * @param string Required prefix of class or function name
3338 * @param boolean If set, no debug() error message is shown if class/function is not present.
3339 * @return mixed Content from method/function call
3342 function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) {
3343 global $TYPO3_CONF_VARS;
3345 // Check persistent object and if found, call directly and exit.
3346 if (is_array($GLOBALS['T3_VAR']['callUserFunction'][$funcName])) {
3347 return call_user_method(
3348 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['method'],
3349 $GLOBALS['T3_VAR']['callUserFunction'][$funcName]['obj'],
3355 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3356 if (strstr($funcName,':')) {
3357 list($file,$funcRef) = t3lib_div
::revExplode(':',$funcName,2);
3358 $requireFile = t3lib_div
::getFileAbsFileName($file);
3359 if ($requireFile) require_once($requireFile);
3361 $funcRef = $funcName;
3364 // Check for persistent object token, "&"
3365 if (substr($funcRef,0,1)=='&') {
3366 $funcRef = substr($funcRef,1);
3367 $storePersistentObject = TRUE;
3369 $storePersistentObject = FALSE;
3372 // Check prefix is valid:
3374 !t3lib_div
::isFirstPartOfStr(trim($funcRef),$checkPrefix) &&
3375 !t3lib_div
::isFirstPartOfStr(trim($funcRef),'tx_')
3377 if (!$silent) debug("Function/Class '".$funcRef."' was not prepended with '".$checkPrefix."'",1);
3381 // Call function or method:
3382 $parts = explode('->',$funcRef);
3383 if (count($parts)==2) { // Class
3385 // Check if class/method exists:
3386 if (class_exists($parts[0])) {
3388 // Get/Create object of class:
3389 if ($storePersistentObject) { // Get reference to current instance of class:
3390 if (!is_object($GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]])) {
3391 $GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]] = &t3lib_div
::makeInstance($parts[0]);
3393 $classObj = &$GLOBALS['T3_VAR']['callUserFunction_classPool'][$parts[0]];
3394 } else { // Create new object:
3395 $classObj = &t3lib_div
::makeInstance($parts[0]);
3398 if (method_exists($classObj, $parts[1])) {
3400 // If persistent object should be created, set reference:
3401 if ($storePersistentObject) {
3402 $GLOBALS['T3_VAR']['callUserFunction'][$funcName] = array (
3403 'method' => $parts[1],
3408 $content = call_user_method(
3415 if (!$silent) debug("<strong>ERROR:</strong> No method name '".$parts[1]."' in class ".$parts[0],1);
3418 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$parts[0],1);
3420 } else { // Function
3421 if (function_exists($funcRef)) {
3422 $content = call_user_func($funcRef, $params, $ref);
3424 if (!$silent) debug("<strong>ERROR:</strong> No function named: ".$funcRef,1);
3431 * Creates and returns reference to a user defined object.
3432 * This function can return an object reference if you like. Just prefix the function call with "&": "$objRef = &t3lib_div::getUserObj('EXT:myext/class.tx_myext_myclass.php:&tx_myext_myclass');". This will work ONLY if you prefix the class name with "&" as well. See description of function arguments.
3435 * @param string Class reference, '[file-reference":"]["&"]class-name'. You can prefix the class name with "[file-reference]:" and t3lib_div::getFileAbsFileName() will then be used to resolve the filename and subsequently include it by "require_once()" which means you don't have to worry about including the class file either! Example: "EXT:realurl/class.tx_realurl.php:&tx_realurl". Finally; for the class name you can prefix it with "&" and you will reuse the previous instance of the object identified by the full reference string (meaning; if you ask for the same $classRef later in another place in the code you will get a reference to the first created one!).
3436 * @param string Required prefix of class name. By default "tx_" is allowed.
3437 * @param boolean If set, no debug() error message is shown if class/function is not present.
3438 * @return object The instance of the class asked for. Instance is created with t3lib_div::makeInstance
3439 * @see callUserFunction()
3441 function &getUserObj($classRef,$checkPrefix='user_',$silent=0) {
3442 global $TYPO3_CONF_VARS;
3443 // Check persistent object and if found, call directly and exit.
3444 if (is_object($GLOBALS['T3_VAR']['getUserObj'][$classRef])) {
3445 return $GLOBALS['T3_VAR']['getUserObj'][$classRef];
3448 // Check file-reference prefix; if found, require_once() the file (should be library of code)
3449 if (strstr($classRef,':')) {
3450 list($file,$class) = t3lib_div
::revExplode(':',$classRef,2);
3451 $requireFile = t3lib_div
::getFileAbsFileName($file);
3452 if ($requireFile) require_once($requireFile);
3457 // Check for persistent object token, "&"
3458 if (substr($class,0,1)=='&') {
3459 $class = substr($class,1);
3460 $storePersistentObject = TRUE;
3462 $storePersistentObject = FALSE;
3465 // Check prefix is valid:
3467 !t3lib_div
::isFirstPartOfStr(trim($class),$checkPrefix) &&
3468 !t3lib_div
::isFirstPartOfStr(trim($class),'tx_')
3470 if (!$silent) debug("Class '".$class."' was not prepended with '".$checkPrefix."'",1);
3474 // Check if class exists:
3475 if (class_exists($class)) {
3476 $classObj = &t3lib_div
::makeInstance($class);
3478 // If persistent object should be created, set reference:
3479 if ($storePersistentObject) {
3480 $GLOBALS['T3_VAR']['getUserObj'][$classRef] = &$classObj;
3485 if (!$silent) debug("<strong>ERROR:</strong> No class named: ".$class,1);
3491 * Make instance of class
3492 * Takes the class-extensions API of TYPO3 into account
3493 * Please USE THIS instead of the PHP "new" keyword. Eg. "$obj = new myclass;" should be "$obj = t3lib_div::makeInstance("myclass")" instead!
3496 * @param string Class name to instantiate
3497 * @return object The object
3499 function &makeInstance($className) {
3500 return class_exists('ux_'.$className) ? t3lib_div
::makeInstance('ux_'.$className) : new $className;
3504 * Return classname for new instance
3505 * Takes the class-extensions API of TYPO3 into account
3508 * @param string Base Class name to evaluate
3509 * @return string Final class name to instantiate with "new [classname]"
3511 function makeInstanceClassName($className) {
3512 return class_exists('ux_'.$className) ? t3lib_div
::makeInstanceClassName('ux_'.$className) : $className;
3516 * Find the best service and check if it works.
3517 * Returns object of the service class.
3519 * @param string Type of service (service key).
3520 * @param string Sub type like file extensions or similar. Defined by the service.
3521 * @param mixed List of service keys which should be exluded in the search for a service. Array or comma list.
3522 * @return object The service object or an array with error info's.
3523 * @author René Fritz <r.fritz@colorcube.de>
3525 function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) {
3526 global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
3530 if (!is_array($excludeServiceKeys) ) {
3531 $excludeServiceKeys = t3lib_div
::trimExplode(',', $excludeServiceKeys, 1);
3533 while ($info = t3lib_extMgm
::findService($serviceType, $serviceSubType, $excludeServiceKeys)) {
3535 // Check persistent object and if found, call directly and exit.
3536 if (is_object($GLOBALS['T3_VAR']['makeInstanceService'][$info['className']])) {
3537 // reset service and return object
3538 $T3_VAR['makeInstanceService'][$info['className']]->reset();
3539 return $GLOBALS['T3_VAR']['makeInstanceService'][$info['className']];
3541 // include file and create object
3543 $requireFile = t3lib_div
::getFileAbsFileName($info['classFile']);
3544 if (@is_file
($requireFile)) {
3545 require_once ($requireFile);
3546 $obj = t3lib_div
::makeInstance($info['className']);
3547 if (is_object($obj)) {
3548 if(!@is_callable
(array($obj,'init'))) {
3549 // use silent logging??? I don't think so.
3550 die ('Broken service:'.t3lib_div
::view_array($info));
3553 if ($obj->init()) { // service available?
3555 // create persistent object
3556 $T3_VAR['makeInstanceService'][$info['className']] = &$obj;
3558 // needed to delete temp files
3559 register_shutdown_function(array(&$obj, '__destruct'));
3561 return $obj; // object is passed as reference by function definition
3563 $error = $obj->getLastErrorArray();
3568 // deactivate the service
3569 t3lib_extMgm
::deactivateService($info['serviceType'],$info['serviceKey']);
3575 * Simple substitute for the PHP function mail() which allows you to specify encoding and character set
3576 * The fifth parameter, $enc, will allow you to specify 'base64' encryption for the output (set $enc=base64)
3577 * Further the output has the charset set to ISO-8859-1 by default.
3580 * @param string Email address to send to. (see PHP function mail())
3581 * @param string Subject line, non-encoded. (see PHP function mail())
3582 * @param string Message content, non-encoded. (see PHP function mail())
3583 * @param string Headers, separated by chr(10)
3584 * @param string Encoding type: "base64", "quoted-printable", "8bit". If blank, no encoding will be used, no encoding headers set.
3585 * @param string Charset used in encoding-headers (only if $enc is set to a valid value which produces such a header)
3586 * @param boolean If set, the content of $subject will not be encoded.
3589 function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0) {
3590 switch((string)$enc) {
3592 $headers=trim($headers).chr(10).
3593 'Mime-Version: 1.0'.chr(10).
3594 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3595 'Content-Transfer-Encoding: base64';
3597 $message=trim(chunk_split(base64_encode($message.chr(10)))).chr(10); // Adding chr(10) because I think MS outlook 2002 wants it... may be removed later again.
3599 if (!$dontEncodeSubject) $subject='=?'.$charset.'?B?'.base64_encode($subject).'?=';
3601 case 'quoted-printable':
3602 $headers=trim($headers).chr(10).
3603 'Mime-Version: 1.0'.chr(10).
3604 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3605 'Content-Transfer-Encoding: quoted-printable';
3607 $message=t3lib_div
::quoted_printable($message);
3609 if (!$dontEncodeSubject) $subject='=?'.$charset.'?Q?'.trim(t3lib_div
::quoted_printable(ereg_replace('[[:space:]]','_',$subject),1000)).'?=';
3612 $headers=trim($headers).chr(10).
3613 'Mime-Version: 1.0'.chr(10).
3614 'Content-Type: text/plain; charset="'.$charset.'"'.chr(10).
3615 'Content-Transfer-Encoding: 8bit';
3618 $headers=trim(implode(chr(10),t3lib_div
::trimExplode(chr(10),$headers,1))); // make sure no empty lines are there.
3620 mail($email,$subject,$message,$headers);
3624 * Implementation of quoted-printable encode.
3625 * This functions is buggy. It seems that in the part where the lines are breaked every 76th character, that it fails if the break happens right in a quoted_printable encode character!
3626 * Important: For the ease of use, this function internally uses Unix linebreaks ("\n") for breaking lines, but the output must use "\r\n" instead!
3627 * See RFC 1521, section 5.1 Quoted-Printable Content-Transfer-Encoding
3630 * @param string Content to encode
3631 * @param integer Length of the lines, default is 76
3632 * @return string The QP encoded string
3634 function quoted_printable($string,$maxlen=76) {
3635 // Make sure the string contains only Unix linebreaks
3636 $string = str_replace(chr(13).chr(10), chr(10), $string); // Replace Windows breaks (\r\n)
3637 $string = str_replace(chr(13), chr(10), $string); // Replace Mac breaks (\r)
3640 $theLines = explode(chr(10),$string); // Split lines
3641 foreach($theLines as $val) {
3643 $theValLen = strlen($val);
3645 for ($index=0; $index < $theValLen; $index++
) { // Walk through each character of this line
3646 $char = substr($val,$index,1);
3647 $ordVal = ord($char);
3648 if ($len>($maxlen-4) ||
($len>(($maxlen-10)-4)&&$ordVal==32)) {
3649 $newVal.='='.chr(13).chr(10); // Add a line break
3650 $len=0; // Reset the length counter
3652 if (($ordVal>=33 && $ordVal<=60) ||
($ordVal>=62 && $ordVal<=126) ||
$ordVal==9 ||
$ordVal==32) {
3653 $newVal.=$char; // This character is ok, add it to the message
3656 $newVal.=sprintf('=%02X',$ordVal); // Special character, needs to be encoded
3660 $newVal = ereg_replace(chr(32).'$','=20',$newVal); // Replaces a possible SPACE-character at the end of a line
3661 $newVal = ereg_replace(chr(9).'$','=09',$newVal); // Replaces a possible TAB-character at the end of a line
3662 $newString.=$newVal.chr(13).chr(10);
3664 return ereg_replace(chr(13).chr(10).'$','',$newString);
3668 * Takes a clear-text message body for a plain text email, finds all 'http://' links and if they are longer than 76 chars they are converted to a shorter URL with a hash parameter. The real parameter is stored in the database and the hash-parameter/URL will be redirected to the real parameter when the link is clicked.
3669 * This function is about preserving long links in messages.
3672 * @param string Message content
3673 * @param string URL mode; "76" or "all"
3674 * @param string URL of index script (see makeRedirectUrl())
3675 * @return string Processed message content
3676 * @see makeRedirectUrl()
3678 function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') {
3679 // Substitute URLs with shorter links:
3680 $urlSplit=explode('http://',$message);
3682 while(list($c,$v)=each($urlSplit)) {
3684 $newParts = split('[[:space:]]|\)|\(',$v,2);
3685 $newURL='http://'.$newParts[0];
3686 switch((string)$urlmode) {
3688 $newURL=t3lib_div
::makeRedirectUrl($newURL,0,$index_script_url);
3691 $newURL=t3lib_div
::makeRedirectUrl($newURL,76,$index_script_url);
3694 $urlSplit[$c]=$newURL.substr($v,strlen($newParts[0]));
3698 $message=implode('',$urlSplit);
3703 * Subfunction for substUrlsInPlainText() above.
3706 * @param string Input URL
3707 * @param integer URL string length limit
3708 * @param string URL of "index script" - the prefix of the "?RDCT=..." parameter. If not supplyed it will default to t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR')
3709 * @return string Processed URL
3712 function makeRedirectUrl($inUrl,$l=0,$index_script_url='') {
3713 if (strlen($inUrl)>$l) {
3714 $md5 = substr(md5($inUrl),0,20);
3715 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('md5hash', 'cache_md5params', 'md5hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($md5, 'cache_md5params'));
3716 if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
3717 $insertFields = array(
3724 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_md5params', $insertFields);
3726 $inUrl=($index_script_url ?
$index_script_url : t3lib_div
::getIndpEnv('TYPO3_REQUEST_DIR')).
3733 * Function to compensate for FreeType2 96 dpi
3736 * @param integer Fontsize for freetype function call
3737 * @return integer Compensated fontsize based on $GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']
3739 function freetypeDpiComp($font_size) {
3740 $dpi = intval($GLOBALS['TYPO3_CONF_VARS']['GFX']['TTFdpi']);
3741 if ($dpi!=72) $font_size = $font_size/$dpi*72;
3746 * Developer log; This should be implemented around the source code, both frontend and backend, logging everything from the flow through an application, messages, results from comparisons to fatal errors.
3747 * The result is meant to make sense to developers during development or debugging of a site.
3748 * The idea is that this function is only a wrapper for external extensions which can set a hook which will be allowed to handle the logging of the information to any format they might wish and with any kind of filter they would like.
3749 * If you want to implement the devLog in your applications, simply add lines like:
3750 * if (TYPO3_DLOG) t3lib_div::devLog('[write message in english here]', 'extension key');
3752 * @param string Message (in english).
3753 * @param string Extension key (from which extension you are calling the log)
3754 * @param integer Severity: 0 is info, 1 is notice, 2 is warning, 3 is fatal error, -1 is "OK" message
3755 * @param array Additional data you want to pass to the logger.
3758 function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) {
3759 global $TYPO3_CONF_VARS;
3761 if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'])) {
3762 $params = array('msg'=>$msg, 'extKey'=>$extKey, 'severity'=>$severity, 'dataVar'=>$dataVar);
3764 foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['devLog'] as $hookMethod) {
3765 t3lib_div
::callUserFunction($hookMethod,$params,$fakeThis);
3771 * Converts a one dimensional array to a one line string which can be used for logging or debugging output
3772 * Example: "loginType: FE; refInfo: Array; HTTP_HOST: www.example.org; REMOTE_ADDR: 192.168.1.5; REMOTE_HOST:; security_level:; showHiddenRecords: 0;"
3774 * @param array Data array which should be outputted
3775 * @param mixed List of keys which should be listed in the output string. Pass a comma list or an array. An empty list outputs the whole array.
3776 * @param integer Long string values are shortened to this length. Default: 20
3777 * @return string Output string with key names and their value as string
3779 function arrayToLogString($arr, $valueList=array(), $valueLength=20) {
3781 if(is_array($arr)) {
3782 if (!is_array($valueList)) {
3783 $valueList = explode(',', $valueList);
3785 foreach($arr as $key => $value) {
3786 if (!count($valueList) OR (count($valueList) AND in_array($key, $valueList))) {
3787 $str .= (string)$key.trim(': '.t3lib_div
::fixed_lgd(str_replace("\n",'|',(string)$value), $valueLength)).'; ';
3795 * Compile the command for running ImageMagick/GraphicsMagick.
3797 * @param string Command to be run
3798 * @param string The parameters string
3799 * @param string Override the default path
3800 * @return string Compiled command that deals with IM6 & GraphicsMagick
3802 function imageMagickCommand($command, $parameters, $path='') {
3803 $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX'];
3804 $isExt = (TYPO3_OS
=='WIN' ?
'.exe' : '');
3805 $switchCompositeParameters=false;
3807 if(!$path) { $path = $gfxConf['im_path']; }
3809 $im_version = strtolower($gfxConf['im_version_5']);
3810 $combineScript = $gfxConf['im_combine_filename'] ?
trim($gfxConf['im_combine_filename']) : 'combine';
3812 if($command==='combine') { // This is only used internally, has no effect outside
3813 $command = 'composite';
3816 // Compile the path & command
3817 if($im_version==='gm') {
3818 $switchCompositeParameters=true;
3819 $path .= 'gm'.$isExt.' '.$command;
3821 if($im_version==='im6') { $switchCompositeParameters=true; }
3822 $path .= (($command=='composite') ?
$combineScript : $command).$isExt;
3825 $cmdLine = $path.' '.$parameters;
3827 if($command=='composite' && $switchCompositeParameters) { // Because of some weird incompatibilities between ImageMagick 4 and 6 (plus GraphicsMagick), it is needed to change the parameters order under some preconditions
3828 $paramsArr = t3lib_div
::unQuoteFilenames($parameters);
3830 if(count($paramsArr)==6) { // The mask image has been specified => swap the parameters
3831 $tmp = $paramsArr[3];
3832 $paramsArr[3] = $paramsArr[2];
3833 $paramsArr[2] = $tmp;
3836 $cmdLine = $path.' '.implode(' ', $paramsArr);
3843 * Explode a string (normally a list of filenames) with whitespaces by considering quotes in that string. This is mostly needed by the imageMagickCommand function above.
3845 * @param string The whole parameters string
3846 * @return array Exploded parameters
3848 function unQuoteFilenames($parameters) {
3849 $paramsArr = explode(' ', trim($parameters));
3851 $quoteActive = -1; // Whenever a quote character (") is found, $quoteActive is set to the element number inside of $params. A value of -1 means that there are not open quotes at the current position.
3852 foreach($paramsArr as $k=>$v) {
3853 if($quoteActive > -1) {
3854 $paramsArr[$quoteActive] .= ' '.$v;
3855 unset($paramsArr[$k]);
3856 if(ereg('"$', $v)) { $quoteActive = -1; }
3858 } elseif(!trim($v)) {
3859 unset($paramsArr[$k]); // Remove empty elements
3861 } elseif(ereg('^"', $v)) {