Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update IPUtils #10844

Merged
merged 2 commits into from
Aug 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Control/Util/IPUtils.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

/**
* These helpful functions were lifted from the Symfony library
* https://github.com/symfony/http-foundation/blob/master/LICENSE
Expand All @@ -7,6 +8,7 @@
*
* @author Fabien Potencier <[email protected]>
*/

namespace SilverStripe\Control\Util;

/**
Expand Down Expand Up @@ -131,4 +133,36 @@ public static function checkIP6($requestIP, $ip)

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;
}
}