}
/**
- * Convert an IP into a nice standard form.
+ * Convert an IP into a verbose, uppercase, normalized form.
* IPv6 addresses in octet notation are expanded to 8 words.
* IPv4 addresses are just trimmed.
*
return $ip;
}
+ /**
+ * Prettify an IP for display to end users.
+ * This will make it more compact and lower-case.
+ *
+ * @param $ip string
+ * @return string
+ */
+ public static function prettifyIP( $ip ) {
+ $ip = self::sanitizeIP( $ip ); // normalize (removes '::')
+ if ( self::isIPv6( $ip ) ) {
+ // Split IP into an address and a CIDR
+ if ( strpos( $ip, '/' ) !== false ) {
+ list( $ip, $cidr ) = explode( '/', $ip, 2 );
+ } else {
+ list( $ip, $cidr ) = array( $ip, '' );
+ }
+ // Get the largest slice of words with multiple zeros
+ $offset = 0;
+ $longest = $longestPos = false;
+ while ( preg_match(
+ '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE, $offset
+ ) ) {
+ list( $match, $pos ) = $m[0]; // full match
+ if ( strlen( $match ) > strlen( $longest ) ) {
+ $longest = $match;
+ $longestPos = $pos;
+ }
+ $offset += ( $pos + strlen( $match ) ); // advance
+ }
+ if ( $longest !== false ) {
+ // Replace this portion of the string with the '::' abbreviation
+ $ip = substr_replace( $ip, '::', $longestPos, strlen( $longest ) );
+ }
+ // Add any CIDR back on
+ if ( $cidr !== '' ) {
+ $ip = "{$ip}/{$cidr}";
+ }
+ // Convert to lower case to make it more readable
+ $ip = strtolower( $ip );
+ }
+ return $ip;
+ }
+
/**
* Given a host/port string, like one might find in the host part of a URL
* per RFC 2732, split the hostname part and the port part and return an
<?php
/**
* Tests for IP validity functions. Ported from /t/inc/IP.t by avar.
+ * @group IP
*/
class IPTest extends MediaWikiTestCase {
array( '0:c1:A2:3:4:5:c6:7', '0:C1:A2:3:4:5:C6:7', 'IPv6 non range' ),
);
}
+
+ /**
+ * Test for IP::prettifyIP()
+ * @dataProvider provideIPsToPrettify
+ */
+ function testPrettifyIP( $ip, $prettified ) {
+ $this->assertEquals( $prettified, IP::prettifyIP( $ip ), "Prettify of $ip" );
+ }
+
+ /**
+ * Provider for IP::testPrettifyIP()
+ */
+ function provideIPsToPrettify() {
+ return array(
+ array( '0:0:0:0:0:0:0:0', '::' ),
+ array( '0:0:0::0:0:0', '::' ),
+ array( '0:0:0:1:0:0:0:0', '0:0:0:1::' ),
+ array( '0:0::f', '::f' ),
+ array( '0::0:0:0:33:fef:b', '::33:fef:b' ),
+ array( '3f:535:0:0:0:0:e:fbb', '3f:535::e:fbb' ),
+ array( '0:0:fef:0:0:0:e:fbb', '0:0:fef::e:fbb' ),
+ array( 'abbc:2004::0:0:0:0', 'abbc:2004::' ),
+ array( 'cebc:2004:f:0:0:0:0:0', 'cebc:2004:f::' ),
+ array( '0:0:0:0:0:0:0:0/16', '::/16' ),
+ array( '0:0:0::0:0:0/64', '::/64' ),
+ array( '0:0::f/52', '::f/52' ),
+ array( '::0:0:33:fef:b/52', '::33:fef:b/52' ),
+ array( '3f:535:0:0:0:0:e:fbb/48', '3f:535::e:fbb/48' ),
+ array( '0:0:fef:0:0:0:e:fbb/96', '0:0:fef::e:fbb/96' ),
+ array( 'abbc:2004:0:0::0:0/40', 'abbc:2004::/40' ),
+ array( 'aebc:2004:f:0:0:0:0:0/80', 'aebc:2004:f::/80' ),
+ );
+ }
}