-
Notifications
You must be signed in to change notification settings - Fork 1
/
RecaptchaTrait.php
40 lines (33 loc) · 1.18 KB
/
RecaptchaTrait.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
<?php
namespace ADT\Forms;
use Nette\Application\UI\Presenter;
use Nette\Forms\Form;
use Tracy\Debugger;
trait RecaptchaTrait
{
/** @var RecaptchaConfig @inject */
public RecaptchaConfig $recaptchaConfig;
/**
* Automatically adds recaptcha input and validator to form on attached
*/
public function injectRecaptcha()
{
$this->setOnAfterInitForm(function (Form $form) {
if ($this->recaptchaConfig->enabled) {
$form->addHidden('recaptchaToken');
$form->getElementPrototype()->setAttribute('data-adt-recaptcha', true);
$form->onValidate[] = function (Form $form) {
// if there are any previous errors, validation is unnecessary
if ($form->getErrors()) {
return;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $this->recaptchaConfig->secretKey . "&response=" . urlencode($form->getValues()['recaptchaToken']) . "&remoteip=" . $_SERVER['REMOTE_ADDR']), true);
if (!$response['success'] || $response['score'] < 0.5) {
$form->addError($this->recaptchaConfig->errorMessage);
Debugger::log('Recaptcha error: ' . print_r($response, true), 'recaptcha');
}
};
}
});
}
}