View source
<?php
require_once dirname(__FILE__) . '/src/HCaptcha/HCaptcha.php';
require_once dirname(__FILE__) . '/src/HCaptcha/RequestMethod.php';
require_once dirname(__FILE__) . '/src/HCaptcha/Drupal7Post.php';
use HCaptcha\HCaptcha;
use HCaptcha\Drupal7Post;
function hcaptcha_menu() {
$items['admin/config/people/captcha/hcaptcha'] = array(
'title' => 'hCaptcha',
'description' => 'Administer the hCaptcha web service.',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'hcaptcha_admin_settings',
),
'access arguments' => array(
'administer hcaptcha',
),
'type' => MENU_LOCAL_TASK,
'file' => 'hcaptcha.admin.inc',
'weight' => 1,
);
return $items;
}
function hcaptcha_permission() {
return array(
'administer hcaptcha' => array(
'title' => t('Administer hCaptcha'),
'description' => t('Administer hCaptcha settings'),
),
);
}
function hcaptcha_captcha($op, $captcha_type = '') {
global $language;
switch ($op) {
case 'list':
return array(
'hCaptcha',
);
case 'generate':
$captcha = array();
if ($captcha_type == 'hCaptcha') {
$hcaptcha_site_key = variable_get('hcaptcha_site_key', '');
$hcaptcha_secret_key = variable_get('hcaptcha_secret_key', '');
if (!empty($hcaptcha_site_key) && !empty($hcaptcha_secret_key)) {
$attributes = array(
'class' => 'h-captcha',
'data-sitekey' => $hcaptcha_site_key,
'data-theme' => variable_get('hcaptcha_theme', ''),
'data-size' => variable_get('hcaptcha_size', ''),
'data-tabindex' => variable_get('hcaptcha_tabindex', 0),
);
$hcaptcha = new HCaptcha($hcaptcha_site_key, $hcaptcha_secret_key, $attributes);
$captcha = $hcaptcha
->getWidget('hcaptcha_captcha_validation');
$hcaptcha_src = variable_get('hcaptcha_src', 'https://hcaptcha.com/1/api.js');
$data = array(
'#tag' => 'script',
'#value' => '',
'#attributes' => array(
'src' => url($hcaptcha_src, array(
'query' => array(
'hl' => $language->language,
),
'absolute' => TRUE,
)),
'async' => 'async',
'defer' => 'defer',
),
);
drupal_add_html_head($data, 'hcaptcha_api');
}
else {
$captcha = captcha_captcha('generate', 'Math');
}
}
return $captcha;
}
}
function hcaptcha_captcha_validation($solution, $response, $element, $form_state) {
$hcaptcha_site_key = variable_get('hcaptcha_site_key', '');
$hcaptcha_secret_key = variable_get('hcaptcha_secret_key', '');
if (!isset($_POST['h-captcha-response']) || empty($_POST['h-captcha-response']) || empty($hcaptcha_secret_key)) {
return false;
}
$captcha = new HCaptcha($hcaptcha_site_key, $hcaptcha_secret_key, array(), new Drupal7Post());
$captcha
->validate($_POST['h-captcha-response'], ip_address());
if ($captcha
->isSuccess()) {
return true;
}
else {
foreach ($captcha
->getErrors() as $error) {
watchdog('hCaptcha', '@error', array(
'@error' => $error,
), WATCHDOG_ERROR);
}
}
return false;
}