IPTools.php in Restrict Login or Role Access by IP Address 8.4
File
src/IPTools.php
View source
<?php
namespace Drupal\restrict_by_ip;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\restrict_by_ip\Exception\InvalidIPException;
use Drupal\restrict_by_ip\Exception\IPOutOfRangeException;
class IPTools implements IPToolsInterface {
protected $config;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->config = $config_factory
->get('restrict_by_ip.settings');
}
public function getUserIP() {
$header = $this->config
->get('header');
$ip_address = '';
if (!empty($_SERVER[$header])) {
$ip_address = $_SERVER[$header];
}
return $ip_address;
}
public static function validateIP($ip) {
$cidr = explode("/", $ip);
if (count($cidr) !== 2) {
throw new InvalidIPException('IP address must be in CIDR notation.');
}
$ipaddr = explode(".", $cidr[0]);
if (count($ipaddr) != 4) {
throw new InvalidIPException('IP address must have four octets.');
}
for ($i = 0; $i < count($ipaddr); $i++) {
if (!is_numeric($ipaddr[$i]) || $ipaddr[$i] < 0 || $ipaddr[$i] > 255) {
throw new InvalidIPException('Octet must be between 0 and 255.');
}
}
if (!is_numeric($cidr[1]) || $cidr[1] < 1 || $cidr[1] > 32) {
throw new InvalidIPException('Routing prefix must be between 0 and 32.');
}
try {
self::validateCIDR($cidr[0], $ip);
} catch (IPOutOfRangeException $e) {
throw new InvalidIPException('IP address and routing prefix are not a valid combination.');
}
}
public static function validateCIDR($ip, $range) {
$netmask = explode("/", $range);
$ip_net = ip2long($netmask[0]);
$ip_mask = ~((1 << 32 - $netmask[1]) - 1);
$ip_ip = ip2long($ip);
$ip_ip_net = $ip_ip & $ip_mask;
if ($ip_ip_net != $ip_net) {
throw new IPOutOfRangeException('IP address and routing prefix are not a valid combination.');
}
}
}