CaptchaValidator.php
1 month ago
RecaptchaValidator.php
2 months ago
TurnstileValidator.php
2 months ago
ValidationError.php
2 months ago
index.php
1 year ago
CaptchaValidator.php
186 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Captcha\Validator; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Captcha\CaptchaPhrase; |
| 9 | use MailPoet\Captcha\CaptchaSession; |
| 10 | use MailPoet\Captcha\CaptchaUrlFactory; |
| 11 | use MailPoet\Subscribers\SubscriberIPsRepository; |
| 12 | use MailPoet\Subscribers\SubscribersRepository; |
| 13 | use MailPoet\Util\Helpers; |
| 14 | use MailPoet\WP\Functions as WPFunctions; |
| 15 | |
| 16 | class CaptchaValidator { |
| 17 | /** @var CaptchaUrlFactory */ |
| 18 | private $captchaUrlFactory; |
| 19 | |
| 20 | /** @var CaptchaPhrase */ |
| 21 | private $captchaPhrase; |
| 22 | |
| 23 | /** @var WPFunctions */ |
| 24 | private $wp; |
| 25 | |
| 26 | /** @var SubscriberIPsRepository */ |
| 27 | private $subscriberIPsRepository; |
| 28 | |
| 29 | /** @var SubscribersRepository */ |
| 30 | private $subscribersRepository; |
| 31 | |
| 32 | /** @var CaptchaSession */ |
| 33 | private $captchaSession; |
| 34 | |
| 35 | public function __construct( |
| 36 | CaptchaUrlFactory $urlFactory, |
| 37 | CaptchaPhrase $captchaPhrase, |
| 38 | WPFunctions $wp, |
| 39 | SubscriberIPsRepository $subscriberIPsRepository, |
| 40 | SubscribersRepository $subscribersRepository, |
| 41 | CaptchaSession $captchaSession |
| 42 | ) { |
| 43 | $this->captchaUrlFactory = $urlFactory; |
| 44 | $this->captchaPhrase = $captchaPhrase; |
| 45 | $this->wp = $wp; |
| 46 | $this->subscriberIPsRepository = $subscriberIPsRepository; |
| 47 | $this->subscribersRepository = $subscribersRepository; |
| 48 | $this->captchaSession = $captchaSession; |
| 49 | } |
| 50 | |
| 51 | public function validate(array $data): bool { |
| 52 | $isBuiltinCaptchaRequired = $this->isRequired(isset($data['email']) ? $data['email'] : null); |
| 53 | if (!$isBuiltinCaptchaRequired) { |
| 54 | return true; |
| 55 | } |
| 56 | return $this->validateChallenge($data); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Validates the user's CAPTCHA answer without consulting isRequired(). |
| 61 | * Use this when the caller has already decided a challenge is needed |
| 62 | * (e.g. the behavioral-signal escalation path). |
| 63 | */ |
| 64 | public function validateChallenge(array $data): bool { |
| 65 | // session ID must be set at this point |
| 66 | $sessionId = $data['captcha_session_id'] ?? null; |
| 67 | if (!$sessionId) { |
| 68 | throw new ValidationError(__('CAPTCHA verification failed.', 'mailpoet')); |
| 69 | } |
| 70 | |
| 71 | if (empty($data['captcha'])) { |
| 72 | $this->captchaPhrase->createPhrase($sessionId); |
| 73 | throw new ValidationError( |
| 74 | __('Please fill in the CAPTCHA.', 'mailpoet'), |
| 75 | $this->getInlineCaptchaData($sessionId) |
| 76 | ); |
| 77 | } |
| 78 | |
| 79 | $captchaHash = $this->captchaPhrase->getPhrase($sessionId); |
| 80 | if (empty($captchaHash)) { |
| 81 | $this->captchaPhrase->createPhrase($sessionId); |
| 82 | throw new ValidationError( |
| 83 | __('Please regenerate the CAPTCHA.', 'mailpoet'), |
| 84 | $this->getInlineCaptchaData($sessionId) |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | if (!hash_equals(strtolower($data['captcha']), strtolower($captchaHash))) { |
| 89 | $this->captchaPhrase->createPhrase($sessionId); |
| 90 | throw new ValidationError( |
| 91 | __('The characters entered do not match with the previous CAPTCHA.', 'mailpoet'), |
| 92 | [ |
| 93 | 'refresh_captcha' => true, |
| 94 | // Keep redirect_url for non-JavaScript form submissions |
| 95 | 'redirect_url' => $this->captchaUrlFactory->getCaptchaUrlForMPForm($sessionId), |
| 96 | ] |
| 97 | ); |
| 98 | } |
| 99 | |
| 100 | return true; |
| 101 | } |
| 102 | |
| 103 | /** |
| 104 | * Creates a fresh inline CAPTCHA challenge: generates a session, primes a |
| 105 | * phrase, and returns the meta the client uses to render it inline. |
| 106 | * Optionally stashes form data so the non-JS captcha-page fallback can |
| 107 | * restore the original submission on resubmit. |
| 108 | * |
| 109 | * @param array<string, mixed>|null $formData Form data to stash, or null to skip stashing. |
| 110 | */ |
| 111 | public function getInlineCaptchaChallenge(?array $formData = null): array { |
| 112 | $sessionId = $this->captchaSession->generateSessionId(); |
| 113 | $this->captchaPhrase->createPhrase($sessionId); |
| 114 | if ($formData !== null) { |
| 115 | $this->captchaSession->setFormData($sessionId, $formData); |
| 116 | } |
| 117 | return $this->getInlineCaptchaData($sessionId); |
| 118 | } |
| 119 | |
| 120 | public function isRequired($subscriberEmail = null) { |
| 121 | if ($this->isUserExemptFromCaptcha()) { |
| 122 | return false; |
| 123 | } |
| 124 | |
| 125 | $subscriptionCaptchaRecipientLimit = $this->wp->applyFilters('mailpoet_subscription_captcha_recipient_limit', 0); |
| 126 | if ($subscriptionCaptchaRecipientLimit === 0) { |
| 127 | return true; |
| 128 | } |
| 129 | |
| 130 | // Check limits per recipient if enabled |
| 131 | if ($subscriberEmail) { |
| 132 | $subscriber = $this->subscribersRepository->findOneBy(['email' => $subscriberEmail]); |
| 133 | if ( |
| 134 | $subscriber && $subscriber->getConfirmationsCount() >= $subscriptionCaptchaRecipientLimit |
| 135 | ) { |
| 136 | return true; |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // Check limits per IP address |
| 141 | /** @var int|string $subscriptionCaptchaWindow */ |
| 142 | $subscriptionCaptchaWindow = $this->wp->applyFilters('mailpoet_subscription_captcha_window', MONTH_IN_SECONDS); |
| 143 | |
| 144 | $subscriberIp = Helpers::getIP(); |
| 145 | if (empty($subscriberIp)) { |
| 146 | return false; |
| 147 | } |
| 148 | |
| 149 | $subscriptionCount = $this->subscriberIPsRepository->getCountByIPAndCreatedAtAfterTimeInSeconds( |
| 150 | $subscriberIp, |
| 151 | (int)$subscriptionCaptchaWindow |
| 152 | ); |
| 153 | |
| 154 | if ($subscriptionCount > 0) { |
| 155 | return true; |
| 156 | } |
| 157 | |
| 158 | return false; |
| 159 | } |
| 160 | |
| 161 | public function isUserExemptFromCaptcha(): bool { |
| 162 | if (!$this->wp->isUserLoggedIn()) { |
| 163 | return false; |
| 164 | } |
| 165 | $user = $this->wp->wpGetCurrentUser(); |
| 166 | $roles = $this->wp->applyFilters('mailpoet_subscription_captcha_exclude_roles', ['administrator', 'editor']); |
| 167 | $stringRoles = is_array($roles) ? array_values(array_filter($roles, 'is_string')) : []; |
| 168 | return !empty(array_intersect($stringRoles, $user->roles)); |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Returns data needed to display the captcha inline within the form. |
| 173 | * Includes redirect_url as a fallback for non-JavaScript submissions. |
| 174 | */ |
| 175 | private function getInlineCaptchaData(string $sessionId): array { |
| 176 | return [ |
| 177 | 'show_captcha' => true, |
| 178 | 'captcha_session_id' => $sessionId, |
| 179 | 'captcha_image_url' => $this->captchaUrlFactory->getCaptchaImageUrl($sessionId), |
| 180 | 'captcha_audio_url' => $this->captchaUrlFactory->getCaptchaAudioUrl($sessionId), |
| 181 | // Keep redirect_url for non-JavaScript form submissions |
| 182 | 'redirect_url' => $this->captchaUrlFactory->getCaptchaUrlForMPForm($sessionId), |
| 183 | ]; |
| 184 | } |
| 185 | } |
| 186 |