-
Notifications
You must be signed in to change notification settings - Fork 1
/
invisible_recaptcha.module
65 lines (57 loc) · 2.06 KB
/
invisible_recaptcha.module
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
<?php
/**
* @file
* Contains hook implementations.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\invisible_recaptcha\InvisibleRecaptcha;
/**
* Implements hook_form().
*/
function invisible_recaptcha_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$state = \Drupal::service('state');
// Only attach recaptcha if it is enabled on the site.
if (!empty($state->get('invisible_recaptcha.enabled'))) {
$site_key = $state->get('invisible_recaptcha.site_key');
// Gets the form ids form the invisible recaptcha configurations.
$config = \Drupal::service('config.factory')
->getEditable('invisible_recaptcha.recaptcha_points');
$forms_ids = $config->get('forms_ids');
// Modifies the current form if it is in the configurations.
if (in_array($form_id, $forms_ids)) {
$form['#attached']['library'][] = 'invisible_recaptcha/invisible_recaptcha';
$form['#validate'][] = '_contact_form_validation';
// Adds a div for invisible recaptcha client side integration.
$form['recaptcha-container'] = [
'#type' => 'container',
'#markup' => '',
'#attributes' => [
'class' => "g-recaptcha",
'data-sitekey' => $site_key,
'data-callback' => "recaptcha_callback",
'data-size' => "invisible",
],
];
}
}
}
/**
* Validates the recaptcha key.
*
* @param array $form
* The structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
function _contact_form_validation(array &$form, FormStateInterface $form_state) {
$state = \Drupal::service('state');
$invisible_recaptcha = new InvisibleRecaptcha();
$secret_key = $state->get('invisible_recaptcha.secret_key');
if (!empty($secret_key)) {
$recaptcha_validation = $invisible_recaptcha->validateInvisibleRecaptchaCode($secret_key);
}
// Sets an error if the recaptcha validation fails.
if (empty($recaptcha_validation) || !$recaptcha_validation) {
$form_state->setErrorByName("recaptcha", "Captcha validation failed.");
}
}