*/ /** * [CLASS/FUNCTION INDEX of SCRIPT] * * 279: public static function _GP($var) * 297: public static function _GET($var=NULL) * 314: public static function _POST($var=NULL) * 330: public static function _GETset($inputGet,$key='') * 357: public static function GPvar($var,$strip=0) * 374: public static function GParrayMerged($var) * 391: public function removeXSS($string) * * SECTION: IMAGE FUNCTIONS * 432: public static function gif_compress($theFile, $type) * 459: public static function png_to_gif_by_imagemagick($theFile) * 483: public static function read_png_gif($theFile,$output_png=0) * * SECTION: STRING FUNCTIONS * 533: public static function fixed_lgd($string,$origChars,$preStr='...') * 558: public static function fixed_lgd_pre($string,$chars) * 572: public static function fixed_lgd_cs($string,$chars) * 590: public static function breakTextForEmail($str,$implChar="\n",$charWidth=76) * 609: public static function breakLinesForEmail($str,$implChar="\n",$charWidth=76) * 645: public static function cmpIP($baseIP, $list) * 666: public static function cmpIPv4($baseIP, $list) * 707: public static function cmpIPv6($baseIP, $list) * 750: public static function IPv6Hex2Bin ($hex) * 765: public static function normalizeIPv6($address) * 821: public static function validIP($ip) * 837: public static function validIPv4($ip) * 858: public static function validIPv6($ip) * 881: public static function cmpFQDN($baseIP, $list) * 911: public static function inList($list, $item) * 923: public static function rmFromList($element,$list) * 941: public static function expandList($list) * 971: public static function intInRange($theInt,$min,$max=2000000000,$zeroValue=0) * 987: public static function intval_positive($theInt) * 1000: public static function int_from_ver($verNumberStr) * 1013: public static function compat_version($verNumberStr) * 1031: public static function md5int($str) * 1044: public static function shortMD5($input, $len=10) * 1057: public static function uniqueList($in_list, $secondParameter=NULL) * 1071: public static function split_fileref($fileref) * 1109: public static function dirname($path) * 1125: public static function modifyHTMLColor($color,$R,$G,$B) * 1145: public static function modifyHTMLColorAll($color,$all) * 1156: public static function rm_endcomma($string) * 1169: public static function danish_strtoupper($string) * 1184: public static function convUmlauts($str) * 1197: public static function testInt($var) * 1209: public static function isFirstPartOfStr($str,$partStr) * 1225: public static function formatSize($sizeInBytes,$labels='') * 1260: public static function convertMicrotime($microtime) * 1274: public static function splitCalc($string,$operators) * 1296: public static function calcPriority($string) * 1338: public static function calcParenthesis($string) * 1364: public static function htmlspecialchars_decode($value) * 1379: public static function deHSCentities($str) * 1392: public static function slashJS($string,$extended=0,$char="'") * 1405: public static function rawUrlEncodeJS($str) * 1417: public static function rawUrlEncodeFP($str) * 1428: public static function validEmail($email) * 1448: public static function isBrokenEmailEnvironment() * 1459: public static function normalizeMailAddress($address) * 1476: public static function formatForTextarea($content) * 1489: public static function strtoupper($str) * 1502: public static function strtolower($str) * * SECTION: ARRAY FUNCTIONS * 1546: public static function inArray(array $in_array, $item) * 1564: public static function intExplode($delim, $string) * 1583: public static function revExplode($delim, $string, $count=0) * 1603: public static function trimExplode($delim, $string, $onlyNonEmptyValues=0) * 1636: public static function uniqueArray(array $valueArray) * 1648: public static function removeArrayEntryByValue(array $array, $cmpValue) * 1672: public static function implodeArrayForUrl($name,array $theArray,$str='',$skipBlank=0,$rawurlencodeParamName=0) * 1695: public static function explodeUrl2Array($string,$multidim=FALSE) * 1721: public static function compileSelectedGetVarsFromArray($varList,array $getArray,$GPvarAlt=1) * 1744: public static function addSlashesOnArray(array &$theArray) * 1765: public static function stripSlashesOnArray(array &$theArray) * 1784: public static function slashArray(array $arr,$cmd) * 1801: public static function array_merge_recursive_overrule(array $arr0,array $arr1,$notAddKeys=0,$includeEmtpyValues=true) * 1833: public static function array_merge(array $arr1,array $arr2) * 1846: public static function csvValues(array $row,$delim=',',$quote='"') * 1863: public static function array2json(array $jsonArray) * 1878: public static function removeDotsFromTS(array $ts) * * SECTION: HTML/XML PROCESSING * 1921: public static function get_tag_attributes($tag) * 1955: public static function split_tag_attributes($tag) * 1990: public static function implodeAttributes(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) * 2015: public static function implodeParams(array $arr,$xhtmlSafe=FALSE,$dontOmitBlankAttribs=FALSE) * 2030: public static function wrapJS($string, $linebreak=TRUE) * 2061: public static function xml2tree($string,$depth=999) * 2137: public static function array2xml_cs(array $array,$docTag='phparray',array $options=array(),$charset='') * 2178: public static function array2xml(array $array,$NSprefix='',$level=0,$docTag='phparray',$spaceInd=0,array $options=array(),array $stackData=array()) * 2303: public static function xml2array($string,$NSprefix='',$reportDocTag=FALSE) * 2408: public static function xmlRecompileFromStructValArray(array $vals) * 2452: public static function xmlGetHeaderAttribs($xmlData) * 2466: public static function minifyJavaScript($script, &$error = '') * * SECTION: FILES FUNCTIONS * 2504: public static function getURL($url, $includeHeader = 0, $requestHeaders = false, &$report = NULL) * 2694: public static function writeFile($file,$content) * 2719: public static function fixPermissions($file) * 2736: public static function writeFileToTypo3tempDir($filepath,$content) * 2779: public static function mkdir($theNewFolder) * 2800: public static function mkdir_deep($destination,$deepDir) * 2821: public static function rmdir($path,$removeNonEmpty=false) * 2856: public static function get_dirs($path) * 2882: public static function getFilesInDir($path,$extensionList='',$prependPath=0,$order='',$excludePattern='') * 2936: public static function getAllFilesAndFoldersInPath(array $fileArr,$path,$extList='',$regDirs=0,$recursivityLevels=99,$excludePattern='') * 2959: public static function removePrefixPathFromList(array $fileArr,$prefixToRemove) * 2977: public static function fixWindowsFilePath($theFile) * 2989: public static function resolveBackPath($pathStr) * 3017: public static function locationHeaderUrl($path) * * SECTION: DEBUG helper FUNCTIONS * 3056: public static function debug_ordvalue($string,$characters=100) * 3073: public static function view_array($array_in) * 3123: public static function print_array($array_in) * 3138: public static function debug($var='',$brOrHeader=0) * 3174: public static function debug_trail() * 3195: public static function debugRows($rows,$header='',$returnHTML=FALSE) * * SECTION: SYSTEM INFORMATION * 3275: public static function getThisUrl() * 3291: public static function linkThisScript(array $getParams=array()) * 3315: public static function linkThisUrl($url,array $getParams=array()) * 3338: public static function getIndpEnv($getEnvName) * 3612: public static function milliseconds() * 3624: public static function clientInfo($useragent='') * 3682: public static function getHostname($requestHost=TRUE) * * SECTION: TYPO3 SPECIFIC FUNCTIONS * 3743: public static function getFileAbsFileName($filename,$onlyRelative=TRUE,$relToTYPO3_mainDir=FALSE) * 3779: public static function validPathStr($theFile) * 3792: public static function isAbsPath($path) * 3803: public static function isAllowedAbsPath($path) * 3820: public static function verifyFilenameAgainstDenyPattern($filename) * 3838: public static function upload_copy_move($source,$destination) * 3864: public static function upload_to_tempfile($uploadedFileName) * 3882: public static function unlink_tempfile($uploadedTempFileName) * 3898: public static function tempnam($filePrefix) * 3911: public static function stdAuthCode($uid_or_record,$fields='',$codeLength=8) * 3941: public static function cHashParams($addQueryParams) * 3980: public static function hideIfNotTranslated($l18n_cfg_fieldValue) * 3996: public static function readLLfile($fileRef, $langKey, $charset='') * 4029: function readLLPHPfile($fileRef, $langKey, $charset='') * 4104: public static function readLLXMLfile($fileRef, $langKey, $charset='') * 4245: public static function llXmlAutoFileName($fileRef,$language) * 4294: public static function loadTCA($table) * 4321: public static function resolveSheetDefInDS($dataStructArray,$sheet='sDEF') * 4354: public static function resolveAllSheetsInDS(array $dataStructArray) * 4383: public static function callUserFunction($funcName,&$params,&$ref,$checkPrefix='user_',$errorMode=0) * 4500: public static function &getUserObj($classRef,$checkPrefix='user_',$silent=0) * 4558: public static function &makeInstance($className) * 4582: public static function makeInstanceClassName($className) * 4596: public static function &makeInstanceService($serviceType, $serviceSubType='', $excludeServiceKeys=array()) * 4652: public static function requireOnce($requireFile) * 4673: public static function plainMailEncoded($email,$subject,$message,$headers='',$encoding='quoted-printable',$charset='',$dontEncodeHeader=false) * 4749: public static function quoted_printable($string,$maxlen=76) * 4796: public static function encodeHeader($line,$enc='quoted-printable',$charset='iso-8859-1') * 4842: public static function substUrlsInPlainText($message,$urlmode='76',$index_script_url='') * 4877: public static function makeRedirectUrl($inUrl,$l=0,$index_script_url='') * 4905: public static function freetypeDpiComp($font_size) * 4917: public static function initSysLog() * 4967: public static function sysLog($msg, $extKey, $severity=0) * 5050: public static function devLog($msg, $extKey, $severity=0, $dataVar=FALSE) * 5071: public static function arrayToLogString(array $arr, $valueList=array(), $valueLength=20) * 5093: public static function imageMagickCommand($command, $parameters, $path='') * 5140: public static function unQuoteFilenames($parameters,$unQuote=FALSE) * 5174: public static function quoteJSvalue($value, $inScriptTags = false) * * TOTAL FUNCTIONS: 153 * (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 */ final class t3lib_div { // Severity constants used by t3lib_div::sysLog() const SYSLOG_SEVERITY_INFO = 0; const SYSLOG_SEVERITY_NOTICE = 1; const SYSLOG_SEVERITY_WARNING = 2; const SYSLOG_SEVERITY_ERROR = 3; const SYSLOG_SEVERITY_FATAL = 4; /************************* * * 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() */ public static 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() */ 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. 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() */ 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. if (is_array($value)) { t3lib_div::stripSlashesOnArray($value); } else { $value = stripslashes($value); } } return $value; } /** * Writes input value to $_GET * Usage: 2 * * @param mixed 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 */ public static 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() */ public static 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 */ public static 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; } /** * Wrapper for the RemoveXSS function. * Removes potential XSS code from an input string. * * Using an external class by Travis Puderbaugh * * @param string Input string * @return string Input string with potential XSS code removed */ public function removeXSS($string) { require_once(PATH_typo3.'contrib/RemoveXSS/RemoveXSS.php'); $string = RemoveXSS::RemoveXSS($string); 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) * * 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. */ 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 $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 */ public static 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.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['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 */ public static 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'); $cmd = t3lib_div::imageMagickCommand('convert', '"'.$theFile.'" "'.$newFile.'"', $GLOBALS['TYPO3_CONF_VARS']['GFX']['im_path']); exec($cmd); 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 '...'. * Usage: 39 * * @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 String to append to the output if it is truncated, default is '...' * @return string new string * @deprecated Works ONLY for single-byte charsets! USE t3lib_div::fixed_lgd_cs() instead * @see fixed_lgd_pre() */ public static 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 * Usage: 6 * * @param string string to truncate * @param integer must be an integer of at least 4 * @return string new string * @deprecated Use either fixed_lgd() or fixed_lgd_cs() (with negative input value for $chars) * @see fixed_lgd() */ public static 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 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. * @return string New string * @see fixed_lgd() */ public static 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 * @deprecated Use PHP function wordwrap() */ public static function breakTextForEmail($str,$implChar="\n",$charWidth=76) { $lines = explode(chr(10),$str); $outArr=array(); foreach ($lines as $lStr) { $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() */ public static 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 * 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 */ public static function cmpIP($baseIP, $list) { $list = trim($list); if ($list === '') { return false; } elseif ($list === '*') { return true; } if (strpos($baseIP, ':') !== false && t3lib_div::validIPv6($baseIP)) { return t3lib_div::cmpIPv6($baseIP, $list); } else { return t3lib_div::cmpIPv4($baseIP, $list); } } /** * 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 */ public static function cmpIPv4($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; foreach ($IPparts as $index => $val) { $val = trim($val); if (strcmp($val,'*') && strcmp($IPpartsReq[$index],$val)) { $yes=0; } } } if ($yes) return true; } } return false; } /** * 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 */ public static function cmpIPv6($baseIP, $list) { $success = false; // Policy default: Deny connection $baseIP = t3lib_div::normalizeIPv6($baseIP); $values = t3lib_div::trimExplode(',',$list,1); foreach ($values as $test) { list($test,$mask) = explode('/',$test); if (t3lib_div::validIPv6($test)) { $test = t3lib_div::normalizeIPv6($test); if (intval($mask)) { switch ($mask) { // test on /48 /64 case '48': $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 48); $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 48); $success = strcmp($testBin, $baseIPBin)==0 ? true : false; break; case '64': $testBin = substr(t3lib_div::IPv6Hex2Bin($test), 0, 64); $baseIPBin = substr(t3lib_div::IPv6Hex2Bin($baseIP), 0, 64); $success = strcmp($testBin, $baseIPBin)==0 ? true : false; break; default: $success = false; } } else { if (t3lib_div::validIPv6($test)) { // test on full ip address 128 bits $testBin = t3lib_div::IPv6Hex2Bin($test); $baseIPBin = t3lib_div::IPv6Hex2Bin($baseIP); $success = strcmp($testBin, $baseIPBin)==0 ? true : false; } } } if ($success) return true; } return false; } /** * [Describe function...] * * @param [type] $hex: ... * @return [type] ... */ public static function IPv6Hex2Bin ($hex) { $bin = ''; $hex = str_replace(':', '', $hex); // Replace colon to nothing for ($i=0; $i