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

Qiang Xue committed
49 50 51 52 53 54 55

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

w  
Qiang Xue committed
64 65 66
	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
w  
Qiang Xue committed
67
	 * @param \yii\base\Model $object the object being validated
w  
Qiang Xue committed
68 69
	 * @param string $attribute the attribute being validated
	 */
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
		if ($this->validateValue($value)) {
			if ($this->defaultScheme !== null && strpos($value, '://') === false) {
				$object->$attribute = $this->defaultScheme . '://' . $value;
			}
Qiang Xue committed
77
		} else {
Qiang Xue committed
78
			$this->addError($object, $attribute, $this->message);
w  
Qiang Xue committed
79 80 81 82
		}
	}

	/**
Qiang Xue committed
83 84 85
	 * Validates the given value.
	 * @param mixed $value the value to be validated.
	 * @return boolean whether the value is valid.
w  
Qiang Xue committed
86 87 88
	 */
	public function validateValue($value)
	{
w  
Qiang Xue committed
89 90 91
		// 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
92
				$value = $this->defaultScheme . '://' . $value;
w  
Qiang Xue committed
93
			}
w  
Qiang Xue committed
94

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

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

w  
Qiang Xue committed
107
			if (preg_match($pattern, $value)) {
Qiang Xue committed
108
				return true;
w  
Qiang Xue committed
109
			}
w  
Qiang Xue committed
110 111 112 113 114 115
		}
		return false;
	}

	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
116
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
117
	 * @param string $attribute the name of the attribute to be validated.
118 119
	 * @param \yii\base\View $view the view object that is going to be used to render views or view files
	 * containing a model form with this validator applied.
w  
Qiang Xue committed
120
	 * @return string the client-side validation script.
Qiang Xue committed
121
	 * @see \yii\Web\ActiveForm::enableClientValidation
w  
Qiang Xue committed
122
	 */
123
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
124
	{
Alexander Makarov committed
125
		if (strpos($this->pattern, '{schemes}') !== false) {
w  
Qiang Xue committed
126
			$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
Alexander Makarov committed
127
		} else {
w  
Qiang Xue committed
128
			$pattern = $this->pattern;
Alexander Makarov committed
129
		}
w  
Qiang Xue committed
130

131 132 133 134 135 136
		$options = array(
			'pattern' => new JsExpression($pattern),
			'message' => Html::encode(strtr($this->message, array(
				'{attribute}' => $object->getAttributeLabel($attribute),
				'{value}' => $object->$attribute,
			))),
137
			'enableIDN' => (boolean)$this->enableIDN,
138
		);
Qiang Xue committed
139
		if ($this->skipOnEmpty) {
140 141 142 143
			$options['skipOnEmpty'] = 1;
		}
		if ($this->defaultScheme !== null) {
			$options['defaultScheme'] = $this->defaultScheme;
w  
Qiang Xue committed
144 145
		}

146
		$view->registerAssetBundle('yii/validation');
147
		if ($this->enableIDN) {
Qiang Xue committed
148
			$view->registerAssetBundle('yii/punycode');
149
		}
150
		return 'yii.validation.url(value, messages, ' . Json::encode($options) . ');';
w  
Qiang Xue committed
151 152
	}
}