load_partials(); } /** * Load partial components */ private function load_partials() { $partials_dir = GUARDPRESS_PLUGIN_DIR . 'admin/views/partials/'; require_once $partials_dir . 'notices.php'; require_once $partials_dir . 'cards.php'; require_once $partials_dir . 'tables.php'; require_once $partials_dir . 'header.php'; require_once $partials_dir . 'buttons.php'; } /** * Register admin menu pages */ public function register_menu() { add_menu_page( 'AI CyberGuard', 'AI CyberGuard', 'manage_options', 'ai-cyberguard', array( $this, 'render_scanner_page' ), 'dashicons-shield', 58 ); // Override the first submenu item name (WordPress auto-creates it with same name as parent) add_submenu_page( 'ai-cyberguard', __( 'Dashboard', 'ai-cyberguard' ), ' ' . __( 'Dashboard', 'ai-cyberguard' ), 'manage_options', 'ai-cyberguard', array( $this, 'render_scanner_page' ) ); add_submenu_page( 'ai-cyberguard', __( 'Settings & Security', 'ai-cyberguard' ), ' ' . __( 'Settings & Security', 'ai-cyberguard' ), 'manage_options', 'guardpress_settings', array( $this, 'render_settings_page' ) ); // PRO submenu pages are added by GuardPress_Pro_Admin // PRO upsell page is added at priority 999 to be at the bottom } /** * Apply the unified shield icon to every AI CyberGuard submenu item. Runs on * admin_menu at a late priority (after every module has registered its page), * strips any per-item dashicon, and prepends the brand shield — except the * "Get Pro" upsell, which keeps its star highlight. */ public function unify_menu_icons() { global $submenu; if ( empty( $submenu['ai-cyberguard'] ) || ! is_array( $submenu['ai-cyberguard'] ) ) { return; } $icon = ' '; foreach ( $submenu['ai-cyberguard'] as $i => $item ) { if ( ! isset( $item[0], $item[2] ) ) { continue; } // Leave the "Get Pro" upsell with its own star highlight, and any // external link (e.g. the Help → docs item) with its own icon. if ( 'guardpress-upgrade' === $item[2] || 0 === strpos( (string) $item[2], 'http' ) ) { continue; } // Strip any existing leading dashicon span, then apply the unified shield. $title = preg_replace( '#^\s*]*\bdashicons\b[^>]*>\s*\s*#', '', (string) $item[0] ); $submenu['ai-cyberguard'][ $i ][0] = $icon . $title; } } /** * Register a "Help" link in the AI CyberGuard submenu that opens the online * documentation. Registered late (priority 998) so it sits near the bottom, * just above the "Get Pro" upsell. The menu slug is the full external URL, * which WordPress renders as a direct link (no page callback needed). */ public function register_help_link() { add_submenu_page( 'ai-cyberguard', __( 'Help & Documentation', 'ai-cyberguard' ), ' ' . __( 'Help', 'ai-cyberguard' ), 'manage_options', self::HELP_URL, '' ); } /** * Output a clear "Help & Documentation" button at the top of every AI * CyberGuard admin page. Hooked to admin_notices so it renders in-flow at * the very top of the page content (works in both LTR and RTL). Also points * the sidebar Help link at a new tab. */ public function render_help_button() { $screen = get_current_screen(); if ( ! $screen || false === strpos( (string) $screen->id, 'ai-cyberguard' ) ) { return; } echo '
'; echo '' . '' . esc_html__( 'Help & Documentation', 'ai-cyberguard' ) . '
'; // Make the sidebar Help link open in a new tab too (WP renders external // submenu links without target). Matched by href, no inline-handler needed. echo ''; } /** * Enqueue admin assets */ public function enqueue_assets( $hook ) { if ( false === strpos( (string) $hook, 'ai-cyberguard' ) ) { return; } wp_enqueue_style( 'dashicons' ); $css_ver = @filemtime( GUARDPRESS_PLUGIN_DIR . 'admin/css/admin-style.css' ); $js_ver = @filemtime( GUARDPRESS_PLUGIN_DIR . 'admin/js/admin.js' ); if ( ! $css_ver ) { $css_ver = GUARDPRESS_VERSION; } if ( ! $js_ver ) { $js_ver = GUARDPRESS_VERSION; } wp_enqueue_style( 'guardpress-admin', GUARDPRESS_PLUGIN_URL . 'admin/css/admin-style.css', array(), $css_ver ); wp_enqueue_script( 'guardpress-admin-js', GUARDPRESS_PLUGIN_URL . 'admin/js/admin.js', array(), $js_ver, true ); // Localize script for AJAX wp_localize_script( 'guardpress-admin-js', 'gpAdminData', array( 'nonce' => wp_create_nonce( $this->nonce_action ), 'ajaxurl' => admin_url( 'admin-ajax.php' ), ) ); } /** * Route to scanner page view */ public function render_scanner_page() { require_once GUARDPRESS_PLUGIN_DIR . 'admin/views/class-view-scanner.php'; $view = new GuardPress_View_Scanner( $this->nonce_action ); $view->render(); } /** * Route to settings page view */ public function render_settings_page() { require_once GUARDPRESS_PLUGIN_DIR . 'admin/views/class-view-settings.php'; $view = new GuardPress_View_Settings( $this->nonce_action ); $view->render(); } /** * Handle all form actions */ public function handle_actions() { // FIX L-2 (audit 2026-05-25): nonce first, then capability — matches // WordPress convention. Previously the cap check ran first, leaking // (via error-message branch) the fact that a URL is gated by // manage_options before requiring a valid nonce. Functionally // equivalent against CSRF/privesc; this is purely the convention // alignment and tiny info-disclosure close. $nonce = isset( $_REQUEST['guardpress_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['guardpress_nonce'] ) ) : ''; if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, $this->nonce_action ) ) { wp_die( esc_html__( 'Security check failed.', 'ai-cyberguard' ) ); } if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'Insufficient permissions.', 'ai-cyberguard' ) ); } $cmd = isset( $_REQUEST['guardpress_cmd'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['guardpress_cmd'] ) ) : ''; // Route to appropriate handler switch ( $cmd ) { case 'save_settings': $this->handle_save_settings(); break; case 'save_login_settings': $this->handle_save_login_settings(); break; case 'unblock_ip': $this->handle_unblock_ip(); break; case 'block_ip_temp': $this->handle_block_ip_temp(); break; case 'add_to_blacklist': $this->handle_add_to_blacklist(); break; case 'remove_from_blacklist': $this->handle_remove_from_blacklist(); break; case 'add_to_whitelist': $this->handle_add_to_whitelist(); break; case 'remove_from_whitelist': $this->handle_remove_from_whitelist(); break; case 'clear_suspicious': $this->handle_clear_suspicious(); break; case 'clear_all_suspicious': $this->handle_clear_all_suspicious(); break; case 'bulk_block_suspicious': $this->handle_bulk_block_suspicious(); break; case 'bulk_blacklist_suspicious': $this->handle_bulk_blacklist_suspicious(); break; case 'bulk_clear_suspicious': $this->handle_bulk_clear_suspicious(); break; case 'bulk_unblock_blocked': $this->handle_bulk_unblock_blocked(); break; case 'bulk_blacklist_blocked': $this->handle_bulk_blacklist_blocked(); break; case 'clear_all_blocked': $this->handle_clear_all_blocked(); break; case 'send_test_email': $this->handle_send_test_email(); break; case 'run_ai_analysis': $this->handle_run_ai_analysis(); break; // GP-REL-022 (audit 2026-06-19): the synchronous admin-post scan and // baseline handlers ('run_scan', 'create_baseline', // 'accept_refresh_baseline') were a SECOND scan engine that bypassed // the scan lock, the MAX_FILES guard and the batched state machine — // a single request walked the whole tree and could exhaust workers / // race the AJAX path on the same baseline.json. They are orphaned: no // view template emits these commands (the live UI uses the batched // AJAX path exclusively), and cron/CLI call GuardPress_Scan_Runner::run() // directly, not through this dispatcher. The cases and their handler // methods are removed so there is exactly ONE scan/baseline path. case 'export_csv': $this->handle_export_csv(); break; case 'ignore_file': $this->handle_ignore_file(); break; case 'unignore_file': $this->handle_unignore_file(); break; case 'scan_database': $this->handle_scan_database(); break; case 'clear_db_scan': $this->handle_clear_db_scan(); break; case 'verify_core': $this->handle_verify_core(); break; case 'clear_core_verify': $this->handle_clear_core_verify(); break; default: // FIX L-13 (audit 2026-05-25): explicitly mark unknown command // in the redirect so the user is told the request didn't do // anything (instead of silently landing on dashboard as if it // had succeeded). Also closes the tiny info-disclosure where // an attacker probing valid $cmd values could distinguish // them by the redirect path differing. wp_safe_redirect // (instead of wp_redirect) enforces same-host on the URL. wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard&gp_notice=unknown_cmd' ) ); exit; } } // ========================================================================= // Privacy Settings Handler // ========================================================================= /** * Handle privacy settings form submission * Saves threat feed and usage stats preferences */ /** * Contribute suggested privacy-policy text to the WordPress core * Privacy Policy Guide (Tools → Privacy). * * FIX 7c (audit follow-up): readme + Settings explain the optional * external services to the developer/admin; this gives the SITE OWNER * ready-made wording to publish to their own visitors. It is suggested * text only — WordPress never auto-inserts it — and it makes no external * request. * * @return void */ public function register_privacy_policy_content() { if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) { return; } $content = '

' . esc_html__( 'AI CyberGuard protects this site. Most of its work (file integrity, malware scanning, login security) runs locally on this server. Some optional features contact external services, and only when you enable or trigger them:', 'ai-cyberguard' ) . '

'; $content .= ''; wp_add_privacy_policy_content( 'AI CyberGuard', wp_kses_post( $content ) ); } public function handle_privacy_settings() { if ( ! isset( $_POST['gp_save_privacy'] ) ) { return; } // FIX L-3 (audit 2026-05-25): nonce first, then capability — // convention alignment, matches the L-2 swap in handle_actions(). if ( ! isset( $_POST['gp_privacy_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['gp_privacy_nonce'] ) ), 'guardpress_save_privacy_settings' ) ) { return; } if ( ! current_user_can( 'manage_options' ) ) { return; } // Save threat feed ENABLED setting (main switch) $threat_feed_enabled = isset( $_POST['gp_threat_feed_enabled'] ) ? true : false; update_option( 'guardpress_threat_feed_enabled', $threat_feed_enabled ); // Save threat feed auto-update setting $threat_feed_auto = isset( $_POST['gp_threat_feed_auto'] ) ? true : false; update_option( 'guardpress_threat_feed_auto_update', $threat_feed_auto ); // Schedule or unschedule threat feed based on BOTH settings // Use the dedicated functions to properly register hooks if ( $threat_feed_enabled && $threat_feed_auto ) { if ( class_exists( 'GuardPress_Threat_Feed' ) && method_exists( 'GuardPress_Threat_Feed', 'enable_auto_updates' ) ) { GuardPress_Threat_Feed::enable_auto_updates(); } } else { if ( class_exists( 'GuardPress_Threat_Feed' ) && method_exists( 'GuardPress_Threat_Feed', 'disable_auto_updates' ) ) { GuardPress_Threat_Feed::disable_auto_updates(); } else { wp_clear_scheduled_hook( 'guardpress_threat_feed_update' ); } } // Save AI enabled setting $ai_enabled = isset( $_POST['gp_ai_enabled'] ) ? true : false; update_option( 'guardpress_ai_enabled', $ai_enabled ); if ( $ai_enabled && ! get_option( 'guardpress_ai_consent_date' ) ) { // FIX H-10 (audit 2026-05-25): autoload=false. This timestamp is // only read on the Privacy/AI Settings UI; it does not need to live // in alloptions on every request. Note: 'guardpress_ai_enabled' a // few lines up DOES stay autoload (default) because AI_Analyzer:: // is_enabled() reads it from bootstrap on every admin request. update_option( 'guardpress_ai_consent_date', current_time( 'mysql' ), false ); } // Save GeoIP enrichment opt-in (audit M-05). Default OFF — when off, no IP // is ever sent to ipinfo.io; the Live Attack Map uses cached/known countries // only. autoload=false: read only at dashboard render via Country_Blocker. $geoip_enabled = isset( $_POST['gp_geoip_enrichment'] ) ? true : false; update_option( 'guardpress_geoip_enrichment_enabled', $geoip_enabled, false ); // Redirect with success notice. // wp_safe_redirect() enforces same-host restriction. // Fallback to a known-safe admin URL if referer is empty or external. $referer = wp_get_referer(); $redirect = $referer ? add_query_arg( 'gp_notice', 'privacy_saved', $referer ) : admin_url( 'admin.php?page=guardpress_settings&gp_notice=privacy_saved' ); wp_safe_redirect( $redirect ); exit; } // ========================================================================= // Action Handlers // ========================================================================= /** * Handle database scan * @since 1.0.0 */ private function handle_scan_database() { if ( class_exists( 'GuardPress_Database_Scanner' ) ) { $results = GuardPress_Database_Scanner::scan(); // ACG-119-003 (2026-07-05, Yossi): persist the DB-scan result for 30 days (was 1 hour) // and stamp it with the scan time, so the dashboard keeps showing the outcome — including // a green "no problems found" state — long after the scan instead of silently reverting to // a bare button that leaves the user unsure whether a scan ever ran. if ( is_array( $results ) ) { $results['scanned_at'] = time(); } set_transient( 'guardpress_db_scan_results', $results, 30 * DAY_IN_SECONDS ); } // The no-JS fallback still redirects with the anchor so a fallback user also lands on the // card. (The primary path is now the in-page AJAX handler ajax_db_scan below, which needs // no redirect at all.) ACG-120-012 supersedes the earlier anchor experiments. wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard&gp_notice=db_scan_done#gp-database-scanner' ) ); exit; } /** * ACG-120-012: in-page DB scan. Runs the existing bounded scan() and returns the result HTML, * so the dashboard shows the outcome (green clean state / red findings) WITHOUT a page reload. */ public function ajax_db_scan() { check_ajax_referer( 'guardpress_db_scan_ajax', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'ai-cyberguard' ) ), 403 ); } if ( ! class_exists( 'GuardPress_Database_Scanner' ) ) { wp_send_json_error( array( 'message' => __( 'Scanner unavailable.', 'ai-cyberguard' ) ), 500 ); } // A full database scan can be memory-hungry on large sites (real-world peak observed ~186 MB // on a 220k-row postmeta table). Lift the memory ceiling for this one request if it is lower, // so the scan completes; this is best-effort (some hosts disallow ini_set) and never lowers a // higher existing limit. $current_memory = function_exists( 'wp_convert_hr_to_bytes' ) ? wp_convert_hr_to_bytes( (string) @ini_get( 'memory_limit' ) ) : 0; if ( $current_memory > 0 && $current_memory < 512 * 1024 * 1024 ) { @ini_set( 'memory_limit', '512M' ); // phpcs:ignore WordPress.PHP.IniSet.memory_limit_Disallowed -- one-request lift for a heavy scan; best-effort } try { $results = GuardPress_Database_Scanner::scan(); if ( is_array( $results ) ) { $results['scanned_at'] = time(); } set_transient( 'guardpress_db_scan_results', $results, 30 * DAY_IN_SECONDS ); // The results markup is produced by GuardPress_View_Scanner. That class is normally loaded // only when the dashboard PAGE renders; this handler runs in a separate admin-ajax.php // request where that never happened, so we must load the view file here before using it. // (Without this, the renderer is absent, the HTML comes back empty, and the card shows // nothing even though findings exist — the bug fixed in 1.0.131.) if ( ! class_exists( 'GuardPress_View_Scanner' ) ) { $view_file = GUARDPRESS_PLUGIN_DIR . 'admin/views/class-view-scanner.php'; if ( is_readable( $view_file ) ) { require_once $view_file; } } $html = ''; if ( class_exists( 'GuardPress_View_Scanner' ) && method_exists( 'GuardPress_View_Scanner', 'render_database_scan_results_html' ) ) { $rendered = GuardPress_View_Scanner::render_database_scan_results_html( $results ); $html = is_string( $rendered ) ? $rendered : ''; } elseif ( function_exists( 'guardpress_debug_log' ) ) { // ACG-143-013 (pre-sale audit): routed through the plugin's own gated logger. error_log() // writes to the host's error log unconditionally, on every production site, for a // condition that is not an error the site owner can act on. guardpress_debug_log( 'DB scan: results view could not be loaded.' ); } $total = is_array( $results ) && isset( $results['total_issues'] ) ? (int) $results['total_issues'] : 0; } catch ( \Throwable $e ) { if ( function_exists( 'guardpress_debug_log' ) ) { // ACG-143-013 (pre-sale audit): getFile() is an ABSOLUTE server path. Writing it on every // failure discloses the host's filesystem layout to anyone who can read the error log; // the basename locates the throw site just as well, and this now honours the debug gate. guardpress_debug_log( 'DB scan failed: ' . $e->getMessage() . ' @ ' . basename( $e->getFile() ) . ':' . $e->getLine() ); } wp_send_json_error( array( 'message' => sprintf( /* translators: %s: technical error detail. */ __( 'The database scan could not finish: %s', 'ai-cyberguard' ), $e->getMessage() ), ), 500 ); } wp_send_json_success( array( 'total_issues' => $total, 'html' => $html, ) ); } /** * Clear database scan results */ private function handle_clear_db_scan() { delete_transient( 'guardpress_db_scan_results' ); wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard' ) ); exit; } /** * Handle WordPress core verification * @since 1.0.0 */ private function handle_verify_core() { // Debug: Log verification attempt if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: Starting Core Verification...' ); } if ( class_exists( 'GuardPress_Repository_Comparison' ) ) { $results = GuardPress_Repository_Comparison::verify_core_files(); // Debug: Log results if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: Core Verification completed. WP Version: ' . ( $results['wp_version'] ?? 'unknown' ) ); guardpress_debug_log( 'GuardPress: Verified: ' . ( $results['verified'] ? 'YES' : 'NO' ) ); // Log what failed if ( ! empty( $results['modified_files'] ) ) { guardpress_debug_log( 'GuardPress: Modified files (' . count( $results['modified_files'] ) . '):' ); foreach ( $results['modified_files'] as $file ) { $filename = is_array( $file ) ? $file['file'] : $file; guardpress_debug_log( ' - ' . $filename ); } } if ( ! empty( $results['missing_files'] ) ) { guardpress_debug_log( 'GuardPress: Missing files (' . count( $results['missing_files'] ) . '):' ); foreach ( array_slice( $results['missing_files'], 0, 10 ) as $file ) { guardpress_debug_log( ' - ' . $file ); } if ( count( $results['missing_files'] ) > 10 ) { guardpress_debug_log( ' ... and ' . ( count( $results['missing_files'] ) - 10 ) . ' more' ); } } if ( ! empty( $results['extra_files'] ) ) { guardpress_debug_log( 'GuardPress: Extra files (' . count( $results['extra_files'] ) . '):' ); foreach ( $results['extra_files'] as $file ) { guardpress_debug_log( ' - ' . $file ); } } if ( isset( $results['message'] ) ) { guardpress_debug_log( 'GuardPress: Message: ' . $results['message'] ); } } set_transient( 'guardpress_core_verify_results', $results, HOUR_IN_SECONDS ); } else { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: ERROR - GuardPress_Repository_Comparison class not found!' ); } } wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard&gp_notice=core_verify_done#gp-core-integrity' ) ); exit; } /** * Clear core verification results */ private function handle_clear_core_verify() { delete_transient( 'guardpress_core_verify_results' ); wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard' ) ); exit; } private function handle_save_settings() { // Debug: Log what we received if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: Saving settings...' ); guardpress_debug_log( 'GuardPress: Frequency received: ' . ( isset( $_POST['gp_schedule_frequency'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_schedule_frequency'] ) ) : 'NOT SET' ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs } if ( class_exists( 'GuardPress_Settings' ) ) { GuardPress_Settings::save_from_request( $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs } if ( class_exists( 'GuardPress_Cron' ) ) { GuardPress_Cron::ensure_schedule(); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=settings_saved' ) ); exit; } private function handle_save_login_settings() { if ( class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::save_settings( $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=settings_saved' ) ); exit; } private function handle_run_ai_analysis() { $notice = 'ai_analysis_error'; if ( class_exists( 'GuardPress_AI_Analyzer' ) && class_exists( 'GuardPress_Scan_Runner' ) ) { $report = GuardPress_Scan_Runner::get_last_report(); $result = GuardPress_AI_Analyzer::analyze_scan( $report ); if ( is_wp_error( $result ) ) { // Store error for display set_transient( 'guardpress_ai_error', $result->get_error_message(), 60 ); $notice = 'ai_analysis_error'; } else { $notice = 'ai_analysis_done'; } } wp_safe_redirect( admin_url( 'admin.php?page=ai-cyberguard&gp_notice=' . $notice ) ); exit; } private function handle_unblock_ip() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::unblock_ip( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=ip_unblocked' ) ); exit; } private function handle_block_ip_temp() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { $result = GuardPress_Login_Security::block_ip_manual( $ip, 60 ); // 1 hour block $notice = $result ? 'ip_blocked' : 'invalid_ip'; } else { $notice = 'invalid_ip'; } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=' . $notice ) ); exit; } private function handle_add_to_blacklist() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { $result = GuardPress_Login_Security::add_to_blacklist( $ip, 'manual' ); $notice = $result ? 'added_blacklist' : 'invalid_ip'; } else { $notice = 'invalid_ip'; } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=' . $notice ) ); exit; } private function handle_remove_from_blacklist() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::remove_from_blacklist( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=removed_blacklist' ) ); exit; } private function handle_add_to_whitelist() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs $label = isset( $_POST['gp_label'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_label'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { $result = GuardPress_Login_Security::add_to_whitelist( $ip, $label ); $notice = $result ? 'added_whitelist' : 'invalid_ip'; } else { $notice = 'invalid_ip'; } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=' . $notice ) ); exit; } private function handle_remove_from_whitelist() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::remove_from_whitelist( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=removed_whitelist' ) ); exit; } private function handle_clear_suspicious() { $ip = isset( $_POST['gp_ip'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ip'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs if ( $ip && class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::clear_failed_attempts( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=cleared_suspicious' ) ); exit; } private function handle_clear_all_suspicious() { if ( class_exists( 'GuardPress_Login_Security' ) ) { GuardPress_Login_Security::clear_all_failed_attempts(); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=cleared_all_suspicious' ) ); exit; } /** * FIX M-8 (audit 2026-05-25): Shared parser for the bulk-IP handlers. * * Hardens 5 sibling handlers (block / blacklist / clear / unblock / * blacklist_blocked) against authenticated DoS: * - Caps the input at MAX_BULK_IPS (1000) entries. Without this cap, a * pasted comma-separated list with 100,000 entries would trigger * 100,000 DB INSERTs in one request; each add_to_blacklist() rewrites * the whole guardpress_ip_blacklist_v1 option, producing O(n²) write * amplification + binlog explosion. * - Validates each entry with FILTER_VALIDATE_IP (defense-in-depth — * the downstream Login_Security methods already validate, but * filtering here lets us early-out before calling them at all). * - Deduplicates so a list with the same IP repeated 1000 times only * hits the DB once per unique IP. * * @param string $raw The raw 'gp_ips' POST value (already sanitized * + wp_unslash'd by the caller). * @param int $max Maximum number of IPs to accept (default 1000). * @return array Validated, deduplicated, capped IP list. */ private function parse_bulk_ips( $raw, $max = 1000 ) { if ( ! is_string( $raw ) || $raw === '' ) { return array(); } $parts = array_map( 'trim', explode( ',', $raw ) ); $valid = array(); foreach ( $parts as $candidate ) { if ( $candidate === '' ) { continue; } if ( false === filter_var( $candidate, FILTER_VALIDATE_IP ) ) { continue; } $valid[ $candidate ] = true; // dedupe via keys if ( count( $valid ) >= $max ) { break; } } return array_keys( $valid ); } private function handle_bulk_block_suspicious() { if ( ! class_exists( 'GuardPress_Login_Security' ) ) { wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings' ) ); exit; } $raw = isset( $_POST['gp_ips'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ips'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs foreach ( $this->parse_bulk_ips( $raw ) as $ip ) { GuardPress_Login_Security::block_ip_temporarily( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=bulk_blocked' ) ); exit; } private function handle_bulk_blacklist_suspicious() { if ( ! class_exists( 'GuardPress_Login_Security' ) ) { wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings' ) ); exit; } $raw = isset( $_POST['gp_ips'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ips'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs foreach ( $this->parse_bulk_ips( $raw ) as $ip ) { GuardPress_Login_Security::add_to_blacklist( $ip ); GuardPress_Login_Security::clear_failed_attempts( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=bulk_blacklisted' ) ); exit; } private function handle_bulk_clear_suspicious() { if ( ! class_exists( 'GuardPress_Login_Security' ) ) { wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings' ) ); exit; } $raw = isset( $_POST['gp_ips'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ips'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs foreach ( $this->parse_bulk_ips( $raw ) as $ip ) { GuardPress_Login_Security::clear_failed_attempts( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=bulk_cleared' ) ); exit; } /** * Unblock a bulk selection of currently-blocked IPs. * Mirrors handle_bulk_clear_suspicious structurally but calls unblock_ip() * on each IP (which resets blocked_until = 0 and attempt_count = 0). */ private function handle_bulk_unblock_blocked() { if ( ! class_exists( 'GuardPress_Login_Security' ) ) { wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings' ) ); exit; } $raw = isset( $_POST['gp_ips'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ips'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs foreach ( $this->parse_bulk_ips( $raw ) as $ip ) { GuardPress_Login_Security::unblock_ip( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=bulk_unblocked' ) ); exit; } /** * Move a bulk selection of currently-blocked IPs onto the permanent blacklist. * Adds each IP to the blacklist and then clears its attempt counters. */ private function handle_bulk_blacklist_blocked() { if ( ! class_exists( 'GuardPress_Login_Security' ) ) { wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings' ) ); exit; } $raw = isset( $_POST['gp_ips'] ) ? sanitize_text_field( wp_unslash( $_POST['gp_ips'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified centrally in handle_actions() before any handler runs foreach ( $this->parse_bulk_ips( $raw ) as $ip ) { GuardPress_Login_Security::add_to_blacklist( $ip ); GuardPress_Login_Security::clear_failed_attempts( $ip ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=bulk_blacklisted' ) ); exit; } /** * Unblock ALL currently-blocked IPs in one sweep. This is equivalent to * clicking "Unblock" on every row of the Currently Blocked IPs table. * Uses a single UPDATE for efficiency instead of a row-by-row loop. */ private function handle_clear_all_blocked() { if ( class_exists( 'GuardPress_Login_Security' ) ) { $blocked = GuardPress_Login_Security::get_blocked_ips(); if ( is_array( $blocked ) ) { foreach ( array_keys( $blocked ) as $ip ) { GuardPress_Login_Security::unblock_ip( $ip ); } } } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=all_unblocked' ) ); exit; } private function handle_send_test_email() { $ok = false; if ( class_exists( 'GuardPress_Settings' ) && class_exists( 'GuardPress_Email_Notifier' ) ) { $ok = GuardPress_Email_Notifier::send_test_email( GuardPress_Settings::get() ); } wp_safe_redirect( admin_url( 'admin.php?page=guardpress_settings&gp_notice=' . ( $ok ? 'test_email_ok' : 'test_email_fail' ) ) ); exit; } // GP-REL-022 (audit 2026-06-19): handle_create_baseline(), handle_run_scan() // and handle_refresh_baseline() were removed together with their dispatcher // cases above. They were a synchronous second scan/baseline engine that // bypassed the scan lock, the MAX_FILES guard and the batched state machine, // and could leave baseline.json half-written while racing the AJAX path. No // view template emitted their commands; the live UI uses the batched AJAX // path (ajax_init_scan / ajax_init_baseline …), and cron/CLI call // GuardPress_Scan_Runner::run() directly. The single scan/baseline path is // now the lock-guarded, MAX_FILES-bounded batched state machine. private function handle_export_csv() { if ( ! current_user_can( 'manage_options' ) ) { return; } $report = class_exists( 'GuardPress_Scan_Runner' ) ? GuardPress_Scan_Runner::get_last_report() : array(); $details = isset( $report['details'] ) && is_array( $report['details'] ) ? $report['details'] : array(); nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); // FIX M-9 / hardening (audit 2026-05-25): X-Content-Type-Options // prevents browsers from MIME-sniffing the CSV as HTML if a stray //