74 lines
2.3 KiB
PHP
74 lines
2.3 KiB
PHP
<?php
|
|
/**
|
|
* @package ogre-captcha
|
|
* @author cleverogre
|
|
* @copyright 2026 CleverOgre
|
|
* @license GLP-3.0-or-later
|
|
* @version 1.0.0
|
|
* @since 1.0.0
|
|
*/
|
|
|
|
namespace Ogre\Captcha;
|
|
|
|
use Ogre\Captcha as Plugin;
|
|
use Ogre\Captcha\Settings;
|
|
use WP_Error;
|
|
|
|
defined('ABSPATH') || exit;
|
|
|
|
final class API {
|
|
|
|
public const ERROR_EMPTY_TOKEN = 'empty_captcha_token';
|
|
public const ERROR_INVALID_CAPTCHA = 'invalid_captcha_result';
|
|
|
|
private static function transaction(string $url, array $data):array|string|bool {
|
|
$ch = curl_init($url);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, wp_json_encode($data));
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'content-type: application/json',
|
|
'accept: application/json',
|
|
]);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
|
|
$result = curl_exec($ch);
|
|
if ($result === false || !is_string($result) || empty($result)) return 'Invalid response';
|
|
|
|
$result = json_decode($result, true);
|
|
if (!is_array($result) || is_null($result)) return 'Invalid formatting';
|
|
|
|
if (isset($result['error']) && !empty($result['error'])) return $result['error'];
|
|
if (isset($result['success']) && is_bool($result['success'])) return $result['success'];
|
|
return $result;
|
|
}
|
|
|
|
private static function get_siteverify_url():string {
|
|
if (!Settings::is_connected()) return '';
|
|
return Settings::get_instance_url(Settings::get_site_key() . '/siteverify');
|
|
}
|
|
|
|
public static function verify(string $token):bool {
|
|
if (empty($token) || !Settings::is_connected()) return false;
|
|
|
|
$result = self::transaction(self::get_siteverify_url(), [
|
|
'secret' => Settings::get_secret_key(),
|
|
'response' => $token,
|
|
]);
|
|
|
|
return is_bool($result) ? $result : false;
|
|
}
|
|
|
|
public static function process(string $token, WP_Error|null $errors = null): WP_Error {
|
|
if (is_null($errors)) $errors = new WP_Error();
|
|
if (!Settings::is_connected()) return $errors;
|
|
|
|
if (empty($token)) {
|
|
$errors->add(self::ERROR_EMPTY_TOKEN, Plugin::__('Please complete CAPTCHA verification.'));
|
|
} else if (!API::verify($token)) {
|
|
$errors->add(self::ERROR_INVALID_CAPTCHA, Plugin::__('Your answer was incorrect - please try again.'));
|
|
}
|
|
|
|
return $errors;
|
|
}
|
|
|
|
}
|