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
ReCaptchaValidator.php
62 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\WP\Functions as WPFunctions; |
| 10 | |
| 11 | class ReCaptchaValidator { |
| 12 | |
| 13 | private const ENDPOINT = 'https://www.google.com/recaptcha/api/siteverify'; |
| 14 | |
| 15 | /** @var WPFunctions */ |
| 16 | private $wp; |
| 17 | |
| 18 | /** @var SettingsController */ |
| 19 | private $settings; |
| 20 | |
| 21 | public function __construct( |
| 22 | WPFunctions $wp, |
| 23 | SettingsController $settings |
| 24 | ) { |
| 25 | $this->wp = $wp; |
| 26 | $this->settings = $settings; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @throws \Exception response token is missing or invalid. |
| 31 | */ |
| 32 | public function validate(string $responseToken) { |
| 33 | $captchaSettings = $this->settings->get('captcha'); |
| 34 | if (empty($responseToken)) { |
| 35 | throw new \Exception(__('Please check the CAPTCHA.', 'mailpoet')); |
| 36 | } |
| 37 | |
| 38 | $secretToken = $captchaSettings['type'] === CaptchaConstants::TYPE_RECAPTCHA |
| 39 | ? $captchaSettings['recaptcha_secret_token'] |
| 40 | : $captchaSettings['recaptcha_invisible_secret_token']; |
| 41 | |
| 42 | $response = $this->wp->wpRemotePost(self::ENDPOINT, [ |
| 43 | 'body' => [ |
| 44 | 'secret' => $secretToken, |
| 45 | 'response' => $responseToken, |
| 46 | ], |
| 47 | ]); |
| 48 | |
| 49 | if ($this->wp->isWpError($response)) { |
| 50 | throw new \Exception(__('Error while validating the CAPTCHA.', 'mailpoet')); |
| 51 | } |
| 52 | |
| 53 | /** @var \stdClass $response */ |
| 54 | $response = json_decode($this->wp->wpRemoteRetrieveBody($response)); |
| 55 | if ($response === null) { // invalid JSON |
| 56 | throw new \Exception(__('Error while validating the CAPTCHA.', 'mailpoet')); |
| 57 | } else if (empty($response->success)) { // missing or false |
| 58 | throw new \Exception(__('Invalid CAPTCHA. Try again.', 'mailpoet')); |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 |