yii2

Форк
1
/
CaptchaValidator.php 
118 строк · 3.6 Кб
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\Json;
13
use yii\validators\ValidationAsset;
14
use yii\validators\Validator;
15

16
/**
17
 * CaptchaValidator validates that the attribute value is the same as the verification code displayed in the CAPTCHA.
18
 *
19
 * CaptchaValidator should be used together with [[CaptchaAction]].
20
 *
21
 * Note that once CAPTCHA validation succeeds, a new CAPTCHA will be generated automatically. As a result,
22
 * CAPTCHA validation should not be used in AJAX validation mode because it may fail the validation
23
 * even if a user enters the same code as shown in the CAPTCHA image which is actually different from the latest CAPTCHA code.
24
 *
25
 * @author Qiang Xue <qiang.xue@gmail.com>
26
 * @since 2.0
27
 */
28
class CaptchaValidator extends Validator
29
{
30
    /**
31
     * @var bool whether to skip this validator if the input is empty.
32
     */
33
    public $skipOnEmpty = false;
34
    /**
35
     * @var bool whether the comparison is case sensitive. Defaults to false.
36
     */
37
    public $caseSensitive = false;
38
    /**
39
     * @var string the route of the controller action that renders the CAPTCHA image.
40
     */
41
    public $captchaAction = 'site/captcha';
42

43

44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function init()
48
    {
49
        parent::init();
50
        if ($this->message === null) {
51
            $this->message = Yii::t('yii', 'The verification code is incorrect.');
52
        }
53
    }
54

55
    /**
56
     * {@inheritdoc}
57
     */
58
    protected function validateValue($value)
59
    {
60
        $captcha = $this->createCaptchaAction();
61
        $valid = !is_array($value) && $captcha->validate($value, $this->caseSensitive);
62

63
        return $valid ? null : [$this->message, []];
64
    }
65

66
    /**
67
     * Creates the CAPTCHA action object from the route specified by [[captchaAction]].
68
     * @return \yii\captcha\CaptchaAction the action object
69
     * @throws InvalidConfigException
70
     */
71
    public function createCaptchaAction()
72
    {
73
        $ca = Yii::$app->createController($this->captchaAction);
74
        if ($ca !== false) {
75
            /* @var $controller \yii\base\Controller */
76
            list($controller, $actionID) = $ca;
77
            $action = $controller->createAction($actionID);
78
            if ($action !== null) {
79
                return $action;
80
            }
81
        }
82
        throw new InvalidConfigException('Invalid CAPTCHA action ID: ' . $this->captchaAction);
83
    }
84

85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function clientValidateAttribute($model, $attribute, $view)
89
    {
90
        ValidationAsset::register($view);
91
        $options = $this->getClientOptions($model, $attribute);
92

93
        return 'yii.validation.captcha(value, messages, ' . Json::htmlEncode($options) . ');';
94
    }
95

96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function getClientOptions($model, $attribute)
100
    {
101
        $captcha = $this->createCaptchaAction();
102
        $code = $captcha->getVerifyCode(false);
103
        $hash = $captcha->generateValidationHash($this->caseSensitive ? $code : strtolower($code));
104
        $options = [
105
            'hash' => $hash,
106
            'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(),
107
            'caseSensitive' => $this->caseSensitive,
108
            'message' => Yii::$app->getI18n()->format($this->message, [
109
                'attribute' => $model->getAttributeLabel($attribute),
110
            ], Yii::$app->language),
111
        ];
112
        if ($this->skipOnEmpty) {
113
            $options['skipOnEmpty'] = 1;
114
        }
115

116
        return $options;
117
    }
118
}
119

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

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

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

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