123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581 |
- <?php
- namespace yii\validators;
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\helpers\Html;
- use yii\helpers\IpHelper;
- use yii\helpers\Json;
- use yii\web\JsExpression;
- class IpValidator extends Validator
- {
-
- const NEGATION_CHAR = '!';
-
- public $networks = [
- '*' => ['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'],
- ];
-
- public $ipv6 = true;
-
- public $ipv4 = true;
-
- public $subnet = false;
-
- public $normalize = false;
-
- public $negation = false;
-
- public $expandIPv6 = false;
-
- public $ipv4Pattern = '/^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$/';
-
- public $ipv6Pattern = '/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/';
-
- public $message;
-
- public $ipv6NotAllowed;
-
- public $ipv4NotAllowed;
-
- public $wrongCidr;
-
- public $noSubnet;
-
- public $hasSubnet;
-
- public $notInRange;
-
- private $_ranges = [];
-
- public function init()
- {
- parent::init();
- if (!$this->ipv4 && !$this->ipv6) {
- throw new InvalidConfigException('Both IPv4 and IPv6 checks can not be disabled at the same time');
- }
- if ($this->message === null) {
- $this->message = Yii::t('yii', '{attribute} must be a valid IP address.');
- }
- if ($this->ipv6NotAllowed === null) {
- $this->ipv6NotAllowed = Yii::t('yii', '{attribute} must not be an IPv6 address.');
- }
- if ($this->ipv4NotAllowed === null) {
- $this->ipv4NotAllowed = Yii::t('yii', '{attribute} must not be an IPv4 address.');
- }
- if ($this->wrongCidr === null) {
- $this->wrongCidr = Yii::t('yii', '{attribute} contains wrong subnet mask.');
- }
- if ($this->noSubnet === null) {
- $this->noSubnet = Yii::t('yii', '{attribute} must be an IP address with specified subnet.');
- }
- if ($this->hasSubnet === null) {
- $this->hasSubnet = Yii::t('yii', '{attribute} must not be a subnet.');
- }
- if ($this->notInRange === null) {
- $this->notInRange = Yii::t('yii', '{attribute} is not in the allowed range.');
- }
- }
-
- public function setRanges($ranges)
- {
- $this->_ranges = $this->prepareRanges((array) $ranges);
- }
-
- public function getRanges()
- {
- return $this->_ranges;
- }
-
- protected function validateValue($value)
- {
- $result = $this->validateSubnet($value);
- if (is_array($result)) {
- $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
- return $result;
- }
- return null;
- }
-
- public function validateAttribute($model, $attribute)
- {
- $value = $model->$attribute;
- $result = $this->validateSubnet($value);
- if (is_array($result)) {
- $result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
- $this->addError($model, $attribute, $result[0], $result[1]);
- } else {
- $model->$attribute = $result;
- }
- }
-
- private function validateSubnet($ip)
- {
- if (!is_string($ip)) {
- return [$this->message, []];
- }
- $negation = null;
- $cidr = null;
- $isCidrDefault = false;
- if (preg_match($this->getIpParsePattern(), $ip, $matches)) {
- $negation = ($matches[1] !== '') ? $matches[1] : null;
- $ip = $matches[2];
- $cidr = isset($matches[4]) ? $matches[4] : null;
- }
- if ($this->subnet === true && $cidr === null) {
- return [$this->noSubnet, []];
- }
- if ($this->subnet === false && $cidr !== null) {
- return [$this->hasSubnet, []];
- }
- if ($this->negation === false && $negation !== null) {
- return [$this->message, []];
- }
- if ($this->getIpVersion($ip) === IpHelper::IPV6) {
- if ($cidr !== null) {
- if ($cidr > IpHelper::IPV6_ADDRESS_LENGTH || $cidr < 0) {
- return [$this->wrongCidr, []];
- }
- } else {
- $isCidrDefault = true;
- $cidr = IpHelper::IPV6_ADDRESS_LENGTH;
- }
- if (!$this->validateIPv6($ip)) {
- return [$this->message, []];
- }
- if (!$this->ipv6) {
- return [$this->ipv6NotAllowed, []];
- }
- if ($this->expandIPv6) {
- $ip = $this->expandIPv6($ip);
- }
- } else {
- if ($cidr !== null) {
- if ($cidr > IpHelper::IPV4_ADDRESS_LENGTH || $cidr < 0) {
- return [$this->wrongCidr, []];
- }
- } else {
- $isCidrDefault = true;
- $cidr = IpHelper::IPV4_ADDRESS_LENGTH;
- }
- if (!$this->validateIPv4($ip)) {
- return [$this->message, []];
- }
- if (!$this->ipv4) {
- return [$this->ipv4NotAllowed, []];
- }
- }
- if (!$this->isAllowed($ip, $cidr)) {
- return [$this->notInRange, []];
- }
- $result = $negation . $ip;
- if ($this->subnet !== false && (!$isCidrDefault || $isCidrDefault && $this->normalize)) {
- $result .= "/$cidr";
- }
- return $result;
- }
-
- private function expandIPv6($ip)
- {
- return IpHelper::expandIPv6($ip);
- }
-
- private function isAllowed($ip, $cidr)
- {
- if (empty($this->ranges)) {
- return true;
- }
- foreach ($this->ranges as $string) {
- list($isNegated, $range) = $this->parseNegatedRange($string);
- if ($this->inRange($ip, $cidr, $range)) {
- return !$isNegated;
- }
- }
- return false;
- }
-
- private function parseNegatedRange($string)
- {
- $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
- return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
- }
-
- private function prepareRanges($ranges)
- {
- $result = [];
- foreach ($ranges as $string) {
- list($isRangeNegated, $range) = $this->parseNegatedRange($string);
- if (isset($this->networks[$range])) {
- $replacements = $this->prepareRanges($this->networks[$range]);
- foreach ($replacements as &$replacement) {
- list($isReplacementNegated, $replacement) = $this->parseNegatedRange($replacement);
- $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
- }
- } else {
- $result[] = $string;
- }
- }
- return array_unique($result);
- }
-
- protected function validateIPv4($value)
- {
- return preg_match($this->ipv4Pattern, $value) !== 0;
- }
-
- protected function validateIPv6($value)
- {
- return preg_match($this->ipv6Pattern, $value) !== 0;
- }
-
- private function getIpVersion($ip)
- {
- return IpHelper::getIpVersion($ip);
- }
-
- private function getIpParsePattern()
- {
- return '/^(' . preg_quote(static::NEGATION_CHAR, '/') . '?)(.+?)(\/(\d+))?$/';
- }
-
- private function inRange($ip, $cidr, $range)
- {
- return IpHelper::inRange($ip . '/' . $cidr, $range);
- }
-
- public function clientValidateAttribute($model, $attribute, $view)
- {
- ValidationAsset::register($view);
- $options = $this->getClientOptions($model, $attribute);
- return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
- }
-
- public function getClientOptions($model, $attribute)
- {
- $messages = [
- 'ipv6NotAllowed' => $this->ipv6NotAllowed,
- 'ipv4NotAllowed' => $this->ipv4NotAllowed,
- 'message' => $this->message,
- 'noSubnet' => $this->noSubnet,
- 'hasSubnet' => $this->hasSubnet,
- ];
- foreach ($messages as &$message) {
- $message = $this->formatMessage($message, [
- 'attribute' => $model->getAttributeLabel($attribute),
- ]);
- }
- $options = [
- 'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv4Pattern)),
- 'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv6Pattern)),
- 'messages' => $messages,
- 'ipv4' => (bool) $this->ipv4,
- 'ipv6' => (bool) $this->ipv6,
- 'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($this->getIpParsePattern())),
- 'negation' => $this->negation,
- 'subnet' => $this->subnet,
- ];
- if ($this->skipOnEmpty) {
- $options['skipOnEmpty'] = 1;
- }
- return $options;
- }
- }
|