array( 'Botward_Settings', 'sanitize' ) ) ); // Обновление таблицы, если плагин обновили без повторной активации. if ( get_option( 'botward_db_version' ) !== Botward_DB::DB_VERSION ) { Botward_DB::install(); } self::handle_bulk(); } public static function links( array $links ): array { array_unshift( $links, '' . esc_html__( 'Settings', 'botward' ) . '' ); return $links; } public static function menu(): void { add_menu_page( __( 'Botward', 'botward' ), __( 'Botward', 'botward' ), self::CAP, 'botward', array( __CLASS__, 'page_overview' ), 'dashicons-shield-alt', 81 ); add_submenu_page( 'botward', __( 'Overview', 'botward' ), __( 'Overview', 'botward' ), self::CAP, 'botward', array( __CLASS__, 'page_overview' ) ); add_submenu_page( 'botward', __( 'Blocked IPs', 'botward' ), __( 'Blocked IPs', 'botward' ), self::CAP, 'botward-blocked', array( __CLASS__, 'page_blocked' ) ); add_submenu_page( 'botward', __( 'Caching', 'botward' ), __( 'Caching', 'botward' ), self::CAP, 'botward-cache', array( 'Botward_Cache', 'render_page' ) ); add_submenu_page( 'botward', __( 'Settings', 'botward' ), __( 'Settings', 'botward' ), self::CAP, 'botward-settings', array( __CLASS__, 'page_settings' ) ); } public static function assets( string $hook ): void { if ( 'index.php' === $hook || false !== strpos( $hook, 'botward' ) ) { wp_enqueue_style( 'botward-admin', BOTWARD_URL . 'assets/admin.css', array(), BOTWARD_VERSION ); } if ( false !== strpos( $hook, 'botward-settings' ) && current_user_can( self::CAP ) ) { wp_enqueue_script( 'botward-settings', BOTWARD_URL . 'assets/settings.js', array(), BOTWARD_VERSION, true ); } if ( false !== strpos( $hook, 'toplevel_page_botward' ) && current_user_can( self::CAP ) ) { wp_enqueue_script( 'botward-admin', BOTWARD_URL . 'assets/admin.js', array(), BOTWARD_VERSION, true ); wp_localize_script( 'botward-admin', 'botward', (array) apply_filters( 'botward_admin_localize', array( 'locale' => str_replace( '_', '-', determine_locale() ), 'i18n' => self::js_strings(), ) ) ); } } /* ------------------------------------------------------------------ */ /* Вспомогательное */ /* ------------------------------------------------------------------ */ public static function guard(): void { if ( ! current_user_can( self::CAP ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'botward' ), 403 ); } } /** * Сообщение пользователю хранится в transient, а не в URL: * иначе любую ссылку вида ...&das_msg=текст можно было бы подсунуть администратору (подмена содержимого страницы). */ public static function back( string $msg, string $type = 'success', string $page = 'botward-blocked' ): void { set_transient( 'botward_flash_' . get_current_user_id(), array( 'msg' => $msg, 'type' => $type ), 120 ); wp_safe_redirect( add_query_arg( 'page', $page, admin_url( 'admin.php' ) ) ); exit; } private static function notice(): void { $key = 'botward_flash_' . get_current_user_id(); $flash = get_transient( $key ); if ( ! is_array( $flash ) || empty( $flash['msg'] ) ) { return; } delete_transient( $key ); $type = ( 'error' === ( $flash['type'] ?? '' ) ) ? 'error' : 'success'; echo '

' . esc_html( (string) $flash['msg'] ) . '

'; } public static function header( string $title ): void { echo '

' . esc_html( $title ) . '

'; self::notice(); } /* ------------------------------------------------------------------ */ /* Обзор */ /* ------------------------------------------------------------------ */ public static function page_overview(): void { self::guard(); $s = Botward_Settings::get(); $st = Botward_Settings::stats(); $ip = Botward_IP::get(); $recent = Botward_DB::recent( 8, 'last_seen' ); $reasons = Botward_DB::reasons(); $attn = Botward_Cache::needs_attention(); self::header( __( 'Botward — Overview', 'botward' ) ); if ( $attn ) { echo '

' . esc_html( sprintf( /* translators: %s: comma-separated list of caching plugins */ __( 'Caching detected (%s): the challenge may be skipped for cached pages.', 'botward' ), implode( ', ', $attn ) ) ) . ' ' . esc_html__( 'Review the Caching page', 'botward' ) . '

'; } // Панель вкладок и кнопок: всегда сверху. $prev = wp_nonce_url( home_url( '/?botward_preview=gate' ), 'botward_preview' ); $prevb = wp_nonce_url( home_url( '/?botward_preview=block' ), 'botward_preview' ); // Вкладки показываются, только если расширение (Pro) добавило вторую вкладку. echo '
'; if ( has_action( 'botward_overview_tabs' ) ) { echo '
' . ''; do_action( 'botward_overview_tabs' ); // Расширение само выводит свои кнопки, экранируя их при выводе. echo '
'; } echo '' . esc_html__( 'Preview the challenge', 'botward' ) . '' . '' . esc_html__( 'Preview the block page', 'botward' ) . '' . '' . esc_html__( 'Settings', 'botward' ) . '
'; // Вкладка «Обзор». echo '
'; echo '

' . esc_html__( 'Protection status:', 'botward' ) . ' '; if ( $s['enabled'] ) { echo '' . esc_html__( 'Enabled', 'botward' ) . ''; } else { echo '' . esc_html__( 'Disabled', 'botward' ) . ''; } echo '   ' . esc_html__( 'Your IP as seen by the plugin:', 'botward' ) . ' ' . esc_html( $ip ) . '

'; self::own_ip_notice(); self::attack_panel( $s ); $cards = array( __( 'Active blocks', 'botward' ) => Botward_DB::count_active(), __( 'Total blocks', 'botward' ) => $st['blocks'], __( 'Passed the check', 'botward' ) => $st['passed'], __( 'Wrong answers', 'botward' ) => $st['wrong'], __( 'Too fast', 'botward' ) => $st['too_fast'], __( 'Caught by honeypot', 'botward' ) => $st['honeypot'], __( 'Passed silently', 'botward' ) => $st['silent'], __( 'Suspicious visitors', 'botward' ) => $st['risky'], __( 'Denied by country / crawler rules', 'botward' ) => $st['denied'], ); echo '
'; foreach ( $cards as $label => $val ) { echo '
' . esc_html( $label ) . '' . esc_html( number_format_i18n( (int) $val ) ) . '
'; } echo '
'; Botward_License::promo_card(); echo '
'; // Вкладка «Аналитика» (Pro) выводится расширением. do_action( 'botward_overview_panes', $s ); // Неделя по дням. echo '

' . esc_html__( 'Last 7 days', 'botward' ) . '

'; echo ''; foreach ( array_reverse( Botward_Settings::daily( 7 ) ) as $d ) { echo ''; } echo '
' . esc_html__( 'Date', 'botward' ) . '' . esc_html__( 'Passed', 'botward' ) . '' . esc_html__( 'Failed', 'botward' ) . '' . esc_html__( 'Honeypot', 'botward' ) . '' . esc_html__( 'Blocks', 'botward' ) . '
' . esc_html( $d['date'] ) . '' . (int) $d['passed'] . '' . ( (int) $d['wrong'] + (int) $d['too_fast'] ) . '' . (int) $d['honeypot'] . '' . (int) $d['blocks'] . '
'; $risky = Botward_Risk::recent_log(); if ( $risky ) { $labels = Botward_Risk::labels(); $results = Botward_Risk::results(); echo '

' . esc_html__( 'Decision log', 'botward' ) . '

' . esc_html__( 'One row per visitor: why the plugin acted and how it ended. Denied requests (country and crawler rules) are logged once per visitor, not on every request.', 'botward' ) . '

'; $l = array( 'ip' => __( 'IP', 'botward' ), 'score' => __( 'Score', 'botward' ), 'sig' => __( 'Signals', 'botward' ), 'result' => __( 'Result', 'botward' ), 'req' => __( 'Requests', 'botward' ), 'ua' => __( 'User-Agent', 'botward' ), 'when' => __( 'When', 'botward' ), ); echo '
'; foreach ( array_slice( $risky, 0, 15 ) as $r ) { $why = array(); foreach ( (array) ( $r['rs'] ?? array() ) as $code ) { $why[] = $labels[ $code ] ?? $code; } $res = (string) ( $r['res'] ?? 'shown' ); echo ''; } echo '
' . esc_html( $l['ip'] ) . '' . esc_html( $l['score'] ) . '' . esc_html( $l['sig'] ) . '' . esc_html( $l['result'] ) . '' . esc_html( $l['req'] ) . '' . esc_html( $l['ua'] ) . '' . esc_html( $l['when'] ) . '
' . esc_html( (string) ( $r['ip'] ?? '' ) ) . '' . (int) ( $r['sc'] ?? 0 ) . '' . esc_html( implode( '; ', $why ) ) . '' . esc_html( $results[ $res ] ?? $res ) . '' . (int) ( $r['n'] ?? 1 ) . '' . esc_html( (string) ( $r['ua'] ?? '' ) ) . '' . esc_html( Botward_Settings::fmt( (int) ( $r['ls'] ?? $r['t'] ?? 0 ) ) ) . '
'; } echo '

' . esc_html__( 'Recent blocks', 'botward' ) . '

'; if ( ! $recent ) { echo '

' . esc_html__( 'Nobody has been blocked yet.', 'botward' ) . '

'; } else { $l = array( 'ip' => __( 'IP', 'botward' ), 'reason' => __( 'Reason', 'botward' ), 'when' => __( 'When', 'botward' ), 'until' => __( 'Until', 'botward' ), ); echo '
'; foreach ( $recent as $r ) { $until = (int) $r->expires_at ? Botward_Settings::fmt( (int) $r->expires_at ) : __( 'permanent', 'botward' ); echo ''; } echo '
' . esc_html( $l['ip'] ) . '' . esc_html( $l['reason'] ) . '' . esc_html( $l['when'] ) . '' . esc_html( $l['until'] ) . '
' . esc_html( $r->ip ) . '' . esc_html( $reasons[ $r->reason ] ?? $r->reason ) . '' . esc_html( Botward_Settings::fmt( (int) $r->created_at ) ) . '' . esc_html( $until ) . '
'; } echo '
'; } /** Тексты для скрипта графика (переводятся стандартным способом). */ private static function js_strings(): array { return array( 'rtMore' => __( 'Show details', 'botward' ), 'rtLess' => __( 'Hide details', 'botward' ), ); } /** Адреса самого сервера, которые заблокировали по ошибке (cron, предзагрузка кэша): предлагаем снять блок. */ private static function own_ip_notice(): void { $addrs = Botward_IP::own_ips(); if ( ! empty( $_SERVER['SERVER_ADDR'] ) && is_string( $_SERVER['SERVER_ADDR'] ) ) { $addrs[] = Botward_IP::normalize( sanitize_text_field( wp_unslash( $_SERVER['SERVER_ADDR'] ) ) ); } foreach ( array_unique( array_filter( $addrs ) ) as $addr ) { $row = Botward_DB::find_active( Botward_IP::bucket( $addr ) ); if ( ! $row ) { continue; } $id = (int) $row->id; $url = wp_nonce_url( admin_url( 'admin-post.php?action=botward_unblock&id=' . $id ), 'botward_unblock_' . $id ); /* translators: %s: IP address of this server */ echo '

' . esc_html( sprintf( __( 'The address of this server (%s) is in the block list. This can break WordPress cron, cache preloading and loopback requests.', 'botward' ), $addr ) ) . ' ' . esc_html__( 'Unblock', 'botward' ) . '

'; } } /** Панель режима «под атакой»: состояние, ручное включение и выключение. */ private static function attack_panel( array $s ): void { $a = Botward_Shield::attack(); $active = $a['until'] > time(); echo '

' . esc_html__( 'Under attack mode', 'botward' ) . '

'; echo '
'; wp_nonce_field( 'botward_attack' ); echo ''; if ( $active ) { /* translators: 1: end time, 2: time left */ echo '' . esc_html__( 'ACTIVE', 'botward' ) . ' ' . esc_html( sprintf( __( 'Every new visitor must solve the challenge until %1$s (%2$s left). Started %3$s.', 'botward' ), Botward_Settings::fmt( $a['until'] ), human_time_diff( time(), $a['until'] ), $a['auto'] ? __( 'automatically', 'botward' ) : __( 'manually', 'botward' ) ) ) . ''; echo ''; submit_button( __( 'Turn off', 'botward' ), 'primary', '', false ); } else { echo '' . esc_html__( 'Off', 'botward' ) . ' '; echo '' . esc_html( ! isset( $s['attack_auto'] ) ? __( 'Switching on by itself during a bot flood is a Botward Pro feature. You can turn the mode on by hand here.', 'botward' ) : ( ! empty( $s['attack_auto'] ) ? sprintf( /* translators: 1: number of suspicious visitors, 2: duration in minutes */ __( 'Turns on by itself when %1$d suspicious visitors appear within 5 minutes, for %2$d min.', 'botward' ), (int) $s['attack_threshold'], (int) $s['attack_minutes'] ) : __( 'Automatic switching is disabled in the settings.', 'botward' ) ) ) . ''; echo ''; echo ' ' . esc_html__( 'min.', 'botward' ) . ' '; submit_button( __( 'Turn on now', 'botward' ), 'secondary', '', false ); } echo '
'; } public static function act_attack(): void { self::guard(); check_admin_referer( 'botward_attack' ); $on = isset( $_POST['do'] ) && 'on' === sanitize_key( wp_unslash( $_POST['do'] ) ); if ( $on ) { $minutes = isset( $_POST['minutes'] ) ? absint( wp_unslash( $_POST['minutes'] ) ) : (int) Botward_Settings::get()['attack_minutes']; Botward_Shield::start_attack( $minutes, false ); self::back( __( 'Under attack mode is on.', 'botward' ), 'success', 'botward' ); } Botward_Shield::stop_attack(); self::back( __( 'Under attack mode is off.', 'botward' ), 'success', 'botward' ); } /** Экспорт активных блокировок: правила для .htaccess (Apache 2.4) или простой список IP/CIDR (Cloudflare, nginx, фаервол). */ public static function act_export_list(): void { self::guard(); check_admin_referer( 'botward_export_list' ); $fmt = isset( $_GET['fmt'] ) && 'list' === sanitize_key( wp_unslash( $_GET['fmt'] ) ) ? 'list' : 'htaccess'; $s = Botward_Settings::get(); $ips = array(); foreach ( Botward_DB::active_ips() as $ip ) { $ip = (string) $ip; if ( Botward_IP::valid_rule( $ip ) && ! Botward_IP::is_whitelisted( preg_replace( '#/64$#', '', $ip ), $s ) ) { $ips[] = $ip; } } $ips = array_values( array_unique( $ips ) ); nocache_headers(); header( 'Content-Type: text/plain; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=das-antibot-' . ( 'list' === $fmt ? 'ip-list' : 'htaccess' ) . '-' . gmdate( 'Ymd-His' ) . '.txt' ); if ( 'list' === $fmt ) { echo esc_html( implode( "\n", $ips ) ) . "\n"; exit; } echo "# Botward: " . esc_html( gmdate( 'Y-m-d H:i' ) ) . " UTC, " . count( $ips ) . " addresses\n"; echo "# Apache 2.4. Paste ABOVE the line '# BEGIN WordPress' in .htaccess. Blocked visitors are rejected by the web server\n"; echo "# before PHP and WordPress start, which saves hosting resources. Remove the block to undo.\n"; echo "# BEGIN Botward\n\nRequire all granted\n"; foreach ( array_chunk( $ips, 20 ) as $chunk ) { echo 'Require not ip ' . esc_html( implode( ' ', $chunk ) ) . "\n"; } echo "\n# END Botward\n"; exit; } /* ------------------------------------------------------------------ */ /* Заблокированные IP */ /* ------------------------------------------------------------------ */ public static function page_blocked(): void { self::guard(); require_once BOTWARD_DIR . 'includes/class-list-table.php'; $table = new Botward_List_Table(); $table->prepare_items(); self::header( __( 'Blocked IPs', 'botward' ) ); // Ручная блокировка. echo '

' . esc_html__( 'Block an IP manually', 'botward' ) . '

'; echo '
'; wp_nonce_field( 'botward_add' ); echo ''; echo ''; echo ''; submit_button( __( 'Block', 'botward' ), 'secondary', '', false ); echo '
'; echo '
'; echo ''; $table->views(); $table->search_box( __( 'Search by IP', 'botward' ), 'botward-search' ); echo '
'; echo '
'; $table->display(); echo '
'; $purge_exp = wp_nonce_url( admin_url( 'admin-post.php?action=botward_purge&what=expired' ), 'botward_purge' ); $purge_all = wp_nonce_url( admin_url( 'admin-post.php?action=botward_purge&what=all' ), 'botward_purge' ); $export = wp_nonce_url( admin_url( 'admin-post.php?action=botward_export' ), 'botward_export' ); echo '

'; echo '' . esc_html__( 'Remove expired', 'botward' ) . ''; echo '' . esc_html__( 'Clear all', 'botward' ) . ''; echo '' . esc_html__( 'Export CSV', 'botward' ) . ''; $ht = wp_nonce_url( admin_url( 'admin-post.php?action=botward_export_list&fmt=htaccess' ), 'botward_export_list' ); $list = wp_nonce_url( admin_url( 'admin-post.php?action=botward_export_list&fmt=list' ), 'botward_export_list' ); echo '' . esc_html__( 'Export for .htaccess', 'botward' ) . ''; echo '' . esc_html__( 'Export IP list', 'botward' ) . '

'; echo '

' . esc_html__( 'Tip: the .htaccess export lets the web server reject blocked addresses before PHP and WordPress start. Cloudflare or a server firewall can use the plain IP list.', 'botward' ) . '

'; } /** Массовые действия из таблицы (POST на ту же страницу). */ private static function handle_bulk(): void { $method = isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- здесь только определяем, наша ли это страница; nonce проверяется ниже. $page = isset( $_GET['page'] ) && is_string( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce проверяется ниже. if ( 'POST' !== $method || 'botward-blocked' !== $page || empty( $_POST['ids'] ) || ! is_array( $_POST['ids'] ) ) { return; } self::guard(); check_admin_referer( 'bulk-botward_blocked' ); $act = ''; foreach ( array( 'action', 'action2' ) as $k ) { if ( ! empty( $_POST[ $k ] ) && is_string( $_POST[ $k ] ) && '-1' !== $_POST[ $k ] ) { $act = sanitize_key( wp_unslash( $_POST[ $k ] ) ); break; } } $ids = array_map( 'absint', wp_unslash( $_POST['ids'] ) ); if ( 'delete' === $act ) { /* translators: %d: number of records */ self::back( sprintf( __( 'Unblocked records: %d', 'botward' ), Botward_DB::delete( $ids ) ) ); } elseif ( 'permanent' === $act ) { /* translators: %d: number of records */ self::back( sprintf( __( 'Blocked permanently: %d', 'botward' ), Botward_DB::make_permanent( $ids ) ) ); } } public static function act_unblock(): void { self::guard(); $id = isset( $_GET['id'] ) ? absint( wp_unslash( $_GET['id'] ) ) : 0; check_admin_referer( 'botward_unblock_' . $id ); Botward_DB::delete( array( $id ) ); self::back( __( 'IP unblocked.', 'botward' ) ); } public static function act_permanent(): void { self::guard(); $id = isset( $_GET['id'] ) ? absint( wp_unslash( $_GET['id'] ) ) : 0; check_admin_referer( 'botward_permanent_' . $id ); Botward_DB::make_permanent( array( $id ) ); self::back( __( 'IP blocked permanently.', 'botward' ) ); } public static function act_add(): void { self::guard(); check_admin_referer( 'botward_add' ); $ip = Botward_IP::normalize( isset( $_POST['ip'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['ip'] ) ) ) : '' ); $minutes = isset( $_POST['minutes'] ) ? max( 0, absint( wp_unslash( $_POST['minutes'] ) ) ) : 0; if ( '' === $ip ) { self::back( __( 'Invalid IP address.', 'botward' ), 'error' ); } // Сравниваем по ключу блокировки (для IPv6 это сеть /64), иначе можно заблокировать соседний адрес себя же. if ( Botward_IP::bucket( Botward_IP::get() ) === Botward_IP::bucket( $ip ) ) { self::back( __( 'You cannot block your own IP.', 'botward' ), 'error' ); } if ( Botward_IP::is_whitelisted( $ip, Botward_Settings::get() ) ) { self::back( __( 'This IP is whitelisted.', 'botward' ), 'error' ); } Botward_DB::block( Botward_IP::bucket( $ip ), 'manual', $minutes, __( 'Added manually', 'botward' ), '' ); /* translators: %s: IP address */ self::back( sprintf( __( 'IP %s blocked.', 'botward' ), $ip ) ); } public static function act_purge(): void { self::guard(); check_admin_referer( 'botward_purge' ); $all = isset( $_GET['what'] ) && 'all' === sanitize_key( wp_unslash( $_GET['what'] ) ); $n = $all ? Botward_DB::purge_all() : Botward_DB::purge_expired(); /* translators: %d: number of records */ self::back( sprintf( __( 'Records removed: %d', 'botward' ), $n ) ); } public static function act_export(): void { self::guard(); check_admin_referer( 'botward_export' ); $rows = Botward_DB::all(); nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename=botward-blocked-' . gmdate( 'Ymd-His' ) . '.csv' ); echo "\xEF\xBB\xBF"; // phpcs:ignore WordPress.Security.EscapeOutput -- BOM для Excel, константная строка. $out = fopen( 'php://output', 'w' ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- потоковый вывод CSV, не файловая система. fputcsv( $out, array( 'ip', 'reason', 'detail', 'offenses', 'hits', 'created', 'expires', 'user_agent', 'uri' ) ); foreach ( $rows as $r ) { fputcsv( $out, array( $r['ip'], $r['reason'], self::csv_safe( Botward_Shield::format_detail( (string) ( $r['detail'] ?? '' ) ) ), $r['offenses'], $r['hits'], gmdate( 'Y-m-d H:i:s', (int) $r['created_at'] ), (int) $r['expires_at'] ? gmdate( 'Y-m-d H:i:s', (int) $r['expires_at'] ) : 'permanent', self::csv_safe( $r['ua'] ), self::csv_safe( $r['uri'] ), ) ); } fclose( $out ); // phpcs:ignore WordPress.WP.AlternativeFunctions -- php://output. exit; } /** Защита от CSV-инъекций в Excel. */ private static function csv_safe( string $v ): string { return ( '' !== $v && in_array( $v[0], array( '=', '+', '-', '@', "\t", "\r" ), true ) ) ? "'" . $v : $v; } public static function act_whitelist_me(): void { self::guard(); check_admin_referer( 'botward_whitelist_me' ); $s = Botward_Settings::get(); $ip = Botward_IP::get(); $list = array_filter( array_map( 'trim', preg_split( '/\R/', (string) $s['whitelist_ips'] ) ) ); if ( ! in_array( $ip, $list, true ) ) { $list[] = $ip; $s['whitelist_ips'] = implode( "\n", $list ); update_option( Botward_Settings::OPT, $s ); Botward_Settings::flush(); } /* translators: %s: IP address */ self::back( sprintf( __( 'Your IP %s was added to the whitelist.', 'botward' ), $ip ), 'success', 'botward-settings' ); } /* ------------------------------------------------------------------ */ /* Настройки */ /* ------------------------------------------------------------------ */ public static function name( string $key ): string { return Botward_Settings::OPT . '[' . $key . ']'; } public static function desc( string $text ): void { if ( '' !== $text ) { echo '

' . esc_html( $text ) . '

'; } } public static function f_check( string $key, string $label, string $desc = '' ): void { $s = Botward_Settings::get(); echo ''; self::desc( $desc ); } public static function f_num( string $key, string $unit = '', string $desc = '', int $min = 0, int $max = 999999 ): void { $s = Botward_Settings::get(); echo ' ' . esc_html( $unit ); self::desc( $desc ); } public static function f_text( string $key, string $desc = '' ): void { $s = Botward_Settings::get(); $td = Botward_Settings::text_defaults(); echo ''; self::desc( $desc ); } public static function f_area( string $key, int $rows, string $desc = '', bool $text = false ): void { $s = Botward_Settings::get(); $td = Botward_Settings::text_defaults(); echo ''; self::desc( $desc ); } public static function row( string $label, callable $cb ): void { echo '' . esc_html( $label ) . ''; $cb(); echo ''; } public static function page_settings(): void { self::guard(); $s = Botward_Settings::get(); $ip = Botward_IP::get(); self::header( __( 'Botward — Settings', 'botward' ) ); settings_errors( Botward_Settings::OPT ); echo '
'; settings_fields( 'botward_group' ); $tabs = array( 'protect' => __( 'Protection', 'botward' ), 'early' => __( 'Early blocking', 'botward' ), 'challenge' => __( 'Challenge', 'botward' ), 'access' => __( 'Access and login', 'botward' ), 'general' => __( 'General', 'botward' ), ); $tabs = (array) apply_filters( 'botward_settings_tabs', $tabs ); echo '
'; foreach ( $tabs as $k => $label ) { echo ''; } echo '
'; // Режим работы. echo '

' . esc_html__( 'Protection mode', 'botward' ) . '

'; self::row( __( 'Mode', 'botward' ), function () use ( $s ) { $modes = array( 'smart' => __( 'Smart (recommended)', 'botward' ), 'always' => __( 'Always: challenge every new visitor', 'botward' ), 'forms' => __( 'Login and comments only', 'botward' ), ); echo ''; echo '

' . esc_html__( 'Smart: ordinary visitors are checked silently in the browser and see nothing; the math challenge is shown only to suspicious requests (no browser headers, automation tools, repeated requests without the browser check, scanners). Always: every new visitor must solve the math challenge. Login and comments only: the site stays open, the challenge protects the login pages and comments are accepted only from browsers that passed the silent check.', 'botward' ) . '

'; } ); self::row( __( 'Sensitivity (Smart mode)', 'botward' ), function () use ( $s, $ip ) { $levels = array( 'low' => __( 'Low: fewer challenges, weaker protection', 'botward' ), 'medium' => __( 'Medium (recommended)', 'botward' ), 'high' => __( 'High: more challenges, stronger protection', 'botward' ), ); echo ''; $r = Botward_Risk::evaluate( $ip, $s, false ); $labels = Botward_Risk::labels(); $why = array(); foreach ( $r['reasons'] as $code ) { $why[] = $labels[ $code ] ?? $code; } /* translators: 1: risk score, 2: threshold, 3: reasons */ echo '

' . esc_html( sprintf( __( 'Your current request scores %1$d (a challenge is shown from %2$d). %3$s', 'botward' ), $r['score'], Botward_Risk::threshold( $s ), $why ? implode( '; ', $why ) : __( 'No suspicious signals.', 'botward' ) ) ) . '

'; } ); self::row( __( 'Automatic blocking', 'botward' ), function () { echo esc_html__( 'Block at a score of', 'botward' ) . ' '; self::f_num( 'auto_block_score', '', '', 0, 500 ); echo ' ' . esc_html__( 'for', 'botward' ) . ' '; self::f_num( 'auto_block_minutes', __( 'min.', 'botward' ), __( 'A visitor whose risk score reaches this number (several strong signals at once), and a visitor without a pass who requests 15 non-existent pages within 10 minutes (a scanner), are blocked right away instead of being shown the challenge again and again. 0 disables automatic blocking. Verified search engine bots are never blocked.', 'botward' ) ); $low = (int) Botward_Settings::get()['auto_block_score']; if ( $low > 0 && $low < 80 ) { echo '

' . esc_html__( 'Warning: a score below 80 can block real visitors, for example a single strong signal such as an old browser or missing headers behind a corporate proxy. 100 is the recommended value. For bots that only crawl, prefer the crawler list, country rules and the rate limit below.', 'botward' ) . '

'; } } ); self::row( __( 'Link preview and monitoring bots', 'botward' ), function () { self::f_check( 'allow_preview_bots', __( 'Let link preview and monitoring bots through', 'botward' ), __( 'Facebook, Telegram, WhatsApp, LinkedIn, PageSpeed and similar. They are recognised by User-Agent only (it cannot be verified), so they are limited to GET/HEAD requests and 12 requests per minute per network. One substring per line, case-insensitive.', 'botward' ) ); self::f_area( 'preview_bot_ua', 6 ); } ); self::row( __( 'Comments', 'botward' ), fn() => self::f_check( 'protect_comments', __( 'Accept comments only from browsers that passed the check', 'botward' ), __( 'Comments without a pass (silent or math) are rejected with an explanation.', 'botward' ) ) ); echo '
'; // Ранний щит. echo '

' . esc_html__( 'Early blocking and limits', 'botward' ) . '

'; echo '

' . esc_html__( 'These rules run before the theme and most plugins load, so rejected bots cost the server very little. Robots.txt, sitemaps, REST API and .well-known are never affected. Verified search engine bots are exempt from the country and rate rules.', 'botward' ) . '

'; echo ''; self::row( __( 'Crawler deny list', 'botward' ), function () { self::f_check( 'deny_ua_on', __( 'Reject crawlers from this User-Agent list with 403', 'botward' ), __( 'Aggressive SEO and data-mining crawlers that bring no visitors but load the server. One substring per line, case-insensitive. Search engines (Google, Bing, Yandex) are not in the list. AI crawlers (GPTBot, ClaudeBot, PerplexityBot) are not in it either: add them if you do not want to be used for training.', 'botward' ) ); self::f_area( 'deny_ua', 8 ); echo '

' . esc_html__( 'A well-behaved crawler obeys robots.txt. To ask a crawler to stay away politely, add it to robots.txt with Disallow: /; this list is for those that ignore it.', 'botward' ) . '

'; } ); if ( ! Botward_License::is_pro() ) { self::row( __( 'Countries', 'botward' ), fn() => self::desc( __( 'Country rules (block or allow by country) are a Botward Pro feature.', 'botward' ) ) ); } do_action( 'botward_settings_rows_countries', $s ); // Pro self::row( __( 'Request rate limit', 'botward' ), function () { self::f_num( 'rate_limit', __( 'requests per minute from one network', 'botward' ), __( 'A network that exceeds this is blocked. 0 disables the limit. Without an object cache (Redis, Memcached) visitors who already passed the check are not counted, so people are not affected; with an object cache everyone is counted but passed visitors get a three times higher limit.', 'botward' ), 0, 10000 ); echo '
'; echo esc_html__( 'Block for', 'botward' ) . ' '; self::f_num( 'rate_block_minutes', __( 'min.', 'botward' ), '', 1, 525600 ); } ); self::row( __( 'Under attack mode', 'botward' ), function () { echo '

' . esc_html__( 'Turn the mode on by hand on the Overview page: every new visitor then has to solve the challenge.', 'botward' ) . '

'; } ); do_action( 'botward_settings_rows_attack', $s ); // Pro: автоматическое включение echo '
'; // Общие. echo '

' . esc_html__( 'General', 'botward' ) . '

'; self::row( __( 'Protection', 'botward' ), fn() => self::f_check( 'enabled', __( 'Enable Botward', 'botward' ), __( 'When disabled, the challenge is not shown and existing blocks are not enforced.', 'botward' ) ) ); self::row( __( 'Logged-in users', 'botward' ), fn() => self::f_check( 'bypass_logged_in', __( 'Skip the challenge for logged-in users', 'botward' ), __( 'Administrators are always skipped.', 'botward' ) ) ); self::row( __( 'Search engine bots', 'botward' ), fn() => self::f_check( 'allow_search_bots', __( 'Allow verified search engine bots', 'botward' ), __( 'Google, Bing, Yandex, Baidu and Apple are verified by reverse DNS, so a fake User-Agent is not enough.', 'botward' ) ) ); echo '
'; // Математика. echo '

' . esc_html__( 'Math challenge', 'botward' ) . '

'; self::row( __( 'Operations', 'botward' ), function () { self::f_check( 'op_add', __( 'Addition (+)', 'botward' ) ); echo '
'; self::f_check( 'op_sub', __( 'Subtraction (−)', 'botward' ), __( 'The result of a subtraction is never negative.', 'botward' ) ); } ); self::row( __( 'Number range', 'botward' ), function () { echo esc_html__( 'from', 'botward' ) . ' '; self::f_num( 'num_min', '', '', 1, 99 ); echo ' ' . esc_html__( 'to', 'botward' ) . ' '; self::f_num( 'num_max', '', __( 'Larger numbers make the problem harder for humans too.', 'botward' ), 2, 999 ); } ); self::row( __( 'Minimum solving time', 'botward' ), fn() => self::f_num( 'min_solve_seconds', __( 'sec.', 'botward' ), __( 'An answer submitted faster than this is treated as a bot (0 disables the check).', 'botward' ), 0, 30 ) ); self::row( __( 'Challenge lifetime', 'botward' ), fn() => self::f_num( 'token_ttl', __( 'min.', 'botward' ), __( 'After it expires the visitor gets a new problem without a penalty.', 'botward' ), 1, 60 ) ); echo '
'; // Блокировка. echo '

' . esc_html__( 'Attempts and blocking', 'botward' ) . '

'; self::row( __( 'Allowed wrong attempts', 'botward' ), fn() => self::f_num( 'max_attempts', '', __( '1 blocks right after the first mistake.', 'botward' ), 1, 10 ) ); self::row( __( 'Attempts window', 'botward' ), fn() => self::f_num( 'attempt_window', __( 'min.', 'botward' ), __( 'The mistake counter resets if the visitor makes no mistakes for this long.', 'botward' ), 1, 1440 ) ); self::row( __( 'Block duration (wrong answers)', 'botward' ), fn() => self::f_num( 'block_minutes', __( 'min.', 'botward' ), __( '1440 = 24 hours, 10080 = 7 days.', 'botward' ), 1, 525600 ) ); self::row( __( 'Block duration (honeypot)', 'botward' ), fn() => self::f_num( 'honeypot_block_minutes', __( 'min.', 'botward' ), __( 'A bot that ticks the hidden checkbox is blocked even if the answer is correct.', 'botward' ), 1, 525600 ) ); self::row( __( 'Permanent block after', 'botward' ), fn() => self::f_num( 'permanent_after', __( 'offenses', 'botward' ), __( 'Repeat offenders are blocked with no expiry. 0 disables this.', 'botward' ), 0, 50 ) ); echo '
'; // Допуск. echo '

' . esc_html__( 'Access', 'botward' ) . '

'; self::row( __( 'Pass lifetime', 'botward' ), fn() => self::f_num( 'pass_hours', __( 'hours', 'botward' ), __( '168 = 7 days. After that the challenge is shown again.', 'botward' ), 1, 8760 ) ); self::row( __( 'Bind pass to IP', 'botward' ), fn() => self::f_check( 'bind_ip', __( 'Bind the pass to the visitor IP address', 'botward' ), __( 'More secure, but visitors with a changing IP (mobile networks) will see the challenge again.', 'botward' ) ) ); self::row( __( 'IP source', 'botward' ), function () use ( $s, $ip ) { echo ''; /* translators: %s: IP address */ self::desc( sprintf( __( 'Pick the matching option if the site is behind Cloudflare or a reverse proxy, otherwise all visitors look like one IP. Detected now: %s', 'botward' ), $ip ) ); } ); self::row( __( 'Trusted proxies', 'botward' ), function () use ( $s ) { $remote = Botward_IP::remote_addr(); $trusted = Botward_IP::is_trusted_proxy( $remote, $s, 'cloudflare' === $s['ip_source'] ); self::f_area( 'trusted_proxies', 3, __( 'One IP or CIDR range per line. The IP headers (CF-Connecting-IP, X-Forwarded-For) are accepted only from these addresses; otherwise any visitor could forge them. Cloudflare ranges are built in.', 'botward' ) ); /* translators: %s: IP address of the server connection */ echo '

' . esc_html( sprintf( __( 'Connection address seen by the server: %s', 'botward' ), $remote ) ) . '

'; if ( 'remote_addr' !== $s['ip_source'] && ! $trusted ) { echo '

' . esc_html__( 'Warning: the connection address is not trusted, so the IP headers are ignored and the real connection address is used. Add your proxy address here.', 'botward' ) . '

'; } } ); self::row( __( 'IP whitelist', 'botward' ), function () use ( $ip ) { self::f_area( 'whitelist_ips', 5, __( 'One IP or CIDR range per line, for example 203.0.113.0/24.', 'botward' ) ); $own = Botward_IP::own_ips(); if ( $own ) { /* translators: %s: list of IP addresses */ self::desc( sprintf( __( 'Always allowed automatically (the server of this site): %s', 'botward' ), implode( ', ', $own ) ) ); } $url = wp_nonce_url( admin_url( 'admin-post.php?action=botward_whitelist_me' ), 'botward_whitelist_me' ); /* translators: %s: IP address */ echo '

' . esc_html( sprintf( __( 'Add my IP (%s)', 'botward' ), $ip ) ) . '

'; } ); self::row( __( 'Excluded paths', 'botward' ), fn() => self::f_area( 'exclude_paths', 8, __( 'One rule per line, matched against the URL path only (the query string is ignored). A rule ending in / matches everything below it, a rule with * is a wildcard, any other rule matches that exact path.', 'botward' ) ) ); echo '
'; // Защита входа. echo '

' . esc_html__( 'Login protection', 'botward' ) . '

'; self::row( __( 'Login page', 'botward' ), fn() => self::f_check( 'protect_login', __( 'Protect wp-login.php and limit failed logins', 'botward' ), __( 'The challenge is shown before the login, registration and lost-password forms; without a pass the password is never checked. Failed logins are counted per IP (XML-RPC and REST included). Add your IP to the whitelist first. Emergency switch: define( \'BOTWARD_DISABLE_LOGIN\', true ); in wp-config.php.', 'botward' ) ) ); self::row( __( 'Allowed failed logins', 'botward' ), fn() => self::f_num( 'login_max_failures', '', __( 'Reaching this number within the window blocks the IP.', 'botward' ), 1, 50 ) ); self::row( __( 'Failed logins window', 'botward' ), fn() => self::f_num( 'login_window', __( 'min.', 'botward' ), '', 1, 1440 ) ); self::row( __( 'Block duration (failed logins)', 'botward' ), fn() => self::f_num( 'login_block_minutes', __( 'min.', 'botward' ), __( 'Keep it moderate: visitors behind a shared IP (office, mobile network) share the counter.', 'botward' ), 1, 525600 ) ); self::row( __( 'Login errors', 'botward' ), fn() => self::f_check( 'login_generic_error', __( 'Same error for a wrong username and a wrong password', 'botward' ), __( 'Prevents guessing which usernames exist.', 'botward' ) ) ); self::row( __( 'XML-RPC', 'botward' ), fn() => self::f_check( 'disable_xmlrpc', __( 'Disable XML-RPC', 'botward' ), __( 'Recommended if you do not use the WordPress mobile app or Jetpack. XML-RPC allows many password guesses in one request.', 'botward' ) ) ); echo '
'; // Кэш. echo '

' . esc_html__( 'Caching', 'botward' ) . '

'; self::row( __( 'Cache integration', 'botward' ), function () { self::f_check( 'cache_integration', __( 'Configure supported cache plugins automatically', 'botward' ), __( 'Currently WP Rocket (mandatory cookie). See the Caching page for LiteSpeed, nginx, Cloudflare and others.', 'botward' ) ); echo '

' . esc_html__( 'Open the Caching page', 'botward' ) . '

'; } ); echo '
'; // Оформление. echo '

' . esc_html__( 'Appearance and texts', 'botward' ) . '

'; echo '

' . esc_html__( 'Leave a text empty to use the default. Defaults are translatable with Loco Translate; a custom text is shown as typed, in every language.', 'botward' ) . '

'; echo ''; self::row( __( 'Accent color', 'botward' ), function () use ( $s ) { echo ''; } ); self::row( __( 'Title', 'botward' ), fn() => self::f_text( 'title' ) ); self::row( __( 'Subtitle', 'botward' ), fn() => self::f_text( 'subtitle' ) ); self::row( __( 'Button text', 'botward' ), fn() => self::f_text( 'button' ) ); self::row( __( 'Message: wrong answer', 'botward' ), fn() => self::f_text( 'err_wrong', __( '{n} is the number of attempts left.', 'botward' ) ) ); self::row( __( 'Message: too fast', 'botward' ), fn() => self::f_text( 'err_fast', __( '{n} is the number of attempts left.', 'botward' ) ) ); self::row( __( 'Message: time is up', 'botward' ), fn() => self::f_text( 'err_expired' ) ); self::row( __( 'Cookie hint', 'botward' ), function () { self::f_check( 'show_cookie_note', __( 'Show the cookie hint', 'botward' ) ); echo '

'; self::f_text( 'cookie_note' ); } ); self::row( __( 'Block page message', 'botward' ), fn() => self::f_area( 'block_message', 4, '', true ) ); echo '
'; do_action( 'botward_settings_panels', $s ); // Pro: Telegram // Данные. echo '

' . esc_html__( 'Data', 'botward' ) . '

'; self::row( __( 'Keep expired records', 'botward' ), fn() => self::f_num( 'log_retention_days', __( 'days', 'botward' ), __( 'Old expired blocks are removed automatically once a day.', 'botward' ), 1, 3650 ) ); self::row( __( 'Uninstall', 'botward' ), fn() => self::f_check( 'delete_on_uninstall', __( 'Delete all plugin data when the plugin is deleted', 'botward' ) ) ); echo '
'; submit_button( __( 'Save settings', 'botward' ) ); echo '
'; } }