expires_at ); self::render_block( $ip, $s ); } } /** Предпросмотр окон для администратора (кнопки в панели). */ private static function maybe_preview( string $ip, array $s ): void { if ( ! isset( $_GET['botward_preview'], $_GET['_wpnonce'] ) || ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) { return; } if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'botward_preview' ) ) { return; } self::send_headers( 200 ); if ( 'block' === sanitize_key( wp_unslash( $_GET['botward_preview'] ) ) ) { self::render_block( $ip, $s, true ); } self::render_gate( $ip, $s, '', true ); } /** Общие условия, при которых плагин вообще не вмешивается. */ private static function should_skip( string $ip, array $s ): bool { if ( empty( $s['enabled'] ) ) { return true; } if ( ( defined( 'WP_CLI' ) && WP_CLI ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) { return true; } if ( Botward_IP::is_whitelisted( $ip, $s ) ) { return true; } if ( is_user_logged_in() && ( ! empty( $s['bypass_logged_in'] ) || current_user_can( 'manage_options' ) ) ) { return true; } return false; } /* ------------------------------------------------------------------ */ /* Этап 2: окно проверки */ /* ------------------------------------------------------------------ */ public static function run_gate(): void { $s = Botward_Shield::apply_attack( Botward_Settings::get() ); $ip = Botward_IP::get(); if ( self::should_skip( $ip, $s ) ) { return; } if ( is_404() ) { // Сканеры дают много 404 подряд. Считаем только посетителей без допуска и только «страничные» адреса // (битые картинки и стили не в счёт), поэтому обычные посетители с cookie сюда не попадают. if ( 'smart' === $s['mode'] && ! self::has_pass( $ip, $s, 's' ) && ! preg_match( '~\.(?:jpe?g|png|gif|webp|avif|svg|ico|css|js|map|woff2?|ttf|eot|otf|mp4|webm|mp3|pdf)$~i', self::request_path() ) ) { $n = Botward_Risk::note_404( $ip ); $hard = (int) $s['auto_block_score']; if ( $hard > 0 && $n >= Botward_Risk::SCAN_404 && ! Botward_IP::is_verified_search_bot( $ip ) && ! Botward_Risk::is_trusted_preview( $ip, $s ) ) { Botward_Risk::log( $ip, array( 'score' => $hard, 'reasons' => array( 'errors' ) ) ); /* translators: %d: number of requests to non-existent pages */ self::do_block( $ip, 'scan', (int) $s['auto_block_minutes'], $s, sprintf( __( '%d requests to non-existent pages in 10 minutes', 'botward' ), $n ) ); } } return; } if ( ! self::applies( $s ) ) { return; } // Проверенные поисковые боты (по rDNS) и боты предпросмотра ссылок не мешаем. if ( ! empty( $s['allow_search_bots'] ) && Botward_IP::is_verified_search_bot( $ip ) ) { return; } if ( ! empty( $s['allow_preview_bots'] ) && Botward_Risk::is_trusted_preview( $ip, $s ) ) { return; } $mode = $s['mode']; // «Всегда» требует пройденную математику (уровень m), остальные режимы принимают и тихую проверку (уровень s). if ( self::has_pass( $ip, $s, 'always' === $mode ? 'm' : 's' ) ) { return; } // «Только вход и комментарии»: сайт открыт, вход и комментарии защищены отдельно; посетителю выдаётся тихий допуск. if ( 'forms' === $mode ) { Botward_Beacon::enqueue(); return; } // «Умный»: проверка только подозрительным. Остальные получают тихую проверку в браузере. if ( 'smart' === $mode ) { $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; $solving = 'POST' === $method && isset( $_POST['botward_token'] ); if ( ! $solving && in_array( $method, array( 'GET', 'HEAD' ), true ) ) { $r = Botward_Risk::evaluate( $ip, $s ); if ( $r['score'] < Botward_Risk::threshold( $s ) ) { Botward_Beacon::enqueue(); return; } if ( Botward_Risk::log( $ip, $r ) ) { Botward_Settings::bump( 'risky' ); // один раз на посетителя за 10 минут Botward_Risk::track( $ip ); Botward_Shield::note_suspicious( $s ); } // Очень высокий балл: автоматическая блокировка вместо бесконечных проверок. $hard = (int) $s['auto_block_score']; if ( $hard > 0 && $r['score'] >= $hard ) { $labels = Botward_Risk::labels(); $names = array(); foreach ( $r['reasons'] as $code ) { $names[] = $labels[ $code ] ?? $code; } /* translators: 1: risk score, 2: list of signals */ self::do_block( $ip, 'risk', (int) $s['auto_block_minutes'], $s, sprintf( __( 'Score %1$d: %2$s', 'botward' ), (int) $r['score'], implode( ', ', $names ) ) ); } } } self::challenge_flow( $ip, $s ); } /** Комментарии: без допуска (хотя бы тихого) отклоняются. Защищает форму там, где сайт открыт посетителям. */ public static function guard_comment(): void { $s = Botward_Settings::get(); if ( empty( $s['protect_comments'] ) ) { return; } $ip = Botward_IP::get(); if ( self::should_skip( $ip, $s ) || self::has_pass( $ip, $s, 's' ) ) { return; } wp_die( esc_html__( 'Verification required: please enable JavaScript and cookies, reload the page and submit your comment again.', 'botward' ), esc_html__( 'Verification required', 'botward' ), array( 'response' => 403, 'back_link' => true ) ); } /** * Страница входа: окно проверки показывается до формы. Без допуска пароль не проверяется вообще. * Выход (logout), пароль записи (postpass) и ссылки сброса пароля из письма (rp, resetpass, confirmaction) не затрагиваются. */ public static function run_login_gate(): void { $s = Botward_Settings::get(); if ( empty( $s['protect_login'] ) || self::login_disabled() ) { return; } $action = isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : ''; if ( ! in_array( $action, array( '', 'login', 'register', 'lostpassword', 'retrievepassword' ), true ) ) { return; } $ip = Botward_IP::get(); if ( self::should_skip( $ip, $s ) ) { return; } self::challenge_flow( $ip, $s ); } /** Общая часть: допуск, методы, обработка ответа, показ окна. Завершает запрос, если допуска нет. */ private static function challenge_flow( string $ip, array $s ): void { // Уже прошёл проверку (математика, уровень m). if ( self::has_pass( $ip, $s, 'm' ) ) { return; } $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET'; // PUT, DELETE, OPTIONS и прочие методы без допуска не обслуживаются. if ( ! in_array( $method, array( 'GET', 'HEAD', 'POST' ), true ) ) { self::send_headers( 405 ); header( 'Allow: GET, HEAD, POST' ); echo esc_html__( 'Method not allowed.', 'botward' ); exit; } if ( 'POST' === $method && isset( $_POST['botward_token'] ) ) { self::process( $ip, $s ); } self::send_headers( 200 ); self::render_gate( $ip, $s ); } /* ------------------------------------------------------------------ */ /* Лимит неудачных входов */ /* ------------------------------------------------------------------ */ private static function login_key( string $bucket ): string { return 'botward_l_' . md5( $bucket ); } /** Считаем неудачи по IP (не по логину: иначе любой мог бы заблокировать чужую учётную запись). */ public static function on_login_failed( $username = '' ): void { $s = Botward_Settings::get(); if ( empty( $s['enabled'] ) || empty( $s['protect_login'] ) || self::login_disabled() ) { return; } $ip = Botward_IP::get(); if ( Botward_IP::is_whitelisted( $ip, $s ) ) { return; } $key = self::login_key( Botward_IP::bucket( $ip ) ); $n = (int) get_transient( $key ) + 1; if ( $n >= (int) $s['login_max_failures'] ) { delete_transient( $key ); /* translators: %d: number of failed logins */ self::do_block( $ip, 'login', (int) $s['login_block_minutes'], $s, sprintf( __( '%d failed logins', 'botward' ), $n ) ); } set_transient( $key, $n, (int) $s['login_window'] * MINUTE_IN_SECONDS ); } public static function on_login_ok(): void { delete_transient( self::login_key( Botward_IP::bucket( Botward_IP::get() ) ) ); } /** Одинаковая ошибка для неверного логина и неверного пароля: перебором нельзя узнать существующие логины. */ public static function generic_login_error( $user ) { $s = Botward_Settings::get(); if ( ! is_wp_error( $user ) || empty( $s['login_generic_error'] ) ) { return $user; } if ( array_intersect( array( 'invalid_username', 'incorrect_password', 'invalid_email' ), $user->get_error_codes() ) ) { return new WP_Error( 'botward_invalid_login', __( 'Invalid username or password.', 'botward' ) ); } return $user; } public static function xmlrpc_enabled( $enabled ) { $s = Botward_Settings::get(); return empty( $s['disable_xmlrpc'] ) ? $enabled : false; } /** Нужно ли показывать проверку для текущего запроса (вызывается на template_redirect). */ private static function applies( array $s ): bool { if ( is_404() || is_robots() ) { return false; } $path = self::request_path(); foreach ( preg_split( '/\R/', (string) $s['exclude_paths'] ) as $rule ) { $rule = trim( $rule ); if ( '' !== $rule && self::match_rule( $path, $rule ) ) { return false; } } return true; } /** Путь запроса без query string, без дублей «/» и без префикса подкаталога установки. */ private static function request_path(): string { $uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/'; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- сырой путь нужен для точного сопоставления; в вывод и SQL не попадает. $uri = is_string( $uri ) ? $uri : '/'; foreach ( array( '?', '#' ) as $sep ) { $p = strpos( $uri, $sep ); if ( false !== $p ) { $uri = substr( $uri, 0, $p ); } } $path = (string) preg_replace( '#/+#', '/', rawurldecode( $uri ) ); $home = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ); if ( '' !== $home && '/' !== $home ) { if ( str_starts_with( $path, $home ) ) { $path = '/' . substr( $path, strlen( $home ) ); } elseif ( rtrim( $home, '/' ) === $path ) { $path = '/'; } } return '' === $path ? '/' : $path; } /** * Совпадение пути с правилом: * - правило с «*» — шаблон (fnmatch) по всему пути; * - правило на «/» — всё, что ниже; * - иначе — точный путь (и всё, что ниже него). * Пути с «/../» исключениями не пользуются. */ private static function match_rule( string $path, string $rule ): bool { if ( preg_match( '#/\.{1,2}(/|$)#', $path ) ) { return false; } $path = strtolower( $path ); $rule = strtolower( $rule ); if ( false !== strpos( $rule, '*' ) ) { return fnmatch( $rule, $path ); } if ( str_ends_with( $rule, '/' ) ) { return str_starts_with( $path, $rule ) || rtrim( $rule, '/' ) === $path; } return $path === $rule || str_starts_with( $path, $rule . '/' ); } /** * Обработка отправленной формы. * * Сначала проверяется, что токен выдан именно этому посетителю (подпись по сети посетителя). Чужие и подделанные * запросы молча игнорируются БЕЗ штрафа: иначе любой сторонний сайт мог бы отправкой скрытой формы заставить * браузер жертвы «нарушить» правила и получить блокировку IP жертвы. */ private static function process( string $ip, array $s ): void { // Межсайтовые POST браузер помечает сам. $site = isset( $_SERVER['HTTP_SEC_FETCH_SITE'] ) ? strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_SEC_FETCH_SITE'] ) ) ) : ''; if ( 'cross-site' === $site ) { return; } $raw = ( isset( $_POST['botward_token'] ) && is_string( $_POST['botward_token'] ) ) ? sanitize_text_field( wp_unslash( $_POST['botward_token'] ) ) : ''; $parts = explode( '.', $raw ); $bucket = Botward_IP::bucket( $ip ); if ( 4 !== count( $parts ) || ! ctype_digit( $parts[0] ) || strlen( $parts[0] ) > 12 || ! ctype_xdigit( $parts[1] ) || strlen( $parts[1] ) > 32 ) { return; } $ts = (int) $parts[0]; $nonce = $parts[1]; if ( ! hash_equals( self::sign_ctx( $ts, $nonce, $bucket ), $parts[3] ) ) { return; // токен выдан не этому посетителю } // Honeypot: даже при верной математике и просроченном примере — блокировка. Имя поля у каждого примера своё. if ( isset( $_POST[ self::hp_name( $nonce ) ] ) ) { Botward_Settings::bump( 'honeypot' ); self::do_block( $ip, 'honeypot', (int) $s['honeypot_block_minutes'], $s, __( 'Hidden field was filled in', 'botward' ) ); } $now = time(); // Пример просрочен или уже использован — новый пример без штрафа. if ( $now - $ts > (int) $s['token_ttl'] * MINUTE_IN_SECONDS || get_transient( 'botward_u_' . $nonce ) ) { self::send_headers( 200 ); self::render_gate( $ip, $s, Botward_Settings::text( 'err_expired' ) ); } // Слишком быстро для человека (time-trap). if ( $now - $ts < (int) $s['min_solve_seconds'] ) { self::fail( $ip, $s, 'too_fast' ); } // Проверка ответа. $answer = ( isset( $_POST['botward_answer'] ) && is_string( $_POST['botward_answer'] ) ) ? trim( sanitize_text_field( wp_unslash( $_POST['botward_answer'] ) ) ) : ''; if ( ! preg_match( '/^-?\d{1,4}$/', $answer ) ) { self::fail( $ip, $s, 'wrong_answer' ); } if ( ! hash_equals( self::sign_answer( $ts, $nonce, (int) $answer, $bucket ), $parts[2] ) ) { self::fail( $ip, $s, 'wrong_answer' ); } // Успех: пример использован (повторно не принимается), сбрасываем счётчик, выдаём cookie. set_transient( 'botward_u_' . $nonce, 1, ( (int) $s['token_ttl'] + 1 ) * MINUTE_IN_SECONDS ); delete_transient( self::attempts_key( $bucket ) ); Botward_Settings::bump( 'passed' ); Botward_Risk::mark( $ip, 'solved' ); Botward_Risk::outcome( $ip, 'solved' ); self::grant( $ip, $s, 'm' ); // Возвращаем на запрошенную страницу. Только путь на этом же сайте: ведущие «/» и «\» убираются, // чтобы адрес вида «/\evil.com» не превратился в переход на чужой домен. $uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/'; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- проходит через wp_safe_redirect(). $uri = is_string( $uri ) ? $uri : '/'; $uri = '/' . ltrim( (string) preg_replace( '/[\r\n]+/', '', $uri ), "/\\" ); wp_safe_redirect( $uri, 303 ); exit; } /** Неудачная попытка: учитываем и либо блокируем, либо показываем новый пример. */ private static function fail( string $ip, array $s, string $reason ): void { Botward_Settings::bump( 'too_fast' === $reason ? 'too_fast' : 'wrong' ); Botward_Risk::mark( $ip, 'wrong' ); $key = self::attempts_key( Botward_IP::bucket( $ip ) ); $n = (int) get_transient( $key ) + 1; $max = (int) $s['max_attempts']; if ( $n >= $max ) { /* translators: %d: number of failed attempts */ self::do_block( $ip, $reason, (int) $s['block_minutes'], $s, sprintf( __( '%d failed attempts', 'botward' ), $n ) ); } set_transient( $key, $n, (int) $s['attempt_window'] * MINUTE_IN_SECONDS ); $tpl = Botward_Settings::text( 'too_fast' === $reason ? 'err_fast' : 'err_wrong' ); self::send_headers( 200 ); self::render_gate( $ip, $s, str_replace( '{n}', (string) ( $max - $n ), $tpl ) ); } /** Блокировка IP с записью причины и подробностей решения (колонка «Details»). */ public static function do_block( string $ip, string $reason, int $minutes, array $s, string $detail = '' ): void { $bucket = Botward_IP::bucket( $ip ); $ua = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; $uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; Botward_DB::block( $bucket, $reason, $minutes, $ua, $uri, $detail ); Botward_Shield::record_country( $s ); Botward_Settings::bump( 'blocks' ); Botward_Risk::mark( $ip, 'blocked' ); Botward_Risk::outcome( $ip, 'blocked' ); delete_transient( self::attempts_key( $bucket ) ); $row = Botward_DB::find_active( $bucket ); self::send_headers( 403, $row ? (int) $row->expires_at : 0 ); self::render_block( $ip, $s ); } private static function attempts_key( string $bucket ): string { return 'botward_a_' . md5( $bucket ); } /* ------------------------------------------------------------------ */ /* Токены и cookie */ /* ------------------------------------------------------------------ */ /** Подпись ответа (знать правильный ответ без секретного ключа нельзя). */ private static function sign_answer( int $ts, string $nonce, int $answer, string $bucket ): string { return hash_hmac( 'sha256', "a|{$ts}|{$nonce}|{$answer}|{$bucket}", Botward_Settings::secret() ); } /** Подпись «токен выдан этому посетителю в это время» — без ответа, проверяется до всего остального. */ private static function sign_ctx( int $ts, string $nonce, string $bucket ): string { return hash_hmac( 'sha256', "c|{$ts}|{$nonce}|{$bucket}", Botward_Settings::secret() ); } /** Имя honeypot-поля: у каждого примера своё, обученный на одном имени бот его не узнает. */ private static function hp_name( string $nonce ): string { return 'f' . substr( hash_hmac( 'sha256', 'hp|' . $nonce, Botward_Settings::secret() ), 0, 11 ); } /** Генерация примера и подписанного токена (ответ в токене не хранится). */ private static function challenge( string $ip, array $s ): array { $ops = array(); if ( ! empty( $s['op_add'] ) ) { $ops[] = '+'; } if ( ! empty( $s['op_sub'] ) ) { $ops[] = '-'; } if ( ! $ops ) { $ops = array( '+' ); } $min = max( 1, (int) $s['num_min'] ); $max = max( $min + 1, (int) $s['num_max'] ); $op = $ops[ random_int( 0, count( $ops ) - 1 ) ]; $a = random_int( $min, $max ); $b = random_int( $min, $max ); if ( '-' === $op && $b > $a ) { list( $a, $b ) = array( $b, $a ); // результат всегда неотрицательный } $answer = '+' === $op ? $a + $b : $a - $b; $ts = time(); $nonce = bin2hex( random_bytes( 8 ) ); $bucket = Botward_IP::bucket( $ip ); return array( 'question' => $a . ' ' . ( '+' === $op ? '+' : '−' ) . ' ' . $b . ' = ?', 'nonce' => $nonce, 'token' => $ts . '.' . $nonce . '.' . self::sign_answer( $ts, $nonce, $answer, $bucket ) . '.' . self::sign_ctx( $ts, $nonce, $bucket ), ); } private static function pass_sig( int $exp, string $level, string $ip, array $s ): string { $bind = ! empty( $s['bind_ip'] ) ? Botward_IP::bucket( $ip ) : ''; return hash_hmac( 'sha256', "pass|{$exp}|{$level}|{$bind}", Botward_Settings::secret() ); } /** * Выдаёт cookie допуска. Уровень: m — решил математику, s — прошёл тихую проверку в браузере. * Уровень m включает s. */ public static function grant( string $ip, array $s, string $level = 'm' ): void { $level = ( 's' === $level ) ? 's' : 'm'; $exp = time() + (int) $s['pass_hours'] * HOUR_IN_SECONDS; setcookie( self::COOKIE, $exp . '.' . $level . '.' . self::pass_sig( $exp, $level, $ip, $s ), array( 'expires' => $exp, 'path' => '/', 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', ) ); } public static function has_pass( string $ip, array $s, string $need = 'm' ): bool { if ( empty( $_COOKIE[ self::COOKIE ] ) || ! is_string( $_COOKIE[ self::COOKIE ] ) ) { return false; } $parts = explode( '.', sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE ] ) ) ); if ( 3 !== count( $parts ) || ! ctype_digit( $parts[0] ) || (int) $parts[0] < time() || ! in_array( $parts[1], array( 's', 'm' ), true ) ) { return false; } if ( 'm' === $need && 'm' !== $parts[1] ) { return false; } return hash_equals( self::pass_sig( (int) $parts[0], $parts[1], $ip, $s ), $parts[2] ); } /* ------------------------------------------------------------------ */ /* Вывод */ /* ------------------------------------------------------------------ */ /** Заголовки ответа. Страницы плагина никогда не должны попадать в кэш. */ /** Страница блокировки на раннем этапе (до init). */ public static function early_block_response( string $ip, array $s, int $expires = 0 ): void { // Pro-сборка подгружает свои переводы здесь; на wordpress.org их подгружает сам WordPress. if ( ! did_action( 'init' ) ) { do_action( 'botward_load_textdomain' ); } self::send_headers( 403, $expires ); self::render_block( $ip, $s ); } /** Путь запроса попадает в исключения (robots.txt, sitemap, REST, .well-known)? Работает до разбора запроса WordPress. */ public static function is_excluded_path( array $s ): bool { $path = self::request_path(); foreach ( preg_split( '/\R/', (string) $s['exclude_paths'] ) as $rule ) { $rule = trim( $rule ); if ( '' !== $rule && self::match_rule( $path, $rule ) ) { return true; } } return false; } private static function send_headers( int $status, int $expires = 0 ): void { // Стандартные константы кэш-плагинов (WP Rocket, LiteSpeed, W3TC и др.): они должны называться именно так. foreach ( array( 'DONOTCACHEPAGE', 'DONOTCACHEOBJECT', 'DONOTCACHEDB', 'DONOTMINIFY', 'DONOTCDN' ) as $const ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.VariableConstantNameFound -- имена констант кэш-плагинов. if ( ! defined( $const ) ) { define( $const, true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound, WordPress.NamingConventions.PrefixAllGlobals.VariableConstantNameFound -- общепринятые константы кэш-плагинов. } } do_action( 'litespeed_control_set_nocache', 'Botward' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- хук стороннего плагина LiteSpeed Cache. if ( headers_sent() ) { return; } nocache_headers(); status_header( $status ); header( 'Content-Type: text/html; charset=utf-8' ); header( 'X-LiteSpeed-Cache-Control: no-cache' ); header( 'X-Content-Type-Options: nosniff' ); header( 'X-Robots-Tag: noindex, nofollow, noarchive' ); header( 'Referrer-Policy: no-referrer' ); header( 'X-Frame-Options: SAMEORIGIN' ); if ( 403 === $status && $expires > time() ) { header( 'Retry-After: ' . ( $expires - time() ) ); } } private static function css( string $accent ): string { $accent = sanitize_hex_color( $accent ); $accent = $accent ? $accent : '#2563eb'; return ':root{--a:' . $accent . ';--bg:#eef1f6;--card:#fff;--tx:#0f172a;--mu:#64748b;--bd:#dbe1ea;--er:#b91c1c;--erbg:#fef2f2}' . '@media(prefers-color-scheme:dark){:root{--bg:#0b1220;--card:#131c2e;--tx:#e8edf5;--mu:#94a3b8;--bd:#26324a;--er:#fca5a5;--erbg:#2a1517}}' . '*{box-sizing:border-box}html,body{height:100%;margin:0}' . 'body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--tx);display:flex;align-items:center;justify-content:center;padding:16px}' . '.bw-card{width:100%;max-width:400px;background:var(--card);border:1px solid var(--bd);border-radius:16px;padding:32px 28px;box-shadow:0 20px 50px rgba(15,23,42,.18);text-align:center;position:relative}' . '.bw-ico{width:56px;height:56px;margin:0 auto 14px;border-radius:50%;background:color-mix(in srgb,var(--a) 14%,transparent);color:var(--a);display:flex;align-items:center;justify-content:center}' . '.bw-ico svg{width:28px;height:28px}' . 'h1{font-size:20px;margin:0 0 6px;font-weight:650}.bw-sub{margin:0 0 20px;color:var(--mu);font-size:14px;line-height:1.5}' . '.bw-q{font-size:34px;font-weight:700;letter-spacing:.02em;margin:0 0 16px;user-select:none;font-variant-numeric:tabular-nums;direction:ltr}' . '.bw-in{width:100%;font-size:20px;text-align:center;padding:12px 14px;border:1.5px solid var(--bd);border-radius:10px;background:transparent;color:var(--tx);outline:0;direction:ltr}' . '.bw-in:focus{border-color:var(--a);box-shadow:0 0 0 3px color-mix(in srgb,var(--a) 25%,transparent)}' . '.bw-btn{width:100%;margin-top:14px;padding:13px;border:0;border-radius:10px;background:var(--a);color:#fff;font-size:16px;font-weight:600;cursor:pointer}' . '.bw-btn:hover{filter:brightness(1.08)}.bw-btn:disabled{opacity:.6;cursor:default}' . '.bw-err{margin:0 0 14px;padding:10px 12px;border-radius:8px;background:var(--erbg);color:var(--er);font-size:14px}' . '.bw-foot{margin:16px 0 0;color:var(--mu);font-size:12px}' . '.bw-pv{position:fixed;top:0;left:0;right:0;background:#f59e0b;color:#111;text-align:center;font-size:13px;padding:6px}' . '.bw-hp{position:absolute!important;left:-9999px!important;top:auto!important;width:1px!important;height:1px!important;overflow:hidden!important;opacity:0}'; } private static function open_page( array $s, string $title ): void { $lang = str_replace( '_', '-', (string) determine_locale() ); echo '' . '' . '' . esc_html( $title ) . ''; wp_register_style( 'botward-gate', false, array(), BOTWARD_VERSION ); wp_add_inline_style( 'botward-gate', self::css( (string) $s['accent'] ) ); wp_print_styles( 'botward-gate' ); echo ''; } private static function render_gate( string $ip, array $s, string $error = '', bool $preview = false ): void { $c = self::challenge( $ip, $s ); self::open_page( $s, Botward_Settings::text( 'title' ) ); if ( $preview ) { echo '
' . esc_html__( 'Preview: the form is not submitted', 'botward' ) . '
'; } echo '
'; echo '
'; echo '

' . esc_html( Botward_Settings::text( 'title' ) ) . '

'; echo '

' . esc_html( Botward_Settings::text( 'subtitle' ) ) . '

'; if ( '' !== $error ) { echo ''; } echo '
' . esc_html( $c['question'] ) . '
'; echo ''; // Honeypot: скрыт для людей и скринридеров, расположен под математическим блоком; имя поля меняется с каждым примером. echo ''; echo ''; echo ''; if ( ! empty( $s['show_cookie_note'] ) ) { echo '

' . esc_html( Botward_Settings::text( 'cookie_note' ) ) . '

'; } echo '
'; wp_print_inline_script_tag( '(function(){var f=document.forms[0];if(!f)return;f.addEventListener("submit",function(){var b=f.querySelector(".bw-btn");if(b)setTimeout(function(){b.disabled=true},0)});})();' ); echo ''; exit; } private static function render_block( string $ip, array $s, bool $preview = false ): void { self::open_page( $s, __( 'Access restricted', 'botward' ) ); if ( $preview ) { echo '
' . esc_html__( 'Preview of the block page', 'botward' ) . '
'; } echo '
'; echo '

' . esc_html__( '403 — Access restricted', 'botward' ) . '

'; echo '

' . nl2br( esc_html( Botward_Settings::text( 'block_message' ) ) ) . '

'; /* translators: %s: visitor IP address */ echo '

' . esc_html( sprintf( __( 'Your IP: %s', 'botward' ), $ip ) ) . '

'; exit; } }