introduce a new setting that allows extension authors to whitelist deprecated funtion...
[lhc/web/wiklou.git] / includes / IP.php
1 <?php
2 /**
3 * Functions and constants to play with IP addresses and ranges
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Antoine Musso <hashar at free dot fr>, Aaron Schulz
22 */
23
24 // Some regex definition to "play" with IP address and IP address blocks
25
26 // An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
27 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
28 define( 'RE_IP_ADD', RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
29 // An IPv4 block is an IP address and a prefix (d1 to d32)
30 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
31 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX );
32
33 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
34 // However, the "::" abbreviation can be used on consecutive x0000 words.
35 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
36 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
37 define( 'RE_IPV6_ADD',
38 '(?:' . // starts with "::" (including "::")
39 ':(?::|(?::' . RE_IPV6_WORD . '){1,7})' .
40 '|' . // ends with "::" (except "::")
41 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,6}::' .
42 '|' . // contains one "::" in the middle, ending in "::WORD"
43 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,5}' . '::' . RE_IPV6_WORD .
44 '|' . // contains one "::" in the middle, not ending in "::WORD" (regex for PCRE 4.0+)
45 RE_IPV6_WORD . '(?::(?P<abn>:(?P<iabn>))?' . RE_IPV6_WORD . '(?!:(?P=abn))){1,5}' .
46 ':' . RE_IPV6_WORD . '(?P=iabn)' .
47 // NOTE: (?!(?P=abn)) fails iff "::" used twice; (?P=iabn) passes iff a "::" was found.
48 '|' . // contains no "::"
49 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){7}' .
50 ')'
51 // NOTE: With PCRE 7.2+, we can combine the two '"::" in the middle' cases into:
52 // RE_IPV6_WORD . '(?::((?(-1)|:))?' . RE_IPV6_WORD . '){1,6}(?(-2)|^)'
53 // This also improves regex concatenation by using relative references.
54 );
55 // An IPv6 block is an IP address and a prefix (d1 to d128)
56 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
57 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
58 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
59 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
60
61 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
62 define( 'IP_ADDRESS_STRING',
63 '(?:' .
64 RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?' . // IPv4
65 '|' .
66 RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?' . // IPv6
67 ')'
68 );
69
70 /**
71 * A collection of public static functions to play with IP address
72 * and IP blocks.
73 */
74 class IP {
75 /**
76 * Determine if a string is as valid IP address or network (CIDR prefix).
77 * SIIT IPv4-translated addresses are rejected.
78 * Note: canonicalize() tries to convert translated addresses to IPv4.
79 *
80 * @param $ip String: possible IP address
81 * @return Boolean
82 */
83 public static function isIPAddress( $ip ) {
84 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
85 }
86
87 /**
88 * Given a string, determine if it as valid IP in IPv6 only.
89 * Note: Unlike isValid(), this looks for networks too.
90 *
91 * @param $ip String: possible IP address
92 * @return Boolean
93 */
94 public static function isIPv6( $ip ) {
95 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?$/', $ip );
96 }
97
98 /**
99 * Given a string, determine if it as valid IP in IPv4 only.
100 * Note: Unlike isValid(), this looks for networks too.
101 *
102 * @param $ip String: possible IP address
103 * @return Boolean
104 */
105 public static function isIPv4( $ip ) {
106 return (bool)preg_match( '/^' . RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?$/', $ip );
107 }
108
109 /**
110 * Validate an IP address. Ranges are NOT considered valid.
111 * SIIT IPv4-translated addresses are rejected.
112 * Note: canonicalize() tries to convert translated addresses to IPv4.
113 *
114 * @param $ip String
115 * @return Boolean: True if it is valid.
116 */
117 public static function isValid( $ip ) {
118 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
119 || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
120 }
121
122 /**
123 * Validate an IP Block (valid address WITH a valid prefix).
124 * SIIT IPv4-translated addresses are rejected.
125 * Note: canonicalize() tries to convert translated addresses to IPv4.
126 *
127 * @param $ipblock String
128 * @return Boolean: True if it is valid.
129 */
130 public static function isValidBlock( $ipblock ) {
131 return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
132 || preg_match( '/^' . RE_IP_BLOCK . '$/', $ipblock ) );
133 }
134
135 /**
136 * Convert an IP into a nice standard form.
137 * IPv6 addresses in octet notation are expanded to 8 words.
138 * IPv4 addresses are just trimmed.
139 *
140 * @param $ip String: IP address in quad or octet form (CIDR or not).
141 * @return String
142 */
143 public static function sanitizeIP( $ip ) {
144 $ip = trim( $ip );
145 if ( $ip === '' ) {
146 return null;
147 }
148 if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
149 return $ip; // nothing else to do for IPv4 addresses or invalid ones
150 }
151 // Remove any whitespaces, convert to upper case
152 $ip = strtoupper( $ip );
153 // Expand zero abbreviations
154 $abbrevPos = strpos( $ip, '::' );
155 if ( $abbrevPos !== false ) {
156 // We know this is valid IPv6. Find the last index of the
157 // address before any CIDR number (e.g. "a:b:c::/24").
158 $CIDRStart = strpos( $ip, "/" );
159 $addressEnd = ( $CIDRStart !== false )
160 ? $CIDRStart - 1
161 : strlen( $ip ) - 1;
162 // If the '::' is at the beginning...
163 if ( $abbrevPos == 0 ) {
164 $repeat = '0:';
165 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
166 $pad = 9; // 7+2 (due to '::')
167 // If the '::' is at the end...
168 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
169 $repeat = ':0';
170 $extra = '';
171 $pad = 9; // 7+2 (due to '::')
172 // If the '::' is in the middle...
173 } else {
174 $repeat = ':0';
175 $extra = ':';
176 $pad = 8; // 6+2 (due to '::')
177 }
178 $ip = str_replace( '::',
179 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
180 $ip
181 );
182 }
183 // Remove leading zereos from each bloc as needed
184 $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip );
185 return $ip;
186 }
187
188 /**
189 * Given a host/port string, like one might find in the host part of a URL
190 * per RFC 2732, split the hostname part and the port part and return an
191 * array with an element for each. If there is no port part, the array will
192 * have false in place of the port. If the string was invalid in some way,
193 * false is returned.
194 *
195 * This was easy with IPv4 and was generally done in an ad-hoc way, but
196 * with IPv6 it's somewhat more complicated due to the need to parse the
197 * square brackets and colons.
198 *
199 * A bare IPv6 address is accepted despite the lack of square brackets.
200 *
201 * @param $both The string with the host and port
202 * @return array
203 */
204 public static function splitHostAndPort( $both ) {
205 if ( substr( $both, 0, 1 ) === '[' ) {
206 if ( preg_match( '/^\[(' . RE_IPV6_ADD . ')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
207 if ( isset( $m['port'] ) ) {
208 return array( $m[1], intval( $m['port'] ) );
209 } else {
210 return array( $m[1], false );
211 }
212 } else {
213 // Square bracket found but no IPv6
214 return false;
215 }
216 }
217 $numColons = substr_count( $both, ':' );
218 if ( $numColons >= 2 ) {
219 // Is it a bare IPv6 address?
220 if ( preg_match( '/^' . RE_IPV6_ADD . '$/', $both ) ) {
221 return array( $both, false );
222 } else {
223 // Not valid IPv6, but too many colons for anything else
224 return false;
225 }
226 }
227 if ( $numColons >= 1 ) {
228 // Host:port?
229 $bits = explode( ':', $both );
230 if ( preg_match( '/^\d+/', $bits[1] ) ) {
231 return array( $bits[0], intval( $bits[1] ) );
232 } else {
233 // Not a valid port
234 return false;
235 }
236 }
237 // Plain hostname
238 return array( $both, false );
239 }
240
241 /**
242 * Given a host name and a port, combine them into host/port string like
243 * you might find in a URL. If the host contains a colon, wrap it in square
244 * brackets like in RFC 2732. If the port matches the default port, omit
245 * the port specification
246 *
247 * @param $host string
248 * @param $port int
249 * @param $defaultPort bool|int
250 * @return string
251 */
252 public static function combineHostAndPort( $host, $port, $defaultPort = false ) {
253 if ( strpos( $host, ':' ) !== false ) {
254 $host = "[$host]";
255 }
256 if ( $defaultPort !== false && $port == $defaultPort ) {
257 return $host;
258 } else {
259 return "$host:$port";
260 }
261 }
262
263 /**
264 * Given an unsigned integer, returns an IPv6 address in octet notation
265 *
266 * @param $ip_int String: IP address.
267 * @return String
268 */
269 public static function toOctet( $ip_int ) {
270 return self::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
271 }
272
273 /**
274 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
275 *
276 * @param $hex String: number, with "v6-" prefix if it is IPv6
277 * @return String: quad-dotted (IPv4) or octet notation (IPv6)
278 */
279 public static function formatHex( $hex ) {
280 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
281 return self::hexToOctet( substr( $hex, 3 ) );
282 } else { // IPv4
283 return self::hexToQuad( $hex );
284 }
285 }
286
287 /**
288 * Converts a hexadecimal number to an IPv6 address in octet notation
289 *
290 * @param $ip_hex String: pure hex (no v6- prefix)
291 * @return String (of format a:b:c:d:e:f:g:h)
292 */
293 public static function hexToOctet( $ip_hex ) {
294 // Pad hex to 32 chars (128 bits)
295 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
296 // Separate into 8 words
297 $ip_oct = substr( $ip_hex, 0, 4 );
298 for ( $n = 1; $n < 8; $n++ ) {
299 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
300 }
301 // NO leading zeroes
302 $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip_oct );
303 return $ip_oct;
304 }
305
306 /**
307 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
308 *
309 * @param $ip_hex String: pure hex
310 * @return String (of format a.b.c.d)
311 */
312 public static function hexToQuad( $ip_hex ) {
313 // Pad hex to 8 chars (32 bits)
314 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
315 // Separate into four quads
316 $s = '';
317 for ( $i = 0; $i < 4; $i++ ) {
318 if ( $s !== '' ) {
319 $s .= '.';
320 }
321 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
322 }
323 return $s;
324 }
325
326 /**
327 * Determine if an IP address really is an IP address, and if it is public,
328 * i.e. not RFC 1918 or similar
329 * Comes from ProxyTools.php
330 *
331 * @param $ip String
332 * @return Boolean
333 */
334 public static function isPublic( $ip ) {
335 if ( self::isIPv6( $ip ) ) {
336 return self::isPublic6( $ip );
337 }
338 $n = self::toUnsigned( $ip );
339 if ( !$n ) {
340 return false;
341 }
342
343 // ip2long accepts incomplete addresses, as well as some addresses
344 // followed by garbage characters. Check that it's really valid.
345 if ( $ip != long2ip( $n ) ) {
346 return false;
347 }
348
349 static $privateRanges = false;
350 if ( !$privateRanges ) {
351 $privateRanges = array(
352 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
353 array( '172.16.0.0', '172.31.255.255' ), # "
354 array( '192.168.0.0', '192.168.255.255' ), # "
355 array( '0.0.0.0', '0.255.255.255' ), # this network
356 array( '127.0.0.0', '127.255.255.255' ), # loopback
357 );
358 }
359
360 foreach ( $privateRanges as $r ) {
361 $start = self::toUnsigned( $r[0] );
362 $end = self::toUnsigned( $r[1] );
363 if ( $n >= $start && $n <= $end ) {
364 return false;
365 }
366 }
367 return true;
368 }
369
370 /**
371 * Determine if an IPv6 address really is an IP address, and if it is public,
372 * i.e. not RFC 4193 or similar
373 *
374 * @param $ip String
375 * @return Boolean
376 */
377 private static function isPublic6( $ip ) {
378 static $privateRanges = false;
379 if ( !$privateRanges ) {
380 $privateRanges = array(
381 array( 'fc00::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
382 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
383 );
384 }
385 $n = self::toHex( $ip );
386 foreach ( $privateRanges as $r ) {
387 $start = self::toHex( $r[0] );
388 $end = self::toHex( $r[1] );
389 if ( $n >= $start && $n <= $end ) {
390 return false;
391 }
392 }
393 return true;
394 }
395
396 /**
397 * Return a zero-padded upper case hexadecimal representation of an IP address.
398 *
399 * Hexadecimal addresses are used because they can easily be extended to
400 * IPv6 support. To separate the ranges, the return value from this
401 * function for an IPv6 address will be prefixed with "v6-", a non-
402 * hexadecimal string which sorts after the IPv4 addresses.
403 *
404 * @param $ip String: quad dotted/octet IP address.
405 * @return String
406 */
407 public static function toHex( $ip ) {
408 if ( self::isIPv6( $ip ) ) {
409 $n = 'v6-' . self::IPv6ToRawHex( $ip );
410 } else {
411 $n = self::toUnsigned( $ip );
412 if ( $n !== false ) {
413 $n = wfBaseConvert( $n, 10, 16, 8, false );
414 }
415 }
416 return $n;
417 }
418
419 /**
420 * Given an IPv6 address in octet notation, returns a pure hex string.
421 *
422 * @param $ip String: octet ipv6 IP address.
423 * @return String: pure hex (uppercase)
424 */
425 private static function IPv6ToRawHex( $ip ) {
426 $ip = self::sanitizeIP( $ip );
427 if ( !$ip ) {
428 return null;
429 }
430 $r_ip = '';
431 foreach ( explode( ':', $ip ) as $v ) {
432 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
433 }
434 return $r_ip;
435 }
436
437 /**
438 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
439 * Like ip2long() except that it actually works and has a consistent error return value.
440 * Comes from ProxyTools.php
441 *
442 * @param $ip String: quad dotted IP address.
443 * @return Mixed: string/int/false
444 */
445 public static function toUnsigned( $ip ) {
446 if ( self::isIPv6( $ip ) ) {
447 $n = self::toUnsigned6( $ip );
448 } else {
449 $n = ip2long( $ip );
450 if ( $n < 0 ) {
451 $n += pow( 2, 32 );
452 }
453 }
454 return $n;
455 }
456
457 /**
458 * @param $ip
459 * @return String
460 */
461 private static function toUnsigned6( $ip ) {
462 return wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
463 }
464
465 /**
466 * Convert a network specification in CIDR notation
467 * to an integer network and a number of bits
468 *
469 * @param $range String: IP with CIDR prefix
470 * @return array(int or string, int)
471 */
472 public static function parseCIDR( $range ) {
473 if ( self::isIPv6( $range ) ) {
474 return self::parseCIDR6( $range );
475 }
476 $parts = explode( '/', $range, 2 );
477 if ( count( $parts ) != 2 ) {
478 return array( false, false );
479 }
480 list( $network, $bits ) = $parts;
481 $network = ip2long( $network );
482 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
483 if ( $bits == 0 ) {
484 $network = 0;
485 } else {
486 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1);
487 }
488 # Convert to unsigned
489 if ( $network < 0 ) {
490 $network += pow( 2, 32 );
491 }
492 } else {
493 $network = false;
494 $bits = false;
495 }
496 return array( $network, $bits );
497 }
498
499 /**
500 * Given a string range in a number of formats,
501 * return the start and end of the range in hexadecimal.
502 *
503 * Formats are:
504 * 1.2.3.4/24 CIDR
505 * 1.2.3.4 - 1.2.3.5 Explicit range
506 * 1.2.3.4 Single IP
507 *
508 * 2001:0db8:85a3::7344/96 CIDR
509 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
510 * 2001:0db8:85a3::7344 Single IP
511 * @param $range String: IP range
512 * @return array(string, string)
513 */
514 public static function parseRange( $range ) {
515 // CIDR notation
516 if ( strpos( $range, '/' ) !== false ) {
517 if ( self::isIPv6( $range ) ) {
518 return self::parseRange6( $range );
519 }
520 list( $network, $bits ) = self::parseCIDR( $range );
521 if ( $network === false ) {
522 $start = $end = false;
523 } else {
524 $start = sprintf( '%08X', $network );
525 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
526 }
527 // Explicit range
528 } elseif ( strpos( $range, '-' ) !== false ) {
529 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
530 if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
531 return self::parseRange6( $range );
532 }
533 if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
534 $start = self::toUnsigned( $start );
535 $end = self::toUnsigned( $end );
536 if ( $start > $end ) {
537 $start = $end = false;
538 } else {
539 $start = sprintf( '%08X', $start );
540 $end = sprintf( '%08X', $end );
541 }
542 } else {
543 $start = $end = false;
544 }
545 } else {
546 # Single IP
547 $start = $end = self::toHex( $range );
548 }
549 if ( $start === false || $end === false ) {
550 return array( false, false );
551 } else {
552 return array( $start, $end );
553 }
554 }
555
556 /**
557 * Convert a network specification in IPv6 CIDR notation to an
558 * integer network and a number of bits
559 *
560 * @param $range
561 *
562 * @return array(string, int)
563 */
564 private static function parseCIDR6( $range ) {
565 # Explode into <expanded IP,range>
566 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
567 if ( count( $parts ) != 2 ) {
568 return array( false, false );
569 }
570 list( $network, $bits ) = $parts;
571 $network = self::IPv6ToRawHex( $network );
572 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
573 if ( $bits == 0 ) {
574 $network = "0";
575 } else {
576 # Native 32 bit functions WONT work here!!!
577 # Convert to a padded binary number
578 $network = wfBaseConvert( $network, 16, 2, 128 );
579 # Truncate the last (128-$bits) bits and replace them with zeros
580 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
581 # Convert back to an integer
582 $network = wfBaseConvert( $network, 2, 10 );
583 }
584 } else {
585 $network = false;
586 $bits = false;
587 }
588 return array( $network, (int)$bits );
589 }
590
591 /**
592 * Given a string range in a number of formats, return the
593 * start and end of the range in hexadecimal. For IPv6.
594 *
595 * Formats are:
596 * 2001:0db8:85a3::7344/96 CIDR
597 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
598 * 2001:0db8:85a3::7344/96 Single IP
599 *
600 * @param $range
601 *
602 * @return array(string, string)
603 */
604 private static function parseRange6( $range ) {
605 # Expand any IPv6 IP
606 $range = IP::sanitizeIP( $range );
607 // CIDR notation...
608 if ( strpos( $range, '/' ) !== false ) {
609 list( $network, $bits ) = self::parseCIDR6( $range );
610 if ( $network === false ) {
611 $start = $end = false;
612 } else {
613 $start = wfBaseConvert( $network, 10, 16, 32, false );
614 # Turn network to binary (again)
615 $end = wfBaseConvert( $network, 10, 2, 128 );
616 # Truncate the last (128-$bits) bits and replace them with ones
617 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
618 # Convert to hex
619 $end = wfBaseConvert( $end, 2, 16, 32, false );
620 # see toHex() comment
621 $start = "v6-$start";
622 $end = "v6-$end";
623 }
624 // Explicit range notation...
625 } elseif ( strpos( $range, '-' ) !== false ) {
626 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
627 $start = self::toUnsigned6( $start );
628 $end = self::toUnsigned6( $end );
629 if ( $start > $end ) {
630 $start = $end = false;
631 } else {
632 $start = wfBaseConvert( $start, 10, 16, 32, false );
633 $end = wfBaseConvert( $end, 10, 16, 32, false );
634 }
635 # see toHex() comment
636 $start = "v6-$start";
637 $end = "v6-$end";
638 } else {
639 # Single IP
640 $start = $end = self::toHex( $range );
641 }
642 if ( $start === false || $end === false ) {
643 return array( false, false );
644 } else {
645 return array( $start, $end );
646 }
647 }
648
649 /**
650 * Determine if a given IPv4/IPv6 address is in a given CIDR network
651 *
652 * @param $addr String: the address to check against the given range.
653 * @param $range String: the range to check the given address against.
654 * @return Boolean: whether or not the given address is in the given range.
655 */
656 public static function isInRange( $addr, $range ) {
657 $hexIP = self::toHex( $addr );
658 list( $start, $end ) = self::parseRange( $range );
659 return ( strcmp( $hexIP, $start ) >= 0 &&
660 strcmp( $hexIP, $end ) <= 0 );
661 }
662
663 /**
664 * Convert some unusual representations of IPv4 addresses to their
665 * canonical dotted quad representation.
666 *
667 * This currently only checks a few IPV4-to-IPv6 related cases. More
668 * unusual representations may be added later.
669 *
670 * @param $addr String: something that might be an IP address
671 * @return String: valid dotted quad IPv4 address or null
672 */
673 public static function canonicalize( $addr ) {
674 if ( self::isValid( $addr ) ) {
675 return $addr;
676 }
677 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
678 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
679 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
680 if ( self::isIPv4( $addr ) ) {
681 return $addr;
682 }
683 }
684 // IPv6 loopback address
685 $m = array();
686 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
687 return '127.0.0.1';
688 }
689 // IPv4-mapped and IPv4-compatible IPv6 addresses
690 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
691 return $m[1];
692 }
693 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
694 ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
695 {
696 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
697 }
698
699 return null; // give up
700 }
701
702 /**
703 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
704 * For example, 127.111.113.151/24 -> 127.111.113.0/24
705 * @param $range String: IP address to normalize
706 * @return string
707 */
708 public static function sanitizeRange( $range ) {
709 list( /*...*/, $bits ) = self::parseCIDR( $range );
710 list( $start, /*...*/ ) = self::parseRange( $range );
711 $start = self::formatHex( $start );
712 if ( $bits === false ) {
713 return $start; // wasn't actually a range
714 }
715 return "$start/$bits";
716 }
717 }