From 32d1b9512cf84d868e5bdfedf682cfb0f0313ddf Mon Sep 17 00:00:00 2001 From: SilverFire - Dima Naumenko Date: Fri, 23 Oct 2015 12:23:04 +0300 Subject: [PATCH] Added IpValidator description to `core-validators` ru,en guides. IpValidaor PHPDoc enhanced --- docs/guide-ru/tutorial-core-validators.md | 72 ++++++++++++++++++++++ docs/guide/tutorial-core-validators.md | 73 +++++++++++++++++++++++ framework/validators/IpValidator.php | 35 ++++++----- 3 files changed, 162 insertions(+), 18 deletions(-) diff --git a/docs/guide-ru/tutorial-core-validators.md b/docs/guide-ru/tutorial-core-validators.md index f8fd1f112c..da60b84a90 100644 --- a/docs/guide-ru/tutorial-core-validators.md +++ b/docs/guide-ru/tutorial-core-validators.md @@ -304,6 +304,78 @@ function foo($model, $attribute) { - `maxHeight`: максимальная высота изображения. По умолчанию null, что значит, что нет верхнего лимита. +## [[yii\validators\IpValidator|ip]] +```php +[ + // проверяет, что "ip_address" - это валидный IPv4 или IPv6 адрес + ['ip_address', 'ip'], + + + // проверяет, что "ip_address" - это валидный IPv6 адрес или подсеть, + // значение будет развернуто в формат полной записи IPv6 адреса + ['ip_address', 'ip', 'ipv4' => false, 'subnet' => null, 'expandIPv6' => true], + + // проверяет, что "ip_address" - это валидный IPv4 или IPv6 адрес, + // разрешает использования символа отрацания `!` + ['ip_address', 'ip', 'negation' => true], +] +``` + +Этот валидатор проверяет, является ли входящее значение валидным IPv4/IPv6 адресом или подсетью. +Он также может изменять значение атрибута, если включена нормализация или развертывание IPv6 адресов. + +Валидатор имеет такие свойства: + +- `ipv4`: может ли проверяемое значение быть IPv4 адрессом. По умолчанию true. +- `ipv6`: может ли проверяемое значение быть IPv6 адрессом. По умолчанию true. +- `subnet`: может ли проверяемое значение быть IP адресом с CIDR (подсетью), например `192.168.10.0/24` + * `true` - указание подсети обязательно; + * `false` - указание подсети запрещено; + * `null` - указание подсети возможно, но не обязательно. + + По умолчанию false. +- `normalize`: нормализировать ли проверяемый IP адрес без CIDR к IP адресу с наименьшим CIDR +(32 для IPv4 или 128 для IPv6). Свойство действует только если `subnet` не установлен в `false`. Например: + * `10.0.1.5` будет приведен к `10.0.1.5/32` + * `2008:db0::1` будет приведен к `2008:db0::1/128` +- `negation`: может ли проверяемое значение иметь символ отрицания `!` в начале, например `!192.168.0.1`. +По умолчанию false. +- `expandIPv6`: разворачивать ли IPv6 адрес в формат полной записи. +Например, IPv6 адрес `2008:db0::1` будет развернут в `2008:0db0:0000:0000:0000:0000:0000:0001`. По умолчанию false. +- `ranges`: массив IPv4 или IPv6 диапазонов, которые разрешены или запрещены. + + Если свойство не установлено, все IP адреса разрешены. Иначе, правила будут проверяться последовательно до первого +вхождения. IP адрес будет запрещен, если не подпадет ни под одно правило. Например: + ```php + [ + 'client_ip', 'ip', 'ranges' => [ + '192.168.10.128' + '!192.168.10.0/24', + 'any' // разрешает все остальные IP адреса + ] + ] + ``` +В этом примере, доступ разрешен для всех IPv4 и IPv6 адресов кроме подсети `192.168.10.0/24`. +IPv4 адрес `192.168.10.128` также разрешен, так как находится перед запрещающим правилом. +- `networks`: массив псевдониимов, которые могут быть использованы в `ranges`. Формат массива: + * ключ - имя псевдонима + * значение - массив строк. Строка может быть как диапазоном адресов, так и другим псведонимом. Строка может иметь + символ отрицания `!` в начале (не зависит от свойства `negation`). + + Следующие псевдонимы определены по умолчанию: + + * `*`: `any` + * `any`: `0.0.0.0/0, ::/0` + * `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8` + * `multicast`: `224.0.0.0/4, ff00::/8` + * `linklocal`: `169.254.0.0/16, fe80::/10` + * `localhost`: `127.0.0.0/8', ::1` + * `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32` + * `system`: `multicast, linklocal, localhost, documentation` + +> Информация: Этот валидатор стал доступным начиная с версии 2.0.7. + + ## [[yii\validators\RangeValidator|in]] ```php diff --git a/docs/guide/tutorial-core-validators.md b/docs/guide/tutorial-core-validators.md index f5667b444d..75e6f1e1b5 100644 --- a/docs/guide/tutorial-core-validators.md +++ b/docs/guide/tutorial-core-validators.md @@ -367,6 +367,79 @@ validation purpose: - `minHeight`: the minimum height of the image. Defaults to null, meaning no lower limit. - `maxHeight`: the maximum height of the image. Defaults to null, meaning no upper limit. +## [[yii\validators\IpValidator|ip]] +```php +[ + // checks if "ip_address" is a valid IPv4 or IPv6 address + ['ip_address', 'ip'], + + // checks if "ip_address" is a valid IPv6 address or subnet, + // value will be expanded to full IPv6 notation. + ['ip_address', 'ip', 'ipv4' => false, 'subnet' => null, 'expandIPv6' => true], + + // checks if "ip_address" is a valid IPv4 or IPv6 address, + // allows negation character `!` at the beginning + ['ip_address', 'ip', 'negation' => true], +] +``` + +The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet. +It also may change attribute's value if normalization or IPv6 expansion is enabled. + +The validator has such configuration options: + +- `ipv4`: whether the validating value can be an IPv4 address. Defaults to true. +- `ipv6`: whether the validating value can be an IPv6 address. Defaults to true. +- `subnet`: whether the address can be an IP with CIDR subnet, like `192.168.10.0/24` + * `true` - the subnet is required, addresses without CIDR will be rejected + * `false` - the address can not have the CIDR + * `null` - the CIDR is optional + + Defaults to false. +- `normalize`: whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an +address without it. Works only when `subnet` is not `false`. For example: + * `10.0.1.5` will normalized to `10.0.1.5/32` + * `2008:db0::1` will be normalized to `2008:db0::1/128` + + Defaults to false. +- `negation`: whether the validation address can have a negation character `!` at the beginning. Defaults to false. +- `expandIPv6`: whether to expand an IPv6 address to the full notation format. +For example, `2008:db0::1` will be expanded to `2008:0db0:0000:0000:0000:0000:0000:0001`. Defaults to false. +- `ranges`: array of IPv4 or IPv6 ranges that are allowed or forbidden. + + When the array is empty, or the option is not set, all the IP addresses are allowed. + Otherwise, the rules are checked sequentially until the first match is found. + IP address is forbidden, when it has not matched any of the rules. + + For example: + ```php + [ + 'client_ip', 'ip', 'ranges' => [ + '192.168.10.128' + '!192.168.10.0/24', + 'any' // allows any other IP addresses + ] + ] + ``` +In this example, access is allowed for all the IPv4 and IPv6 addresses excluding `192.168.10.0/24` subnet. +IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction. +- `networks`: array of network aliases, that can be used in `ranges`. Format of array: + * key - alias name + * value - array of strings. String can be a range, IP address or another alias. String can be + negated with `!` (independent of `negation` option). + + The following aliases are defined by default: + + * `*`: `any` + * `any`: `0.0.0.0/0, ::/0` + * `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8` + * `multicast`: `224.0.0.0/4, ff00::/8` + * `linklocal`: `169.254.0.0/16, fe80::/10` + * `localhost`: `127.0.0.0/8', ::1` + * `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32` + * `system`: `multicast, linklocal, localhost, documentation` + +> Info: This validator has been available since version 2.0.7. ## [[yii\validators\RangeValidator|in]] diff --git a/framework/validators/IpValidator.php b/framework/validators/IpValidator.php index 06aca9159d..51bec8f2e0 100644 --- a/framework/validators/IpValidator.php +++ b/framework/validators/IpValidator.php @@ -15,14 +15,14 @@ use yii\helpers\StringHelper; use yii\web\JsExpression; /** - * IpValidator validates whether the attribute value is a valid IPv4/IPv6 address or subnet. - * May change attribute's value if normalization is enabled. + * The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet. + * It also may change attribute's value if normalization or IPv6 expansion is enabled. * - * @property array $ranges IPv4 or IPv6 ranges that are allowed or denied. + * @property array $ranges IPv4 or IPv6 ranges that are allowed or forbidden. * - * When the array is empty, all IP addresses are allowed. - * When the array is not empty, the rules are checked sequentially until the first match is found. - * IP address is denied, when it did not match any of the rules. + * When the array is empty, or the option not set, all IP addresses are allowed. + * Otherwise, the rules are checked sequentially until the first match is found. + * IP address is forbidden, when it has not matched any of the rules. * * Example: * ```php @@ -36,7 +36,7 @@ use yii\web\JsExpression; * ``` * * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding `192.168.10.0/24` subnet. - * IPv4 address `192.168.10.128` is also allowed, because is listed above the restriction. * + * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction. * @see isAllowed() * * @author Dmitry Naumenko @@ -66,10 +66,8 @@ class IpValidator extends Validator /** * @var array The network aliases, that can be used in [[ranges]]. * - key - alias name - * - value - array of strings - * - * When $networks contains another alias, the value will be substituted recursively. - * The range or alias could be negated with [[NEGATION_CHAR]]. + * - value - array of strings. String can be an IP range, IP address or another alias. String can be + * negated with [[NEGATION_CHAR]] (independent of `negation` option). * * The following aliases are defined by default: * - `*`: `any` @@ -94,17 +92,17 @@ class IpValidator extends Validator ]; /** - * @var boolean whether support of IPv6 addresses is enabled + * @var boolean whether the validating value can be an IPv6 address. Defaults to true. */ public $ipv6 = true; /** - * @var boolean whether support of IPv4 addresses is enabled + * @var boolean whether the validating value can be an IPv4 address. Defaults to true. */ public $ipv4 = true; /** - * @var boolean whether the address can be a CIDR subnet + * @var boolean whether the address can be an IP with CIDR subnet, like `192.168.10.0/24` * true - the subnet is required * false - the address can not have the subnet * null - ths subnet is optional @@ -112,10 +110,11 @@ class IpValidator extends Validator public $subnet = false; /** - * @var boolean whether to add the prefix with the smallest length (32 for IPv4 and 128 for IPv6) - * to an address without it. - * Works only when attribute [[subnet]] is not false. - * Example: `10.0.1.5` will normalized to `10.0.1.5/32`, `2008:db0::1` will be normalized to `2008:db0::1/128` + * @var boolean whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an + * address without it. Works only when `subnet` is not `false`. For example: + * - `10.0.1.5` will normalized to `10.0.1.5/32` + * - `2008:db0::1` will be normalized to `2008:db0::1/128` + * Defaults to false. * @see subnet */ public $normalize = false;