UrlValidator.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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\helpers\Json;
  11. use yii\web\JsExpression;
  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 bool 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 '://' . $this->idnToAscii($matches[1]);
  91. }, $value);
  92. }
  93. if (preg_match($pattern, $value)) {
  94. return null;
  95. }
  96. }
  97. return [$this->message, []];
  98. }
  99. private function idnToAscii($idn)
  100. {
  101. if (PHP_VERSION_ID < 50600) {
  102. // TODO: drop old PHP versions support
  103. return idn_to_ascii($idn);
  104. }
  105. return idn_to_ascii($idn, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function clientValidateAttribute($model, $attribute, $view)
  111. {
  112. ValidationAsset::register($view);
  113. if ($this->enableIDN) {
  114. PunycodeAsset::register($view);
  115. }
  116. $options = $this->getClientOptions($model, $attribute);
  117. return 'yii.validation.url(value, messages, ' . Json::htmlEncode($options) . ');';
  118. }
  119. /**
  120. * {@inheritdoc}
  121. */
  122. public function getClientOptions($model, $attribute)
  123. {
  124. if (strpos($this->pattern, '{schemes}') !== false) {
  125. $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
  126. } else {
  127. $pattern = $this->pattern;
  128. }
  129. $options = [
  130. 'pattern' => new JsExpression($pattern),
  131. 'message' => $this->formatMessage($this->message, [
  132. 'attribute' => $model->getAttributeLabel($attribute),
  133. ]),
  134. 'enableIDN' => (bool) $this->enableIDN,
  135. ];
  136. if ($this->skipOnEmpty) {
  137. $options['skipOnEmpty'] = 1;
  138. }
  139. if ($this->defaultScheme !== null) {
  140. $options['defaultScheme'] = $this->defaultScheme;
  141. }
  142. return $options;
  143. }
  144. }