-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReCaptchaValidator.php
172 lines (147 loc) · 4.51 KB
/
ReCaptchaValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?php
/**
* Based on
*
* @link https://github.com/himiklab/yii2-recaptcha-widget/issues/57
*/
namespace lgxenos\yii2\recaptcha;
use Yii;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\validators\Validator;
/**
* ReCaptcha widget validator.
*/
class ReCaptchaValidator extends Validator {
const GRABBER_PHP = 1; // file_get_contents
const GRABBER_CURL = 2; // CURL, because sometimes file_get_contents is deprecated
const SITE_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
const CAPTCHA_RESPONSE_FIELD = 'g-recaptcha-response';
/** @var boolean Whether to skip this validator if the input is empty. */
public $skipOnEmpty = false;
/** @var string The shared key between your site and ReCAPTCHA. */
public $secret;
/**
* @var int Choose your grabber for getting JSON,
* self::GRABBER_PHP = file_get_contents, self::GRABBER_CURL = CURL
*/
public $grabberType = self::GRABBER_PHP;
/** @var string */
public $uncheckedMessage;
/** @var boolean */
protected $isValid = false;
public function init() {
parent::init();
if (empty($this->secret)) {
/** @var ReCaptcha $reCaptcha */
$reCaptcha = Yii::$app->reCaptcha;
if (!empty($reCaptcha->secret)) {
$this->secret = $reCaptcha->secret;
}
else {
throw new InvalidConfigException('Required `secret` param isn\'t set.');
}
}
if ($this->message === null) {
$this->message = Yii::t('yii', 'The verification code is incorrect.');
}
}
/**
* @param \yii\base\Model $model
* @param string $attribute
* @param \yii\web\View $view
*
* @return string
*/
public function clientValidateAttribute($model, $attribute, $view) {
$message = addslashes($this->uncheckedMessage ? : Yii::t(
'yii',
'{attribute} cannot be blank.',
['attribute' => $model->getAttributeLabel($attribute)]
));
$recaptchaId = Html::getInputId($model, $attribute) . '-recaptcha';
$js = <<<JS
(function(messages){
var
inputClientId = jQuery('#{$recaptchaId}').data('recaptcha-client-id'),
response = grecaptcha.getResponse(inputClientId);
if(!response){ messages.push('{$message}') }
})(messages);
JS;
return $js;
}
/**
* @param string|array $value
*
* @return array|null
* @throws Exception
* @throws \yii\base\InvalidParamException
*/
protected function validateValue($value) {
if (empty($value)) {
if (!($value = Yii::$app->request->post(self::CAPTCHA_RESPONSE_FIELD))) {
return [$this->message, []];
}
}
if (!$this->isValid) {
$request = self::SITE_VERIFY_URL . '?' . http_build_query([
'secret' => $this->secret,
'response' => $value,
'remoteip' => Yii::$app->request->userIP
]);
$response = $this->getResponse($request);
if (!isset($response['success'])) {
throw new Exception('Invalid recaptcha verify response.');
}
$this->isValid = (boolean)$response['success'];
}
return $this->isValid ? null : [$this->message, []];
}
/**
* @param string $request
*
* @return mixed
* @throws Exception
* @throws \yii\base\InvalidParamException
*/
protected function getResponse($request) {
if ($this->grabberType === self::GRABBER_PHP) {
$response = @file_get_contents($request);
if ($response === false) {
throw new Exception('Unable connection to the captcha server.');
}
}
else {
$options = [
CURLOPT_CUSTOMREQUEST => 'GET', //set request type post or get
CURLOPT_POST => false, //set to GET
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => '', // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
];
$ch = curl_init($request);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
$header = curl_getinfo($ch);
curl_close($ch);
$header['errno'] = $errno;
$header['errmsg'] = $errmsg;
$response = $content;
if ($header['errno'] !== 0) {
throw new Exception(
'Unable connection to the captcha server. Curl error #' . $header['errno'] . ' ' . $header['errmsg']
);
}
}
return Json::decode($response, true);
}
}