UrlValidator.php 4.11 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

w  
Qiang Xue committed
8 9
namespace yii\validators;

Qiang Xue committed
10
use Yii;
11
use yii\base\InvalidConfigException;
Qiang Xue committed
12
use yii\web\JsExpression;
13
use yii\helpers\Json;
Qiang Xue committed
14

w  
Qiang Xue committed
15
/**
w  
Qiang Xue committed
16
 * UrlValidator validates that the attribute value is a valid http or https URL.
w  
Qiang Xue committed
17
 *
Qiang Xue committed
18 19 20
 * Note that this validator only checks if the URL scheme and host part are correct.
 * It does not check the rest part of a URL.
 *
w  
Qiang Xue committed
21
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
22
 * @since 2.0
w  
Qiang Xue committed
23
 */
w  
Qiang Xue committed
24
class UrlValidator extends Validator
w  
Qiang Xue committed
25 26 27
{
	/**
	 * @var string the regular expression used to validate the attribute value.
w  
Qiang Xue committed
28 29
	 * The pattern may contain a `{schemes}` token that will be replaced
	 * by a regular expression which represents the [[validSchemes]].
w  
Qiang Xue committed
30 31 32 33 34 35
	 */
	public $pattern = '/^{schemes}:\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i';
	/**
	 * @var array list of URI schemes which should be considered valid. By default, http and https
	 * are considered to be valid schemes.
	 **/
Alexander Makarov committed
36
	public $validSchemes = ['http', 'https'];
w  
Qiang Xue committed
37 38 39 40 41 42
	/**
	 * @var string the default URI scheme. If the input doesn't contain the scheme part, the default
	 * scheme will be prepended to it (thus changing the input). Defaults to null, meaning a URL must
	 * contain the scheme part.
	 **/
	public $defaultScheme;
43 44 45
	/**
	 * @var boolean whether validation process should take into account IDN (internationalized
	 * domain names). Defaults to false meaning that validation of URLs containing IDN will always
46 47
	 * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
	 * extension, otherwise an exception would be thrown.
48
	 */
49
	public $enableIDN = false;
w  
Qiang Xue committed
50

Qiang Xue committed
51 52

	/**
Qiang Xue committed
53
	 * @inheritdoc
Qiang Xue committed
54 55 56 57
	 */
	public function init()
	{
		parent::init();
58 59 60
		if ($this->enableIDN && !function_exists('idn_to_ascii')) {
			throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
		}
Qiang Xue committed
61
		if ($this->message === null) {
62
			$this->message = Yii::t('yii', '{attribute} is not a valid URL.');
Qiang Xue committed
63 64 65
		}
	}

w  
Qiang Xue committed
66
	/**
Qiang Xue committed
67
	 * @inheritdoc
w  
Qiang Xue committed
68
	 */
w  
Qiang Xue committed
69
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
70 71
	{
		$value = $object->$attribute;
Qiang Xue committed
72 73 74 75 76
		$result = $this->validateValue($value);
		if (!empty($result)) {
			$this->addError($object, $attribute, $result[0], $result[1]);
		} elseif ($this->defaultScheme !== null && strpos($value, '://') === false) {
			$object->$attribute = $this->defaultScheme . '://' . $value;
w  
Qiang Xue committed
77 78 79 80
		}
	}

	/**
Qiang Xue committed
81
	 * @inheritdoc
w  
Qiang Xue committed
82
	 */
Qiang Xue committed
83
	protected function validateValue($value)
w  
Qiang Xue committed
84
	{
w  
Qiang Xue committed
85 86 87
		// make sure the length is limited to avoid DOS attacks
		if (is_string($value) && strlen($value) < 2000) {
			if ($this->defaultScheme !== null && strpos($value, '://') === false) {
w  
Qiang Xue committed
88
				$value = $this->defaultScheme . '://' . $value;
w  
Qiang Xue committed
89
			}
w  
Qiang Xue committed
90

w  
Qiang Xue committed
91
			if (strpos($this->pattern, '{schemes}') !== false) {
w  
Qiang Xue committed
92
				$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
Qiang Xue committed
93
			} else {
w  
Qiang Xue committed
94
				$pattern = $this->pattern;
w  
Qiang Xue committed
95
			}
w  
Qiang Xue committed
96

97
			if ($this->enableIDN) {
resurtm committed
98
				$value = preg_replace_callback('/:\/\/([^\/]+)/', function ($matches) {
99 100 101 102
					return '://' . idn_to_ascii($matches[1]);
				}, $value);
			}

w  
Qiang Xue committed
103
			if (preg_match($pattern, $value)) {
Qiang Xue committed
104
				return null;
w  
Qiang Xue committed
105
			}
w  
Qiang Xue committed
106
		}
Qiang Xue committed
107
		return [$this->message, []];
w  
Qiang Xue committed
108 109 110
	}

	/**
Qiang Xue committed
111
	 * @inheritdoc
w  
Qiang Xue committed
112
	 */
113
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
114
	{
Alexander Makarov committed
115
		if (strpos($this->pattern, '{schemes}') !== false) {
w  
Qiang Xue committed
116
			$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
Alexander Makarov committed
117
		} else {
w  
Qiang Xue committed
118
			$pattern = $this->pattern;
Alexander Makarov committed
119
		}
w  
Qiang Xue committed
120

Alexander Makarov committed
121
		$options = [
122
			'pattern' => new JsExpression($pattern),
Alexander Makarov committed
123
			'message' => Yii::$app->getI18n()->format($this->message, [
124
				'attribute' => $object->getAttributeLabel($attribute),
125
			], Yii::$app->language),
126
			'enableIDN' => (boolean)$this->enableIDN,
Alexander Makarov committed
127
		];
Qiang Xue committed
128
		if ($this->skipOnEmpty) {
129 130 131 132
			$options['skipOnEmpty'] = 1;
		}
		if ($this->defaultScheme !== null) {
			$options['defaultScheme'] = $this->defaultScheme;
w  
Qiang Xue committed
133 134
		}

135
		ValidationAsset::register($view);
136
		if ($this->enableIDN) {
137
			PunycodeAsset::register($view);
138
		}
139
		return 'yii.validation.url(value, messages, ' . Json::encode($options) . ');';
w  
Qiang Xue committed
140 141
	}
}