From bd91d8ece71e66a4a6911723b97e2956d8077016 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Tim=20D=C3=BCsterhus?= Date: Fri, 4 Jun 2021 13:40:00 +0200 Subject: [PATCH] Add `IpAddress::toBulletMasked()` --- .../files/lib/util/IpAddress.class.php | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/wcfsetup/install/files/lib/util/IpAddress.class.php b/wcfsetup/install/files/lib/util/IpAddress.class.php index 574fbafce5..d96dc4c557 100644 --- a/wcfsetup/install/files/lib/util/IpAddress.class.php +++ b/wcfsetup/install/files/lib/util/IpAddress.class.php @@ -108,6 +108,47 @@ final class IpAddress return new self(\inet_ntop(\inet_pton((string)$ipAddress) & $mask)); } + /** + * Returns a masked IP address with the masked parts replaced by bullets. + * + * @see IpAddress::toMasked() + */ + public function toBulletMasked(int $mask4, int $mask6): string + { + $masked = $this->toMasked($mask4, $mask6); + + if (($mask4 % 8) !== 0) { + throw new \InvalidArgumentException('Given $mask4 is not a multiple of 8.'); + } + if (($mask6 % 4) !== 0) { + throw new \InvalidArgumentException('Given $mask6 is not a multiple of 4.'); + } + + if ($masked->asV4()) { + $maskedBlocks = (32 - $mask4) / 8; + $replacement = \str_repeat(".\u{2022}\u{2022}\u{2022}", $maskedBlocks); + + return \preg_replace( + '/(\.0){' . ($maskedBlocks) . '}$/', + $replacement, + (string)$masked + ); + } else { + $maskedDigits = (128 - $mask6) / 4; + + // Partially masked quadruplet. + $replacement = \str_repeat("\u{2022}", ($maskedDigits % 4)); + // Fully masked quadruplets. + $replacement .= \str_repeat(":\u{2022}\u{2022}\u{2022}\u{2022}", ($maskedDigits / 4)); + + return \preg_replace( + '/.{' . ($maskedDigits % 4) . '}::$/', + $replacement, + (string)$masked + ); + } + } + /** * @see IpAddress::getIpAddress() */ -- 2.20.1