This repository has been archived by the owner on Nov 28, 2019. It is now read-only.
/
RecaptchaField.php
298 lines (261 loc) · 8.27 KB
/
RecaptchaField.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<?php
/**
* @package recaptcha
*/
/**
* Provides an {@link FormField} which allows form to validate for non-bot submissions
* by giving them a challenge to decrypt an image.
* Generation and validation of captchas is handled on external server.
* This field doesn't save anything back to the form,
* and only submits recaptcha-related form-data to an external server.
*
* @see https://www.google.com/recaptcha/
* @see https://www.google.com/recaptcha/admin
*/
class RecaptchaField extends FormField {
/**
* Javasript-object formatted as a string,
* which can contain options about the used theme/language etc.
* <example>
* "array('theme' => 'white')
* </example>
*
* @see https://developers.google.com/recaptcha/docs/display
* @var array
*/
public $options = array();
/**
* Your public API key for a specific domain (get one at https://www.google.com/recaptcha/admin)
*
* @var string
*/
public static $public_api_key = '';
/**
* Your private API key for a specific domain (get one at https://www.google.com/recaptcha/admin)
*
* @var string
*/
public static $private_api_key = '';
/**
* Your proxy server details including the port
*
* @var string
*/
public static $proxy_server = '';
/**
* Your proxy server authentication
*
* @var string
*/
public static $proxy_auth = '';
/**
* Verify API server address (relative)
*
* @var string
*/
public static $api_verify_server = 'https://www.google.com/recaptcha/api/siteverify';
/**
* Javascript-address which includes necessary logic from the recaptcha-server.
* Your public key is automatically inserted.
*
* @var string
*/
public static $recaptcha_js_url = "https://www.google.com/recaptcha/api.js";
/**
* @var string
*/
public static $recaptcha_noscript_url = "https://www.google.com/recaptcha/api/fallback?k=%s";
/**
* @var string
*/
public static $httpclient_class = 'RecaptchaField_HTTPClient';
function __construct($name, $title = null, $value = null) {
parent::__construct($name, $title, $value);
}
public function Field($properties=array()) {
if(empty(self::$public_api_key) || empty(self::$private_api_key)) {
user_error('RecaptchaField::FieldHolder() Please specify valid Recaptcha Keys', E_USER_ERROR);
}
$html = '';
$previousError = Session::get("FormField.{$this->form->FormName()}.{$this->getName()}.error");
Session::clear("FormField.{$this->form->FormName()}.{$this->getName()}.error");
// iframe (fallback)
$iframeURL = sprintf(self::$recaptcha_noscript_url, self::$public_api_key);
if(!empty($previousError)) $iframeURL .= "&error={$previousError}";
// js (main logic)
$jsURL = sprintf(self::$recaptcha_js_url, self::$public_api_key);
if(!empty($previousError)) $jsURL .= "&error={$previousError}";
// turn options array into data attributes
$optionString = '';
foreach($this->options as $option => $value) {
$optionString .= ' data-' . htmlentities($option) . '="' . htmlentities($value) . '"';
}
Requirements::javascript($jsURL);
$html .= '<div class="g-recaptcha" id="' . $this->getName() . '"
data-sitekey="' . self::$public_api_key . '"' . $optionString . '></div>';
// noscript fallback
$html .= <<<EOF
<noscript>
<div style="width: 302px; height: 462px;">
<div style="width: 302px; height: 422px; position: relative;">
<div style="width: 302px; height: 422px; position: absolute;">
<iframe src="{$iframeURL}"
frameborder="0" scrolling="no"
style="width: 302px; height:422px; border-style: none;">
</iframe>
</div>
</div>
<div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px;
right: 25px; background: #f9f9f9; border: 1px solid #c1c1c1;
border-radius: 3px; height: 60px; width: 300px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response"
class="g-recaptcha-response"
style="width: 250px; height: 40px; border: 1px solid #c1c1c1;
margin: 10px 25px; padding: 0px; resize: none;">
</textarea>
</div>
</div>
<br>
</noscript>
EOF;
return $html;
}
/**
* Validate by submitting to external service
*
* @todo implement socket timeout handling (or switch to curl?)
* @param Validator $validator
* @return boolean
*/
public function validate($validator) {
// don't bother querying the recaptcha-service if fields were empty
if(
!isset($_REQUEST['g-recaptcha-response'])
|| empty($_REQUEST['g-recaptcha-response'])
) {
$validator->validationError(
$this->name,
_t(
'RecaptchaField.EMPTY',
"Please answer the captcha question",
"Recaptcha (https://www.google.com/recaptcha) protects this website "
. "from spam and abuse."
),
"validation",
false
);
return false;
}
$response = $this->recaptchaHTTPPost($_REQUEST['g-recaptcha-response']);
if(!$response) {
$validator->validationError(
$this->name,
_t(
'RecaptchaField.NORESPONSE',
"The recaptcha service gave no response. Please try again later.",
"Recaptcha (https://www.google.com/recaptcha) protects this website "
. "from spam and abuse."
),
"validation",
false
);
return false;
}
// get the payload of the response and decode it
$response = json_decode($response, true);
if($response['success'] != 'true') {
// Count some errors as "user level", meaning they raise a validation error rather than a system error
$userLevelErrors = array('missing-input-response', 'invalid-input-response');
if(count(array_intersect($response['error-codes'], $userLevelErrors)) === 0) {
$error = implode(', ', $response['error-codes']);
user_error("RecatpchaField::validate(): Recaptcha-service error: '{$error}'", E_USER_ERROR);
return false;
} else {
// Internal error-string returned by recaptcha, e.g. "incorrect-captcha-sol".
// Used to generate the new iframe-url/js-url after form-refresh.
Session::set("FormField.{$this->form->FormName()}.{$this->getName()}.error", trim($error));
$validator->validationError(
$this->name,
_t(
'RecaptchaField.VALIDSOLUTION',
"Your answer didn't match the captcha words, please try again",
"Recaptcha (https://www.google.com/recaptcha) protects this website "
. "from spam and abuse."
),
"validation",
false
);
return false;
}
}
return true;
}
/**
* Fires off a HTTP-POST request
*
* @see Based on http://recaptcha.net/plugins/php/
* @param string $challengeStr
* @param string $responseStr
* @return string Raw HTTP-response
*/
protected function recaptchaHTTPPost($responseStr) {
$postVars = array(
'secret' => self::$private_api_key,
'remoteip' => $_SERVER['REMOTE_ADDR'],
'response' => $responseStr,
);
$client = $this->getHTTPClient();
$response = $client->post(self::$api_verify_server, $postVars);
return $response->getBody();
}
/**
* @param RecaptchaField_HTTPClient
*/
function setHTTPClient($client) {
$this->client = $client;
return $this;
}
/**
* @return RecaptchaField_HTTPClient
*/
function getHTTPClient() {
if(!$this->client) {
$class = self::$httpclient_class;
$this->client = new $class();
}
return $this->client;
}
}
/**
* Simple HTTP client, mainly to make it mockable.
*/
class RecaptchaField_HTTPClient extends Object {
/**
* @param String $url
* @param Array $data
* @return String HTTPResponse
*/
function post($url, $postVars) {
$ch = curl_init($url);
if(!empty(RecaptchaField::$proxy_server)){
curl_setopt($ch, CURLOPT_PROXY, RecaptchaField::$proxy_server);
if (!empty(RecaptchaField::$proxy_auth)){
curl_setopt($ch, CURLOPT_PROXYUSERPWD, RecaptchaField::$proxy_auth);
}
}
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'reCAPTCHA/PHP');
// we need application/x-www-form-urlencoded
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postVars));
$response = curl_exec($ch);
if(class_exists('SS_HTTPResponse')) {
$responseObj = new SS_HTTPResponse();
} else {
// 2.3 backwards compat
$responseObj = new HTTPResponse();
}
$responseObj->setBody($response); // 2.2. compat
return $responseObj;
}
}