Validator
1 month ago
BehavioralSignals.php
1 month ago
CaptchaConstants.php
2 months ago
CaptchaFormRenderer.php
2 weeks ago
CaptchaHooks.php
2 months ago
CaptchaPhrase.php
1 year ago
CaptchaRenderer.php
4 months ago
CaptchaSession.php
1 year ago
CaptchaUrlFactory.php
4 months ago
PageRenderer.php
5 months ago
ReCaptchaHooks.php
2 months ago
ReCaptchaRenderer.php
1 year ago
ReCaptchaValidator.php
1 year ago
TurnstileHooks.php
2 months ago
TurnstileRenderer.php
2 months ago
TurnstileValidator.php
2 months ago
index.php
1 year ago
TurnstileValidator.php
65 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Captcha; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Settings\SettingsController; |
| 9 | use MailPoet\Util\Helpers; |
| 10 | use MailPoet\WP\Functions as WPFunctions; |
| 11 | |
| 12 | class TurnstileValidator { |
| 13 | |
| 14 | private const ENDPOINT = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; |
| 15 | |
| 16 | /** @var WPFunctions */ |
| 17 | private $wp; |
| 18 | |
| 19 | /** @var SettingsController */ |
| 20 | private $settings; |
| 21 | |
| 22 | public function __construct( |
| 23 | WPFunctions $wp, |
| 24 | SettingsController $settings |
| 25 | ) { |
| 26 | $this->wp = $wp; |
| 27 | $this->settings = $settings; |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * @throws \Exception response token is missing or invalid. |
| 32 | */ |
| 33 | public function validate(string $responseToken) { |
| 34 | if (empty($responseToken)) { |
| 35 | throw new \Exception(__('Please check the CAPTCHA.', 'mailpoet')); |
| 36 | } |
| 37 | |
| 38 | $captchaSettings = $this->settings->get('captcha'); |
| 39 | $body = [ |
| 40 | 'secret' => $captchaSettings['turnstile_secret_token'] ?? '', |
| 41 | 'response' => $responseToken, |
| 42 | ]; |
| 43 | $remoteIp = Helpers::getIP(); |
| 44 | if (is_string($remoteIp) && $remoteIp !== '') { |
| 45 | $body['remoteip'] = $remoteIp; |
| 46 | } |
| 47 | $response = $this->wp->wpRemotePost(self::ENDPOINT, [ |
| 48 | 'body' => $body, |
| 49 | 'timeout' => 5, |
| 50 | ]); |
| 51 | |
| 52 | if ($this->wp->isWpError($response)) { |
| 53 | throw new \Exception(__('Error while validating the CAPTCHA.', 'mailpoet')); |
| 54 | } |
| 55 | |
| 56 | /** @var \stdClass $response */ |
| 57 | $response = json_decode($this->wp->wpRemoteRetrieveBody($response)); |
| 58 | if ($response === null) { |
| 59 | throw new \Exception(__('Error while validating the CAPTCHA.', 'mailpoet')); |
| 60 | } else if (empty($response->success)) { |
| 61 | throw new \Exception(__('Invalid CAPTCHA. Try again.', 'mailpoet')); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 |