UrlValidator.php 4.44 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\helpers\Html;
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 18
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
w  
Qiang Xue committed
19
 * @since 2.0
w  
Qiang Xue committed
20
 */
w  
Qiang Xue committed
21
class UrlValidator extends Validator
w  
Qiang Xue committed
22 23 24
{
	/**
	 * @var string the regular expression used to validate the attribute value.
w  
Qiang Xue committed
25 26
	 * The pattern may contain a `{schemes}` token that will be replaced
	 * by a regular expression which represents the [[validSchemes]].
w  
Qiang Xue committed
27 28 29 30 31 32 33 34 35 36 37 38 39
	 */
	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;
40 41 42 43 44
	/**
	 * @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
	 * fail.
	 */
45
	public $enableIDN = false;
w  
Qiang Xue committed
46

Qiang Xue committed
47 48 49 50 51 52 53 54

	/**
	 * Initializes the validator.
	 */
	public function init()
	{
		parent::init();
		if ($this->message === null) {
55
			$this->message = Yii::t('yii', '{attribute} is not a valid URL.');
Qiang Xue committed
56 57 58
		}
	}

w  
Qiang Xue committed
59 60 61
	/**
	 * Validates the attribute of the object.
	 * If there is any error, the error message is added to the object.
w  
Qiang Xue committed
62
	 * @param \yii\base\Model $object the object being validated
w  
Qiang Xue committed
63 64
	 * @param string $attribute the attribute being validated
	 */
w  
Qiang Xue committed
65
	public function validateAttribute($object, $attribute)
w  
Qiang Xue committed
66 67
	{
		$value = $object->$attribute;
Qiang Xue committed
68 69 70 71
		if ($this->validateValue($value)) {
			if ($this->defaultScheme !== null && strpos($value, '://') === false) {
				$object->$attribute = $this->defaultScheme . '://' . $value;
			}
Qiang Xue committed
72
		} else {
Qiang Xue committed
73
			$this->addError($object, $attribute, $this->message);
w  
Qiang Xue committed
74 75 76 77
		}
	}

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

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

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

w  
Qiang Xue committed
102
			if (preg_match($pattern, $value)) {
Qiang Xue committed
103
				return true;
w  
Qiang Xue committed
104
			}
w  
Qiang Xue committed
105 106 107 108 109 110
		}
		return false;
	}

	/**
	 * Returns the JavaScript needed for performing client-side validation.
w  
Qiang Xue committed
111
	 * @param \yii\base\Model $object the data object being validated
w  
Qiang Xue committed
112
	 * @param string $attribute the name of the attribute to be validated.
113 114
	 * @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
115
	 * @return string the client-side validation script.
Qiang Xue committed
116
	 * @see \yii\Web\ActiveForm::enableClientValidation
w  
Qiang Xue committed
117
	 */
118
	public function clientValidateAttribute($object, $attribute, $view)
w  
Qiang Xue committed
119
	{
Alexander Makarov committed
120
		if (strpos($this->pattern, '{schemes}') !== false) {
w  
Qiang Xue committed
121
			$pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
Alexander Makarov committed
122
		} else {
w  
Qiang Xue committed
123
			$pattern = $this->pattern;
Alexander Makarov committed
124
		}
w  
Qiang Xue committed
125

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

141
		$view->registerAssetBundle('yii/validation');
142
		if ($this->enableIDN) {
Qiang Xue committed
143
			$view->registerAssetBundle('yii/punycode');
144
		}
145
		return 'yii.validation.url(value, messages, ' . Json::encode($options) . ');';
w  
Qiang Xue committed
146 147
	}
}