Captcha.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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\captcha;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Html;
  11. use yii\helpers\Json;
  12. use yii\helpers\Url;
  13. use yii\widgets\InputWidget;
  14. /**
  15. * Captcha renders a CAPTCHA image and an input field that takes user-entered verification code.
  16. *
  17. * Captcha is used together with [[CaptchaAction]] to provide [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) - a way
  18. * of preventing website spamming.
  19. *
  20. * The image element rendered by Captcha will display a CAPTCHA image generated by
  21. * an action whose route is specified by [[captchaAction]]. This action must be an instance of [[CaptchaAction]].
  22. *
  23. * When the user clicks on the CAPTCHA image, it will cause the CAPTCHA image
  24. * to be refreshed with a new CAPTCHA.
  25. *
  26. * You may use [[\yii\captcha\CaptchaValidator]] to validate the user input matches
  27. * the current CAPTCHA verification code.
  28. *
  29. * The following example shows how to use this widget with a model attribute:
  30. *
  31. * ```php
  32. * echo Captcha::widget([
  33. * 'model' => $model,
  34. * 'attribute' => 'captcha',
  35. * ]);
  36. * ```
  37. *
  38. * The following example will use the name property instead:
  39. *
  40. * ```php
  41. * echo Captcha::widget([
  42. * 'name' => 'captcha',
  43. * ]);
  44. * ```
  45. *
  46. * You can also use this widget in an [[\yii\widgets\ActiveForm|ActiveForm]] using the [[\yii\widgets\ActiveField::widget()|widget()]]
  47. * method, for example like this:
  48. *
  49. * ```php
  50. * <?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
  51. * // configure additional widget properties here
  52. * ]) ?>
  53. * ```
  54. *
  55. * @author Qiang Xue <qiang.xue@gmail.com>
  56. * @since 2.0
  57. */
  58. class Captcha extends InputWidget
  59. {
  60. /**
  61. * @var string|array the route of the action that generates the CAPTCHA images.
  62. * The action represented by this route must be an action of [[CaptchaAction]].
  63. * Please refer to [[\yii\helpers\Url::toRoute()]] for acceptable formats.
  64. */
  65. public $captchaAction = 'site/captcha';
  66. /**
  67. * @var array HTML attributes to be applied to the CAPTCHA image tag.
  68. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  69. */
  70. public $imageOptions = [];
  71. /**
  72. * @var string the template for arranging the CAPTCHA image tag and the text input tag.
  73. * In this template, the token `{image}` will be replaced with the actual image tag,
  74. * while `{input}` will be replaced with the text input tag.
  75. */
  76. public $template = '{image} {input}';
  77. /**
  78. * @var array the HTML attributes for the input tag.
  79. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  80. */
  81. public $options = ['class' => 'form-control'];
  82. /**
  83. * Initializes the widget.
  84. */
  85. public function init()
  86. {
  87. parent::init();
  88. static::checkRequirements();
  89. if (!isset($this->imageOptions['id'])) {
  90. $this->imageOptions['id'] = $this->options['id'] . '-image';
  91. }
  92. }
  93. /**
  94. * Renders the widget.
  95. */
  96. public function run()
  97. {
  98. $this->registerClientScript();
  99. $input = $this->renderInputHtml('text');
  100. $route = $this->captchaAction;
  101. if (is_array($route)) {
  102. $route['v'] = uniqid('', true);
  103. } else {
  104. $route = [$route, 'v' => uniqid('', true)];
  105. }
  106. $image = Html::img($route, $this->imageOptions);
  107. echo strtr($this->template, [
  108. '{input}' => $input,
  109. '{image}' => $image,
  110. ]);
  111. }
  112. /**
  113. * Registers the needed JavaScript.
  114. */
  115. public function registerClientScript()
  116. {
  117. $options = $this->getClientOptions();
  118. $options = empty($options) ? '' : Json::htmlEncode($options);
  119. $id = $this->imageOptions['id'];
  120. $view = $this->getView();
  121. CaptchaAsset::register($view);
  122. $view->registerJs("jQuery('#$id').yiiCaptcha($options);");
  123. }
  124. /**
  125. * Returns the options for the captcha JS widget.
  126. * @return array the options
  127. */
  128. protected function getClientOptions()
  129. {
  130. $route = $this->captchaAction;
  131. if (is_array($route)) {
  132. $route[CaptchaAction::REFRESH_GET_VAR] = 1;
  133. } else {
  134. $route = [$route, CaptchaAction::REFRESH_GET_VAR => 1];
  135. }
  136. $options = [
  137. 'refreshUrl' => Url::toRoute($route),
  138. 'hashKey' => 'yiiCaptcha/' . trim($route[0], '/'),
  139. ];
  140. return $options;
  141. }
  142. /**
  143. * Checks if there is graphic extension available to generate CAPTCHA images.
  144. * This method will check the existence of ImageMagick and GD extensions.
  145. * @return string the name of the graphic extension, either "imagick" or "gd".
  146. * @throws InvalidConfigException if neither ImageMagick nor GD is installed.
  147. */
  148. public static function checkRequirements()
  149. {
  150. if (extension_loaded('imagick')) {
  151. $imagickFormats = (new \Imagick())->queryFormats('PNG');
  152. if (in_array('PNG', $imagickFormats, true)) {
  153. return 'imagick';
  154. }
  155. }
  156. if (extension_loaded('gd')) {
  157. $gdInfo = gd_info();
  158. if (!empty($gdInfo['FreeType Support'])) {
  159. return 'gd';
  160. }
  161. }
  162. throw new InvalidConfigException('Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.');
  163. }
  164. }