| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSupport\App\Hooks\Handlers; |
| 4 |
use FluentSupport\App\Models\Meta; |
| 5 |
use FluentSupport\App\Services\Helper; |
| 6 |
|
| 7 |
|
| 8 |
class ReCaptchaHandler |
| 9 |
{ |
| 10 |
|
| 11 |
public static function getSettings() |
| 12 |
{ |
| 13 |
$reCaptchaSettingsData = Meta::where('object_type', '_fs_recaptcha_settings')->first(); |
| 14 |
|
| 15 |
return $reCaptchaSettingsData ? Helper::safeUnserialize($reCaptchaSettingsData->value, []) : []; |
| 16 |
} |
| 17 |
|
| 18 |
public static function isRecaptchaApplicable($formName, $settings = null) |
| 19 |
{ |
| 20 |
// $settings can be pre-fetched via getSettings() to avoid a duplicate query |
| 21 |
$settings = $settings ?? static::getSettings(); |
| 22 |
|
| 23 |
if (empty($settings['is_enabled']) || !filter_var($settings['is_enabled'], FILTER_VALIDATE_BOOLEAN)) { |
| 24 |
return false; |
| 25 |
} |
| 26 |
|
| 27 |
$formContainingReCaptcha = $settings['formContainingReCaptcha'] ?? []; |
| 28 |
|
| 29 |
return ($formContainingReCaptcha[$formName] ?? 'no') === 'yes'; |
| 30 |
} |
| 31 |
|
| 32 |
public static function validateRecaptcha($token, $secret = null, $recaptchaVersion = null, $expectedAction = null) |
| 33 |
{ |
| 34 |
|
| 35 |
$verifyUrl = 'https://www.google.com/recaptcha/api/siteverify'; |
| 36 |
|
| 37 |
if(!$secret){ |
| 38 |
$settings = static::getSettings(); |
| 39 |
if (!$settings) { |
| 40 |
return false; |
| 41 |
} |
| 42 |
$recaptchaVersion = $settings["reCaptcha_version"] ?? null; |
| 43 |
$secret = $settings['secretKey'] ?? ''; |
| 44 |
} |
| 45 |
|
| 46 |
$response = wp_remote_post($verifyUrl, [ |
| 47 |
'body' => [ |
| 48 |
'secret' => $secret, |
| 49 |
'response' => $token |
| 50 |
], |
| 51 |
]); |
| 52 |
|
| 53 |
if (is_wp_error($response)) { |
| 54 |
return false; |
| 55 |
} |
| 56 |
|
| 57 |
$result = json_decode(wp_remote_retrieve_body($response), true); |
| 58 |
|
| 59 |
if (empty($result['success'])) { |
| 60 |
return false; |
| 61 |
} |
| 62 |
|
| 63 |
if (!empty($result['hostname'])) { |
| 64 |
$expectedHost = wp_parse_url(site_url(), PHP_URL_HOST); |
| 65 |
if ($expectedHost && $result['hostname'] !== $expectedHost) { |
| 66 |
return false; |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
if ('recaptcha_v3' === $recaptchaVersion) { |
| 71 |
if ($expectedAction) { |
| 72 |
$acceptedActions = [$expectedAction, 'submit']; |
| 73 |
|
| 74 |
if (!in_array($result['action'] ?? '', $acceptedActions, true)) { |
| 75 |
return false; |
| 76 |
} |
| 77 |
} |
| 78 |
$score = $result['score'] ?? 0; |
| 79 |
$checkScore = apply_filters('fluent_support/recaptcha_v3_ref_score', 0.5); |
| 80 |
|
| 81 |
return $score >= $checkScore; |
| 82 |
} |
| 83 |
|
| 84 |
return true; |
| 85 |
} |
| 86 |
} |
| 87 |
|