options = get_option(self::OPTION_SETTINGS, []); require_once plugin_dir_path(__FILE__) . 'class-advaipbl-waf-manager.php'; require_once plugin_dir_path(__FILE__) . 'class-advaipbl-rate-limiting-manager.php'; require_once plugin_dir_path(__FILE__) . 'class-advaipbl-asn-manager.php'; require_once plugin_dir_path(__FILE__) . 'class-advaipbl-dashboard-manager.php'; $this->api_manager = new ADVAIPBL_Api_Manager(); $this->session_manager = new ADVAIPBL_User_Session_Manager($this, $this->api_manager); $this->waf_manager = new ADVAIPBL_Waf_Manager($this); $this->rate_limit_manager = new ADVAIPBL_Rate_Limiting_Manager($this); $this->asn_manager = new ADVAIPBL_Asn_Manager($this, $this->api_manager); $this->dashboard_manager = new ADVAIPBL_Dashboard_Manager($this); $this->add_hooks(); } private function add_hooks() { // Hooks del Frontend y Globales add_action('init', [$this, 'log_wp_cron_execution'], 1); add_action('init', [$this->rate_limit_manager, 'check_request_rate'], -1); add_action('init', [$this, 'run_all_block_checks'], 0); add_action('init', [$this, 'add_admin_ip_to_whitelist_on_first_run']); add_action('status_header', [$this, 'detect_http_error_status'], 10, 2); add_action('init', [$this, 'prevent_author_enumeration_redirect'], 9); add_action('wp_login_failed', [$this, 'registrar_intento_login_fallido']); add_action('login_init', [ $this, 'handle_login_page_restriction' ], 1 ); add_filter('rest_endpoints', [ $this, 'disable_rest_api_user_endpoints' ] ); if ( ! empty( $this->options['show_admin_bar_menu'] ) && '1' === $this->options['show_admin_bar_menu'] ) { add_action( 'admin_bar_menu', [ $this, 'add_admin_bar_menu' ], 999 ); } // Hooks de Cron add_action('advaipbl_purge_old_logs_event', [$this, 'purge_old_logs']); add_action('advaipbl_send_summary_email', [$this, 'process_and_send_summary']); add_filter('cron_schedules', [$this, 'add_cron_intervals']); add_action('advaipbl_clear_expired_blocks_event', [$this, 'limpiar_ips_expiradas']); // Hooks del Backend if (is_admin()) { add_action('admin_init', [$this, 'check_database_update']); add_action('admin_init', [$this, 'schedule_cron_jobs']); add_action('admin_init', [$this, 'conditionally_remove_admin_notices']); add_action('admin_menu', [$this, 'admin_menu']); add_action('admin_init', [$this, 'register_settings']); add_action('admin_init', [$this, 'handle_admin_actions']); add_action('update_option_' . self::OPTION_SETTINGS, [$this, 'on_settings_update'], 10, 2); add_action('update_option_' . self::OPTION_WAF_RULES, [$this, 'on_waf_rules_update'], 10, 2); add_action('admin_notices', [$this, 'display_admin_notice']); add_action('admin_enqueue_scripts', [$this, 'load_admin_scripts']); // Hooks de AJAX y Admin Post add_action('wp_ajax_advaipbl_test_outbound_connection', [$this, 'ajax_test_outbound_connection']); add_action('wp_ajax_advaipbl_add_ip_to_whitelist', [$this, 'ajax_add_ip_to_whitelist']); add_action('wp_ajax_advaipbl_verify_api_key', [$this, 'ajax_verify_api_key']); add_action('wp_ajax_advaipbl_get_dashboard_stats', [$this, 'ajax_get_dashboard_stats']); add_action('wp_ajax_advaipbl_export_settings_ajax', [ $this, 'handle_export_settings_ajax' ] ); add_action('admin_post_advaipbl_import_settings', [ $this, 'handle_import_settings' ] ); add_action('admin_post_advaipbl_clear_location_cache_action', [$this, 'handle_clear_cache_action']); add_action('admin_post_advaipbl_send_test_email', [ $this, 'handle_send_test_email' ] ); } if ( ! empty( $this->options['xmlrpc_protection_mode'] ) && 'disabled' === $this->options['xmlrpc_protection_mode'] ) { add_filter( 'xmlrpc_enabled', '__return_false' ); remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'wlwmanifest_link' ); } if ( !empty($this->options['recaptcha_enable']) && '1' === $this->options['recaptcha_enable'] && !empty($this->options['recaptcha_site_key']) && !empty($this->options['recaptcha_secret_key']) ) { add_action('login_enqueue_scripts', array($this, 'enqueue_recaptcha_script')); add_action('login_form', array($this, 'display_recaptcha_field')); add_filter('authenticate', array($this, 'validate_recaptcha_response'), 20, 3); } } public function ajax_get_dashboard_stats() { if (!current_user_can('manage_options')) { wp_send_json_error(['message' => 'Permission denied.']); } $stats = $this->dashboard_manager->get_dashboard_stats(); if ($stats) { wp_send_json_success($stats); } else { wp_send_json_error(['message' => 'Could not retrieve stats.']); } } /** * Detecta y registra las ejecuciones de WP-Cron. * Enganchada a 'init' con una prioridad alta para ejecutarse pronto. */ public function log_wp_cron_execution() { // wp-cron.php puede ser llamado de dos maneras. // 1. A través de una constante definida, que es la forma más común. // 2. A través de la URL, si alguien lo llama directamente. $is_doing_cron = ( defined( 'DOING_CRON' ) && DOING_CRON ); $is_cron_url = ( isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'wp-cron.php') !== false ); if ( $is_doing_cron || $is_cron_url ) { // Obtenemos los detalles de la petición $ip = $this->get_client_ip(); // Evitamos el "ruido" de registrar la misma IP repetidamente en un corto periodo. // Creamos un transient que dura 60 segundos. $transient_key = 'advaipbl_cron_log_lock_' . md5($ip); if ( false !== get_transient($transient_key) ) { return; // Ya hemos registrado esta IP recientemente. } set_transient($transient_key, true, 60); global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; $details = [ 'url' => $_SERVER['REQUEST_URI'] ?? 'N/A', 'method' => $_SERVER['REQUEST_METHOD'] ?? 'N/A', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'N/A', ]; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert( $table_name, [ 'timestamp' => current_time('mysql', 1), 'ip' => $ip, 'log_type' => 'wp_cron', // Usamos un tipo de log único 'level' => 'info', 'message' => __('WP-Cron execution triggered.', 'advanced-ip-blocker'), 'details' => wp_json_encode($details) ] ); } } /** * Muestra la tabla de logs específica para las ejecuciones de WP-Cron. * Esto es principalmente una herramienta de diagnóstico. */ private function display_cron_logs_tab() { // Añadimos una descripción para que el usuario sepa para qué es esta pestaña. echo '
'; esc_html_e( 'This log shows which IP addresses are triggering WP-Cron tasks on your site. This can be a visitor, a search engine bot, or your own server if you have configured a real cron job.', 'advanced-ip-blocker' ); echo '
%1$s) does not support this feature. Please switch to "ip-api.com" or "ipinfo.io" in the Settings tab to enable this functionality.', 'advanced-ip-blocker'),
['strong' => [], 'a' => ['href' => []]]
),
esc_html($provider),
esc_url(admin_url('admin.php?page=advaipbl_settings_page&tab=general_settings'))
);
?>
ipinfo.io website.', 'advanced-ip-blocker')); ?>
options['recaptcha_site_key'] ?? ''; $version = $this->options['recaptcha_version'] ?? 'v3'; if ('v2' === $version) { echo ''; } else { echo ''; ?> options['recaptcha_secret_key'] ?? ''; // La comprobación principal ya se hace en add_hooks, // pero si alguien modificara la opción mientras tanto, esto es un seguro. if (empty($secret_key)) { return $user; } if (!isset($_POST['g-recaptcha-response']) || empty($_POST['g-recaptcha-response'])) { return new WP_Error('recaptcha_empty', __('ERROR: Please complete the reCAPTCHA verification.', 'advanced-ip-blocker')); } $token = sanitize_text_field($_POST['g-recaptcha-response']); $visitor_ip = $this->get_client_ip(); $response = wp_remote_post('https://www.google.com/recaptcha/api/siteverify', array( 'body' => array( 'secret' => $secret_key, 'response' => $token, 'remoteip' => $visitor_ip, ), )); if (is_wp_error($response)) { return new WP_Error('recaptcha_api_error', __('ERROR: Could not connect to the reCAPTCHA service.', 'advanced-ip-blocker')); } $result = json_decode(wp_remote_retrieve_body($response), true); if (!isset($result['success']) || true !== $result['success']) { return new WP_Error('recaptcha_failed', __('ERROR: reCAPTCHA verification failed. Please try again.', 'advanced-ip-blocker')); } $version = $this->options['recaptcha_version'] ?? 'v3'; if ('v3' === $version) { $threshold = (float) ($this->options['recaptcha_score_threshold'] ?? 0.5); if (!isset($result['score']) || $result['score'] < $threshold) { return new WP_Error('recaptcha_low_score', __('ERROR: Your action was blocked as it was flagged as automated.', 'advanced-ip-blocker')); } } return $user; } /** * Detecta plugins activos que probablemente usan la interfaz XML-RPC. * * Utiliza una combinación de una lista de plugins conocidos y un análisis de los hooks de XML-RPC. * * @return array Un array con los nombres de los plugins detectados. Vacío si no se encuentra ninguno. */ private function get_xmlrpc_dependent_plugins() { $dependent_plugins = []; $active_plugins = get_option('active_plugins'); // 1. Lista de plugins conocidos que dependen de XML-RPC (basada en tu lista). $known_slugs = [ 'jetpack/jetpack.php', // Si encuentras más en el futuro, como la app de WooCommerce si usa un plugin puente. 'xmlrpc-debugger/xmlrpc-debugger.php' ]; foreach ($known_slugs as $slug) { if (in_array($slug, $active_plugins, true)) { $plugin_path = WP_PLUGIN_DIR . '/' . $slug; if (file_exists($plugin_path)) { $plugin_data = get_plugin_data($plugin_path); if (!empty($plugin_data['Name'])) { $dependent_plugins[$slug] = $plugin_data['Name']; } } } } // 2. Análisis de Hooks (Heurística). // Buscamos plugins que se enganchen a los eventos de XML-RPC. global $wp_filter; $xmlrpc_hooks = [ 'xmlrpc_methods', 'xmlrpc_call', 'xmlrpc_call_success', 'xmlrpc_call_failure', 'xmlrpc_before_insert_post', ]; foreach ($xmlrpc_hooks as $hook_name) { if (isset($wp_filter[$hook_name])) { foreach ($wp_filter[$hook_name]->callbacks as $priority => $callbacks) { foreach ($callbacks as $callback) { $function = $callback['function']; $reflection = null; try { if (is_array($function) && is_object($function[0])) { $reflection = new ReflectionClass($function[0]); } elseif (is_string($function) && function_exists($function)) { $reflection = new ReflectionFunction($function); } } catch (ReflectionException $e) { // Ignorar funciones/clases que no se pueden reflejar (ej. closures) continue; } if ($reflection) { $file_path = $reflection->getFileName(); // Comprobamos si la ruta del archivo está dentro del directorio de plugins. if ($file_path && strpos($file_path, WP_PLUGIN_DIR) !== false) { $plugin_dir_path = str_replace('\\', '/', WP_PLUGIN_DIR); $file_path = str_replace('\\', '/', $file_path); $relative_path = ltrim(str_replace($plugin_dir_path, '', $file_path), '/'); $plugin_slug_parts = explode('/', $relative_path); $plugin_folder = $plugin_slug_parts[0]; // Buscamos el nombre real del plugin para no mostrar solo el slug. foreach ($active_plugins as $active_plugin_slug) { if (strpos($active_plugin_slug, $plugin_folder) === 0) { if (!isset($dependent_plugins[$active_plugin_slug])) { $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $active_plugin_slug); if (!empty($plugin_data['Name'])) { $dependent_plugins[$active_plugin_slug] = $plugin_data['Name']; } } break; } } } } } } } } return array_values($dependent_plugins); } /** * Obtiene el número de IPs bloqueadas. * La primera vez que se llama, ejecuta la limpieza de IPs expiradas y cachea el resultado. * * @return int El número total de entradas bloqueadas. */ private function get_blocked_count() { // Si ya hemos calculado el conteo en esta petición, lo devolvemos directamente. if ( null !== $this->blocked_count ) { return $this->blocked_count; } // 1. Ejecutar la limpieza de IPs expiradas PRIMERO. $this->limpiar_ips_expiradas(); // 2. Obtener las entradas limpias y contarlas. $entries = $this->get_all_blocked_entries(); $this->blocked_count = count( $entries ); // 3. Devolver el conteo. return $this->blocked_count; } /** * AJAX callback to test the server's outbound connection. */ public function ajax_test_outbound_connection() { if ( ! current_user_can('manage_options') ) { wp_send_json_error( [ 'message' => 'Permission denied.' ] ); } check_ajax_referer( 'advaipbl_test_connection_nonce', 'nonce' ); $response = wp_remote_get('https://api.ipify.org?format=json', [ 'timeout' => 10 ]); if ( is_wp_error($response) ) { wp_send_json_error( [ 'message' => 'Error: ' . $response->get_error_message() ] ); } $http_code = wp_remote_retrieve_response_code( $response ); if ( $http_code !== 200 ) { wp_send_json_error( [ 'message' => sprintf( 'Error: Received HTTP status code %d.', $http_code ) ] ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( isset( $body['ip'] ) && filter_var( $body['ip'], FILTER_VALIDATE_IP ) ) { wp_send_json_success( [ 'message' => sprintf( 'Success! Connection established from IP: %s', $body['ip'] ) ] ); } wp_send_json_error( [ 'message' => 'Error: The response from the test service was invalid.' ] ); } /** * Gets the username of the current logged-in administrator. * * @return string The username or a default string if not available. */ private function get_current_admin_username() { $user = wp_get_current_user(); // Si el usuario existe y tiene un ID, devuelve su login. Si no, devuelve un texto genérico. return ( $user && $user->ID ) ? $user->user_login : __( 'an unknown user', 'advanced-ip-blocker' ); } /** * Añade una entrada (IP o rango) a la whitelist y se asegura de que sea eliminada * de todas las listas de bloqueo. Este es el método centralizado para esta acción. * * @param string $entry_to_whitelist La IP o rango a añadir a la whitelist. * @param string $detail Una descripción de por qué se añadió. * @return bool True si la entrada se añadió con éxito, false si ya existía. */ public function add_to_whitelist_and_unblock( $entry_to_whitelist, $detail ) { if ( ! $this->is_valid_ip_or_range( $entry_to_whitelist ) ) { return false; } $whitelist = get_option( self::OPTION_WHITELIST, [] ); if ( array_key_exists( $entry_to_whitelist, $whitelist ) ) { return false; } $whitelist[ $entry_to_whitelist ] = [ 'timestamp' => time(), 'detail' => $detail ]; update_option( self::OPTION_WHITELIST, $whitelist ); if ( filter_var( $entry_to_whitelist, FILTER_VALIDATE_IP ) ) { $this->desbloquear_ip( $entry_to_whitelist ); } else { // Usar el mapa de constantes para limpiar el rango de TODAS las listas. $option_key_map = [ 'geoblock' => self::OPTION_BLOCKED_GEO, 'honeypot' => self::OPTION_BLOCKED_HONEYPOT, 'user_agent' => self::OPTION_BLOCKED_USER_AGENT, 'manual' => self::OPTION_BLOCKED_MANUAL, '404' => self::OPTION_BLOCKED_404, '403' => self::OPTION_BLOCKED_403, 'login' => self::OPTION_BLOCKED_LOGIN, ]; foreach ( $option_key_map as $type => $option_key ) { $list = get_option( $option_key, [] ); if ( is_array($list) && array_key_exists( $entry_to_whitelist, $list ) ) { unset( $list[ $entry_to_whitelist ] ); update_option( $option_key, $list ); } } } /* translators: 1: The whitelisted IP/range, 2: The admin username. */ $this->log_event( sprintf( __( 'Entry %1$s added to whitelist by %2$s.', 'advanced-ip-blocker' ), $entry_to_whitelist, $this->get_current_admin_username() ), 'info', is_array($entry_to_whitelist) ? wp_json_encode($entry_to_whitelist) : $entry_to_whitelist ); return true; } /** * AJAX callback to add a specific IP to the whitelist. * This is used by the interactive buttons in the admin interface. */ public function ajax_add_ip_to_whitelist() { // 1. Validar permisos y nonce de seguridad (esto no cambia). if ( ! current_user_can('manage_options') ) { wp_send_json_error( [ 'message' => __( 'Permission denied.', 'advanced-ip-blocker' ) ] ); } check_ajax_referer( 'advaipbl_add_whitelist_nonce', 'nonce' ); // 2. Obtener y validar la IP del POST. Esta función AJAX solo maneja IPs individuales. if ( ! isset( $_POST['ip'] ) || ! filter_var( wp_unslash( $_POST['ip'] ), FILTER_VALIDATE_IP ) ) { wp_send_json_error( [ 'message' => __( 'Invalid or missing IP address.', 'advanced-ip-blocker' ) ] ); } $ip = sanitize_text_field( wp_unslash( $_POST['ip'] ) ); $detail = isset( $_POST['detail'] ) ? sanitize_text_field( wp_unslash( $_POST['detail'] ) ) : __('Added via admin action', 'advanced-ip-blocker'); // 3. Reutilizar nuestra nueva lógica centralizada. $success = $this->add_to_whitelist_and_unblock( $ip, $detail ); if ( $success ) { /* translators: %s: The IP address that was successfully whitelisted. */ wp_send_json_success( [ 'message' => sprintf( __( '%s successfully added to the whitelist.', 'advanced-ip-blocker' ), $ip ) ] ); } else { /* translators: %s: The IP address that is already whitelisted. */ wp_send_json_success( [ 'message' => sprintf( __( '%s is already whitelisted.', 'advanced-ip-blocker' ), $ip ) ] ); } } public function handle_clear_cache_action() { if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'advaipbl_clear_location_cache_nonce')) { wp_die('Invalid nonce.'); } if (!current_user_can('manage_options')) { wp_die('Permission denied.'); } delete_transient(ADVAIPBL_USM_LOCATION_CACHE_KEY); /* translators: %s: Admin username. */ $this->log_event( sprintf( __( 'User session location cache manually cleared by %s.', 'advanced-ip-blocker' ), $this->get_current_admin_username() ), 'info' ); set_transient('advaipbl_admin_notice', ['message' => __('Location cache has been cleared.', 'advanced-ip-blocker'), 'type' => 'success'], 30); wp_safe_redirect(wp_get_referer()); exit; } /** * Envuelve el contenido de un email en una plantilla HTML básica y profesional. * * @param string $subject El asunto del email. * @param string $content_html El contenido principal del email en HTML. * @return string El cuerpo completo del email en HTML. */ private function get_html_email_template( $subject, $content_html ) { $site_name = get_bloginfo( 'name' ); $site_url = home_url(); $settings_url = admin_url( 'options-general.php?page=advaipbl_settings_page' ); $logo_url = plugin_dir_url( dirname( __FILE__ ) ) . 'assets/img/logo-email.png'; // Estilos CSS en línea $body_style = "background-color: #f6f7f8; padding: 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';"; $wrapper_style = "background-color: #ffffff; border: 1px solid #e0e0e0; border-radius: 4px; padding: 40px; max-width: 600px; margin: 0 auto;"; $logo_wrapper_style = "text-align: center; margin-bottom: 25px;"; // Estilos flexibles para el logo $logo_style = "max-width: 220px; height: auto; border: 0; display: inline-block; vertical-align: middle;"; $header_style = "font-size: 24px; font-weight: bold; color: #2271b1; margin-top: 0; margin-bottom: 20px; text-align: center;"; $footer_style = "font-size: 12px; color: #777777; text-align: center; margin-top: 30px; line-height: 1.6; border-top: 1px solid #e0e0e0; padding-top: 20px;"; ob_start(); ?>
settings page.', 'advanced-ip-blocker' ),
[ 'a' => [ 'href' => [], 'style' => [] ] ]
),
esc_url( $settings_url )
);
echo '
';
/* translators: 1: Plugin name, 2: Plugin version. */
printf( esc_html__( 'Sent by %1$s v%2$s', 'advanced-ip-blocker' ), 'Advanced IP Blocker', esc_html( ADVAIPBL_VERSION ) );
?>
' . esc_html__( 'Thank you for using Advanced IP Blocker! This email confirms your email settings are working. Here is a quick guide to get the most out of the plugin:', 'advanced-ip-blocker' ) . '
' . '' . /* translators: %s: a link to the Status & Debug tab. */ sprintf( wp_kses( __( 'This is the most important step to prevent locking yourself out. Go to the Status & Debug tab to confirm that your IP address and your server\'s IP are correctly detected. If they are not on the whitelist, add them with a single click.', 'advanced-ip-blocker' ), [ 'a' => [ 'href' => [] ] ] ), esc_url( add_query_arg( 'tab', 'status', $settings_url ) ) ) . '
' . '' .
/* translators: %s: a link to the User Agents tab. */
sprintf(
wp_kses(
__( 'Go to the User Agents tab and copy the suggested list of malicious bots into the "Blocked" text area.', 'advanced-ip-blocker' ),
[ 'a' => [ 'href' => [] ] ]
),
esc_url( add_query_arg( 'tab', 'user_agents', $settings_url ) )
) . '
' .
/* translators: %s: a link to the Honeypot URLs tab. */
sprintf(
wp_kses(
__( 'Then, go to the Honeypot URLs tab and do the same. This will immediately block thousands of common automated attacks.', 'advanced-ip-blocker' ),
[ 'a' => [ 'href' => [] ] ]
),
esc_url( add_query_arg( 'tab', 'honeypot', $settings_url ) )
) .
'
' . /* translators: %s: a link to the main Settings tab. */ sprintf( wp_kses( __( 'Finally, visit the main Settings tab to enable logging and configure notification frequency to your liking. The default blocking rules are a great starting point for most sites.', 'advanced-ip-blocker' ), [ 'a' => [ 'href' => [] ] ] ), esc_url( add_query_arg( 'tab', 'general_settings', $settings_url ) ) ) . '
'; // 4. Envolver en la plantilla y enviar (usando las nuevas variables) $body = $this->get_html_email_template( $template_title, $content_html ); add_filter( 'wp_mail_content_type', [ $this, 'set_html_mail_content_type' ] ); $sent = wp_mail( $to, $email_subject, $body ); remove_filter( 'wp_mail_content_type', [ $this, 'set_html_mail_content_type' ] ); // 5. Lógica de notificación y redirección if ( $sent ) { $message = __( 'The setup guide has been sent successfully to your configured email address.', 'advanced-ip-blocker' ); $type = 'success'; /* translators: 1: Recipient's email address, 2: Admin username */ $this->log_event( sprintf( __( 'Setup guide sent to %1$s by %2$s.', 'advanced-ip-blocker' ), $to, $this->get_current_admin_username() ), 'info' ); } else { $message = __( 'Failed to send the setup guide email. Please check your site\'s email configuration.', 'advanced-ip-blocker' ); $type = 'error'; /* translators: 1: Recipient's email address, 2: Admin username */ $this->log_event( sprintf( __( 'FAILED to send setup guide to %1$s. Action by %2$s.', 'advanced-ip-blocker' ), $to, $this->get_current_admin_username() ), 'error' ); } set_transient( 'advaipbl_admin_notice', [ 'message' => $message, 'type' => $type ], 30 ); wp_safe_redirect( wp_get_referer() ); exit; } public function load_admin_scripts($hook) { // 1. Comprobamos si estamos en CUALQUIERA de las páginas de nuestro plugin. // El hook de la página principal es 'toplevel_page_advaipbl_settings_page' // Los hooks de las subpáginas son 'security_page_advaipbl_settings_page-settings', etc. // Usar strpos es la forma más fiable de detectarlas todas. if ( strpos( $hook, 'advaipbl_settings_page' ) === false ) { return; } // --- Carga de scripts y estilos comunes para todas las páginas del plugin --- $this->session_manager->enqueue_scripts_styles(); wp_enqueue_style( 'advaipbl-select2-css', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/css/select2.min.css', [], '4.1.0-rc.0' ); wp_enqueue_script( 'advaipbl-select2-js', plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/select2.min.js', [ 'jquery' ], '4.1.0-rc.0', true ); wp_enqueue_script( 'advaipbl-admin-js', plugin_dir_url( dirname( __FILE__ ) ) . 'js/advaipbl-admin.js', [ 'jquery', 'advaipbl-select2-js' ], ADVAIPBL_VERSION, true ); $floating_bar_css = " #advaipbl-floating-save-bar { position: fixed; bottom: 0; left: 160px; /* Ancho del menú de admin */ right: 0; background-color: #fff; box-shadow: 0 -2px 5px rgba(0,0,0,0.1); padding: 15px 30px; z-index: 999; transition: transform 0.3s ease-in-out; transform: translateY(100%); /* Oculto por defecto */ } #advaipbl-floating-save-bar.advaipbl-save-bar-visible { transform: translateY(0); /* Visible */ } .advaipbl-save-bar-content { display: flex; justify-content: space-between; align-items: center; max-width: 1200px; margin: 0 auto; } .advaipbl-save-bar-text { font-size: 1.1em; font-weight: 600; } .advaipbl-save-bar-buttons .button { margin-left: 10px; } @media screen and (max-width: 960px) { #advaipbl-floating-save-bar { left: 36px; /* Ancho del menú de admin colapsado */ } } @media screen and (max-width: 782px) { #advaipbl-floating-save-bar { left: 0; padding: 10px 15px; } .advaipbl-save-bar-text { display: none; /* Ocultar texto en móviles para más espacio */ } .advaipbl-save-bar-content { justify-content: flex-end; } }"; wp_add_inline_style('advaipbl-select2-css', $floating_bar_css); // Enganchamos al CSS existente $server_ip = $this->get_server_ip(); $server_info = [ 'ip' => $server_ip, 'country_code' => '', 'country_name' => '', 'is_whitelisted' => false ]; if ( $server_ip ) { $location = $this->api_manager->fetch_location( $server_ip ); if ( $location && empty($location['error']) ) { $server_info['country_code'] = $location['country_code'] ?? ''; $server_info['country_name'] = $location['country'] ?? ''; } $server_info['is_whitelisted'] = $this->is_whitelisted( $server_ip ); } $admin_ip = $this->get_client_ip(); $admin_info = [ 'ip' => $admin_ip, 'country_code' => '', 'country_name' => '', 'is_whitelisted' => false ]; if ( $admin_ip && filter_var( $admin_ip, FILTER_VALIDATE_IP ) ) { $location = $this->api_manager->fetch_location( $admin_ip ); if ( $location && empty($location['error']) ) { $admin_info['country_code'] = $location['country_code'] ?? ''; $admin_info['country_name'] = $location['country'] ?? ''; } $admin_info['is_whitelisted'] = $this->is_whitelisted( $admin_ip ); } $blocked_count = count( $this->get_all_blocked_entries() ); // Usamos un nombre de objeto genérico y una estructura más organizada. wp_localize_script( 'advaipbl-admin-js', 'advaipbl_admin_data', [ 'counts' => [ 'blocked' => $blocked_count, ], 'geoblock' => [ 'server' => $server_info, 'admin' => $admin_info, 'blocked_countries' => $this->options['geoblock_countries'] ?? [], ], 'nonces' => [ 'test_connection' => wp_create_nonce( 'advaipbl_test_connection_nonce' ), 'add_whitelist' => wp_create_nonce( 'advaipbl_add_whitelist_nonce' ), 'export' => wp_create_nonce( 'advaipbl_export_nonce' ), 'verify_api' => wp_create_nonce( 'advaipbl_verify_api_nonce' ), 'get_dashboard_stats' => wp_create_nonce( 'wp_ajax_advaipbl_get_dashboard_stats' ) // <-- Añadir Nonce para el dashboard ], 'text' => [ 'server_whitelisted' => __( 'Info: Your server is located in %1$s and its IP (%2$s) is correctly whitelisted. You can safely block this country.', 'advanced-ip-blocker' ), 'server_not_whitelisted' => __( 'CRITICAL WARNING! Your server is located in %1$s and its IP (%2$s) is NOT whitelisted. Blocking this country WILL likely break your site. Please add the server IP to the whitelist BEFORE blocking this country.', 'advanced-ip-blocker' ), 'admin_whitelisted' => __( 'Info: Your current IP address (%1$s) from %2$s is whitelisted. You will not be locked out if you block this country.', 'advanced-ip-blocker' ), 'admin_not_whitelisted' => __( 'Caution: Your current IP address (%1$s) from %2$s is NOT whitelisted. If you block this country, you may lose access to your admin panel.', 'advanced-ip-blocker' ), 'remove_server_ip_warning' => __( 'CRITICAL WARNING: This IP (%1$s) belongs to your server, located in a blocked country (%2$s). REMOVING IT FROM THE WHITELIST WILL LIKELY BREAK YOUR SITE!', 'advanced-ip-blocker' ), 'remove_admin_ip_warning' => __( 'CAUTION: This is your current IP address (%1$s) from a blocked country (%2$s). REMOVING THIS IP FROM THE WHITELIST MAY LOCK YOU OUT OF YOUR ADMIN PANEL.', 'advanced-ip-blocker' ), 'confirm_removal' => __( 'Are you absolutely sure you want to proceed?', 'advanced-ip-blocker' ), 'add_to_whitelist_btn' => __( 'Add to Whitelist', 'advanced-ip-blocker' ), 'adding_to_whitelist' => __( 'Adding...', 'advanced-ip-blocker' ), 'added_to_whitelist' => __( 'Successfully Added!', 'advanced-ip-blocker' ), 'select2_placeholder' => __( 'Search for a country to block...', 'advanced-ip-blocker' ), 'verify_api_button' => __( 'Verify', 'advanced-ip-blocker' ), 'verifying_api' => __( 'Verifying...', 'advanced-ip-blocker' ), 'enter_api_key' => __( 'Please enter an API key.', 'advanced-ip-blocker' ), 'ajax_error' => __( 'AJAX error. Check browser console.', 'advanced-ip-blocker' ), 'discard_title' => __( 'Discard Changes?', 'advanced-ip-blocker' ), 'discard_message' => __( 'You have unsaved changes. Are you sure you want to discard them?', 'advanced-ip-blocker' ), 'discard_confirm_btn' => __( 'Yes, Discard', 'advanced-ip-blocker' ), 'attacks_label' => __( 'attacks', 'advanced-ip-blocker' ), 'blocks_label' => __( 'blocks', 'advanced-ip-blocker' ), ], ] ); // 2. LÓGICA MEJORADA PARA DETERMINAR LA SUB-PESTAÑA ACTIVA $active_sub_tab = null; $current_page_slug = isset($_GET['page']) ? sanitize_key($_GET['page']) : ''; if (isset($_GET['sub-tab'])) { // Si la sub-pestaña está explícitamente en la URL, la usamos. $active_sub_tab = sanitize_key($_GET['sub-tab']); } else { // Si no, la deducimos del slug de la página (que viene del $hook). // Este mapa debe coincidir con el de settings_page_content. $page_slug_to_sub_tab_map = [ 'advaipbl_settings_page' => 'main_dashboard', 'advaipbl_settings_page-settings' => 'general_settings', 'advaipbl_settings_page-rules' => 'waf', 'advaipbl_settings_page-ip-management' => 'blocked_ips', 'advaipbl_settings_page-logs' => 'security_log', 'advaipbl_settings_page-about' => 'credits', ]; if (isset($page_slug_to_sub_tab_map[$current_page_slug])) { $active_sub_tab = $page_slug_to_sub_tab_map[$current_page_slug]; } } // --- Carga de scripts condicionales --- if ('main_dashboard' === $active_sub_tab) { wp_enqueue_script( 'chartjs', 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js', [], '3.9.1', true ); wp_enqueue_script( 'advaipbl-dashboard-js', plugin_dir_url( dirname( __FILE__ ) ) . 'js/advaipbl-dashboard.js', ['jquery', 'chartjs'], ADVAIPBL_VERSION, true ); } if ('credits' === $active_sub_tab) { wp_enqueue_script( 'stripe-buy-button', 'https://js.stripe.com/v3/buy-button.js', [], null, true ); } } public function detect_http_error_status($status_header, $code) { if ($this->error_handled_this_request || is_admin()) { return; } $excluded_urls = $this->options['excluded_error_urls'] ?? ''; if (!empty($excluded_urls)) { $excluded_list = array_filter(array_map('trim', explode("\n", $excluded_urls))); $current_url = isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : ''; foreach ($excluded_list as $excluded_item) { if (!empty($excluded_item) && stripos($current_url, $excluded_item) !== false) { return; } } } if ($code === 404) { $this->error_handled_this_request = true; $ip = $this->get_client_ip(); if ($this->is_whitelisted($ip)) return; $honeypot_urls = get_option('advaipbl_honeypot_urls', []); if (!empty($honeypot_urls)) { $requested_url = isset($_SERVER['REQUEST_URI']) ? strtolower(esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))) : ''; foreach ($honeypot_urls as $trap_url) { if (!empty($trap_url) && stripos($requested_url, strtolower(trim($trap_url))) !== false) { $reason = sprintf(__('Honeypot URL accessed: %s', 'advanced-ip-blocker'), $trap_url); $this->block_ip_instantly($ip, 'honeypot', $reason, ['url' => $requested_url]); } } } $this->handle_error('404'); } elseif ($code === 403) { $this->error_handled_this_request = true; $ip = $this->get_client_ip(); $all_block_types = ['geoblock', 'honeypot', '404', '403', 'login', 'user_agent', 'waf', 'rate_limit', 'asn', 'xmlrpc_block']; //['geoblock', 'honeypot', 'manual', '404', '403', 'login', 'user_agent', 'waf', 'rate_limit', 'asn', 'xmlrpc_block']; foreach ($all_block_types as $type) { if (get_transient('advaipbl_bloqueo_' . $type . '_' . md5($ip))) { return; } } // Si la IP no tenía un bloqueo por transient, procedemos a contar el error 403. $this->handle_error('403'); } } /** * Renders the checkbox for the Whitelist Login Access feature, including security checks. */ public function restrict_login_page_callback() { $args = [ 'name' => 'restrict_login_page', 'label' => __( 'Restrict access to wp-login.php to whitelisted IPs only', 'advanced-ip-blocker' ) ]; $client_ip = $this->get_client_ip(); $is_whitelisted = $this->is_whitelisted( $client_ip ); // Llama al callback del checkbox normal $this->checkbox_field_callback($args); // Añadimos la advertencia de seguridad echo '' . esc_html__( 'WARNING: This is a highly restrictive feature. Only enable it if you have a static IP address and public user registration is disabled on your site.', 'advanced-ip-blocker' ) . '
'; // Si la IP del admin no está en la whitelist, mostramos un aviso y un botón para añadirla if ( ! $is_whitelisted ) { echo ''; /* translators: %s: The admin's current IP address. */ echo '' . sprintf( esc_html__( 'Your current IP address (%s) is NOT whitelisted.', 'advanced-ip-blocker' ), esc_html( $client_ip ) ) . ' ' . esc_html__( 'You MUST add it to the whitelist before enabling this feature, or you will be locked out.', 'advanced-ip-blocker' ); echo ''; echo '
' . esc_html__("An IP address has been automatically blocked on your website.", 'advanced-ip-blocker') . '
' . '| ' . esc_html__('Blocked IP', 'advanced-ip-blocker') . ' | ' . esc_html($ip) . ' |
| ' . esc_html__('Date and Time', 'advanced-ip-blocker') . ' | ' . esc_html(self::get_formatted_datetime(time())) . ' |
| ' . esc_html__('Reason', 'advanced-ip-blocker') . ' | ' . esc_html($reason) . ' |
| ' . esc_html__('Block Duration', 'advanced-ip-blocker') . ' | ' . esc_html($duration_text) . ' |
' . esc_html__( 'Here is your security summary for the last period.', 'advanced-ip-blocker' ) . '
'; $summary_html .= '| ' . esc_html__('Time', 'advanced-ip-blocker') . ' | ' . '' . esc_html__('Blocked IP', 'advanced-ip-blocker') . ' | ' . '' . esc_html__('Reason', 'advanced-ip-blocker') . ' | ' . '
|---|---|---|
| ' . esc_html( self::get_formatted_datetime( $notification->timestamp ) ) . ' | ' . '' . esc_html( $notification->ip ) . ' | ' . '' . esc_html( $notification->reason ) . ' | ' . '
| ' . '' . esc_html__( 'Manage All Blocked IPs', 'advanced-ip-blocker' ) . '' . ' |
' . esc_html__( "An IP address has been automatically blocked on your website.", 'advanced-ip-blocker' ) . '
' . '| ' . esc_html__( 'Blocked IP', 'advanced-ip-blocker' ) . ' | ' . esc_html( $ip ) . ' |
| ' . esc_html__( 'Date and Time', 'advanced-ip-blocker' ) . ' | ' . esc_html( self::get_formatted_datetime(time()) ) . ' |
| ' . esc_html__( 'Reason', 'advanced-ip-blocker' ) . ' | ' . esc_html( $reason ) . ' |
| ' . esc_html__( 'Block Duration', 'advanced-ip-blocker' ) . ' | ' . esc_html( $duration_text ) . ' |
' . esc_html__( 'No action is required on your part. This is just a notification.', 'advanced-ip-blocker' ) . '
'. '| ' . '' . esc_html__( 'View Blocked IPs', 'advanced-ip-blocker' ) . '' . ' |
%2$s