Merge pull request #10844 from lekoala/patch-40

update IPUtils
This commit is contained in:
Guy Sartorelli 2023-08-11 20:47:09 +12:00 committed by GitHub
commit b178647dee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* These helpful functions were lifted from the Symfony library * These helpful functions were lifted from the Symfony library
* https://github.com/symfony/http-foundation/blob/master/LICENSE * https://github.com/symfony/http-foundation/blob/master/LICENSE
@ -7,6 +8,7 @@
* *
* @author Fabien Potencier <fabien@symfony.com> * @author Fabien Potencier <fabien@symfony.com>
*/ */
namespace SilverStripe\Control\Util; namespace SilverStripe\Control\Util;
/** /**
@ -131,4 +133,36 @@ class IPUtils
return true; return true;
} }
/**
* Anonymizes an IP/IPv6.
*
* Removes the last byte for v4 and the last 8 bytes for v6 IPs
*/
public static function anonymize(string $ip): string
{
$wrappedIPv6 = false;
if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
$wrappedIPv6 = true;
$ip = substr($ip, 1, -1);
}
$packedAddress = inet_pton($ip);
if (4 === \strlen($packedAddress)) {
$mask = '255.255.255.0';
} elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
$mask = '::ffff:ffff:ff00';
} elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
$mask = '::ffff:ff00';
} else {
$mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
}
$ip = inet_ntop($packedAddress & inet_pton($mask));
if ($wrappedIPv6) {
$ip = '[' . $ip . ']';
}
return $ip;
}
} }