X-Git-Url: https://git.typo3.org/Packages/TYPO3.CMS.git/blobdiff_plain/5900e2e46ba5bba65e63fcba8620f199a741ba24..0707d0b01a7472a4130ecf22e20825b26cfd2663:/t3lib/class.t3lib_div.php diff --git a/t3lib/class.t3lib_div.php b/t3lib/class.t3lib_div.php index 1b42bc1..674db0e 100644 --- a/t3lib/class.t3lib_div.php +++ b/t3lib/class.t3lib_div.php @@ -24,195 +24,10 @@ * * This copyright notice MUST APPEAR in all copies of the script! ***************************************************************/ -/** - * Contains the reknown class "t3lib_div" with general purpose functions - * - * Revised for TYPO3 3.6 July/2003 by Kasper SkÃ¥rhøj - * XHTML compliant - * Usage counts are based on search 22/2 2003 through whole source including tslib/ - * - * @author Kasper SkÃ¥rhøj - */ -/** - * [CLASS/FUNCTION INDEX of SCRIPT] - * - * - * - * 232: class t3lib_div - * - * SECTION: GET/POST Variables - * 262: function _GP($var) - * 280: function _GET($var=NULL) - * 297: function _POST($var=NULL) - * 313: function _GETset($inputGet,$key='') - * 336: function GPvar($var,$strip=0) - * 353: function GParrayMerged($var) - * - * SECTION: IMAGE FUNCTIONS - * 397: function gif_compress($theFile, $type) - * 425: function png_to_gif_by_imagemagick($theFile) - * 450: function read_png_gif($theFile,$output_png=0) - * - * SECTION: STRING FUNCTIONS - * 499: function fixed_lgd($string,$origChars,$preStr='...') - * 524: function fixed_lgd_pre($string,$chars) - * 538: function fixed_lgd_cs($string,$chars) - * 555: function breakTextForEmail($str,$implChar=LF,$charWidth=76) - * 574: function breakLinesForEmail($str,$implChar=LF,$charWidth=76) - * 610: function cmpIP($baseIP, $list) - * 626: function cmpIPv4($baseIP, $list) - * 668: function cmpIPv6($baseIP, $list) - * 711: function IPv6Hex2Bin ($hex) - * 726: function normalizeIPv6($address) - * 782: function validIPv6($ip) - * 805: function cmpFQDN($baseIP, $list) - * 835: function inList($list,$item) - * 847: function rmFromList($element,$list) - * 863: function expandList($list) - * 894: function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) - * 910: function intval_positive($theInt) - * 923: function int_from_ver($verNumberStr) - * 934: function compat_version($verNumberStr) - * 952: function md5int($str) - * 965: function shortMD5($input, $len=10) - * 978: function uniqueList($in_list, $secondParameter=NULL) - * 992: function split_fileref($fileref) - * 1030: function dirname($path) - * 1046: function modifyHTMLColor($color,$R,$G,$B) - * 1066: function modifyHTMLColorAll($color,$all) - * 1077: function rm_endcomma($string) - * 1090: function danish_strtoupper($string) - * 1105: function convUmlauts($str) - * 1118: function testInt($var) - * 1130: function isFirstPartOfStr($str,$partStr) - * 1146: function formatSize($sizeInBytes,$labels='') - * 1181: function convertMicrotime($microtime) - * 1195: function splitCalc($string,$operators) - * 1217: function calcPriority($string) - * 1258: function calcParenthesis($string) - * 1284: function htmlspecialchars_decode($value) - * 1299: function deHSCentities($str) - * 1312: function slashJS($string,$extended=0,$char="'") - * 1325: function rawUrlEncodeJS($str) - * 1337: function rawUrlEncodeFP($str) - * 1348: function validEmail($email) - * 1363: function formatForTextarea($content) - * - * SECTION: ARRAY FUNCTIONS - * 1394: function inArray($in_array,$item) - * 1411: function intExplode($delim, $string) - * 1430: function revExplode($delim, $string, $count=0) - * 1450: function trimExplode($delim, $string, $onlyNonEmptyValues=0) - * 1472: function uniqueArray($valueArray) - * 1484: function removeArrayEntryByValue($array,$cmpValue) - * 1513: function implodeArrayForUrl($name,$theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) - * 1538: function explodeUrl2Array($string,$multidim=FALSE) - * 1564: function compileSelectedGetVarsFromArray($varList,$getArray,$GPvarAlt=1) - * 1587: function addSlashesOnArray(&$theArray) - * 1611: function stripSlashesOnArray(&$theArray) - * 1633: function slashArray($arr,$cmd) - * 1650: function array_merge_recursive_overrule($arr0,$arr1,$notAddKeys=0,$includeEmptyValues=true) - * 1683: function array_merge($arr1,$arr2) - * 1696: function csvValues($row,$delim=',',$quote='"') - * - * SECTION: HTML/XML PROCESSING - * 1738: function get_tag_attributes($tag) - * 1775: function split_tag_attributes($tag) - * 1809: function implodeAttributes($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) - * 1836: function implodeParams($arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) - * 1851: function wrapJS($string, $linebreak=TRUE) - * 1882: function xml2tree($string,$depth=999) - * 1969: function array2xml($array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0, $options=array(),$stackData=array()) - * 2088: function xml2array($string,$NSprefix='',$reportDocTag=FALSE) - * 2198: function xmlRecompileFromStructValArray($vals) - * 2242: function xmlGetHeaderAttribs($xmlData) - * - * SECTION: FILES FUNCTIONS - * 2275: function getURL($url, $includeHeader=0) - * 2342: function writeFile($file,$content) - * 2367: function fixPermissions($file) - * 2384: function writeFileToTypo3tempDir($filepath,$content) - * 2427: function mkdir($theNewFolder) - * 2446: function mkdir_deep($destination,$deepDir) - * 2468: function get_dirs($path) - * 2493: function getFilesInDir($path,$extensionList='',$prependPath=0,$order='') - * 2547: function getAllFilesAndFoldersInPath($fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99) - * 2570: function removePrefixPathFromList($fileArr,$prefixToRemove) - * 2586: function fixWindowsFilePath($theFile) - * 2598: function resolveBackPath($pathStr) - * 2626: function locationHeaderUrl($path) - * - * SECTION: DEBUG helper FUNCTIONS - * 2666: function debug_ordvalue($string,$characters=100) - * 2683: function view_array($array_in) - * 2711: function print_array($array_in) - * 2726: function debug($var="",$brOrHeader=0) - * 2757: function debug_trail() - * 2779: function debugRows($rows,$header='') - * - * SECTION: SYSTEM INFORMATION - * 2857: function getThisUrl() - * 2873: function linkThisScript($getParams=array()) - * 2897: function linkThisUrl($url,$getParams=array()) - * 2920: function getIndpEnv($getEnvName) - * 3113: function milliseconds() - * 3125: function clientInfo($useragent='') - * - * SECTION: TYPO3 SPECIFIC FUNCTIONS - * 3212: function getFileAbsFileName($filename,$onlyRelative=1,$relToTYPO3_mainDir=0) - * 3248: function validPathStr($theFile) - * 3259: function isAbsPath($path) - * 3270: function isAllowedAbsPath($path) - * 3287: function verifyFilenameAgainstDenyPattern($filename) - * 3305: function upload_copy_move($source,$destination) - * 3331: function upload_to_tempfile($uploadedFileName) - * 3349: function unlink_tempfile($uploadedTempFileName) - * 3365: function tempnam($filePrefix) - * 3379: function stdAuthCode($uid_or_record,$fields='',$codeLength=8) - * 3410: function cHashParams($addQueryParams) - * 3433: function hideIfNotTranslated($l18n_cfg_fieldValue) - * 3448: function readLLfile($fileRef,$langKey) - * 3472: function readLLXMLfile($fileRef,$langKey) - * 3589: function llXmlAutoFileName($fileRef,$language) - * 3633: function loadTCA($table) - * 3653: function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') - * 3686: function resolveAllSheetsInDS($dataStructArray) - * 3715: function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$silent=0) - * 3813: function &getUserObj($classRef,$checkPrefix='user_',$silent=0) - * 3871: function &makeInstance($className) - * 3883: function makeInstanceClassName($className) - * 3897: function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) - * 3961: function plainMailEncoded($email,$subject,$message,$headers='',$enc='',$charset='',$dontEncodeHeader=false) - * 4031: function quoted_printable($string,$maxlen=76) - * 4078: function encodeHeader($line,$enc='',$charset='ISO-8859-1') - * 4121: function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') - * 4155: function makeRedirectUrl($inUrl,$l=0,$index_script_url='') - * 4182: function freetypeDpiComp($font_size) - * 4194: function initSysLog() - * 4251: function sysLog($msg, $extKey, $severity=0) - * 4334: function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) - * 4355: function arrayToLogString($arr, $valueList=array(), $valueLength=20) - * 4378: function imageMagickCommand($command, $parameters, $path='') - * 4425: function unQuoteFilenames($parameters,$unQuote=FALSE) - * 4459: function quoteJSvalue($value, $inScriptTags = false) - * - * TOTAL FUNCTIONS: 138 - * (This index is automatically created/updated by the extension "extdeveval") - * - */ - - // a tabulator -define('TAB', chr(9)); - // a linefeed -define('LF', chr(10)); - // a carriage return -define('CR', chr(13)); - // a CR-LF combination -define('CRLF', CR . LF); /** * The legendary "t3lib_div" class - Miscellaneous functions for general purpose. - * Most of the functions does not relate specifically to TYPO3 + * Most of the functions do 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! @@ -222,7 +37,7 @@ define('CRLF', CR . LF); * 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 SkÃ¥rhøj + * @author Kasper SkÃ¥rhøj * @package TYPO3 * @subpackage t3lib */ @@ -250,13 +65,6 @@ final class t3lib_div { */ protected static $nonSingletonInstances = array(); - /** - * Register for makeInstance with given class name and final class names to reduce number of class_exists() calls - * - * @var array Given class name => final class name - */ - protected static $finalClassNameRegister = array(); - /************************* * * GET/POST Variables @@ -273,11 +81,11 @@ final class t3lib_div { /** * 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. - * 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 + * 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! * - * @param string GET/POST var to return - * @return mixed POST var named $var and if not set, the GET var of the same name. + * @param string $var GET/POST var to return + * @return mixed POST var named $var and if not set, the GET var of the same name. */ public static function _GP($var) { if (empty($var)) { @@ -297,8 +105,8 @@ final class t3lib_div { /** * Returns the global arrays $_GET and $_POST merged with $_POST taking precedence. * - * @param string Key (variable name) from GET or POST vars - * @return array Returns the GET vars merged recursively onto the POST vars. + * @param string $parameter Key (variable name) from GET or POST vars + * @return array Returns the GET vars merged recursively onto the POST vars. */ public static function _GPmerged($parameter) { $postParameter = (isset($_POST[$parameter]) && is_array($_POST[$parameter])) ? $_POST[$parameter] : array(); @@ -313,15 +121,15 @@ final class t3lib_div { /** * 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!* + * @param string $var 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() */ public static 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. + // Removes slashes since TYPO3 has added them regardless of magic_quotes setting. + if (isset($value)) { if (is_array($value)) { self::stripSlashesOnArray($value); } else { @@ -334,15 +142,15 @@ final class t3lib_div { /** * 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!* + * @param string $var 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() */ public static 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. + // Removes slashes since TYPO3 has added them regardless of magic_quotes setting. + if (isset($value)) { if (is_array($value)) { self::stripSlashesOnArray($value); } else { @@ -354,24 +162,23 @@ final class t3lib_div { /** * Writes input value to $_GET. - * Usage: 2 * * @param mixed $inputGet - * array or single value to write to $_GET. Values should NOT be + * Array or single value to write to $_GET. Values should NOT be * escaped at input time (but will be escaped before writing * according to TYPO3 standards). * @param string $key - * alternative key; If set, this will not set the WHOLE GET array, + * Alternative key; If set, this will not set the WHOLE GET array, * but only the key in it specified by this value! * You can specify to replace keys on deeper array levels by * separating the keys with a pipe. * Example: 'parentKey|childKey' will result in * array('parentKey' => array('childKey' => $inputGet)) * - * @return void + * @return void */ public static function _GETset($inputGet, $key = '') { - // adds slashes since TYPO3 standard currently is that slashes + // Adds slashes since TYPO3 standard currently is that slashes // must be applied (regardless of magic_quotes setting) if (is_array($inputGet)) { self::addSlashesOnArray($inputGet); @@ -410,8 +217,8 @@ final class t3lib_div { * * Using an external class by Travis Puderbaugh * - * @param string Input string - * @return string Input string with potential XSS code removed + * @param string $string Input string + * @return string Input string with potential XSS code removed */ public static function removeXSS($string) { require_once(PATH_typo3 . 'contrib/RemoveXSS/RemoveXSS.php'); @@ -419,14 +226,12 @@ final class t3lib_div { return $string; } - /************************* * * 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) @@ -440,20 +245,21 @@ final class t3lib_div { * * $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. + * @param string $theFile Filepath + * @param string $type 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. */ public static 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 - // use temporary file to prevent problems with read and write lock on same file on network file systems + // GIF... + if ($gfxConf['gif_compress'] && strtolower(substr($theFile, -4, 4)) == '.gif') { + // IM + if (($type == 'IM' || !$type) && $gfxConf['im'] && $gfxConf['im_path_lzw']) { + // Use temporary file to prevent problems with read and write lock on same file on network file systems $temporaryName = dirname($theFile) . '/' . md5(uniqid()) . '.gif'; - // rename could fail, if a simultaneous thread is currently working on the same thing + // Rename could fail, if a simultaneous thread is currently working on the same thing if (@rename($theFile, $temporaryName)) { $cmd = self::imageMagickCommand('convert', '"' . $temporaryName . '" "' . $theFile . '"', $gfxConf['im_path_lzw']); t3lib_utility_Command::exec($cmd); @@ -479,11 +285,10 @@ final class t3lib_div { /** * 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 + * This converts a png file to gif IF the FLAG $GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] is set TRUE. * - * @param string $theFile the filename with path - * @return string new filename + * @param string $theFile The filename with path + * @return string New filename */ public static function png_to_gif_by_imagemagick($theFile) { if ($GLOBALS['TYPO3_CONF_VARS']['FE']['png_to_gif'] @@ -498,7 +303,8 @@ final class t3lib_div { if (@is_file($newFile)) { self::fixPermissions($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!! + // unlink old file?? May be bad idea because 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; } @@ -506,13 +312,12 @@ final class t3lib_div { /** * 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 + * @param string $theFile Filepath of image file + * @param boolean $output_png If set, then input file is converted to PNG, otherwise to GIF + * @return string If the new image file exists, its filepath is returned */ - public static function read_png_gif($theFile, $output_png = 0) { + public static function read_png_gif($theFile, $output_png = FALSE) { if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['im'] && @is_file($theFile)) { $ext = strtolower(substr($theFile, -4, 4)); if ( @@ -532,7 +337,6 @@ final class t3lib_div { } } - /************************* * * STRING FUNCTIONS @@ -541,12 +345,11 @@ final class t3lib_div { /** * Truncates a string with appended/prepended "..." and takes current character set into consideration. - * Usage: 75 * - * @param string string to truncate - * @param integer must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end. - * @param string appendix to the truncated string - * @return string cropped string + * @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 $appendString Appendix to the truncated string + * @return string Cropped string */ public static function fixed_lgd_cs($string, $chars, $appendString = '...') { if (is_object($GLOBALS['LANG'])) { @@ -555,60 +358,19 @@ final class t3lib_div { $charSet = ($GLOBALS['TSFE']->renderCharset != '' ? $GLOBALS['TSFE']->renderCharset : $GLOBALS['TSFE']->defaultCharSet); return $GLOBALS['TSFE']->csConvObj->crop($charSet, $string, $chars, $appendString); } else { - // this case should not happen + // This case should not happen $csConvObj = self::makeInstance('t3lib_cs'); - return $csConvObj->crop('iso-8859-1', $string, $chars, $appendString); + return $csConvObj->crop('utf-8', $string, $chars, $appendString); } } /** - * 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 - */ - public static function breakLinesForEmail($str, $implChar = LF, $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 * Dispatcher method for switching into specialised IPv4 and IPv6 methods. - * 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). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE. - * @return boolean True if an IP-mask from $list matches $baseIP + * @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). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE. + * @return boolean TRUE if an IP-mask from $list matches $baseIP */ public static function cmpIP($baseIP, $list) { $list = trim($list); @@ -627,9 +389,9 @@ final class t3lib_div { /** * Match IPv4 number with list of numbers with wildcard * - * @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 + * @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), could also contain IPv6 addresses + * @return boolean TRUE if an IP-mask from $list matches $baseIP */ public static function cmpIPv4($baseIP, $list) { $IPpartsReq = explode('.', $baseIP); @@ -637,7 +399,12 @@ final class t3lib_div { $values = self::trimExplode(',', $list, 1); foreach ($values as $test) { - list($test, $mask) = explode('/', $test); + $testList = explode('/', $test); + if (count($testList) == 2) { + list($test, $mask) = $testList; + } else { + $mask = FALSE; + } if (intval($mask)) { // "192.168.3.0/24" @@ -654,7 +421,7 @@ final class t3lib_div { $yes = 1; foreach ($IPparts as $index => $val) { $val = trim($val); - if (strcmp($val, '*') && strcmp($IPpartsReq[$index], $val)) { + if (($val !== '*') && ($IPpartsReq[$index] !== $val)) { $yes = 0; } } @@ -670,39 +437,50 @@ final class t3lib_div { /** * Match IPv6 address with a list of IPv6 prefixes * - * @param string $baseIP is the current remote IP address for instance - * @param string $list is a comma-list of IPv6 prefixes, could also contain IPv4 addresses - * @return boolean True if an baseIP matches any prefix + * @param string $baseIP Is the current remote IP address for instance + * @param string $list Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses + * @return boolean TRUE If an baseIP matches any prefix */ public static function cmpIPv6($baseIP, $list) { - $success = FALSE; // Policy default: Deny connection + // Policy default: Deny connection + $success = FALSE; $baseIP = self::normalizeIPv6($baseIP); $values = self::trimExplode(',', $list, 1); foreach ($values as $test) { - list($test, $mask) = explode('/', $test); + $testList = explode('/', $test); + if (count($testList) == 2) { + list($test, $mask) = $testList; + } else { + $mask = FALSE; + } + if (self::validIPv6($test)) { $test = self::normalizeIPv6($test); - if (intval($mask)) { - switch ($mask) { // test on /48 /64 - case '48': - $testBin = substr(self::IPv6Hex2Bin($test), 0, 48); - $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 48); - $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE; - break; - case '64': - $testBin = substr(self::IPv6Hex2Bin($test), 0, 64); - $baseIPBin = substr(self::IPv6Hex2Bin($baseIP), 0, 64); - $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE; - break; - default: - $success = FALSE; - } + $maskInt = intval($mask) ? intval($mask) : 128; + // Special case; /0 is an allowed mask - equals a wildcard + if ($mask === '0') { + $success = TRUE; + } elseif ($maskInt == 128) { + $success = ($test === $baseIP); } else { - if (self::validIPv6($test)) { // test on full ip address 128 bits - $testBin = self::IPv6Hex2Bin($test); - $baseIPBin = self::IPv6Hex2Bin($baseIP); - $success = strcmp($testBin, $baseIPBin) == 0 ? TRUE : FALSE; + $testBin = self::IPv6Hex2Bin($test); + $baseIPBin = self::IPv6Hex2Bin($baseIP); + $success = TRUE; + + // Modulo is 0 if this is a 8-bit-boundary + $maskIntModulo = $maskInt % 8; + $numFullCharactersUntilBoundary = intval($maskInt / 8); + + if (substr($testBin, 0, $numFullCharactersUntilBoundary) !== substr($baseIPBin, 0, $numFullCharactersUntilBoundary)) { + $success = FALSE; + } elseif ($maskIntModulo > 0) { + // If not an 8-bit-boundary, check bits of last character + $testLastBits = str_pad(decbin(ord(substr($testBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); + $baseIPLastBits = str_pad(decbin(ord(substr($baseIPBin, $numFullCharactersUntilBoundary, 1))), 8, '0', STR_PAD_LEFT); + if (strncmp($testLastBits, $baseIPLastBits, $maskIntModulo) != 0) { + $success = FALSE; + } } } } @@ -714,31 +492,49 @@ final class t3lib_div { } /** - * [Describe function...] + * Transform a regular IPv6 address from hex-representation into binary * - * @param [type] $hex: ... - * @return [type] ... + * @param string $hex IPv6 address in hex-presentation + * @return string Binary representation (16 characters, 128 characters) + * @see IPv6Bin2Hex() */ public static function IPv6Hex2Bin($hex) { - $bin = ''; - $hex = str_replace(':', '', $hex); // Replace colon to nothing - for ($i = 0; $i < strlen($hex); $i = $i + 2) { - $bin .= chr(hexdec(substr($hex, $i, 2))); - } - return $bin; + return inet_pton($hex); + } + + /** + * Transform an IPv6 address from binary to hex-representation + * + * @param string $bin IPv6 address in hex-presentation + * @return string Binary representation (16 characters, 128 characters) + * @see IPv6Hex2Bin() + */ + public static function IPv6Bin2Hex($bin) { + return inet_ntop($bin); } /** * Normalize an IPv6 address to full length * - * @param string Given IPv6 address - * @return string Normalized address + * @param string $address Given IPv6 address + * @return string Normalized address + * @see compressIPv6() */ public static function normalizeIPv6($address) { $normalizedAddress = ''; $stageOneAddress = ''; - $chunks = explode('::', $address); // Count 2 if if address has hidden zero blocks + // According to RFC lowercase-representation is recommended + $address = strtolower($address); + + // Normalized representation has 39 characters (0000:0000:0000:0000:0000:0000:0000:0000) + if (strlen($address) == 39) { + // Already in full expanded form + return $address; + } + + // Count 2 if if address has hidden zero blocks + $chunks = explode('::', $address); if (count($chunks) == 2) { $chunksLeft = explode(':', $chunks[0]); $chunksRight = explode(':', $chunks[1]); @@ -767,7 +563,7 @@ final class t3lib_div { $stageOneAddress = $address; } - // normalize the blocks: + // Normalize the blocks: $blocks = explode(':', $stageOneAddress); $divCounter = 0; foreach ($blocks as $block) { @@ -787,13 +583,25 @@ final class t3lib_div { return $normalizedAddress; } + + /** + * Compress an IPv6 address to the shortest notation + * + * @param string $address Given IPv6 address + * @return string Compressed address + * @see normalizeIPv6() + */ + public static function compressIPv6($address) { + return inet_ntop(inet_pton($address)); + } + /** * Validate a given IP address. * * Possible format are IPv4 and IPv6. * - * @param string IP address to be tested - * @return boolean True if $ip is either of IPv4 or IPv6 format. + * @param string $ip IP address to be tested + * @return boolean TRUE if $ip is either of IPv4 or IPv6 format. */ public static function validIP($ip) { return (filter_var($ip, FILTER_VALIDATE_IP) !== FALSE); @@ -802,10 +610,10 @@ final class t3lib_div { /** * Validate a given IP address to the IPv4 address format. * - * Example for possible format: 10.0.45.99 + * Example for possible format: 10.0.45.99 * - * @param string IP address to be tested - * @return boolean True if $ip is of IPv4 format. + * @param string $ip IP address to be tested + * @return boolean TRUE if $ip is of IPv4 format. */ public static function validIPv4($ip) { return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== FALSE); @@ -814,10 +622,10 @@ final class t3lib_div { /** * Validate a given IP address to the IPv6 address format. * - * Example for possible format: 43FB::BB3F:A0A0:0 | ::1 + * Example for possible format: 43FB::BB3F:A0A0:0 | ::1 * - * @param string IP address to be tested - * @return boolean True if $ip is of IPv6 format. + * @param string $ip IP address to be tested + * @return boolean TRUE if $ip is of IPv6 format. */ public static function validIPv6($ip) { return (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== FALSE); @@ -826,28 +634,69 @@ final class t3lib_div { /** * Match fully qualified domain name with list of strings with wildcard * - * @param string The current remote IP address for instance, typ. REMOTE_ADDR - * @param string A comma-list of domain names to match with. *-wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost.*.com => correct, myhost.*domain.com => wrong) - * @return boolean True if a domain name mask from $list matches $baseIP + * @param string $baseHost A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR) + * @param string $list 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 */ - public static function cmpFQDN($baseIP, $list) { - if (count(explode('.', $baseIP)) == 4) { - $resolvedHostName = explode('.', gethostbyaddr($baseIP)); - $values = self::trimExplode(',', $list, 1); + public static function cmpFQDN($baseHost, $list) { + $baseHost = trim($baseHost); + if (empty($baseHost)) { + return FALSE; + } + if (self::validIPv4($baseHost) || self::validIPv6($baseHost)) { + // Resolve hostname + // Note: this is reverse-lookup and can be randomly set as soon as somebody is able to set + // the reverse-DNS for his IP (security when for example used with REMOTE_ADDR) + $baseHostName = gethostbyaddr($baseHost); + if ($baseHostName === $baseHost) { + // Unable to resolve hostname + return FALSE; + } + } else { + $baseHostName = $baseHost; + } + $baseHostNameParts = explode('.', $baseHostName); - foreach ($values as $test) { - $hostNameParts = explode('.', $test); - $yes = 1; + $values = self::trimExplode(',', $list, 1); + + foreach ($values as $test) { + $hostNameParts = explode('.', $test); + + // To match hostNameParts can only be shorter (in case of wildcards) or equal + if (count($hostNameParts) > count($baseHostNameParts)) { + continue; + } - foreach ($hostNameParts as $index => $val) { - $val = trim($val); - if (strcmp($val, '*') && strcmp($resolvedHostName[$index], $val)) { - $yes = 0; + $yes = TRUE; + foreach ($hostNameParts as $index => $val) { + $val = trim($val); + if ($val === '*') { + // Wildcard valid for one or more hostname-parts + + $wildcardStart = $index + 1; + // Wildcard as last/only part always matches, otherwise perform recursive checks + if ($wildcardStart < count($hostNameParts)) { + $wildcardMatched = FALSE; + $tempHostName = implode('.', array_slice($hostNameParts, $index + 1)); + while (($wildcardStart < count($baseHostNameParts)) && (!$wildcardMatched)) { + $tempBaseHostName = implode('.', array_slice($baseHostNameParts, $wildcardStart)); + $wildcardMatched = self::cmpFQDN($tempBaseHostName, $tempHostName); + $wildcardStart++; + } + if ($wildcardMatched) { + // Match found by recursive compare + return TRUE; + } else { + $yes = FALSE; + } } + } elseif ($baseHostNameParts[$index] !== $val) { + // In case of no match + $yes = FALSE; } - if ($yes) { - return TRUE; - } + } + if ($yes) { + return TRUE; } } return FALSE; @@ -857,8 +706,8 @@ final class t3lib_div { * Checks if a given URL matches the host that currently handles this HTTP request. * Scheme, hostname and (optional) port of the given URL are compared. * - * @param string $url: URL to compare with the TYPO3 request host - * @return boolean Whether the URL matches the TYPO3 request host + * @param string $url URL to compare with the TYPO3 request host + * @return boolean Whether the URL matches the TYPO3 request host */ public static function isOnCurrentHost($url) { return (stripos($url . '/', self::getIndpEnv('TYPO3_REQUEST_HOST') . '/') === 0); @@ -867,11 +716,10 @@ final class t3lib_div { /** * 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 + * @param string $list Comma-separated list of items (string) + * @param string $item Item to check for + * @return boolean TRUE if $item is in $list */ public static function inList($list, $item) { return (strpos(',' . $list . ',', ',' . $item . ',') !== FALSE ? TRUE : FALSE); @@ -879,11 +727,10 @@ final class t3lib_div { /** * Removes an item from a comma-separated list of items. - * Usage: 1 * - * @param string element to remove - * @param string comma-separated list of items (string) - * @return string new comma-separated list of items + * @param string $element Element to remove + * @param string $list Comma-separated list of items (string) + * @return string New comma-separated list of items */ public static function rmFromList($element, $list) { $items = explode(',', $list); @@ -899,9 +746,8 @@ final class t3lib_div { * 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 comma-separated list of integers with ranges (string) - * @return string new comma-separated list of items - * @author Martin Kutschker + * @param string $list Comma-separated list of integers with ranges (string) + * @return string New comma-separated list of items */ public static function expandList($list) { $items = explode(',', $list); @@ -926,70 +772,32 @@ final class t3lib_div { } /** - * 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 - */ - public static 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 - */ - public static 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) + * @param string $verNumberStr Version number on format x.x.x + * @return integer Integer version of version number (where each part can count to 999) + * @deprecated since TYPO3 4.6, will be removed in TYPO3 6.1 - Use t3lib_utility_VersionNumber::convertVersionNumberToInteger() instead */ public static 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)); + // Deprecation log is activated only for TYPO3 4.7 and above + if (t3lib_utility_VersionNumber::convertVersionNumberToInteger(TYPO3_version) >= 4007000) { + self::logDeprecatedFunction(); + } + return t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr); } /** - * Returns true if the current TYPO3 version (or compatibility version) is compatible to the input version + * Returns TRUE if the current TYPO3 version (or compatibility version) is compatible to the input version * Notice that this function compares branches, not versions (4.0.1 would be > 4.0.0 although they use the same compat_version) * - * @param string Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!) - * @return boolean Returns true if this setup is compatible with the provided version number - * @todo Still needs a function to convert versions to branches + * @param string $verNumberStr Minimum branch number required (format x.y / e.g. "4.0" NOT "4.0.0"!) + * @return boolean Returns TRUE if this setup is compatible with the provided version number + * @todo Still needs a function to convert versions to branches */ public static function compat_version($verNumberStr) { - global $TYPO3_CONF_VARS; - $currVersionStr = $TYPO3_CONF_VARS['SYS']['compat_version'] ? $TYPO3_CONF_VARS['SYS']['compat_version'] : TYPO3_branch; + $currVersionStr = $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['compat_version'] : TYPO3_branch; - if (self::int_from_ver($currVersionStr) < self::int_from_ver($verNumberStr)) { + if (t3lib_utility_VersionNumber::convertVersionNumberToInteger($currVersionStr) < t3lib_utility_VersionNumber::convertVersionNumberToInteger($verNumberStr)) { return FALSE; } else { return TRUE; @@ -998,10 +806,9 @@ final class t3lib_div { /** * 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 + * @param string $str String to md5-hash + * @return integer Returns 28bit integer-hash */ public static function md5int($str) { return hexdec(substr(md5($str), 0, 7)); @@ -1010,11 +817,9 @@ final class t3lib_div { /** * 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) + * @param string $input Input string to be md5-hashed + * @param integer $len The string-length of the output + * @return string Substring of the resulting md5-hash, being $len chars long (from beginning) */ public static function shortMD5($input, $len = 10) { return substr(md5($input), 0, $len); @@ -1023,8 +828,8 @@ final class t3lib_div { /** * Returns a proper HMAC on a given input string and secret TYPO3 encryption key. * - * @param string Input string to create HMAC from - * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1) + * @param string $input Input string to create HMAC from + * @return string resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1) */ public static function hmac($input) { $hashAlgorithm = 'sha1'; @@ -1034,15 +839,15 @@ final class t3lib_div { if (extension_loaded('hash') && function_exists('hash_hmac') && function_exists('hash_algos') && in_array($hashAlgorithm, hash_algos())) { $hmac = hash_hmac($hashAlgorithm, $input, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']); } else { - // outer padding + // Outer padding $opad = str_repeat(chr(0x5C), $hashBlocksize); - // innner padding + // Inner padding $ipad = str_repeat(chr(0x36), $hashBlocksize); if (strlen($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) > $hashBlocksize) { - // keys longer than blocksize are shorten + // Keys longer than block size are shorten $key = str_pad(pack('H*', call_user_func($hashAlgorithm, $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])), $hashBlocksize, chr(0x00)); } else { - // keys shorter than blocksize are zero-padded + // Keys shorter than block size are zero-padded $key = str_pad($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], $hashBlocksize, chr(0x00)); } $hmac = call_user_func($hashAlgorithm, ($key ^ $opad) . pack('H*', call_user_func($hashAlgorithm, ($key ^ $ipad) . $input))); @@ -1053,11 +858,10 @@ final class t3lib_div { /** * 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 if set will show a warning! - * @return string Returns the list without any duplicates of values, space around values are trimmed + * @param string $in_list Accept multiple parameters which can be comma-separated lists of values and arrays. + * @param mixed $secondParameter Dummy field, which if set will show a warning! + * @return string Returns the list without any duplicates of values, space around values are trimmed */ public static function uniqueList($in_list, $secondParameter = NULL) { if (is_array($in_list)) { @@ -1078,10 +882,9 @@ final class t3lib_div { /** * 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] + * @param string $fileref Filename/filepath to be analysed + * @return array Contains keys [path], [file], [filebody], [fileext], [realFileext] */ public static function split_fileref($fileref) { $reg = array(); @@ -1117,10 +920,9 @@ final class t3lib_div { * 'd/script.php' => 'd' * '/script.php' => '' * '' => '' - * Usage: 5 * - * @param string Directory name / path - * @return string Processed input value. See function description. + * @param string $path Directory name / path + * @return string Processed input value. See function description. */ public static function dirname($path) { $p = self::revExplode('/', $path, 2); @@ -1129,20 +931,19 @@ final class t3lib_div { /** * 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 + * @param string $color A hexadecimal color code, #xxxxxx + * @param integer $R Offset value 0-255 + * @param integer $G Offset value 0-255 + * @param integer $B Offset value 0-255 + * @return string A hexadecimal color code, #xxxxxx, modified according to input vars * @see modifyHTMLColorAll() */ public static 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 = self::intInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255); - $nG = self::intInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255); - $nB = self::intInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255); + $nR = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 1, 2)) + $R, 0, 255); + $nG = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 3, 2)) + $G, 0, 255); + $nB = t3lib_utility_Math::forceIntegerInRange(hexdec(substr($color, 5, 2)) + $B, 0, 255); return '#' . substr('0' . dechex($nR), -2) . substr('0' . dechex($nG), -2) . @@ -1151,11 +952,10 @@ final class t3lib_div { /** * 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 + * @param string $color A hexadecimal color code, #xxxxxx + * @param integer $all Offset value 0-255 for all three channels. + * @return string A hexadecimal color code, #xxxxxx, modified according to input vars * @see modifyHTMLColor() */ public static function modifyHTMLColorAll($color, $all) { @@ -1163,39 +963,11 @@ final class t3lib_div { } /** - * 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 - * @deprecated since TYPO3 4.5, will be removed in TYPO3 4.7 - Use rtrim() directly - */ - public static function rm_endcomma($string) { - self::logDeprecatedFunction(); - - return rtrim($string, ','); - } - - /** - * Tests if the input can be interpreted as integer. - * - * @param mixed Any input variable to test - * @return boolean Returns true if string is an integer - */ - public static function testInt($var) { - if ($var === '') { - return FALSE; - } - return (string) intval($var) === (string) $var; - } - - /** - * Returns true if the first part of $str matches the string $partStr - * Usage: 59 + * Returns TRUE if the first part of $str matches the string $partStr * - * @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 + * @param string $str Full string to check + * @param string $partStr 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 */ public static function isFirstPartOfStr($str, $partStr) { return $partStr != '' && strpos((string) $str, (string) $partStr, 0) === 0; @@ -1203,11 +975,10 @@ final class t3lib_div { /** * 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. + * @param integer $sizeInBytes Number of bytes to format. + * @param string $labels 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. */ public static function formatSize($sizeInBytes, $labels = '') { @@ -1221,11 +992,11 @@ final class t3lib_div { // Find size: if ($sizeInBytes > 900) { - if ($sizeInBytes > 900000000) { // GB + // GB + if ($sizeInBytes > 900000000) { $val = $sizeInBytes / (1024 * 1024 * 1024); return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[3]; - } - elseif ($sizeInBytes > 900000) { // MB + } elseif ($sizeInBytes > 900000) { // MB $val = $sizeInBytes / (1024 * 1024); return number_format($val, (($val < 20) ? 1 : 0), '.', '') . $labelArr[2]; } else { // KB @@ -1239,10 +1010,9 @@ final class t3lib_div { /** * Returns microtime input to milliseconds - * Usage: 2 * - * @param string Microtime - * @return integer Microtime input string converted to an integer (milliseconds) + * @param string $microtime Microtime + * @return integer Microtime input string converted to an integer (milliseconds) */ public static function convertMicrotime($microtime) { $parts = explode(' ', $microtime); @@ -1251,11 +1021,10 @@ final class t3lib_div { /** * 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. + * @param string $string Input string, eg "123 + 456 / 789 - 4" + * @param string $operators Operators to split by, typically "/+-*" + * @return array Array with operators and operands separated. * @see tslib_cObj::calc(), tslib_gifBuilder::calcOffset() */ public static function splitCalc($string, $operators) { @@ -1273,98 +1042,10 @@ final class t3lib_div { } /** - * 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() - */ - public static function calcPriority($string) { - $string = preg_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: - $reg = array(); - 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() - */ - public static function calcParenthesis($string) { - $securC = 100; - do { - $valueLenO = strcspn($string, '('); - $valueLenC = strcspn($string, ')'); - if ($valueLenC == strlen($string) || $valueLenC < $valueLenO) { - $value = self::calcPriority(substr($string, 0, $valueLenC)); - $string = $value . substr($string, $valueLenC + 1); - return $string; - } else { - $string = substr($string, 0, $valueLenO) . self::calcParenthesis(substr($string, $valueLenO + 1)); - } - // Security: - $securC--; - if ($securC <= 0) { - break; - } - } while ($valueLenO < strlen($string)); - return $string; - } - - /** * Inverse version of htmlspecialchars() - * Usage: 4 * - * @param string Value where >, <, " and & should be converted to regular chars. - * @return string Converted result. + * @param string $value Value where >, <, " and & should be converted to regular chars. + * @return string Converted result. */ public static function htmlspecialchars_decode($value) { $value = str_replace('>', '>', $value); @@ -1376,10 +1057,9 @@ final class t3lib_div { /** * 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. + * @param string $str String which contains eg. "&amp;" which should stay "&". Or "&#1234;" to "Ӓ". Or "&#x1b;" to "" + * @return string Converted result. */ public static function deHSCentities($str) { return preg_replace('/&([#[:alnum:]]*;)/', '&\1', $str); @@ -1387,27 +1067,25 @@ final class t3lib_div { /** * 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 + * @param string $string String to escape + * @param boolean $extended If set, also backslashes are escaped. + * @param string $char The character to escape, default is ' (single-quote) + * @return string Processed input string */ - public static function slashJS($string, $extended = 0, $char = "'") { + public static function slashJS($string, $extended = FALSE, $char = "'") { if ($extended) { - $string = str_replace("\\", "\\\\", $string); + $string = str_replace('\\', '\\\\', $string); } - return str_replace($char, "\\" . $char, $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 + * Useful when passing text to JavaScript where you simply url-encode it to get around problems with syntax-errors, linebreaks etc. * - * @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. + * @param string $str 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. */ public static function rawUrlEncodeJS($str) { return str_replace('%20', ' ', rawurlencode($str)); @@ -1415,11 +1093,10 @@ final class t3lib_div { /** * rawurlencode which preserves "/" chars - * Usefull when filepaths should keep the "/" chars, but have all other special chars encoded. - * Usage: 5 + * Useful when file paths should keep the "/" chars, but have all other special chars encoded. * - * @param string Input string - * @return string Output string + * @param string $str Input string + * @return string Output string */ public static function rawUrlEncodeFP($str) { return str_replace('%2F', '/', rawurlencode($str)); @@ -1427,31 +1104,33 @@ final class t3lib_div { /** * 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 + * @param string $email Input string to evaluate + * @return boolean Returns TRUE if the $email address (input string) is valid */ public static function validEmail($email) { - // enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP + // Enforce maximum length to prevent libpcre recursion crash bug #52929 in PHP // fixed in PHP 5.3.4; length restriction per SMTP RFC 2821 if (strlen($email) > 320) { return FALSE; } - return (filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE); + require_once(PATH_typo3 . 'contrib/idna/idna_convert.class.php'); + $IDN = new idna_convert(array('idn_version' => 2008)); + + return (filter_var($IDN->encode($email), FILTER_VALIDATE_EMAIL) !== FALSE); } /** * Checks if current e-mail sending method does not accept recipient/sender name * in a call to PHP mail() function. Windows version of mail() and mini_sendmail * program are known not to process such input correctly and they cause SMTP - * errors. This function will return true if current mail sending method has + * errors. This function will return TRUE if current mail sending method has * problem with recipient name in recipient/sender argument for mail(). * * TODO: 4.3 should have additional configuration variable, which is combined * by || with the rest in this function. * - * @return boolean true if mail() does not accept recipient name + * @return boolean TRUE if mail() does not accept recipient name */ public static function isBrokenEmailEnvironment() { return TYPO3_OS == 'WIN' || (FALSE !== strpos(ini_get('sendmail_path'), 'mini_sendmail')); @@ -1460,8 +1139,8 @@ final class t3lib_div { /** * Changes from/to arguments for mail() function to work in any environment. * - * @param string $address Address to adjust - * @return string Adjusted address + * @param string $address Address to adjust + * @return string Adjusted address * @see t3lib_::isBrokenEmailEnvironment() */ public static function normalizeMailAddress($address) { @@ -1476,10 +1155,9 @@ final class t3lib_div { * Formats a string for output between