| Server IP : 141.193.213.10 / Your IP : 216.73.216.101 Web Server : nginx System : Linux pod-400555 6.8.0-1055-gke #61-Ubuntu SMP Tue May 26 22:57:42 UTC 2026 x86_64 User : fpm200079 ( 200079) PHP Version : 8.2.36 Disable Function : apache_child_terminate,apache_get_modules,apache_get_version,apache_getenv,apache_note,apache_setenv,disk_free_space,disk_total_space,diskfreespace,dl,exec,fastcgi_finish_request,link,opcache_compile_file,opcache_get_configuration,opcache_invalidate,opcache_is_script_cached,opcache_reset,passthru,pclose,pcntl_exec,popen,posix_getpid,posix_getppid,posix_getpwuid,posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setuid,posix_uname,proc_close,proc_get_status,proc_nice,proc_open,proc_terminate,realpath_cache_get,shell_exec,show_source,symlink,system MySQL : OFF | cURL : ON | WGET : OFF | Perl : ON | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /nas/content/live/bartislaw/wp-content/plugins/speak-api/inc/ |
Upload File : |
<?php
/**
* Anti-Spam Validation Class
* Comprehensive spam prevention for SpeakEasy API Plugin
*
* Features:
* - reCAPTCHA v3 validation
* - Honeypot field detection
* - Time-based form validation
* - Origin/header validation
* - Easy integration across multiple sites
*
* @version 1.0
* @author SpeakEasy Marketing
*/
class AntiSpamValidator {
// Include configuration
private $config;
/**
* Get configuration value
*/
private function get_config($key, $default = null) {
if (function_exists('get_anti_spam_config')) {
return get_anti_spam_config($key, $default);
}
// Fallback constants - NO HARDCODED KEYS
$fallbacks = [
'recaptcha_v3_secret' => '',
'recaptcha_v3_site_key' => '',
'recaptcha_v3_threshold' => 0.5,
'min_form_time' => 2,
'honeypot_field_name' => 'website_verification'
];
return $fallbacks[$key] ?? $default;
}
/**
* Get form-specific configuration
*/
private function get_form_specific_config($form_type) {
if (function_exists('get_anti_spam_form_config')) {
return get_anti_spam_form_config($form_type);
}
// Fallback form configurations
$fallback_configs = [
'cform' => [
'min_time' => 2,
'recaptcha_threshold' => 0.5,
'require_origin' => true
],
'book' => [
'min_time' => 1,
'recaptcha_threshold' => 0.4,
'require_origin' => true
],
'newsletter' => [
'min_time' => 1,
'recaptcha_threshold' => 0.3,
'require_origin' => false
]
];
return $fallback_configs[$form_type] ?? $fallback_configs['cform'];
}
private $errors = [];
private $form_start_time;
private $allowed_origins = [];
public function __construct() {
$this->form_start_time = time();
$this->set_allowed_origins();
// Load configuration file
$config_file = plugin_dir_path(__FILE__) . 'anti-spam-config.php';
if (file_exists($config_file)) {
include_once $config_file;
}
}
/**
* Set allowed origins for form submissions
*/
private function set_allowed_origins() {
$this->allowed_origins = [
home_url(),
get_site_url(),
'https://' . $_SERVER['HTTP_HOST'],
'http://' . $_SERVER['HTTP_HOST']
];
}
/**
* Main validation method - validates all anti-spam measures
*
* @param array $form_data Form submission data
* @param string $form_type Type of form (cform, book, newsletter)
* @return array Validation result with success/error status
*/
public function validate_form($form_data, $form_type = 'cform') {
$this->errors = [];
// 1. Validate origin/headers
if (!$this->validate_origin()) {
$this->log_spam_attempt('Invalid origin', $form_data);
return $this->create_error_response('Invalid request origin');
}
// 2. Validate honeypot field
if (!$this->validate_honeypot($form_data)) {
$this->log_spam_attempt('Honeypot triggered', $form_data);
return $this->create_error_response('Invalid form submission');
}
// 3. Validate form timing
if (!$this->validate_timing($form_data, $form_type)) {
$this->log_spam_attempt('Form submitted too quickly', $form_data);
return $this->create_error_response('Form submitted too quickly');
}
// 4. Validate reCAPTCHA
$recaptcha_result = $this->validate_recaptcha($form_data, $form_type);
if (!$recaptcha_result['success']) {
$this->log_spam_attempt('reCAPTCHA failed: ' . $recaptcha_result['reason'], $form_data);
return $this->create_error_response($recaptcha_result['message']);
}
// All validations passed
return $this->create_success_response();
}
/**
* Validate request origin
*/
private function validate_origin() {
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';
// Check origin
if (!empty($origin) && !in_array($origin, $this->allowed_origins)) {
return false;
}
// Check referer
if (!empty($referer)) {
$parsed_referer = parse_url($referer);
$referer_host = $parsed_referer['host'] ?? '';
$current_host = $_SERVER['HTTP_HOST'] ?? '';
if ($referer_host !== $current_host) {
return false;
}
}
return true;
}
/**
* Validate honeypot field
*/
private function validate_honeypot($form_data) {
$honeypot_field_name = $this->get_config('honeypot_field_name', 'website_verification');
$honeypot_value = $form_data[$honeypot_field_name] ?? '';
return empty($honeypot_value);
}
/**
* Validate form timing
*/
private function validate_timing($form_data, $form_type = 'cform') {
$form_time = $form_data['form_time'] ?? 0;
$current_time = time();
// Get form-specific timing or fall back to global timing
$form_config = $this->get_form_specific_config($form_type);
$min_time = $form_config['min_time'] ?? $this->get_config('min_form_time', 2);
// Check if form was submitted too quickly
if (($current_time - $form_time) < $min_time) {
return false;
}
return true;
}
/**
* Validate reCAPTCHA v3 only
*/
private function validate_recaptcha($form_data, $form_type) {
// Use reCAPTCHA v3 only
if (!empty($form_data['g-recaptcha-response-v3'])) {
$v3_result = $this->verify_recaptcha_v3($form_data['g-recaptcha-response-v3']);
if ($v3_result['success']) {
// Get form-specific threshold or fall back to global threshold
$form_config = $this->get_form_specific_config($form_type);
$threshold = $form_config['recaptcha_threshold'] ?? $this->get_config('recaptcha_v3_threshold', 0.5);
if ($v3_result['score'] >= $threshold) {
return ['success' => true, 'method' => 'v3'];
} else {
return [
'success' => false,
'reason' => 'v3_score_low',
'message' => 'Security verification failed. Please try again.'
];
}
} else {
return [
'success' => false,
'reason' => 'v3_verification_failed',
'message' => 'Security verification failed. Please try again.'
];
}
}
// No reCAPTCHA response
return [
'success' => false,
'reason' => 'no_recaptcha',
'message' => 'Please complete the security verification'
];
}
/**
* Verify reCAPTCHA v3
*/
private function verify_recaptcha_v3($response) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$secret = $this->get_config('recaptcha_v3_secret');
$data = [
'secret' => $secret,
'response' => $response,
'remoteip' => $this->get_client_ip()
];
$result = $this->make_recaptcha_request($url, $data);
if ($result && isset($result['success']) && $result['success']) {
return [
'success' => true,
'score' => $result['score'] ?? 0
];
}
return ['success' => false];
}
/**
* Make reCAPTCHA verification request
*/
private function make_recaptcha_request($url, $data) {
// Use WordPress HTTP API instead of file_get_contents
$response = wp_remote_post($url, [
'body' => $data,
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded'
]
]);
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false;
}
return $result;
}
/**
* Get client IP address
*/
private function get_client_ip() {
$ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
foreach ($ip_keys as $key) {
if (!empty($_SERVER[$key])) {
$ip = $_SERVER[$key];
if (strpos($ip, ',') !== false) {
$ip = trim(explode(',', $ip)[0]);
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}
/**
* Log spam attempts
*/
private function log_spam_attempt($reason, $form_data) {
$log_data = [
'timestamp' => current_time('mysql'),
'reason' => $reason,
'ip' => $this->get_client_ip(),
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'form_data' => $this->sanitize_form_data($form_data)
];
// Log to WordPress error log
// Optionally log to database
$this->log_to_database($log_data);
}
/**
* Sanitize form data for logging
*/
private function sanitize_form_data($form_data) {
$sensitive_fields = ['password', 'credit_card', 'ssn', 'g-recaptcha-response-v3'];
$sanitized = $form_data;
foreach ($sensitive_fields as $field) {
if (isset($sanitized[$field])) {
$sanitized[$field] = '[REDACTED]';
}
}
return $sanitized;
}
/**
* Log to database (optional)
*/
private function log_to_database($log_data) {
global $wpdb;
$table_name = $wpdb->prefix . 'speak_api_spam_log';
// Create table if it doesn't exist
$this->create_spam_log_table();
$wpdb->insert(
$table_name,
[
'log_data' => json_encode($log_data),
'created_at' => current_time('mysql')
],
['%s', '%s']
);
}
/**
* Create spam log table
*/
private function create_spam_log_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'speak_api_spam_log';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
log_data longtext NOT NULL,
created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (id),
KEY created_at (created_at)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
/**
* Create error response
*/
private function create_error_response($message) {
return [
'result' => 'error',
'msg' => [$message],
'spam_blocked' => true
];
}
/**
* Create success response
*/
private function create_success_response() {
return [
'result' => 'success',
'msg' => ['Form validated successfully'],
'spam_blocked' => false
];
}
/**
* Generate honeypot field HTML
*/
public function get_honeypot_field() {
$field_name = $this->get_config('honeypot_field_name', 'website_verification');
return sprintf(
'<input type="text" name="%s" value="" style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0;" tabindex="-1" autocomplete="off" aria-hidden="true">',
$field_name
);
}
/**
* Generate reCAPTCHA v3 script
*/
public function get_recaptcha_v3_script() {
$site_key = $this->get_config('recaptcha_v3_site_key');
return sprintf(
'<script src="https://www.google.com/recaptcha/api.js?render=%s"></script>',
$site_key
);
}
/**
* Get form time field
*/
public static function get_form_time_field() {
return sprintf(
'<input type="hidden" name="form_time" value="%d">',
time()
);
}
}