*/ private array $scriptData = []; public static function instance(): self { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } private function __construct() { } public function boot(): void { add_action('admin_init', [Settings::class, 'register']); add_action('admin_menu', [$this, 'registerSettingsPage']); add_filter( 'plugin_action_links_' . plugin_basename(GATEFORM_PLUGIN_FILE), [$this, 'pluginActionLinks'] ); add_filter('script_loader_tag', [$this, 'filterScriptTag'], 10, 2); // Виджеты используют только публичные ключи и работают без secret_key. Widgets::instance()->boot(); if (!Settings::isConfigured()) { return; } $settings = Settings::get(); if (!empty($settings['protect_comments']) || !empty($settings['protect_cf7']) || !empty($settings['protect_wpforms']) || !empty($settings['protect_gravity']) || !empty($settings['protect_ninja']) || !empty($settings['protect_elementor']) || !empty($settings['protect_formidable']) || !empty($settings['protect_fluent']) || !empty($settings['protect_woocommerce']) || Settings::customSelectors() !== [] ) { add_action('wp_enqueue_scripts', [$this, 'enqueueFrontendScript']); } if (!empty($settings['protect_login']) || !empty($settings['protect_registration'])) { add_action('login_enqueue_scripts', [$this, 'enqueueLoginScript']); } if (!empty($settings['protect_comments'])) { add_action('pre_comment_on_post', [$this, 'validateComment']); } if (!empty($settings['protect_login'])) { add_filter('authenticate', [$this, 'validateLogin'], 5, 3); } if (!empty($settings['protect_registration'])) { add_filter('registration_errors', [$this, 'validateRegistration'], 10, 3); } if (!empty($settings['protect_cf7'])) { Cf7::instance()->boot(); } if (!empty($settings['protect_wpforms'])) { add_action('wpforms_process', [$this, 'validateWpForms'], 10, 3); } if (!empty($settings['protect_gravity'])) { add_filter('gform_validation', [$this, 'validateGravity']); } if (!empty($settings['protect_ninja'])) { add_filter('ninja_forms_submit_data', [$this, 'validateNinja']); } if (!empty($settings['protect_elementor'])) { add_action('elementor_pro/forms/validation', [$this, 'validateElementor'], 10, 2); } if (!empty($settings['protect_formidable'])) { add_filter('frm_validate_entry', [$this, 'validateFormidable'], 10, 3); } if (!empty($settings['protect_fluent'])) { add_filter('fluentform/validation_errors', [$this, 'validateFluent'], 10, 3); } if (!empty($settings['protect_woocommerce'])) { add_action('woocommerce_checkout_process', [$this, 'validateWooCheckout']); add_filter('woocommerce_login_errors', [$this, 'validateWooLogin']); add_filter('woocommerce_registration_errors', [$this, 'validateWooRegistration'], 10, 3); } } public function registerSettingsPage(): void { add_options_page( 'GateForm', 'GateForm', 'manage_options', Settings::PAGE, [Settings::class, 'renderPage'] ); } /** * @param list $links * @return list */ public function pluginActionLinks(array $links): array { $url = admin_url('options-general.php?page=' . Settings::PAGE); array_unshift($links, 'Настройки'); return $links; } /** * Подключает client.js к стандартным и популярным формам. */ public function enqueueFrontendScript(): void { if ($this->frontendScriptPrinted || is_admin() || is_feed()) { return; } $settings = Settings::get(); $selectors = []; if (!empty($settings['protect_comments']) && is_singular() && comments_open()) { $selectors[] = '#commentform'; } if (!empty($settings['protect_cf7'])) { $selectors[] = 'form.wpcf7-form'; } if (!empty($settings['protect_wpforms'])) { $selectors[] = 'form.wpforms-form'; } if (!empty($settings['protect_gravity'])) { $selectors[] = 'form[id^="gform_"]'; } if (!empty($settings['protect_ninja'])) { $selectors[] = 'form.ninja-forms-form'; } if (!empty($settings['protect_elementor'])) { $selectors[] = 'form.elementor-form'; } if (!empty($settings['protect_formidable'])) { $selectors[] = '.frm_forms form'; } if (!empty($settings['protect_fluent'])) { $selectors[] = 'form.frm-fluent-form'; } if (!empty($settings['protect_woocommerce'])) { $selectors[] = 'form.checkout'; $selectors[] = 'form.woocommerce-form-login'; $selectors[] = 'form.woocommerce-form-register'; } foreach (Settings::customSelectors() as $selector) { $selectors[] = $selector; } $selectors = array_values(array_unique(array_filter($selectors))); if ($selectors === []) { return; } $this->frontendScriptPrinted = true; $this->enqueueScript(implode(', ', $selectors), $settings); } /** * Подключает client.js к формам входа и регистрации (wp-login.php). */ public function enqueueLoginScript(): void { if ($this->loginScriptPrinted) { return; } $settings = Settings::get(); $selectors = []; if (!empty($settings['protect_login'])) { $selectors[] = '#loginform'; } if (!empty($settings['protect_registration']) && get_option('users_can_register')) { $selectors[] = '#registerform'; } if ($selectors === []) { return; } $this->loginScriptPrinted = true; $this->enqueueScript(implode(', ', $selectors), $settings); } /** * Проверка токена при отправке комментария. */ public function validateComment(): void { $result = $this->validateRequest('comment'); if ($result['valid']) { return; } $this->reject($this->failureMessage($result)); } /** * Проверка токена при входе (wp-login.php). * * @param mixed $user * @param mixed $username * @param mixed $password * @return mixed */ public function validateLogin($user, $username, $password) { if (is_wp_error($user)) { return $user; } if (!$this->isLoginRequest()) { return $user; } $result = $this->validateRequest('login'); if ($result['valid']) { return $user; } return new \WP_Error('gateform_failed', $this->failureMessage($result)); } /** * Проверка токена при регистрации. * * @param mixed $errors * @param mixed $sanitizedUserLogin * @param mixed $userEmail * @return mixed */ public function validateRegistration($errors, $sanitizedUserLogin = '', $userEmail = '') { if (!$errors instanceof \WP_Error) { $errors = new \WP_Error(); } $result = $this->validateRequest('registration'); if (!$result['valid']) { $errors->add('gateform_failed', $this->failureMessage($result)); } return $errors; } /** * WPForms. * * @param array $fields * @param array $entry * @param array $formData */ public function validateWpForms($fields, $entry, $formData): void { $result = $this->validateRequest('wpforms'); if ($result['valid']) { return; } if (function_exists('wpforms') && isset(wpforms()->process) && isset($formData['id']) ) { wpforms()->process->errors[$formData['id']]['header'] = $this->failureMessage($result); } } /** * Gravity Forms. * * @param array $validationResult * @return array */ public function validateGravity($validationResult) { $result = $this->validateRequest('gravity'); if ($result['valid']) { return $validationResult; } $validationResult['is_valid'] = false; if (!empty($validationResult['form']['fields'][0])) { $validationResult['form']['fields'][0]['failed_validation'] = true; $validationResult['form']['fields'][0]['validation_message'] = $this->failureMessage($result); } return $validationResult; } /** * Ninja Forms. * * @param array $formData * @return array */ public function validateNinja($formData) { $result = $this->validateRequest('ninja'); if ($result['valid']) { return $formData; } if (!isset($formData['errors']) || !is_array($formData['errors'])) { $formData['errors'] = []; } $formData['errors']['gateform'] = $this->failureMessage($result); return $formData; } /** * Elementor Pro Forms. * * @param mixed $record * @param mixed $ajaxHandler */ public function validateElementor($record, $ajaxHandler): void { $result = $this->validateRequest('elementor'); if ($result['valid']) { return; } if (is_object($ajaxHandler) && method_exists($ajaxHandler, 'add_error_message')) { $ajaxHandler->add_error_message($this->failureMessage($result)); } } /** * Formidable Forms. * * @param mixed $errors * @param mixed $values * @param mixed $form * @return mixed */ public function validateFormidable($errors, $values, $form) { $result = $this->validateRequest('formidable'); if ($result['valid']) { return $errors; } if (!is_array($errors)) { $errors = []; } $errors['gateform'] = $this->failureMessage($result); return $errors; } /** * Fluent Forms. * * @param mixed $errors * @param mixed $formData * @param mixed $form * @return mixed */ public function validateFluent($errors, $formData, $form) { $result = $this->validateRequest('fluent'); if ($result['valid']) { return $errors; } if (!is_array($errors)) { $errors = []; } $errors['gateform'] = $this->failureMessage($result); return $errors; } /** * WooCommerce checkout. */ public function validateWooCheckout(): void { $result = $this->validateRequest('woocommerce_checkout'); if ($result['valid']) { return; } if (function_exists('wc_add_notice')) { wc_add_notice($this->failureMessage($result), 'error'); } } /** * WooCommerce login. * * @param mixed $errors * @return mixed */ public function validateWooLogin($errors) { $result = $this->validateRequest('woocommerce_login'); if (!$result['valid'] && $errors instanceof \WP_Error) { $errors->add('gateform_failed', $this->failureMessage($result)); } return $errors; } /** * WooCommerce registration. * * @param mixed $errors * @param mixed $username * @param mixed $email * @return mixed */ public function validateWooRegistration($errors, $username, $email) { $result = $this->validateRequest('woocommerce_registration'); if (!$result['valid'] && $errors instanceof \WP_Error) { $errors->add('gateform_failed', $this->failureMessage($result)); } return $errors; } /** * Токен из обычного POST или из объекта CF7. * * @param mixed $submission */ private function tokenFromRequest($submission = null): string { // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Token is verified by the GateForm service; the hosting form verifies its own nonce. if (isset($_POST['gf_token']) && is_string($_POST['gf_token'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Token is verified by the GateForm service. return sanitize_text_field(wp_unslash($_POST['gf_token'])); } if (is_object($submission) && method_exists($submission, 'get_posted_data')) { $value = $submission->get_posted_data('gf_token'); if (is_array($value)) { $value = reset($value); } if (is_array($value) || is_object($value)) { return ''; } return sanitize_text_field((string) $value); } return ''; } /** * @param mixed $submission * @return array{valid: bool, code: string, fail_open: bool, message: string} */ private function validateRequest(string $context, $submission = null): array { $token = $this->tokenFromRequest($submission); $result = (new Api(Settings::get()))->validate($token); /** * Позволяет добавить проверку для собственной формы. * * @param array{valid: bool, code: string, fail_open: bool, message: string} $result * @param string $context * @param string $token */ return apply_filters('gateform_validate_token', $result, $context, $token); } /** * @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 : 'Не удалось подтвердить, что вы человек. Обновите страницу и попробуйте снова.'; } /** * Добавляет data-атрибуты GateForm к тегу подключённого скрипта. */ public function filterScriptTag(string $tag, string $handle): string { if ($handle !== self::SCRIPT_HANDLE || $this->scriptData === []) { return $tag; } $attributes = ''; foreach ($this->scriptData as $name => $value) { $attributes .= ' ' . esc_attr($name) . '="' . esc_attr($value) . '"'; } return str_replace('