yii2

Форк
1
/
Captcha.php 
177 строк · 5.5 Кб
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7

8
namespace yii\captcha;
9

10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Html;
13
use yii\helpers\Json;
14
use yii\helpers\Url;
15
use yii\widgets\InputWidget;
16

17
/**
18
 * Captcha renders a CAPTCHA image and an input field that takes user-entered verification code.
19
 *
20
 * Captcha is used together with [[CaptchaAction]] to provide [CAPTCHA](https://en.wikipedia.org/wiki/CAPTCHA) - a way
21
 * of preventing website spamming.
22
 *
23
 * The image element rendered by Captcha will display a CAPTCHA image generated by
24
 * an action whose route is specified by [[captchaAction]]. This action must be an instance of [[CaptchaAction]].
25
 *
26
 * When the user clicks on the CAPTCHA image, it will cause the CAPTCHA image
27
 * to be refreshed with a new CAPTCHA.
28
 *
29
 * You may use [[\yii\captcha\CaptchaValidator]] to validate the user input matches
30
 * the current CAPTCHA verification code.
31
 *
32
 * The following example shows how to use this widget with a model attribute:
33
 *
34
 * ```php
35
 * echo Captcha::widget([
36
 *     'model' => $model,
37
 *     'attribute' => 'captcha',
38
 * ]);
39
 * ```
40
 *
41
 * The following example will use the name property instead:
42
 *
43
 * ```php
44
 * echo Captcha::widget([
45
 *     'name' => 'captcha',
46
 * ]);
47
 * ```
48
 *
49
 * You can also use this widget in an [[\yii\widgets\ActiveForm|ActiveForm]] using the [[\yii\widgets\ActiveField::widget()|widget()]]
50
 * method, for example like this:
51
 *
52
 * ```php
53
 * <?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
54
 *     // configure additional widget properties here
55
 * ]) ?>
56
 * ```
57
 *
58
 * @author Qiang Xue <qiang.xue@gmail.com>
59
 * @since 2.0
60
 */
61
class Captcha extends InputWidget
62
{
63
    /**
64
     * @var string|array the route of the action that generates the CAPTCHA images.
65
     * The action represented by this route must be an action of [[CaptchaAction]].
66
     * Please refer to [[\yii\helpers\Url::toRoute()]] for acceptable formats.
67
     */
68
    public $captchaAction = 'site/captcha';
69
    /**
70
     * @var array HTML attributes to be applied to the CAPTCHA image tag.
71
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
72
     */
73
    public $imageOptions = [];
74
    /**
75
     * @var string the template for arranging the CAPTCHA image tag and the text input tag.
76
     * In this template, the token `{image}` will be replaced with the actual image tag,
77
     * while `{input}` will be replaced with the text input tag.
78
     */
79
    public $template = '{image} {input}';
80
    /**
81
     * @var array the HTML attributes for the input tag.
82
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
83
     */
84
    public $options = ['class' => 'form-control'];
85

86

87
    /**
88
     * Initializes the widget.
89
     */
90
    public function init()
91
    {
92
        parent::init();
93

94
        static::checkRequirements();
95

96
        if (!isset($this->imageOptions['id'])) {
97
            $this->imageOptions['id'] = $this->options['id'] . '-image';
98
        }
99
    }
100

101
    /**
102
     * Renders the widget.
103
     */
104
    public function run()
105
    {
106
        $this->registerClientScript();
107
        $input = $this->renderInputHtml('text');
108
        $route = $this->captchaAction;
109
        if (is_array($route)) {
110
            $route['v'] = uniqid('', true);
111
        } else {
112
            $route = [$route, 'v' => uniqid('', true)];
113
        }
114
        $image = Html::img($route, $this->imageOptions);
115
        echo strtr($this->template, [
116
            '{input}' => $input,
117
            '{image}' => $image,
118
        ]);
119
    }
120

121
    /**
122
     * Registers the needed JavaScript.
123
     */
124
    public function registerClientScript()
125
    {
126
        $options = $this->getClientOptions();
127
        $options = empty($options) ? '' : Json::htmlEncode($options);
128
        $id = $this->imageOptions['id'];
129
        $view = $this->getView();
130
        CaptchaAsset::register($view);
131
        $view->registerJs("jQuery('#$id').yiiCaptcha($options);");
132
    }
133

134
    /**
135
     * Returns the options for the captcha JS widget.
136
     * @return array the options
137
     */
138
    protected function getClientOptions()
139
    {
140
        $route = $this->captchaAction;
141
        if (is_array($route)) {
142
            $route[CaptchaAction::REFRESH_GET_VAR] = 1;
143
        } else {
144
            $route = [$route, CaptchaAction::REFRESH_GET_VAR => 1];
145
        }
146

147
        $options = [
148
            'refreshUrl' => Url::toRoute($route),
149
            'hashKey' => 'yiiCaptcha/' . trim($route[0], '/'),
150
        ];
151

152
        return $options;
153
    }
154

155
    /**
156
     * Checks if there is graphic extension available to generate CAPTCHA images.
157
     * This method will check the existence of ImageMagick and GD extensions.
158
     * @return string the name of the graphic extension, either "imagick" or "gd".
159
     * @throws InvalidConfigException if neither ImageMagick nor GD is installed.
160
     */
161
    public static function checkRequirements()
162
    {
163
        if (extension_loaded('imagick')) {
164
            $imagickFormats = (new \Imagick())->queryFormats('PNG');
165
            if (in_array('PNG', $imagickFormats, true)) {
166
                return 'imagick';
167
            }
168
        }
169
        if (extension_loaded('gd')) {
170
            $gdInfo = gd_info();
171
            if (!empty($gdInfo['FreeType Support'])) {
172
                return 'gd';
173
            }
174
        }
175
        throw new InvalidConfigException('Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.');
176
    }
177
}
178

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.