Completed
Push — fix-numbervalidator-comma-deci... ( 08054b...a7f0a3 )
by Alexander
40:41 queued 37:41
created

Captcha::checkRequirements()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6.8088

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 7
cts 12
cp 0.5833
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 7
nop 0
crap 6.8088
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
8
namespace yii\captcha;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Url;
13
use yii\helpers\Html;
14
use yii\helpers\Json;
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](http://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 <[email protected]>
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 1
    public function init()
91
    {
92 1
        parent::init();
93
94 1
        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
        if ($this->hasModel()) {
108
            $input = Html::activeTextInput($this->model, $this->attribute, $this->options);
109
        } else {
110
            $input = Html::textInput($this->name, $this->value, $this->options);
111
        }
112
        $route = $this->captchaAction;
113
        if (is_array($route)) {
114
            $route['v'] = uniqid();
115
        } else {
116
            $route = [$route, 'v' => uniqid()];
117
        }
118
        $image = Html::img($route, $this->imageOptions);
119
        echo strtr($this->template, [
120
            '{input}' => $input,
121
            '{image}' => $image,
122
        ]);
123
    }
124
125
    /**
126
     * Registers the needed JavaScript.
127
     */
128
    public function registerClientScript()
129
    {
130
        $options = $this->getClientOptions();
131
        $options = empty($options) ? '' : Json::htmlEncode($options);
132
        $id = $this->imageOptions['id'];
133
        $view = $this->getView();
134
        CaptchaAsset::register($view);
135
        $view->registerJs("jQuery('#$id').yiiCaptcha($options);");
136
    }
137
138
    /**
139
     * Returns the options for the captcha JS widget.
140
     * @return array the options
141
     */
142
    protected function getClientOptions()
143
    {
144
        $route = $this->captchaAction;
145
        if (is_array($route)) {
146
            $route[CaptchaAction::REFRESH_GET_VAR] = 1;
147
        } else {
148
            $route = [$route, CaptchaAction::REFRESH_GET_VAR => 1];
149
        }
150
151
        $options = [
152
            'refreshUrl' => Url::toRoute($route),
153
            'hashKey' => 'yiiCaptcha/' . trim($route[0], '/'),
154
        ];
155
156
        return $options;
157
    }
158
159
    /**
160
     * Checks if there is graphic extension available to generate CAPTCHA images.
161
     * This method will check the existence of ImageMagick and GD extensions.
162
     * @return string the name of the graphic extension, either "imagick" or "gd".
163
     * @throws InvalidConfigException if neither ImageMagick nor GD is installed.
164
     */
165 1
    public static function checkRequirements()
166
    {
167 1
        if (extension_loaded('imagick')) {
168
            $imagickFormats = (new \Imagick())->queryFormats('PNG');
169
            if (in_array('PNG', $imagickFormats, true)) {
170
                return 'imagick';
171
            }
172
        }
173 1
        if (extension_loaded('gd')) {
174 1
            $gdInfo = gd_info();
175 1
            if (!empty($gdInfo['FreeType Support'])) {
176
                return 'gd';
177
            }
178 1
        }
179 1
        throw new InvalidConfigException('Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required.');
180
    }
181
}
182