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'] ) . '
' . 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' ) . '
' . 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 ) . '
| ' . 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'] . ' |
' . 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 '| ' . 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 ) ) ) . ' |
' . esc_html__( 'Nobody has been blocked yet.', 'botward' ) . '
'; } else { $l = array( 'ip' => __( 'IP', 'botward' ), 'reason' => __( 'Reason', 'botward' ), 'when' => __( 'When', 'botward' ), 'until' => __( 'Until', 'botward' ), ); 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 ) . ' |
' . 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' ) . '
'; 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 '