*/ /** * [CLASS/FUNCTION INDEX of SCRIPT] * * * * 211: class t3lib_div * * SECTION: GET/POST Variables * 241: function _GP($var) * 259: function _GET($var=NULL) * 276: function _POST($var=NULL) * 292: function _GETset($inputGet,$key='') * 315: function GPvar($var,$strip=0) * 332: function GParrayMerged($var) * * SECTION: IMAGE FUNCTIONS * 376: function gif_compress($theFile, $type) * 402: function png_to_gif_by_imagemagick($theFile) * 426: function read_png_gif($theFile,$output_png=0) * * SECTION: STRING FUNCTIONS * 475: function fixed_lgd($string,$origChars,$preStr='...') * 500: function fixed_lgd_pre($string,$chars) * 514: function fixed_lgd_cs($string,$chars) * 531: function breakTextForEmail($str,$implChar="\n",$charWidth=76) * 550: function breakLinesForEmail($str,$implChar="\n",$charWidth=76) * 585: function cmpIP($baseIP, $list) * 627: function cmpFQDN($baseIP, $list) * 657: function inList($list,$item) * 669: function rmFromList($element,$list) * 687: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) * 703: function intval_positive($theInt) * 716: function int_from_ver($verNumberStr) * 728: function md5int($str) * 741: function shortMD5($input, $len=10) * 754: function uniqueList($in_list, $secondParameter=NULL) * 768: function split_fileref($fileref) * 805: function dirname($path) * 821: function modifyHTMLColor($color,$R,$G,$B) * 841: function modifyHTMLColorAll($color,$all) * 852: function rm_endcomma($string) * 865: function danish_strtoupper($string) * 880: function convUmlauts($str) * 893: function testInt($var) * 905: function isFirstPartOfStr($str,$partStr) * 921: function formatSize($sizeInBytes,$labels='') * 956: function convertMicrotime($microtime) * 970: function splitCalc($string,$operators) * 992: function calcPriority($string) * 1032: function calcParenthesis($string) * 1058: function htmlspecialchars_decode($value) * 1073: function deHSCentities($str) * 1086: function slashJS($string,$extended=0,$char="'") * 1099: function rawUrlEncodeJS($str) * 1111: function rawUrlEncodeFP($str) * 1122: function validEmail($email) * 1137: function formatForTextarea($content) * * SECTION: ARRAY FUNCTIONS * 1168: function inArray($in_array,$item) * 1185: function intExplode($delim, $string) * 1204: function revExplode($delim, $string, $count=0) * 1224: function trimExplode($delim, $string, $onlyNonEmptyValues=0) * 1246: function uniqueArray($valueArray) * 1258: function removeArrayEntryByValue($array,$cmpValue) * 1286: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) * 1313: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) * 1336: function addSlashesOnArray(&$theArray) * 1360: function stripSlashesOnArray(&$theArray) * 1382: function slashArray($arr,$cmd) * 1399: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmtpyValues=true) * 1432: function array_merge($arr1,$arr2) * 1445: function csvValues($row,$delim=',',$quote='"') * * SECTION: HTML/XML PROCESSING * 1487: function get_tag_attributes($tag) * 1524: function split_tag_attributes($tag) * 1558: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) * 1585: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) * 1600: function wrapJS($string, $linebreak=TRUE) * 1630: function xml2tree($string,$depth=999) * 1716: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array()) * 1830: function xml2array($string,$NSprefix='',$reportDocTag=FALSE) * 1940: function xmlRecompileFromStructValArray($vals) * 1984: function xmlGetHeaderAttribs($xmlData) * * SECTION: FILES FUNCTIONS * 2016: function getURL($url) * 2058: function writeFile($file,$content) * 2075: function fixPermissions($file) * 2092: function writeFileToTypo3tempDir($filepath,$content) * 2135: function mkdir($theNewFolder) * 2155: function get_dirs($path) * 2180: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') * 2234: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) * 2257: function removePrefixPathFromList($fileArr,$prefixToRemove) * 2273: function fixWindowsFilePath($theFile) * 2285: function resolveBackPath($pathStr) * 2312: function locationHeaderUrl($path) * * SECTION: DEBUG helper FUNCTIONS * 2352: function debug_ordvalue($string,$characters=100) * 2369: function view_array($array_in) * 2397: function print_array($array_in) * 2412: function debug($var="",$brOrHeader=0) * * SECTION: SYSTEM INFORMATION * 2481: function getThisUrl() * 2497: function linkThisScript($getParams=array()) * 2521: function linkThisUrl($url,$getParams=array()) * 2546: function getIndpEnv($getEnvName) * 2735: function milliseconds() * 2747: function clientInfo($useragent='') * * SECTION: TYPO3 SPECIFIC FUNCTIONS * 2834: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) * 2870: function validPathStr($theFile) * 2881: function isAbsPath($path) * 2892: function isAllowedAbsPath($path) * 2909: function verifyFilenameAgainstDenyPattern($filename) * 2927: function upload_copy_move($source,$destination) * 2953: function upload_to_tempfile($uploadedFileName) * 2971: function unlink_tempfile($uploadedTempFileName) * 2987: function tempnam($filePrefix) * 3000: function stdAuthCode($uid_or_record,$fields='') * 3030: function cHashParams($addQueryParams) * 3059: function loadTCA($table) * 3079: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') * 3109: function resolveAllSheetsInDS($dataStructArray) * 3138: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) * 3237: function &getUserObj($classRef,$checkPrefix='user_',$silent=0) * 3295: function &makeInstance($className) * 3307: function makeInstanceClassName($className) * 3321: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) * 3382: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='ISO-8859-1',$dontEncodeSubject=0) * 3427: function quoted_printable($string,$maxlen=76) * 3471: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') * 3505: function makeRedirectUrl($inUrl,$l=0,$index_script_url='') * 3532: function freetypeDpiComp($font_size) * 3551: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) * 3572: function arrayToLogString($arr, $valueList=array(), $valueLength=20) * * TOTAL FUNCTIONS: 117 * (This index is automatically created/updated by the extension "extdeveval") * */ /** * The legendary "t3lib_div" class - Miscellaneous functions for general purpose. * Most of the functions does not relate specifically to TYPO3 * However a section of functions requires certain TYPO3 features available * See comments in the source. * You are encouraged to use this library in your own scripts! * * USE: * The class is intended to be used without creating an instance of it. * So: Don't instantiate - call functions with "t3lib_div::" prefixed the function name. * So use t3lib_div::[method-name] to refer to the functions, eg. 't3lib_div::milliseconds()' * * @author Kasper Skaarhoj * @package TYPO3 * @subpackage t3lib */ class t3lib_div { /************************* * * GET/POST Variables * * Background: * Input GET/POST variables in PHP may have their quotes escaped with "\" or not depending on configuration. * TYPO3 has always converted quotes to BE escaped if the configuration told that they would not be so. * But the clean solution is that quotes are never escaped and that is what the functions below offers. * Eventually TYPO3 should provide this in the global space as well. * In the transitional phase (or forever..?) we need to encourage EVERY to read and write GET/POST vars through the API functions below. * *************************/ /** * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order) * Strips slashes from all output, both strings and arrays. * This function substitutes t3lib_div::GPvar() * 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! * Usage: 537 * * @param string GET/POST var to return * @return mixed POST var named $var and if not set, the GET var of the same name. * @see GPvar() */ function _GP($var) { if(empty($var)) return; $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var]; if (isset($value)) { if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); } } return $value; } /** * Returns the global GET array (or value from) normalized to contain un-escaped values. * ALWAYS use this API function to acquire the GET variables! * Usage: 27 * * @param string Optional pointer to value in GET array (basically name of GET var) * @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!* * @see _POST(), _GP(), _GETset() */ function _GET($var=NULL) { $value = ($var === NULL) ? $_GET : (empty($var) ? NULL : $_GET[$var]); if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); } } return $value; } /** * Returns the global POST array (or value from) normalized to contain un-escaped values. * ALWAYS use this API function to acquire the POST variables! * Usage: 41 * * @param string Optional pointer to value in POST array (basically name of POST var) * @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!* * @see _GET(), _GP() */ function _POST($var=NULL) { $value = ($var === NULL) ? $_POST : (empty($var) ? NULL : $_POST[$var]); if (isset($value)) { // Removes slashes since TYPO3 has added them regardless of magic_quotes setting. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); } } return $value; } /** * Writes input value to $_GET * Usage: 2 * * @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). * @param string Alternative key; If set, this will not set the WHOLE GET array, but only the key in it specified by this value! * @return void */ function _GETset($inputGet,$key='') { // ADDS slashes since TYPO3 standard currently is that slashes MUST be applied (regardless of magic_quotes setting). if (strcmp($key,'')) { if (is_array($inputGet)) { t3lib_div::addSlashesOnArray($inputGet); } else { $inputGet = addslashes($inputGet); } $GLOBALS['HTTP_GET_VARS'][$key] = $_GET[$key] = $inputGet; } elseif (is_array($inputGet)){ t3lib_div::addSlashesOnArray($inputGet); $GLOBALS['HTTP_GET_VARS'] = $_GET = $inputGet; } } /** * GET/POST variable * Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST (that is equalent to 'GP' order) * Strips slashes of string-outputs, but not arrays UNLESS $strip is set. If $strip is set all output will have escaped characters unescaped. * Usage: 2 * * @param string GET/POST var to return * @param boolean If set, values are stripped of return values that are *arrays!* - string/integer values returned are always strip-slashed() * @return mixed POST var named $var and if not set, the GET var of the same name. * @deprecated Use t3lib_div::_GP instead (ALWAYS delivers a value with un-escaped values!) * @see _GP() */ function GPvar($var,$strip=0) { if(empty($var)) return; $value = isset($_POST[$var]) ? $_POST[$var] : $_GET[$var]; 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. if ($strip && isset($value) && is_array($value)) { t3lib_div::stripSlashesOnArray($value); } return $value; } /** * Returns the GET/POST global arrays merged with POST taking precedence. * Usage: 1 * * @param string Key (variable name) from GET or POST vars * @return array Returns the GET vars merged recursively onto the POST vars. * @ignore * @deprecated */ function GParrayMerged($var) { $postA = is_array($_POST[$var]) ? $_POST[$var] : array(); $getA = is_array($_GET[$var]) ? $_GET[$var] : array(); $mergedA = t3lib_div::array_merge_recursive_overrule($getA,$postA); t3lib_div::stripSlashesOnArray($mergedA); return $mergedA; } /************************* * * IMAGE FUNCTIONS * *************************/ /** * Compressing a GIF file if not already LZW compressed * 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) * * The function takes a file-reference, $theFile, and saves it again through GD or ImageMagick in order to compress the file * GIF: * 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!) * If $type is set to either 'IM' or 'GD' the compression is done with ImageMagick and GD respectively * PNG: * No changes. * * $theFile is expected to be a valid GIF-file! * The function returns a code for the operation. * Usage: 9 * * @param string Filepath * @param string See description of function * @return string Returns "GD" if GD was used, otherwise "IM" if ImageMagick was used. If nothing done at all, it returns empty string. * @internal */ function gif_compress($theFile, $type) { $gfxConf = $GLOBALS['TYPO3_CONF_VARS']['GFX']; $returnCode=''; if ($gfxConf['gif_compress'] && strtolower(substr($theFile,-4,4))=='.gif') { // GIF... if (($type=='IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { // IM $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$theFile.'"', $gfxConf['im_path_lzw']); exec($cmd); $returnCode='IM'; } elseif (($type=='GD' || !$type) && $gfxConf['gdlib'] && !$gfxConf['gdlib_png']) { // GD $tempImage = imageCreateFromGif($theFile); imageGif($tempImage, $theFile); imageDestroy($tempImage); $returnCode='GD'; } } return $returnCode; } /** * Converts a png file to gif * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set true. * Usage: 5 * * @param string $theFile the filename with path * @return string new filename * @internal */ function png_to_gif_by_imagemagick($theFile) { if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path_lzw'] && strtolower(substr($theFile,-4,4))=='.png' && @is_file($theFile)) { // IM $newFile = substr($theFile,0,-4).'.gif'; $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $gfxConf['im_path_lzw']); exec($cmd); $theFile = $newFile; // 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!! } return $theFile; } /** * Returns filename of the png/gif version of the input file (which can be png or gif). * If input file type does not match the wanted output type a conversion is made and temp-filename returned. * Usage: 2 * * @param string Filepath of image file * @param boolean If set, then input file is converted to PNG, otherwise to GIF * @return string If the new image file exists, it's filepath is returned * @internal */ function read_png_gif($theFile,$output_png=0) { if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) { $ext = strtolower(substr($theFile,-4,4)); if ( ((string)$ext=='.png' && $output_png) || ((string)$ext=='.gif' && !$output_png) ) { return $theFile; } else { $newFile = PATH_site.'typo3temp/readPG_'.md5($theFile.'|'.filemtime($theFile)).($output_png?'.png':'.gif'); exec($GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path'].'convert "'.$theFile.'" "'.$newFile.'"'); if (@is_file($newFile)) return $newFile; } } } /************************* * * STRING FUNCTIONS * *************************/ /** * Truncate string * Returns a new string of max. $chars length. * If the string is longer, it will be truncated and appended with '...'. * DEPRECIATED. Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead * Usage: 39 * * @param string $string string to truncate * @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. * @param string String to append to the output if it is truncated, default is '...' * @return string new string * @see fixed_lgd_pre() */ function fixed_lgd($string,$origChars,$preStr='...') { $chars = abs($origChars); if ($chars >= 4) { if(strlen($string)>$chars) { return $origChars < 0 ? $preStr.trim(substr($string, -($chars-3))) : trim(substr($string, 0, $chars-3)).$preStr; } } return $string; } /** * Truncate string * Returns a new string of max. $chars length. * If the string is longer, it will be truncated and prepended with '...'. * This works like fixed_lgd, but is truncated in the start of the string instead of the end * DEPRECIATED. Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars) * Usage: 6 * * @param string $string string to truncate * @param integer $chars must be an integer of at least 4 * @return string new string * @see fixed_lgd() */ function fixed_lgd_pre($string,$chars) { return strrev(t3lib_div::fixed_lgd(strrev($string),$chars)); } /** * Truncates a string with appended/prepended "..." and takes backend character set into consideration * Use only from backend! * Usage: 75 * * @param string $string string to truncate * @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. * @return string New string * @see fixed_lgd() */ function fixed_lgd_cs($string,$chars) { if (is_object($GLOBALS['LANG'])) { return $GLOBALS['LANG']->csConvObj->crop($GLOBALS['LANG']->charSet,$string,$chars,'...'); } else { return t3lib_div::fixed_lgd($string, $chars); } } /** * Breaks up the text for emails * Usage: 1 * * @param string The string to break up * @param string The string to implode the broken lines with (default/typically \n) * @param integer The line length * @return string */ function breakTextForEmail($str,$implChar="\n",$charWidth=76) { $lines = explode(chr(10),$str); $outArr=array(); while(list(,$lStr)=each($lines)) { $outArr = array_merge($outArr,t3lib_div::breakLinesForEmail($lStr,$implChar,$charWidth)); } return implode(chr(10),$outArr); } /** * Breaks up a single line of text for emails * Usage: 5 * * @param string The string to break up * @param string The string to implode the broken lines with (default/typically \n) * @param integer The line length * @return string * @see breakTextForEmail() */ function breakLinesForEmail($str,$implChar="\n",$charWidth=76) { $lines=array(); $l=$charWidth; $p=0; while(strlen($str)>$p) { $substr=substr($str,$p,$l); if (strlen($substr)==$l) { $count = count(explode(' ',trim(strrev($substr)))); if ($count>1) { // OK... $parts = explode(' ',strrev($substr),2); $theLine = strrev($parts[1]); } else { $afterParts = explode(' ',substr($str,$l+$p),2); $theLine = $substr.$afterParts[0]; } if (!strlen($theLine)) {break; } // Error, because this would keep us in an endless loop. } else { $theLine=$substr; } $lines[]=trim($theLine); $p+=strlen($theLine); if (!trim(substr($str,$p,$l))) break; // added... } return implode($implChar,$lines); } /** * Match IP number with list of numbers with wildcard * Usage: 10 * * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR * @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) * @return boolean True if an IP-mask from $list matches $baseIP */ function cmpIP($baseIP, $list) { $IPpartsReq = explode('.',$baseIP); if (count($IPpartsReq)==4) { $values = t3lib_div::trimExplode(',',$list,1); foreach($values as $test) { list($test,$mask) = explode('/',$test); if(intval($mask)) { // "192.168.3.0/24" $lnet = ip2long($test); $lip = ip2long($baseIP); $binnet = str_pad( decbin($lnet),32,'0','STR_PAD_LEFT'); $firstpart = substr($binnet,0,$mask); $binip = str_pad( decbin($lip),32,'0','STR_PAD_LEFT'); $firstip = substr($binip,0,$mask); $yes = (strcmp($firstpart,$firstip)==0); } else { // "192.168.*.*" $IPparts = explode('.',$test); $yes = 1; reset($IPparts); while(list($index,$val)=each($IPparts)) { $val = trim($val); if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) { $yes=0; } } } if ($yes) return true; } } return false; } /** * Match fully qualified domain name with list of strings with wildcard * * @param string $baseIP is the current remote IP address for instance, typ. REMOTE_ADDR * @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) * @return boolean True if a domain name mask from $list matches $baseIP */ function cmpFQDN($baseIP, $list) { if (count(explode('.',$baseIP))==4) { $resolvedHostName = explode('.', gethostbyaddr($baseIP)); $values = t3lib_div::trimExplode(',',$list,1); foreach($values as $test) { $hostNameParts = explode('.',$test); $yes = 1; foreach($hostNameParts as $index => $val) { $val = trim($val); if (strcmp($val,'*') && strcmp($resolvedHostName[$index],$val)) { $yes=0; } } if ($yes) return true; } } return false; } /** * Check for item in list * Check if an item exists in a comma-separated list of items. * Usage: 163 * * @param string comma-separated list of items (string) * @param string item to check for * @return boolean true if $item is in $list */ function inList($list,$item) { return strstr(','.$list.',', ','.$item.',') ? true : false; } /** * Removes an item from a comma-separated list of items. * Usage: 1 * * @param string $element element to remove * @param string $list comma-separated list of items (string) * @return string new comma-separated list of items */ function rmFromList($element,$list) { $items = explode(',',$list); while(list($k,$v)=each($items)) { if ($v==$element) {unset($items[$k]);} } return implode(',',$items); } /** * Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7). * Ranges are limited to 1000 values per range. * * @param string $list comma-separated list of integers with ranges (string) * @return string new comma-separated list of items * @author Martin Kutschker */ function expandList($list) { $items = explode(',',$list); $list = array(); while(list(,$item)=each($items)) { $range = explode('-',$item); if (isset($range[1])) { $runAwayBrake = 1000; for ($n=$range[0]; $n<=$range[1]; $n++) { $list[] = $n; $runAwayBrake--; if ($runAwayBrake<=0) break; } } else { $list[] = $item; } } return implode(',',$list); } /** * Forces the integer $theInt into the boundaries of $min and $max. If the $theInt is 'false' then the $zeroValue is applied. * Usage: 224 * * @param integer Input value * @param integer Lower limit * @param integer Higher limit * @param integer Default value if input is false. * @return integer The input value forced into the boundaries of $min and $max */ function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) { // Returns $theInt as an integer in the integerspace from $min to $max $theInt = intval($theInt); if ($zeroValue && !$theInt) {$theInt=$zeroValue;} // If the input value is zero after being converted to integer, zeroValue may set another default value for it. if ($theInt<$min){$theInt=$min;} if ($theInt>$max){$theInt=$max;} return $theInt; } /** * Returns the $integer if greater than zero, otherwise returns zero. * Usage: 1 * * @param integer Integer string to process * @return integer */ function intval_positive($theInt) { $theInt = intval($theInt); if ($theInt<0){$theInt=0;} return $theInt; } /** * Returns an integer from a three part version number, eg '4.12.3' -> 4012003 * Usage: 2 * * @param string Version number on format x.x.x * @return integer Integer version of version number (where each part can count to 999) */ function int_from_ver($verNumberStr) { $verParts = explode('.',$verNumberStr); 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)); } /** * Makes a positive integer hash out of the first 7 chars from the md5 hash of the input * Usage: 5 * * @param string String to md5-hash * @return integer Returns 28bit integer-hash */ function md5int($str) { return hexdec(substr(md5($str),0,7)); } /** * Returns the first 10 positions of the MD5-hash (changed from 6 to 10 recently) * * Usage: 37 * * @param string Input string to be md5-hashed * @param integer The string-length of the output * @return string Substring of the resulting md5-hash, being $len chars long (from beginning) */ function shortMD5($input, $len=10) { return substr(md5($input),0,$len); } /** * Takes comma-separated lists and arrays and removes all duplicates * If a value in the list is trim(empty), the value is ignored. * Usage: 16 * * @param string Accept multiple parameters wich can be comma-separated lists of values and arrays. * @param mixed $secondParameter: Dummy field, which is set will show a warning! * @return string Returns the list without any duplicates of values, space around values are trimmed */ function uniqueList($in_list, $secondParameter=NULL) { if (is_array($in_list)) die('t3lib_div::uniqueList() does NOT support array arguments anymore! Only string comma lists!'); if (isset($secondParameter)) die('t3lib_div::uniqueList() does NOT support more than a single argument value anymore. You have specified more than one.'); return implode(',',array_unique(t3lib_div::trimExplode(',',$in_list,1))); } /** * Splits a reference to a file in 5 parts * Usage: 43 * * @param string Filename/filepath to be analysed * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext] */ function split_fileref($fileref) { if ( ereg('(.*/)(.*)$',$fileref,$reg) ) { $info['path'] = $reg[1]; $info['file'] = $reg[2]; } else { $info['path'] = ''; $info['file'] = $fileref; } $reg=''; if ( ereg('(.*)\.([^\.]*$)',$info['file'],$reg) ) { $info['filebody'] = $reg[1]; $info['fileext'] = strtolower($reg[2]); $info['realFileext'] = $reg[2]; } else { $info['filebody'] = $info['file']; $info['fileext'] = ''; } reset($info); return $info; } /** * Returns the directory part of a path without trailing slash * If there is no dir-part, then an empty string is returned. * Behaviour: * * '/dir1/dir2/script.php' => '/dir1/dir2' * '/dir1/' => '/dir1' * 'dir1/script.php' => 'dir1' * 'd/script.php' => 'd' * '/script.php' => '' * '' => '' * Usage: 5 * * @param string Directory name / path * @return string Processed input value. See function description. */ function dirname($path) { $p=t3lib_div::revExplode('/',$path,2); return count($p)==2?$p[0]:''; } /** * Modifies a HTML Hex color by adding/subtracting $R,$G and $B integers * Usage: 11 * * @param string A hexadecimal color code, #xxxxxx * @param integer Offset value 0-255 * @param integer Offset value 0-255 * @param integer Offset value 0-255 * @return string A hexadecimal color code, #xxxxxx, modified according to input vars * @see modifyHTMLColorAll() */ function modifyHTMLColor($color,$R,$G,$B) { // This takes a hex-color (# included!) and adds $R, $G and $B to the HTML-color (format: #xxxxxx) and returns the new color $nR = t3lib_div::intInRange(hexdec(substr($color,1,2))+$R,0,255); $nG = t3lib_div::intInRange(hexdec(substr($color,3,2))+$G,0,255); $nB = t3lib_div::intInRange(hexdec(substr($color,5,2))+$B,0,255); return '#'. substr('0'.dechex($nR),-2). substr('0'.dechex($nG),-2). substr('0'.dechex($nB),-2); } /** * Modifies a HTML Hex color by adding/subtracting $all integer from all R/G/B channels * Usage: 6 * * @param string A hexadecimal color code, #xxxxxx * @param integer Offset value 0-255 for all three channels. * @return string A hexadecimal color code, #xxxxxx, modified according to input vars * @see modifyHTMLColor() */ function modifyHTMLColorAll($color,$all) { return t3lib_div::modifyHTMLColor($color,$all,$all,$all); } /** * Removes comma (if present) in the end of string * Usage: 2 * * @param string String from which the comma in the end (if any) will be removed. * @return string */ function rm_endcomma($string) { return ereg_replace(',$','',$string); } /** * strtoupper which converts danish (and other characters) characters as well * (DEPRECIATED, use t3lib_cs::conv_case() instead or for HTML output, wrap your content in ...) * Usage: 0 * * @param string String to process * @return string * @ignore */ function danish_strtoupper($string) { $value = strtoupper($string); return strtr($value, 'áéúíâêûôîæøåäöü', 'ÁÉÚÍÄËÜÖÏÆØÅÄÖÜ'); } /** * Change umlaut characters to plain ASCII with normally two character target * Only known characters will be converted, so don't expect a result for any character. * (DEPRECIATED: Works only for western europe single-byte charsets! Use t3lib_cs::specCharsToASCII() instead!) * * ä => ae, Ö => Oe * * @param string String to convert. * @return string */ function convUmlauts($str) { $pat = array ( '/ä/', '/Ä/', '/ö/', '/Ö/', '/ü/', '/Ü/', '/ß/', '/å/', '/Å/', '/ø/', '/Ø/', '/æ/', '/Æ/' ); $repl = array ( 'ae', 'Ae', 'oe', 'Oe', 'ue', 'Ue', 'ss', 'aa', 'AA', 'oe', 'OE', 'ae', 'AE' ); return preg_replace($pat,$repl,$str); } /** * Tests if the input is an integer. * Usage: 77 * * @param mixed Any input variable to test. * @return boolean Returns true if string is an integer */ function testInt($var) { return !strcmp($var,intval($var)); } /** * Returns true if the first part of $str matches the string $partStr * Usage: 59 * * @param string Full string to check * @param string Reference string which must be found as the "first part" of the full string * @return boolean True if $partStr was found to be equal to the first part of $str */ function isFirstPartOfStr($str,$partStr) { // Returns true, if the first part of a $str equals $partStr and $partStr is not '' $psLen = strlen($partStr); if ($psLen) { return substr($str,0,$psLen)==(string)$partStr; } else return false; } /** * Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M) * Usage: 53 * * @param integer Number of bytes to format. * @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) * @return string Formatted representation of the byte number, for output. */ function formatSize($sizeInBytes,$labels='') { // Set labels: if (strlen($labels) == 0) { $labels = ' | K| M| G'; } else { $labels = str_replace('"','',$labels); } $labelArr = explode('|',$labels); // Find size: if ($sizeInBytes>900) { if ($sizeInBytes>900000000) { // GB $val = $sizeInBytes/(1024*1024*1024); return number_format($val, (($val<20)?1:0), '.', '').$labelArr[3]; } elseif ($sizeInBytes>900000) { // MB $val = $sizeInBytes/(1024*1024); return number_format($val, (($val<20)?1:0), '.', '').$labelArr[2]; } else { // KB $val = $sizeInBytes/(1024); return number_format($val, (($val<20)?1:0), '.', '').$labelArr[1]; } } else { // Bytes return $sizeInBytes.$labelArr[0]; } } /** * Returns microtime input to milliseconds * Usage: 2 * * @param string Microtime * @return integer Microtime input string converted to an integer (milliseconds) */ function convertMicrotime($microtime) { $parts = explode(' ',$microtime); return round(($parts[0]+$parts[1])*1000); } /** * This splits a string by the chars in $operators (typical /+-*) and returns an array with them in * Usage: 2 * * @param string Input string, eg "123 + 456 / 789 - 4" * @param string Operators to split by, typically "/+-*" * @return array Array with operators and operands separated. * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset() */ function splitCalc($string,$operators) { $res = Array(); $sign='+'; while($string) { $valueLen=strcspn($string,$operators); $value=substr($string,0,$valueLen); $res[] = Array($sign,trim($value)); $sign=substr($string,$valueLen,1); $string=substr($string,$valueLen+1); } reset($res); return $res; } /** * Calculates the input by +,-,*,/,%,^ with priority to + and - * Usage: 1 * * @param string Input string, eg "123 + 456 / 789 - 4" * @return integer Calculated value. Or error string. * @see calcParenthesis() */ function calcPriority($string) { $string=ereg_replace('[[:space:]]*','',$string); // removing all whitespace $string='+'.$string; // Ensuring an operator for the first entrance $qm='\*\/\+-^%'; $regex = '(['.$qm.'])(['.$qm.']?[0-9\.]*)'; // split the expression here: preg_match_all('/'.$regex.'/',$string,$reg); reset($reg[2]); $number=0; $Msign='+'; $err=''; $buffer=doubleval(current($reg[2])); next($reg[2]); // Advance pointer while(list($k,$v)=each($reg[2])) { $v=doubleval($v); $sign = $reg[1][$k]; if ($sign=='+' || $sign=='-') { $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer; $Msign = $sign; $buffer=$v; } else { if ($sign=='/') {if ($v) $buffer/=$v; else $err='dividing by zero';} if ($sign=='%') {if ($v) $buffer%=$v; else $err='dividing by zero';} if ($sign=='*') {$buffer*=$v;} if ($sign=='^') {$buffer=pow($buffer,$v);} } } $number = $Msign=='-' ? $number-=$buffer : $number+=$buffer; return $err ? 'ERROR: '.$err : $number; } /** * Calculates the input with parenthesis levels * Usage: 2 * * @param string Input string, eg "(123 + 456) / 789 - 4" * @return integer Calculated value. Or error string. * @see calcPriority(), tslib_cObj::stdWrap() */ function calcParenthesis($string) { $securC=100; do { $valueLenO=strcspn($string,'('); $valueLenC=strcspn($string,')'); if ($valueLenC==strlen($string) || $valueLenC < $valueLenO) { $value = t3lib_div::calcPriority(substr($string,0,$valueLenC)); $string = $value.substr($string,$valueLenC+1); return $string; } else { $string = substr($string,0,$valueLenO).t3lib_div::calcParenthesis(substr($string,$valueLenO+1)); } // Security: $securC--; if ($securC<=0) break; } while($valueLenO',$value); $value = str_replace('<','<',$value); $value = str_replace('"','"',$value); $value = str_replace('&','&',$value); return $value; } /** * Re-converts HTML entities if they have been converted by htmlspecialchars() * Usage: 10 * * @param string String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to "" * @return string Converted result. */ function deHSCentities($str) { return ereg_replace('&([#[:alnum:]]*;)','&\1',$str); } /** * This function is used to escape any ' -characters when transferring text to JavaScript! * Usage: 3 * * @param string String to escape * @param boolean If set, also backslashes are escaped. * @param string The character to escape, default is ' (single-quote) * @return string Processed input string */ function slashJS($string,$extended=0,$char="'") { if ($extended) {$string = str_replace ("\\", "\\\\", $string);} return str_replace ($char, "\\".$char, $string); } /** * Version of rawurlencode() where all spaces (%20) are re-converted to space-characters. * Usefull when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc. * Usage: 4 * * @param string String to raw-url-encode with spaces preserved * @return string Rawurlencoded result of input string, but with all %20 (space chars) converted to real spaces. */ function rawUrlEncodeJS($str) { return str_replace('%20',' ',rawurlencode($str)); } /** * rawurlencode which preserves "/" chars * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded. * Usage: 5 * * @param string Input string * @return string Output string */ function rawUrlEncodeFP($str) { return str_replace('%2F','/',rawurlencode($str)); } /** * Checking syntax of input email address * Usage: 5 * * @param string Input string to evaluate * @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. */ function validEmail($email) { $email = trim ($email); if (strstr($email,' ')) return FALSE; return ereg('^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$',$email) ? TRUE : FALSE; } /** * Formats a string for output between