From 6311a56fc4d8ff33c5b39bba3bfdedb261cf3594 Mon Sep 17 00:00:00 2001 From: marcus Date: Mon, 29 Sep 2008 15:03:51 +0000 Subject: Added IP address tools, todo check licence. git-svn-id: https://code.elgg.org/elgg/trunk@2147 36083f99-b078-4883-b0ff-0f9b5a30f544 --- engine/lib/elgglib.php | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) (limited to 'engine/lib/elgglib.php') diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 1562fd003..0d2b1e073 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -1647,6 +1647,100 @@ $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI']; } + + /** + * Useful function found in the comments on the PHP man page for ip2long. + * Returns 1 if an IP matches a given range. + * + * TODO: Check licence... assuming this is PD since it was found several places on the interwebs.. + * please check or rewrite. + * + * Matches: + * xxx.xxx.xxx.xxx (exact) + * xxx.xxx.xxx.[yyy-zzz] (range) + * xxx.xxx.xxx.xxx/nn (nn = # bits, cisco style -- i.e. /24 = class C) + * Does not match: + * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) + */ + function test_ip($range, $ip) + { + $result = 1; + + # IP Pattern Matcher + # J.Adams + # + # Matches: + # + # xxx.xxx.xxx.xxx (exact) + # xxx.xxx.xxx.[yyy-zzz] (range) + # xxx.xxx.xxx.xxx/nn (nn = # bits, cisco style -- i.e. /24 = class C) + # + # Does not match: + # xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) + + + if (ereg("([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)",$range,$regs)) { + + # perform a mask match + $ipl = ip2long($ip); + $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]); + + $maskl = 0; + + for ($i = 0; $i< 31; $i++) { + if ($i < $regs[5]-1) { + $maskl = $maskl + pow(2,(30-$i)); + } + } + + if (($maskl & $rangel) == ($maskl & $ipl)) { + return 1; + } else { + return 0; + } + } else { + + # range based + $maskocts = split("\.",$range); + $ipocts = split("\.",$ip); + + # perform a range match + for ($i=0; $i<4; $i++) { + if (ereg("\[([0-9]+)\-([0-9]+)\]",$maskocts[$i],$regs)) { + if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) { + $result = 0; + } + } + else + { + if ($maskocts[$i] <> $ipocts[$i]) { + $result = 0; + } + } + } + } + return $result; + } + + /** + * Match an IP address against a number of ip addresses or ranges, returning true if found. + * + * @param array $networks + * @param string $ip + * @return bool + */ + function is_ip_in_array(array $networks, $ip) + { + global $SYSTEM_LOG; + + foreach ($networks as $network) + { + if (test_ip(trim($network), $ip)) + return true; + } + + return false; + } /** * An interface for objects that behave as elements within a social network that have a profile. -- cgit v1.2.3