UrlValidator.php 4.09 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;
12
use yii\helpers\Html;
Qiang Xue committed
13
use yii\web\JsExpression;
14
use yii\helpers\Json;
Qiang Xue committed
15

w  
Qiang Xue committed
16
/**
w  
Qiang Xue committed
17
 * UrlValidator validates that the attribute value is a valid http or https URL.
w  
Qiang Xue committed
18
 *
Qiang Xue committed
19 20 21
 * 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
22
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
23
 * @since 2.0
w  
Qiang Xue committed
24
 */
w  
Qiang Xue committed
25
class UrlValidator extends Validator
w  
Qiang Xue committed
26 27 28
{
	/**
	 * @var string the regular expression used to validate the attribute value.
w  
Qiang Xue committed
29 30
	 * The pattern may contain a `{schemes}` token that will be replaced
	 * by a regular expression which represents the [[validSchemes]].
w  
Qiang Xue committed
31 32 33 34 35 36
	 */
	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
37
	public $validSchemes = ['http', 'https'];
w  
Qiang Xue committed
38 39 40 41 42 43
	/**
	 * @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;
44 45 46
	/**
	 * @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
47 48
	 * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
	 * extension, otherwise an exception would be thrown.
49
	 */
50
	public $enableIDN = false;
w  
Qiang Xue committed
51

Qiang Xue committed
52 53

	/**
Qiang Xue committed
54
	 * @inheritdoc
Qiang Xue committed
55 56 57 58
	 */
	public function init()
	{
		parent::init();
59 60 61
		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
62
		if ($this->message === null) {
63
			$this->message = Yii::t('yii', '{attribute} is not a valid URL.');
Qiang Xue committed
64 65 66
		}
	}

w  
Qiang Xue committed
67
	/**
Qiang Xue committed
68
	 * @inheritdoc
w  
Qiang Xue committed
69
	 */
w  
Qiang Xue committed
70
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
71 72
	{
		$value = $object->$attribute;
Qiang Xue committed
73 74 75 76 77
		$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
78 79 80 81
		}
	}

	/**
Qiang Xue committed
82
	 * @inheritdoc
w  
Qiang Xue committed
83
	 */
Qiang Xue committed
84
	protected function validateValue($value)
w  
Qiang Xue committed
85
	{
w  
Qiang Xue committed
86 87 88
		// 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
89
				$value = $this->defaultScheme . '://' . $value;
w  
Qiang Xue committed
90
			}
w  
Qiang Xue committed
91

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

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

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

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

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

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