You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UrlValidator.php 4.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\validators;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\web\JsExpression;
  11. use yii\helpers\Json;
  12. /**
  13. * UrlValidator validates that the attribute value is a valid http or https URL.
  14. *
  15. * Note that this validator only checks if the URL scheme and host part are correct.
  16. * It does not check the remaining parts of a URL.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class UrlValidator extends Validator
  22. {
  23. /**
  24. * @var string the regular expression used to validate the attribute value.
  25. * The pattern may contain a `{schemes}` token that will be replaced
  26. * by a regular expression which represents the [[validSchemes]].
  27. */
  28. public $pattern = '/^{schemes}:\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?(?:$|[?\/#])/i';
  29. /**
  30. * @var array list of URI schemes which should be considered valid. By default, http and https
  31. * are considered to be valid schemes.
  32. */
  33. public $validSchemes = ['http', 'https'];
  34. /**
  35. * @var string the default URI scheme. If the input doesn't contain the scheme part, the default
  36. * scheme will be prepended to it (thus changing the input). Defaults to null, meaning a URL must
  37. * contain the scheme part.
  38. */
  39. public $defaultScheme;
  40. /**
  41. * @var boolean whether validation process should take into account IDN (internationalized
  42. * domain names). Defaults to false meaning that validation of URLs containing IDN will always
  43. * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
  44. * extension, otherwise an exception would be thrown.
  45. */
  46. public $enableIDN = false;
  47. /**
  48. * @inheritdoc
  49. */
  50. public function init()
  51. {
  52. parent::init();
  53. if ($this->enableIDN && !function_exists('idn_to_ascii')) {
  54. throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
  55. }
  56. if ($this->message === null) {
  57. $this->message = Yii::t('yii', '{attribute} is not a valid URL.');
  58. }
  59. }
  60. /**
  61. * @inheritdoc
  62. */
  63. public function validateAttribute($model, $attribute)
  64. {
  65. $value = $model->$attribute;
  66. $result = $this->validateValue($value);
  67. if (!empty($result)) {
  68. $this->addError($model, $attribute, $result[0], $result[1]);
  69. } elseif ($this->defaultScheme !== null && strpos($value, '://') === false) {
  70. $model->$attribute = $this->defaultScheme . '://' . $value;
  71. }
  72. }
  73. /**
  74. * @inheritdoc
  75. */
  76. protected function validateValue($value)
  77. {
  78. // make sure the length is limited to avoid DOS attacks
  79. if (is_string($value) && strlen($value) < 2000) {
  80. if ($this->defaultScheme !== null && strpos($value, '://') === false) {
  81. $value = $this->defaultScheme . '://' . $value;
  82. }
  83. if (strpos($this->pattern, '{schemes}') !== false) {
  84. $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
  85. } else {
  86. $pattern = $this->pattern;
  87. }
  88. if ($this->enableIDN) {
  89. $value = preg_replace_callback('/:\/\/([^\/]+)/', function ($matches) {
  90. return '://' . idn_to_ascii($matches[1]);
  91. }, $value);
  92. }
  93. if (preg_match($pattern, $value)) {
  94. return null;
  95. }
  96. }
  97. return [$this->message, []];
  98. }
  99. /**
  100. * @inheritdoc
  101. */
  102. public function clientValidateAttribute($model, $attribute, $view)
  103. {
  104. if (strpos($this->pattern, '{schemes}') !== false) {
  105. $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
  106. } else {
  107. $pattern = $this->pattern;
  108. }
  109. $options = [
  110. 'pattern' => new JsExpression($pattern),
  111. 'message' => Yii::$app->getI18n()->format($this->message, [
  112. 'attribute' => $model->getAttributeLabel($attribute),
  113. ], Yii::$app->language),
  114. 'enableIDN' => (bool) $this->enableIDN,
  115. ];
  116. if ($this->skipOnEmpty) {
  117. $options['skipOnEmpty'] = 1;
  118. }
  119. if ($this->defaultScheme !== null) {
  120. $options['defaultScheme'] = $this->defaultScheme;
  121. }
  122. ValidationAsset::register($view);
  123. if ($this->enableIDN) {
  124. PunycodeAsset::register($view);
  125. }
  126. return 'yii.validation.url(value, messages, ' . Json::htmlEncode($options) . ');';
  127. }
  128. }