registerTag(); } add_filter('wpcf7_validate', [$this, 'validate'], 20, 2); add_filter('wpcf7_form_elements', [$this, 'appendBranding']); } /** * Регистрирует тег [gateform] для форм Contact Form 7. */ public function registerTag(): void { if (!function_exists('wpcf7_add_form_tag')) { return; } wpcf7_add_form_tag('gateform', [$this, 'renderTag'], ['name-attr' => true]); } /** * Выводит брендинг и скрытое поле токена. * * @param mixed $tag */ public function renderTag($tag): string { if (!Settings::isConfigured()) { return ''; } return $this->fieldMarkup(true, $this->brandingEnabled()); } /** * Проверяет токен перед отправкой формы CF7. * * @param mixed $result * @param mixed $tags * @return mixed */ public function validate($result, $tags) { if (!is_object($result) || !method_exists($result, 'invalidate')) { return $result; } $validation = $this->validateToken($this->tokenFromRequest()); if ($validation['valid']) { return $result; } $tag = $this->findTag($tags); if ($tag === null) { return $result; } $result->invalidate($tag, $this->failureMessage($validation)); return $result; } /** * Добавляет брендинг и скрытое поле в форму, где нет тега [gateform]. * * @param mixed $elements * @return mixed */ public function appendBranding($elements) { if (!is_string($elements) || is_admin() || !Settings::isConfigured()) { return $elements; } if (strpos($elements, 'data-gateform-cf7') !== false) { return $elements; } return $elements . $this->fieldMarkup(true, $this->brandingEnabled()); } private function brandingEnabled(): bool { /** * Позволяет отключить подпись «Защищено GateForm» в формах CF7. * * @param bool $enabled */ return (bool) apply_filters('gateform_cf7_branding', true); } private function fieldMarkup(bool $withToken, bool $withBranding): string { $baseUrl = Settings::BASE_URL; $html = ''; if ($withBranding) { $logo = esc_url(GATEFORM_PLUGIN_URL . 'images/logo-mark.svg'); $site = esc_url($baseUrl . '/'); $html .= ''; $html .= ''; $html .= 'Защищено GateForm'; $html .= ''; } if ($withToken) { $html .= ''; } $html .= ''; return $html; } /** * @param mixed $tags * @return object|null */ private function findTag($tags) { if (!is_array($tags)) { return null; } $first = null; foreach ($tags as $tag) { if (!is_object($tag)) { continue; } if ($first === null) { $first = $tag; } $type = isset($tag->type) ? (string) $tag->type : ''; if (str_starts_with($type, 'gateform')) { return $tag; } } return $first; } private function tokenFromRequest(): string { // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Contact Form 7 validates its own nonce before this filter runs. if (!isset($_POST['gf_token']) || !is_string($_POST['gf_token'])) { return ''; } // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Contact Form 7 validates its own nonce before this filter runs. return sanitize_text_field(wp_unslash($_POST['gf_token'])); } /** * @return array{valid: bool, code: string, fail_open: bool, message: string} */ private function validateToken(string $token): array { // Токен одноразовый, а CF7 может вызывать валидацию несколько раз // в рамках одного запроса. Кешируем результат для того же токена. if ($this->lastResult !== null && $this->lastToken === $token) { return $this->lastResult; } $result = (new Api(Settings::get()))->validate($token); /** * Позволяет добавить собственную проверку для формы CF7. * * @param array{valid: bool, code: string, fail_open: bool, message: string} $result * @param string $context * @param string $token */ $result = apply_filters('gateform_validate_token', $result, 'cf7', $token); $this->lastToken = $token; $this->lastResult = $result; return $result; } /** * @param array{valid: bool, code: string, fail_open: bool, message: string} $result */ private function failureMessage(array $result): string { $message = trim((string) ($result['message'] ?? '')); return $message !== '' ? $message : 'Не удалось подтвердить, что вы человек. Обновите страницу и попробуйте снова.'; } }