options = get_option('advaipbl_settings', []); $this->session_manager = new ADVAIPBL_User_Session_Manager($this); $this->add_hooks(); } private function add_hooks() { 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('wp_login_failed', [$this, 'registrar_intento_login_fallido']); add_action('advaipbl_purge_old_logs_event', [$this, 'purge_old_logs']); add_filter('cron_schedules', [$this, 'add_cron_intervals']); add_action('advaipbl_send_summary_email', [$this, 'process_and_send_summary']); add_action('admin_post_advaipbl_clear_location_cache_action', [$this, 'handle_clear_cache_action']); if (is_admin()) { add_action('admin_init', [$this, 'check_database_update']); add_action('admin_init', [$this, 'schedule_cron_jobs']); add_action('admin_menu', [$this, 'admin_menu']); add_action('admin_init', [$this, 'register_settings']); add_action('admin_init', [$this, 'handle_admin_actions']); add_action('admin_init', [$this, 'limpiar_ips_expiradas']); add_action('update_option_' . 'advaipbl_settings', [$this, 'on_settings_update'], 10, 2); add_action('admin_notices', [$this, 'display_admin_notice']); add_action('admin_enqueue_scripts', [$this, 'load_admin_scripts']); } } 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); $this->log_event(__('User session location cache manually cleared.', 'advanced-ip-blocker'), 'info'); // Creamos un aviso para el usuario. set_transient('advaipbl_admin_notice', ['message' => __('Location cache has been cleared.', 'advanced-ip-blocker'), 'type' => 'success'], 30); // Redirigimos de vuelta a la página de ajustes. wp_safe_redirect(wp_get_referer()); exit; } public function load_admin_scripts($hook) { if ( 'settings_page_advaipbl_settings_page' !== $hook ) { return; } // Saneamos la entrada $_GET para evitar warnings. // phpcs:ignore WordPress.Security.NonceVerification.Recommended $current_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : 'general'; if ( in_array( $current_tab, [ 'user_sessions', 'blocked_ips', 'general' ], true ) ) { $this->session_manager->enqueue_scripts_styles(); } if ( 'credits' === $current_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))); // Saneamos la variable $_SERVER. $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)) { // Saneamos la variable $_SERVER. $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) { /* translators: %s: The specific honeypot URL that was accessed. */ $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; $this->handle_error('403'); } } public function run_all_block_checks() { $ip = $this->get_client_ip(); if ($this->is_whitelisted($ip)) { return; } // Primero, comprobamos si la IP ya está bloqueada por CUALQUIER motivo. $block_reasons = ['honeypot', 'manual', '404', '403', 'login', 'user_agent']; foreach ($block_reasons as $type) { if (get_transient('advaipbl_bloqueo_' . $type . '_' . md5($ip))) { $this->access_denied_page( __('403 - Access Denied', 'advanced-ip-blocker'), $this->get_block_message($type) ); } } // Saneamos la variable $_SERVER antes de usarla. $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : ''; if (!empty($user_agent) && !$this->is_internal_request($user_agent)) { $is_ua_whitelisted = false; $whitelisted_user_agents = get_option('advaipbl_whitelisted_user_agents', []); if (!empty($whitelisted_user_agents)) { foreach ($whitelisted_user_agents as $whitelisted_ua) { if (!empty($whitelisted_ua) && stripos($user_agent, trim($whitelisted_ua)) !== false) { $is_ua_whitelisted = true; break; } } } if (!$is_ua_whitelisted) { $blocked_user_agents = get_option('advaipbl_blocked_user_agents', []); if (!empty($blocked_user_agents)) { foreach ($blocked_user_agents as $blocked_ua) { if (!empty($blocked_ua) && stripos($user_agent, trim($blocked_ua)) !== false) { /* translators: %s: The User-Agent pattern that was blocked. */ $reason_message = sprintf(__('Blocked User-Agent pattern: %s', 'advanced-ip-blocker'), $blocked_ua); $this->block_ip_instantly($ip, 'user_agent', $reason_message, ['user_agent' => $user_agent]); } } } } } } public function get_all_blocked_ips_for_cli() { $all_blocked = []; $block_types = [ 'honeypot' => __('Honeypot', 'advanced-ip-blocker'), 'user_agent' => __('User-Agent', 'advanced-ip-blocker'), 'manual' => __('Manual', 'advanced-ip-blocker'), '404' => __('404 Error', 'advanced-ip-blocker'), '403' => __('403 Error', 'advanced-ip-blocker'), 'login' => __('Login Failure', 'advanced-ip-blocker'), ]; foreach ( $block_types as $type => $label ) { $key = 'advaipbl_ips_bloqueadas_' . $type; $ips = get_option( $key, [] ); if ( ! is_array($ips) ) continue; foreach ( $ips as $ip => $block_data ) { $timestamp = is_array($block_data) ? ($block_data['timestamp'] ?? time()) : $block_data; $detail = is_array($block_data) ? ($block_data['detail'] ?? '') : ''; $all_blocked[] = [ 'ip' => $ip, 'type' => $type, 'type_label' => $label, 'timestamp' => self::get_formatted_datetime($timestamp), 'detail' => $detail, ]; } } usort($all_blocked, function($a, $b) { return strtotime($b['timestamp']) <=> strtotime($a['timestamp']); }); return $all_blocked; } private function is_whitelisted($ip) { $whitelist = get_option('advaipbl_ips_whitelist', []); return !empty($whitelist) && array_key_exists($ip, $whitelist); } private function is_internal_request($user_agent) { return strpos($user_agent, 'WordPress/') === 0; } private function get_block_message($type) { $messages = [ 'honeypot' => __('Access blocked due to suspicious activity.', 'advanced-ip-blocker'), 'manual' => __('Access manually blocked.', 'advanced-ip-blocker'), '404' => __('Access blocked due to repeated 404 errors.', 'advanced-ip-blocker'), '403' => __('Access blocked due to repeated attempts on protected resources.', 'advanced-ip-blocker'), 'login' => __('Access blocked due to multiple failed login attempts.', 'advanced-ip-blocker'), 'user_agent' => __('Access blocked due to suspicious User-Agent.', 'advanced-ip-blocker') ]; return $messages[$type] ?? __('Access blocked.', 'advanced-ip-blocker'); } private function block_ip_instantly($ip, $type, $reason_message, $extra_data = []) { $block_key = 'advaipbl_bloqueo_' . $type . '_' . md5($ip); if (get_transient($block_key)) return; $duration_key = 'duration_' . $type; $duration = (int) ($this->options[$duration_key] ?? 1440) * 60; $option_key = 'advaipbl_ips_bloqueadas_' . $type; set_transient($block_key, true, $duration); $list = get_option($option_key, []); $block_details = ['timestamp' => time()]; if ($type === 'user_agent' && isset($extra_data['user_agent'])) { $block_details['detail'] = $extra_data['user_agent']; } elseif ($type === 'honeypot' && isset($extra_data['url'])) { $block_details['detail'] = $extra_data['url']; } $list[$ip] = $block_details; update_option($option_key, $list); /* translators: 1: The blocked IP address, 2: The reason for the block. */ $log_message = sprintf(__('IP %1$s instantly blocked. Reason: %2$s', 'advanced-ip-blocker'), $ip, $reason_message); $this->log_event($log_message, 'critical', $extra_data); $this->send_block_notification($ip, $type, 1, $extra_data); $this->access_denied_page(__('403 - Access Denied', 'advanced-ip-blocker'), __('Access blocked due to suspicious activity.', 'advanced-ip-blocker')); exit; } public function add_admin_ip_to_whitelist_on_first_run() { if (get_option('advaipbl_admin_ip_whitelist_trigger')) { if (!wp_doing_cron() && is_user_logged_in() && current_user_can('manage_options')) { $ip = $this->get_client_ip(); // Saneamos la variable $_SERVER. $server_addr = isset($_SERVER['SERVER_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_ADDR'])) : ''; if (filter_var($ip, FILTER_VALIDATE_IP) && $ip !== $server_addr) { $whitelist = get_option('advaipbl_ips_whitelist', []); if (!isset($whitelist[$ip])) { $whitelist[$ip] = time(); update_option('advaipbl_ips_whitelist', $whitelist); /* translators: %s: The administrator's IP address. */ $this->log_event(sprintf(__('Administrator IP (%s) automatically added to whitelist during activation/update.', 'advanced-ip-blocker'), $ip), 'info'); } delete_option('advaipbl_admin_ip_whitelist_trigger'); } } } } public function schedule_cron_jobs() { if (!wp_next_scheduled('advaipbl_purge_old_logs_event')) { wp_schedule_event(time(), 'daily', 'advaipbl_purge_old_logs_event'); } $freq = $this->options['notification_frequency'] ?? 'disabled'; if (($freq === 'daily' || $freq === 'weekly') && !wp_next_scheduled('advaipbl_send_summary_email')) { $this->schedule_notification_cron(); } } public function purge_old_logs() { $this->options = get_option('advaipbl_settings', []); $retention_days = (int) ($this->options['log_retention_days'] ?? 30); if ($retention_days <= 0) return; global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query($wpdb->prepare("DELETE FROM $table_name WHERE timestamp < DATE_SUB(NOW(), INTERVAL %d DAY)", $retention_days)); } public function check_database_update() { if (get_option('ip_blocker_pro_db_version') != ADVAIPBL_DB_VERSION) { self::setup_database_tables(); } if (get_option('ip_blocker_pro_log_migration_status') !== 'complete') { $this->migrate_old_logs(); } } private function migrate_old_logs() { global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; $logs_migrated = 0; $log_types_to_migrate = ['404', '403']; foreach ($log_types_to_migrate as $type) { $option_name = ADVAIPBL_PLUGIN_NAME . "_{$type}_errors_log"; $old_logs = get_option($option_name, []); if (empty($old_logs)) { delete_option($option_name); continue; } foreach ($old_logs as $log_entry) { if (!is_array($log_entry) || !isset($log_entry['ip']) || !isset($log_entry['timestamp'])) continue; $details = ['url' => $log_entry['url'] ?? '', 'method' => $log_entry['method'] ?? 'N/A', 'referrer' => $log_entry['referrer'] ?? 'N/A', 'user_agent' => $log_entry['user_agent'] ?? 'N/A']; /* translators: %s: The error type, e.g., 404 or 403. */ $message = sprintf(__("A %s error occurred (migrated).", 'advanced-ip-blocker'), $type); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery if ($wpdb->insert($table_name, ['timestamp' => date_i18n('Y-m-d H:i:s', $log_entry['timestamp']), 'ip' => $log_entry['ip'], 'log_type' => $type, 'level' => 'warning', 'message' => $message, 'details' => wp_json_encode($details)])) { $logs_migrated++; } } delete_option($option_name); } if ($logs_migrated > 0) { /* translators: %d: The number of migrated log records. */ $this->log_event(sprintf(__('%d old log records have been migrated to the new table.', 'advanced-ip-blocker'), $logs_migrated), 'info'); } update_option('ip_blocker_pro_log_migration_status', 'complete'); } public static function setup_database_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); $table_name_logs = $wpdb->prefix . 'advaipbl_logs'; $sql_logs = "CREATE TABLE $table_name_logs ( log_id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', ip VARCHAR(100) NOT NULL, log_type VARCHAR(20) NOT NULL, level VARCHAR(20) NOT NULL, message TEXT NOT NULL, details LONGTEXT NULL, PRIMARY KEY (log_id), KEY ip (ip(16)), KEY log_type (log_type), KEY timestamp (timestamp) ) $charset_collate;"; dbDelta($sql_logs); $table_name_queue = $wpdb->prefix . 'advaipbl_notifications_queue'; $sql_queue = "CREATE TABLE $table_name_queue ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, timestamp DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00', ip VARCHAR(100) NOT NULL, block_type VARCHAR(20) NOT NULL, reason TEXT NOT NULL, PRIMARY KEY (id), KEY timestamp (timestamp) ) $charset_collate;"; dbDelta($sql_queue); update_option('ip_blocker_pro_db_version', ADVAIPBL_DB_VERSION); } public static function get_formatted_datetime($timestamp) { if (!is_numeric($timestamp)) { $timestamp = strtotime($timestamp); } if ($timestamp === false) { return __('Invalid date', 'advanced-ip-blocker'); } $options = get_option('advaipbl_settings', []); $timezone_string = $options['log_timezone'] ?? wp_timezone_string(); try { $date = new DateTime('@' . $timestamp); $timezone = new DateTimeZone($timezone_string); $date->setTimezone($timezone); return $date->format('Y-m-d H:i:s T'); } catch (Exception $e) { $format = get_option('date_format') . ' ' . get_option('time_format'); return date_i18n($format, $timestamp); } } public function get_client_ip() { if ( null !== $this->client_ip ) { return $this->client_ip; } $headers = [ 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR', ]; foreach ( $headers as $header ) { if ( isset( $_SERVER[ $header ] ) ) { // Saneamos la cabecera antes de procesarla. $header_value = sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ); $ips = explode( ',', $header_value ); foreach ( $ips as $ip ) { $ip = trim( $ip ); if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false ) { $this->client_ip = $ip; return $this->client_ip; } } } } $this->client_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '0.0.0.0'; return $this->client_ip; } public function log_event( $message, $level = 'info', $details = [] ) { if ( empty( $this->options['enable_logging'] ) ) { return; } global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert( $table_name, [ 'timestamp' => current_time( 'mysql', 1 ), 'ip' => $this->get_client_ip(), 'log_type' => 'general', 'level' => $level, 'message' => $message, 'details' => ! empty( $details ) ? wp_json_encode( $details ) : null, ] ); } private function log_specific_error($type, $ip) { if (empty($this->options['enable_logging'])) { return; } global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; $details = [ 'url' => isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : '', 'method' => isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : 'N/A', 'referrer' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : 'N/A', 'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : 'N/A', ]; /* translators: %s: The error type, e.g., 404 or 403. */ $message = sprintf(__("A %s error occurred.", 'advanced-ip-blocker'), $type); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert( $table_name, [ 'timestamp' => current_time('mysql', 1), 'ip' => $ip, 'log_type' => $type, 'level' => 'warning', 'message' => $message, 'details' => wp_json_encode($details) ] ); } public function registrar_intento_login_fallido($username) { $this->handle_error('login', ['username' => $username]); } private function handle_error($type, $extra_data = []) { $ip = $this->get_client_ip(); if ($this->is_whitelisted($ip)) { return; } $block_reasons = ['honeypot', 'manual', '404', '403', 'login', 'user_agent']; foreach ($block_reasons as $reason_type) { if (get_transient('advaipbl_bloqueo_' . $reason_type . '_' . md5($ip))) { $this->log_specific_error($type, $ip, $extra_data); return; } } $this->log_specific_error($type, $ip, $extra_data); $s = $this->options; $minute_in_seconds = 60; $threshold = (int) ($s["threshold_{$type}"] ?? 5); $window = (int) ($s["transient_expiration_{$type}"] ?? 60) * $minute_in_seconds; $count_key = "advaipbl_errores_{$type}_" . md5($ip); $detail_key = "advaipbl_detail_{$type}_" . md5($ip); $errors = (int) get_transient($count_key) + 1; if ($errors === 1) { $detail_to_store = ($type === 'login') ? ($extra_data['username'] ?? '') : (isset($_SERVER['REQUEST_URI']) ? esc_url_raw(wp_unslash($_SERVER['REQUEST_URI'])) : ''); set_transient($detail_key, $detail_to_store, $window); } set_transient($count_key, $errors, $window); if ($errors >= $threshold) { $trigger_detail = get_transient($detail_key) ?: 'N/A'; self::$block_queue = [ 'ip' => $ip, 'type' => $type, 'trigger' => $trigger_detail, 'to' => !empty($this->options['notification_email']) && is_email($this->options['notification_email']) ? $this->options['notification_email'] : get_option('admin_email'), 'options' => $this->options, 'errors' => $errors, ]; if (!self::$shutdown_hook_registered) { register_shutdown_function([$this, 'execute_shutdown_block']); self::$shutdown_hook_registered = true; } delete_transient($count_key); delete_transient($detail_key); } } /** * Versión simplificada para procesar el bloqueo en el shutdown. * Envía un email de texto plano sin usar funciones complejas de WP. */ public function execute_shutdown_block() { if (empty(self::$block_queue)) { return; } $q = self::$block_queue; $ip = $q['ip']; $type = $q['type']; $trigger = $q['trigger']; $to = $q['to']; $options = $q['options']; $errors = (isset($q['errors']) && is_numeric($q['errors'])) ? $q['errors'] : (isset($q['count']) ? $q['count'] : 1); // 1. Acciones de bloqueo $duration = (int) ($options["duration_{$type}"] ?? 120) * 60; $block_key = "advaipbl_bloqueo_{$type}_" . md5($ip); $option_key = "advaipbl_ips_bloqueadas_{$type}"; set_transient($block_key, true, $duration); $list = get_option($option_key, []); if (!is_array($list)) $list = []; $list[$ip] = ['timestamp' => time(), 'detail' => $trigger]; update_option($option_key, $list); // 2. Lógica de email $notification_enabled = !empty($options['enable_email_notifications']) && '1' === $options['enable_email_notifications']; $frequency = $options['notification_frequency'] ?? 'disabled'; $email_sent = null; if ($notification_enabled && $frequency === 'instant') { $site_host = wp_parse_url(home_url(), PHP_URL_HOST) ?: 'Your Website'; /* translators: %s: Site name. */ $subject = sprintf(__('[%s] Security Alert: IP Automatically Blocked', 'advanced-ip-blocker'), $site_host); $duration_minutes = (int) ($options["duration_{$type}"] ?? 120); $reason_text = "Type: " . strtoupper($type) . ", Trigger: " . $trigger; if($errors > 1) { $reason_text .= ", Errors: " . $errors; } $body_lines = [ __("Hello,", 'advanced-ip-blocker'), "", /* translators: %s: Site name. */ sprintf(__("An IP address has been automatically blocked on your website '%s'.", 'advanced-ip-blocker'), $site_host), "", __("Block Details:", 'advanced-ip-blocker'), "-------------------------------------", /* translators: %s: IP Address. */ sprintf(__("Blocked IP: %s", 'advanced-ip-blocker'), $ip), /* translators: %s: The date and time of the block. */ sprintf(__("Date and Time: %s", 'advanced-ip-blocker'), self::get_formatted_datetime(time())), /* translators: %s: Reason for the block. */ sprintf(__("Reason: %s", 'advanced-ip-blocker'), $reason_text), /* translators: %d: Duration in minutes. */ sprintf(__("Block Duration: %d minutes", 'advanced-ip-blocker'), $duration_minutes), "-------------------------------------", "", __("No action is required on your part.", 'advanced-ip-blocker'), "", "--", /* translators: 1: Plugin name, 2: Plugin version. */ sprintf(__('Sent by %1$s v%2$s', 'advanced-ip-blocker'), 'Advanced IP Blocker', ADVAIPBL_VERSION) ]; $body = implode("\n", $body_lines); $email_sent = wp_mail($to, $subject, $body); } elseif ($notification_enabled && in_array($frequency, ['daily', 'weekly'])) { global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_notifications_queue'; $reason_for_summary = sprintf( /* translators: 1: Number of errors, 2: Error type (e.g., 404), 3: Triggering URL. */ __('Generated %1$d %2$s errors. Triggering URL: %3$s', 'advanced-ip-blocker'), $errors, strtoupper($type), $trigger ); // phpcs:ignore WordPress.WP.I18n.InterpolatedVariableText.Found, WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert( $table_name, ['timestamp' => current_time('mysql', 1), 'ip' => $ip, 'block_type' => $type, 'reason' => $reason_for_summary], ['%s', '%s', '%s', '%s'] ); } // 3. Loguear los eventos de forma segura if (!empty($options['enable_logging']) && '1' === $options['enable_logging']) { global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; $log_message_critical = sprintf( 'IP %1$s blocked via shutdown: %2$d %3$s errors. Notification action: %4$s.', $ip, $errors, strtoupper($type), $frequency ); // phpcs:ignore WordPress.WP.I18n.InterpolatedVariableText.Found, WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert($table_name, [ 'timestamp' => current_time('mysql', 1), 'ip' => $ip, 'log_type' => 'general', 'level' => 'critical', 'message' => $log_message_critical, 'details' => wp_json_encode(['trigger' => $trigger]) ]); if (is_bool($email_sent)) { $email_log_level = $email_sent ? 'info' : 'error'; $email_log_message = $email_sent ? /* translators: 1: The blocked IP address. 2: The email address the notification was sent to. */ sprintf(__('Block notification for IP %1$s sent to %2$s.', 'advanced-ip-blocker'), $ip, $to) : /* translators: 1: The blocked IP address. 2: The email address the notification was sent to. */ sprintf(__('FAILED to send block notification for IP %1$s to %2$s.', 'advanced-ip-blocker'), $ip, $to); // phpcs:ignore WordPress.WP.I18n.InterpolatedVariableText.Found, WordPress.DB.DirectDatabaseQuery.DirectQuery @$wpdb->insert($table_name, [ 'timestamp' => current_time('mysql', 1), 'ip' => $ip, 'log_type' => 'general', 'level' => $email_log_level, 'message' => $email_log_message, 'details' => '' ]); } } } public function add_cron_intervals($schedules) { $schedules['weekly'] = ['interval' => 604800, 'display' => esc_html__('Once Weekly', 'advanced-ip-blocker')]; return $schedules; } public function schedule_notification_cron() { $frequency = $this->options['notification_frequency'] ?? 'disabled'; $this->clear_notification_cron(); if ($frequency === 'daily' || $frequency === 'weekly') { $timestamp = strtotime('tomorrow 2:00 am'); wp_schedule_event($timestamp, $frequency, 'advaipbl_send_summary_email'); } } public function clear_notification_cron() { wp_clear_scheduled_hook('advaipbl_send_summary_email'); } public function process_and_send_summary() { global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_notifications_queue'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $notifications = $wpdb->get_results("SELECT * FROM $table_name ORDER BY timestamp ASC"); if (empty($notifications)) { return; } $total_blocks = count($notifications); $blocks_by_type = []; foreach ($notifications as $notification) { $blocks_by_type[$notification->block_type][] = $notification; } $to = !empty($this->options['notification_email']) && is_email($this->options['notification_email']) ? $this->options['notification_email'] : get_option('admin_email'); $site_name = get_bloginfo('name'); /* translators: 1: Site name, 2: Total number of blocked IPs. */ $subject = sprintf(__('[%1$s] Security Summary: %2$d IPs Blocked', 'advanced-ip-blocker'), $site_name, $total_blocks); $body_lines = [ __('Hello,', 'advanced-ip-blocker'), '', /* translators: %s: Site name. */ sprintf(__("This is your security summary for the site '%s'.", 'advanced-ip-blocker'), $site_name), '', /* translators: %d: Total number of blocked IPs. */ sprintf(__('Total IPs blocked: %d', 'advanced-ip-blocker'), $total_blocks), '-------------------------------------', '' ]; foreach ( $blocks_by_type as $type => $blocks ) { $type_capitalized = ucfirst( $type ); $block_count = count( $blocks ); // Separamos la traducción del sprintf para evitar el falso positivo del linter. /* translators: 1: Block type (e.g. Honeypot, 404). 2: Number of blocks. */ $summary_line = __( 'Blocks by %1$s: %2$d', 'advanced-ip-blocker' ); $body_lines[] = sprintf( $summary_line, $type_capitalized, $block_count ); } $body_lines[] = ''; $body_lines[] = '--- ' . __('Some recent blocks', 'advanced-ip-blocker') . ' ---'; $details_limit = 10; $limited_notifications = array_slice($notifications, -$details_limit); foreach ( $limited_notifications as $notification ) { $formatted_date = self::get_formatted_datetime( $notification->timestamp ); $ip_address = $notification->ip; $block_reason = $notification->reason; // Separamos la traducción del sprintf para evitar el falso positivo. /* translators: 1: Date and time, 2: IP address, 3: Reason. */ $detail_line = __( '- %1$s | IP: %2$s | Reason: %3$s', 'advanced-ip-blocker' ); $body_lines[] = sprintf( $detail_line, $formatted_date, $ip_address, $block_reason ); } $body_lines[] = ''; $body_lines[] = '-------------------------------------'; $body_lines[] = ''; $body_lines[] = '--'; /* translators: 1: Plugin name, 2: Plugin version. */ $body_lines[] = sprintf(__('Sent by %1$s v%2$s', 'advanced-ip-blocker'), 'Advanced IP Blocker', ADVAIPBL_VERSION); $body = implode("\n", $body_lines); $sent = wp_mail($to, $subject, $body); if ($sent) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query("TRUNCATE TABLE $table_name"); $this->log_event(sprintf('CRON aibp_send_summary_email: Summary sent to %s and queue cleared.', $to), 'info'); } else { $this->log_event(sprintf('CRON aibp_send_summary_email: FAILED to send summary to %s. Queue NOT cleared.', $to), 'error'); } } private function send_block_notification($ip, $type, $count, $extra_data) { if ( empty($this->options['enable_email_notifications']) || '1' !== $this->options['enable_email_notifications'] ) { return; } $frequency = $this->options['notification_frequency'] ?? 'disabled'; if ('disabled' === $frequency) { return; } $reason = __('Unknown reason', 'advanced-ip-blocker'); switch ($type) { case '404': case '403': $error_type_upper = strtoupper($type); $trigger_url = $extra_data['trigger'] ?? 'N/A'; /* translators: 1: Number of errors (integer), 2: Error type (e.g., 404), 3: The URL that triggered the block. */ $reason = sprintf(__("Generated %1\$d %2\$s errors. Triggering URL: %3\$s", 'advanced-ip-blocker'), $count, $error_type_upper, $trigger_url); break; case 'login': $username = isset($extra_data['trigger']) ? sanitize_text_field($extra_data['trigger']) : __('unknown', 'advanced-ip-blocker'); /* translators: 1: Number of failed login attempts (integer), 2: The username used in the attempts. */ $reason_format = __('Made %1$d failed login attempts for user: %2$s', 'advanced-ip-blocker'); $reason = sprintf($reason_format, $count, $username); break; case 'honeypot': $honeypot_url = $extra_data['url'] ?? 'N/A'; /* translators: %s: The honeypot URL that was accessed. */ $reason = sprintf(__('Accessed Honeypot URL: %s', 'advanced-ip-blocker'), $honeypot_url); break; case 'user_agent': $user_agent_string = $extra_data['user_agent'] ?? 'N/A'; /* translators: %s: The blocked User-Agent string. */ $reason = sprintf(__('Used a blocked User-Agent: %s', 'advanced-ip-blocker'), $user_agent_string); break; } if ($frequency === 'instant') { $to = !empty($this->options['notification_email']) && is_email($this->options['notification_email']) ? $this->options['notification_email'] : get_option('admin_email'); $site_name = get_bloginfo('name'); /* translators: %s: The name of the website. */ $subject = sprintf(__('[%s] Security Alert: IP Automatically Blocked', 'advanced-ip-blocker'), $site_name); $duration_minutes = (int) ($this->options['duration_' . $type] ?? 120); $body_lines = [ __("Hello,", 'advanced-ip-blocker'), "", /* translators: %s: The name of the website. */ sprintf(__("An IP address has been automatically blocked on your website '%s'.", 'advanced-ip-blocker'), $site_name), "", __("Block Details:", 'advanced-ip-blocker'), "-------------------------------------", /* translators: %s: The blocked IP address. */ sprintf(__("Blocked IP: %s", 'advanced-ip-blocker'), esc_html($ip)), /* translators: %s: The date and time of the block. */ sprintf(__("Date and Time: %s", 'advanced-ip-blocker'), self::get_formatted_datetime(time())), /* translators: %s: The reason for the block. */ sprintf(__("Reason: %s", 'advanced-ip-blocker'), esc_html($reason)), /* translators: %d: The duration of the block in minutes. */ sprintf(__("Block Duration: %d minutes", 'advanced-ip-blocker'), $duration_minutes), "-------------------------------------", "", __("No action is required on your part.", 'advanced-ip-blocker'), "", "--", /* translators: 1: Plugin name, 2: Plugin version. */ sprintf(__('Sent by %1$s v%2$s', 'advanced-ip-blocker'), 'Advanced IP Blocker', ADVAIPBL_VERSION) ]; $body = implode("\n", $body_lines); $sent = wp_mail($to, $subject, $body); if ($sent) { /* translators: 1: The blocked IP address. 2: The email address the notification was sent to. */ $this->log_event(sprintf(__('Block notification for IP %1$s sent to %2$s.', 'advanced-ip-blocker'), $ip, $to), 'info'); } else { /* translators: 1: The blocked IP address. 2: The email address the notification failed to send to. */ $this->log_event(sprintf(__('FAILED to send block notification for IP %1$s to %2$s.', 'advanced-ip-blocker'), $ip, $to), 'error'); } } else { global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_notifications_queue'; // phpcs:ignore WordPress.WP.I18n.InterpolatedVariableText.Found, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->insert($table_name, [ 'timestamp' => current_time('mysql', 1), 'ip' => $ip, 'block_type' => $type, 'reason' => $reason ]); } } public function on_settings_update($old_value, $new_value) { $this->log_settings_change($old_value, $new_value); $old_freq = $old_value['notification_frequency'] ?? 'disabled'; $new_freq = $new_value['notification_frequency'] ?? 'disabled'; if ($old_freq !== $new_freq) { wp_clear_scheduled_hook('advaipbl_send_summary_email'); if ($new_freq === 'daily' || $new_freq === 'weekly') { $this->schedule_notification_cron(); } } } public function log_settings_change($old_value, $new_value) { $user = wp_get_current_user(); $username = ($user && $user->ID) ? $user->user_login : __('an unknown user', 'advanced-ip-blocker'); $changed_fields = []; foreach ($new_value as $key => $value) { if (!isset($old_value[$key]) || $old_value[$key] !== $value) { $changed_fields[] = $key; } } if (empty($changed_fields)) { return; } $fields_string = implode(', ', $changed_fields); // phpcs:ignore WordPress.WP.I18n.InterpolatedVariableText $message = sprintf( /* translators: 1: The username. 2: A comma-separated list of changed fields. */ __('Plugin settings updated by %1$s. Changed fields: %2$s', 'advanced-ip-blocker'), $username, $fields_string ); $this->log_event($message, 'info'); } private function access_denied_page($title, $message) { if (isset($this->block_response_initiated) && $this->block_response_initiated) { exit; } $this->block_response_initiated = true; if ( ! headers_sent() ) { status_header(403); } $custom_message = $this->options['custom_block_message'] ?? ''; $display_message = ! empty($custom_message) ? nl2br(esc_html($custom_message)) : esc_html($message); // La función wp_die escapa el título, pero es buena práctica escapar el mensaje antes. wp_die( wp_kses_post($display_message), esc_html($title) ); } public function desbloquear_ip($ip) { // La lista ya incluye 'manual', por lo que esta función es correcta. // Solo verificamos que la lista esté completa. foreach (['404', '403', 'login', 'manual', 'honeypot', 'user_agent'] as $type) { delete_transient("advaipbl_bloqueo_{$type}_" . md5($ip)); // Los contadores solo existen para los bloqueos por umbral. if (in_array($type, ['404', '403', 'login'])) { delete_transient("advaipbl_errores_{$type}_" . md5($ip)); delete_transient("advaipbl_detail_{$type}_" . md5($ip)); } $key = 'advaipbl_ips_bloqueadas_' . $type; $list = get_option($key, []); if ( is_array($list) && array_key_exists($ip, $list) ) { unset($list[$ip]); update_option($key, $list); } } /* translators: %s: The IP address that was manually unblocked. */ $this->log_event(sprintf(__('IP %s manually unblocked.', 'advanced-ip-blocker'), $ip)); } public function limpiar_ips_expiradas() { foreach (['404', '403', 'login', 'honeypot', 'user_agent'] as $type) { $key = ADVAIPBL_PLUGIN_NAME . "_ips_bloqueadas_{$type}"; $list = get_option($key, []); if ( ! is_array($list) ) continue; foreach ($list as $ip => $block_data) { if (!get_transient("advaipbl_bloqueo_{$type}_" . md5($ip))) { unset($list[$ip]); /* translators: 1: The unblocked IP address. 2: The type of block that expired (e.g., 404, login). */ $this->log_event(sprintf(__('IP %1$s automatically unblocked (expired %2$s).', 'advanced-ip-blocker'), $ip, $type)); } } update_option($key, $list); } } public function get_default_settings() { return [ 'threshold_404' => 10, 'duration_404' => 120, 'transient_expiration_404' => 60, 'threshold_403' => 5, 'duration_403' => 60, 'transient_expiration_403' => 30, 'threshold_login' => 5, 'duration_login' => 120, 'transient_expiration_login' => 60, 'duration_honeypot' => 1440, 'duration_user_agent' => 1440, 'enable_logging' => '1', 'custom_block_message' => '', 'excluded_error_urls' => '', 'enable_email_notifications' => '0', // Correcto: desactivado por defecto. 'notification_frequency' => 'disabled', 'notification_email' => '', 'log_timezone' => wp_timezone_string(), 'log_retention_days' => 30, 'geolocation_provider' => 'ip-api.com', 'api_key_ipapicom' => '', 'api_key_ipstackcom' => '', 'api_key_ipinfocom' => '', 'api_key_ip_apicom' => '', 'delete_data_on_uninstall' => '0' ]; } public static function activate_plugin() { self::setup_database_tables(); if ( ! wp_next_scheduled( 'advaipbl_purge_old_logs_event' ) ) { wp_schedule_event( time(), 'daily', 'advaipbl_purge_old_logs_event' ); } $existing_options = get_option( 'advaipbl_settings', [] ); $instance = self::get_instance(); $defaults = $instance->get_default_settings(); $updated_options = wp_parse_args( $existing_options, $defaults ); if ( $updated_options !== $existing_options ) { update_option( 'advaipbl_settings', $updated_options ); } $notification_frequency = $updated_options['notification_frequency'] ?? 'disabled'; if ( 'disabled' !== $notification_frequency && 'instant' !== $notification_frequency ) { if ( ! wp_next_scheduled( 'advaipbl_send_summary_email' ) ) { $instance->schedule_notification_cron(); } } add_option( 'advaipbl_blocked_user_agents', [], '', 'no' ); add_option( 'advaipbl_whitelisted_user_agents', [], '', 'no' ); add_option( 'advaipbl_ips_whitelist', [], '', 'no' ); add_option( 'advaipbl_ips_bloqueadas_manual', [], '', 'no' ); add_option( 'advaipbl_ips_bloqueadas_honeypot', [], '', 'no' ); add_option( 'advaipbl_ips_bloqueadas_user_agent', [], '', 'no' ); add_option( ADVAIPBL_USM_OPTION_PER_PAGE, ADVAIPBL_USM_DEFAULT_PER_PAGE, '', 'no' ); add_option( 'advaipbl_honeypot_urls', [], '', 'no' ); update_option( 'ip_blocker_pro_log_migration_status', 'pending' ); add_option( 'advaipbl_admin_ip_whitelist_trigger', 'yes', '', 'no' ); } public static function deactivate_plugin() { wp_clear_scheduled_hook('advaipbl_purge_old_logs_event'); $instance = self::get_instance(); $instance->clear_notification_cron(); } public function admin_menu() { add_options_page( __( 'Advanced IP Blocker Settings', 'advanced-ip-blocker' ), __( 'Advanced IP Blocker', 'advanced-ip-blocker' ), 'manage_options', 'advaipbl_settings_page', [ $this, 'settings_page_content' ] ); } public function display_admin_notice() { $notice = get_transient('advaipbl_admin_notice'); if ( $notice ) { $type = ( 'success' === $notice['type'] ) ? 'success' : 'error'; printf( '

%2$s

', esc_attr( $type ), esc_html( $notice['message'] ) // Escapamos aquí directamente. ); delete_transient('advaipbl_admin_notice'); } } public function handle_admin_actions() { // Saneamos el nonce antes de verificarlo. $nonce = isset( $_POST['advaipbl_admin_nonce_action'] ) ? sanitize_text_field( wp_unslash( $_POST['advaipbl_admin_nonce_action'] ) ) : ''; if ( empty( $_POST['action_type'] ) || ! wp_verify_nonce( $nonce, 'advaipbl_admin_nonce_action' ) ) { return; } if (!current_user_can('manage_options')) { return; } $action = sanitize_key($_POST['action_type']); $message = ''; $type = 'info'; $current_user_login = wp_get_current_user()->user_login; if ($action === 'save_user_agents') { $blocked_raw = isset($_POST['blocked_user_agents']) ? sanitize_textarea_field(wp_unslash($_POST['blocked_user_agents'])) : ''; update_option('advaipbl_blocked_user_agents', array_filter(array_map('trim', explode("\n", $blocked_raw)))); $whitelisted_raw = isset($_POST['whitelisted_user_agents']) ? sanitize_textarea_field(wp_unslash($_POST['whitelisted_user_agents'])) : ''; update_option('advaipbl_whitelisted_user_agents', array_filter(array_map('trim', explode("\n", $whitelisted_raw)))); /* translators: %s: The username of the user who updated the lists. */ $this->log_event(sprintf(__('User-Agent lists updated by %s.', 'advanced-ip-blocker'), $current_user_login), 'info'); $message = __('User-Agent lists saved successfully.', 'advanced-ip-blocker'); $type = 'success'; } elseif ($action === 'clear_location_cache') { delete_transient(ADVAIPBL_USM_LOCATION_CACHE_KEY); /* translators: %s: The username of the user who cleared the cache. */ $this->log_event(sprintf(__('User session location cache cleared by %s.', 'advanced-ip-blocker'), $current_user_login), 'info'); $message = __('Location cache has been cleared.', 'advanced-ip-blocker'); $type = 'success'; } elseif ($action === 'save_honeypot_urls') { $urls_raw = isset($_POST['honeypot_urls']) ? sanitize_textarea_field(wp_unslash($_POST['honeypot_urls'])) : ''; update_option('advaipbl_honeypot_urls', array_filter(array_map('trim', explode("\n", $urls_raw)))); /* translators: %s: The username of the user who updated the list. */ $this->log_event(sprintf(__('Honeypot URLs list updated by %s.', 'advanced-ip-blocker'), $current_user_login), 'info'); $message = __('Honeypot URLs list saved successfully.', 'advanced-ip-blocker'); $type = 'success'; } elseif ($action === 'clear_specific_logs') { global $wpdb; $log_type_to_clear = isset($_POST['log_type_to_clear']) ? sanitize_key(wp_unslash($_POST['log_type_to_clear'])) : ''; if (in_array($log_type_to_clear, ['404', '403'], true)) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete($wpdb->prefix . 'advaipbl_logs', ['log_type' => $log_type_to_clear], ['%s']); $log_type_upper = strtoupper($log_type_to_clear); /* translators: 1: The log type (e.g., "404"). 2: The username of the user who deleted the logs. */ $this->log_event(sprintf(__('%1$s logs manually deleted by %2$s.', 'advanced-ip-blocker'), $log_type_upper, $current_user_login), 'warning'); /* translators: %s: The type of log that was deleted (e.g., "404"). */ $message = sprintf(__('%s logs deleted.', 'advanced-ip-blocker'), $log_type_upper); $type = 'success'; } } elseif ($action === 'clear_all_logs') { global $wpdb; $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}advaipbl_logs`"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->query("TRUNCATE TABLE `{$wpdb->prefix}advaipbl_notifications_queue`"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $this->log_event(__('All records have been manually deleted from the log table.', 'advanced-ip-blocker'), 'critical'); $message = __('All logs have been deleted.', 'advanced-ip-blocker'); $type = 'success'; } else { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized $ip = isset($_POST['ip_address']) ? sanitize_text_field(trim(wp_unslash($_POST['ip_address']))) : null; if ($ip && !filter_var($ip, FILTER_VALIDATE_IP)) { $message = __('The entered IP is not valid.', 'advanced-ip-blocker'); $type = 'error'; } elseif ($ip) { switch ($action) { case 'add_manual_block': $list = get_option( 'advaipbl_ips_bloqueadas_manual', [] ); if ( ! array_key_exists( $ip, $list ) ) { $list[ $ip ] = [ 'timestamp' => time(), 'detail' => __( 'Manual Block', 'advanced-ip-blocker' ) ]; update_option( 'advaipbl_ips_bloqueadas_manual', $list ); set_transient( 'advaipbl_bloqueo_manual_' . md5( $ip ), true, 10 * YEAR_IN_SECONDS ); /* translators: %s: The manually blocked IP address. */ $this->log_event( sprintf( __( 'IP %s manually blocked.', 'advanced-ip-blocker' ), $ip ) ); /* translators: %s: The manually blocked IP address. */ $message = sprintf( __( 'IP %s blocked.', 'advanced-ip-blocker' ), $ip ); $type = 'success'; } else { /* translators: %s: The IP address that was already blocked. */ $message = sprintf( __( 'IP %s was already blocked.', 'advanced-ip-blocker' ), $ip ); } break; case 'remove_block': $this->desbloquear_ip( $ip ); /* translators: %s: The unblocked IP address. */ $message = sprintf( __( 'IP %s unblocked.', 'advanced-ip-blocker' ), $ip ); $type = 'success'; break; case 'add_whitelist': $list = get_option( 'advaipbl_ips_whitelist', [] ); if ( ! array_key_exists( $ip, $list ) ) { $list[ $ip ] = time(); update_option( 'advaipbl_ips_whitelist', $list ); $this->desbloquear_ip( $ip ); /* translators: %s: The IP address added to the whitelist. */ $this->log_event( sprintf( __( 'IP %s added to whitelist.', 'advanced-ip-blocker' ), $ip ) ); /* translators: %s: The IP address added to the whitelist. */ $message = sprintf( __( 'IP %s added to whitelist and unblocked.', 'advanced-ip-blocker' ), $ip ); $type = 'success'; } else { /* translators: %s: The IP address that was already in the whitelist. */ $message = sprintf( __( 'IP %s was already in the whitelist.', 'advanced-ip-blocker' ), $ip ); } break; case 'remove_whitelist': $list = get_option( 'advaipbl_ips_whitelist', [] ); unset( $list[ $ip ] ); update_option( 'advaipbl_ips_whitelist', $list ); /* translators: %s: The IP address removed from the whitelist. */ $this->log_event( sprintf( __( 'IP %s removed from whitelist.', 'advanced-ip-blocker' ), $ip ) ); /* translators: %s: The IP address removed from the whitelist. */ $message = sprintf( __( 'IP %s removed from whitelist.', 'advanced-ip-blocker' ), $ip ); $type = 'success'; break; } } } if ($message) { set_transient('advaipbl_admin_notice', ['message' => $message, 'type' => $type], 30); } wp_safe_redirect(remove_query_arg(['settings-updated', 's'], wp_get_referer())); exit; } public function settings_page_content() { if (!current_user_can('manage_options')) return; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'general'; settings_errors('advaipbl_notices'); ?>

display_user_agents_tab();break; case 'honeypot':$this->display_honeypot_tab();break; case 'blocked_ips':$this->display_blocked_ips_tab();break; case 'whitelist':$this->display_whitelist_tab();break; case '404_logs':$this->display_log_table('404');break; case '403_logs':$this->display_log_table('403');break; case 'user_sessions':$this->session_manager->display_admin_page();break; case 'logs':$this->display_logs_tab();break; case 'credits':$this->display_credits_tab();break; default: $this->display_general_settings_tab(); break; } ?>


/blog/ or /contact/). Use attack-specific patterns.', 'advanced-ip-blocker') ); ?>


get_all_blocked_ips_for_cli(); $all_ips = wp_list_pluck($all_blocked_data, 'ip'); $locations = $this->session_manager->get_cached_locations($all_ips); // phpcs:disable WordPress.Security.NonceVerification.Recommended $filter_type = isset($_GET['filter_type']) ? sanitize_key(wp_unslash($_GET['filter_type'])) : 'all'; $orderby = isset($_GET['orderby']) && in_array(wp_unslash($_GET['orderby']), ['ip', 'type', 'timestamp'], true) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'timestamp'; $order = isset($_GET['order']) && in_array(strtolower(wp_unslash($_GET['order'])), ['asc', 'desc'], true) ? strtolower(sanitize_key(wp_unslash($_GET['order']))) : 'desc'; $current_page = isset($_GET['paged']) ? absint(wp_unslash($_GET['paged'])) : 1; $page_slug = isset($_REQUEST['page']) ? sanitize_key(wp_unslash($_REQUEST['page'])) : ''; // phpcs:enable $filtered_data = $all_blocked_data; if ('all' !== $filter_type) { $filtered_data = array_filter($all_blocked_data, function($block) use ($filter_type) { return $block['type'] === $filter_type; }); } usort($filtered_data, function($a, $b) use ($orderby, $order) { $a_val = $a[$orderby] ?? ''; $b_val = $b[$orderby] ?? ''; if ($a_val == $b_val) return 0; return ($order === 'asc') ? ($a_val < $b_val ? -1 : 1) : ($a_val > $b_val ? -1 : 1); }); $per_page = 20; $total_items = count($filtered_data); $total_pages = ceil($total_items / $per_page); $items_for_page = array_slice($filtered_data, ($current_page - 1) * $per_page, $per_page); ?>
add_query_arg('paged', '%#%'), 'format' => '', 'total' => $total_pages, 'current' => $current_page]); if ($page_links) echo wp_kses_post($page_links); ?>
print_sortable_header(__('IP', 'advanced-ip-blocker'), 'ip', $orderby, $order); ?> print_sortable_header(__('Block Type', 'advanced-ip-blocker'), 'type_label', $orderby, $order); ?> print_sortable_header(__('Since', 'advanced-ip-blocker'), 'timestamp', $orderby, $order); ?>

$column_key, 'order' => $next_order, 'filter_type' => $filter_type_sanitized, ]); echo '' . esc_html($label) . ''; } private function print_log_sortable_header($label, $column_key, $orderby, $order) { $next_order = ($orderby === $column_key && 'asc' === $order) ? 'desc' : 'asc'; $arrow_class = ($orderby === $column_key) ? 'sorted ' . $order : 'sortable desc'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $search_term_sanitized = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : ''; $url = add_query_arg([ 'orderby' => $column_key, 'order' => $next_order, 's' => $search_term_sanitized, ]); echo '' . esc_html($label) . ''; } private function display_whitelist_tab() { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $current_tab = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : ''; $whitelist_key = 'advaipbl_ips_whitelist'; $whitelist_ips = get_option($whitelist_key, []); if (is_admin() && !wp_doing_ajax() && 'whitelist' === $current_tab && !empty($whitelist_ips) && is_int(key($whitelist_ips))) { $migrated_whitelist = []; foreach ($whitelist_ips as $ip) { if (is_string($ip) && filter_var($ip, FILTER_VALIDATE_IP)) { $migrated_whitelist[$ip] = time(); } } update_option($whitelist_key, $migrated_whitelist); $whitelist_ips = $migrated_whitelist; } $whitelist_data = []; if (is_array($whitelist_ips)) { foreach ($whitelist_ips as $ip => $timestamp) { if (is_int($ip) && filter_var($timestamp, FILTER_VALIDATE_IP)) { // Formato antiguo $whitelist_data[] = ['ip' => $timestamp, 'timestamp' => 0]; } elseif (filter_var($ip, FILTER_VALIDATE_IP)) { // Formato nuevo $whitelist_data[] = ['ip' => $ip, 'timestamp' => $timestamp]; } } } // phpcs:disable WordPress.Security.NonceVerification.Recommended $sortable_columns = ['ip', 'timestamp']; $orderby = isset($_GET['orderby']) && in_array(wp_unslash($_GET['orderby']), $sortable_columns, true) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'timestamp'; $order = isset($_GET['order']) && in_array(strtolower(wp_unslash($_GET['order'])), ['asc', 'desc'], true) ? strtolower(sanitize_key(wp_unslash($_GET['order']))) : 'desc'; $current_page = isset($_GET['paged']) ? absint(wp_unslash($_GET['paged'])) : 1; // phpcs:enable usort($whitelist_data, function($a, $b) use ($orderby, $order) { $a_val = $a[$orderby]; $b_val = $b[$orderby]; if ($a_val == $b_val) return 0; return ($order === 'asc') ? ($a_val <=> $b_val) : ($b_val <=> $a_val); }); $per_page = 20; $total_items = count($whitelist_data); $total_pages = ceil($total_items / $per_page); $items_for_page = array_slice($whitelist_data, ($current_page - 1) * $per_page, $per_page); ?>

add_query_arg('paged', '%#%'), 'format' => '', 'total' => $total_pages, 'current' => $current_page]); if ($page_links) echo wp_kses_post($page_links); ?>
print_log_sortable_header(__('IP', 'advanced-ip-blocker'), 'ip', $orderby, $order); ?> print_log_sortable_header(__('Added Since', 'advanced-ip-blocker'), 'timestamp', $orderby, $order); ?>
0 ? esc_html(self::get_formatted_datetime($item['timestamp'])) : '' . esc_html__('Old format - no date', 'advanced-ip-blocker') . ''; ?>
prefix . 'advaipbl_logs'; /* translators: %s: Log type (404,403 or General */ $where_clauses = [$wpdb->prepare("log_type = %s", $type)]; if (!empty($search_term)) { $search_like = '%' . $wpdb->esc_like($search_term) . '%'; $where_clauses[] = $wpdb->prepare("(ip LIKE %s OR details LIKE %s)", $search_like, $search_like); } $where_sql = implode(' AND ', $where_clauses); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $total_items = $wpdb->get_var("SELECT COUNT(log_id) FROM $table_name WHERE $where_sql"); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $per_page = 20; $total_pages = ceil($total_items / $per_page); $offset = ($current_page - 1) * $per_page; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $logs = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE $where_sql ORDER BY " . esc_sql($orderby) . " " . esc_sql($order) . " LIMIT %d OFFSET %d", $per_page, $offset), ARRAY_A); ?>

add_query_arg('paged', '%#%'), 'format' => '', 'total' => $total_pages, 'current' => $current_page]); if ($page_links) echo wp_kses_post($page_links); ?>
print_log_sortable_header(__('Date/Time', 'advanced-ip-blocker'), 'timestamp', $orderby, $order); ?> print_log_sortable_header(__('IP', 'advanced-ip-blocker'), 'ip', $orderby, $order); ?>
options['enable_logging'])) { echo '

' . esc_html__('General event logging is disabled in the "Settings" tab.', 'advanced-ip-blocker') . '

'; return; } global $wpdb; $table_name = $wpdb->prefix . 'advaipbl_logs'; // phpcs:disable WordPress.Security.NonceVerification.Recommended // Saneamos todas las entradas GET al principio. Nonce no es necesario para operaciones de solo lectura (filtrar, ordenar, paginar). $sortable_columns = ['timestamp', 'level', 'ip']; $orderby = isset($_GET['orderby']) && in_array(wp_unslash($_GET['orderby']), $sortable_columns, true) ? sanitize_key(wp_unslash($_GET['orderby'])) : 'timestamp'; $order = isset($_GET['order']) && in_array(strtolower(wp_unslash($_GET['order'])), ['asc', 'desc'], true) ? strtolower(sanitize_key(wp_unslash($_GET['order']))) : 'desc'; $current_page = isset($_GET['paged']) ? absint(wp_unslash($_GET['paged'])) : 1; // phpcs:enable $per_page = 25; $offset = ($current_page - 1) * $per_page; $where_sql = $wpdb->prepare("log_type = %s", 'general'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $total_items = $wpdb->get_var("SELECT COUNT(log_id) FROM $table_name WHERE $where_sql"); $total_pages = ceil($total_items / $per_page); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $logs = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared "SELECT * FROM $table_name WHERE $where_sql ORDER BY " . esc_sql($orderby) . " " . esc_sql($order) . " LIMIT %d OFFSET %d", $per_page, $offset ), ARRAY_A ); ?>

add_query_arg(['paged' => '%#%', 'orderby' => $orderby, 'order' => $order]), 'format' => '', 'total' => $total_pages, 'current' => $current_page, ]); if ($page_links) { echo '' . wp_kses_post($page_links) . ''; } ?>
print_log_sortable_header(__('Date/Time', 'advanced-ip-blocker'), 'timestamp', $orderby, $order); ?> print_log_sortable_header(__('Level', 'advanced-ip-blocker'), 'level', $orderby, $order); ?> print_log_sortable_header(__('IP', 'advanced-ip-blocker'), 'ip', $orderby, $order); ?>
User-Agent: %s', esc_html($details['user_agent']) ); } ?>

  • Stripe
  • bc1qxfsmpqk0q7an82ckm7380pzpsea2sa294824lg
  • 0xAF8CC1B71EAbF5dffDa2aF58AEF43b2559163284


# 

wp help advaipbl

# ---  ---

wp advaipbl block  [--reason=]
wp advaipbl unblock 

# ---  ---

wp advaipbl whitelist list [--format=]
wp advaipbl whitelist add 
wp advaipbl whitelist remove 

# ---  ---

wp advaipbl session list [--role=]
wp advaipbl session terminate [--user-id=] [--user-login=] [--role=] [--all]

# ---  ---

wp advaipbl blocked [--type=] [--format=]

# ---  ---

wp advaipbl log list [--type=] [--count=]
wp advaipbl log clear [--type=] [--force]

# ---  ---

wp advaipbl config get []
wp advaipbl config set  
                    

MaxMind.', 'advanced-ip-blocker'), [ 'a' => [ 'href' => [], 'target' => [], 'rel' => [] ] ] ), 'https://www.maxmind.com' ); ?>

'enable_logging', 'label' => __('Enable logging of events to the database.', 'advanced-ip-blocker')]); add_settings_field('advaipbl_log_timezone', __('Timezone for Logs', 'advanced-ip-blocker'), [$this, 'timezone_select_callback'], $page, 'advaipbl_general_settings_section'); add_settings_field('advaipbl_log_retention_days', __('Log Retention (days)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_general_settings_section', ['name' => 'log_retention_days', 'default' => 30, 'description' => __('Number of days to keep logs in the DB. 0 to disable automatic purging.', 'advanced-ip-blocker')]); add_settings_field('advaipbl_custom_block_message', __('Block Message', 'advanced-ip-blocker'), [$this, 'textarea_field_callback'], $page, 'advaipbl_general_settings_section', ['name' => 'custom_block_message', 'label' => __('Message for blocked users.', 'advanced-ip-blocker')]); add_settings_field('advaipbl_excluded_error_urls', __('Exclude URLs from Error Logging', 'advanced-ip-blocker'), [$this, 'textarea_field_callback'], $page, 'advaipbl_general_settings_section', ['name' => 'excluded_error_urls', 'label' => __('Add one URL or fragment per line. If a 403 or 404 error URL contains one of these strings, it will not be logged as an error. Useful for ignoring false positives from plugins.', 'advanced-ip-blocker')]); add_settings_section('advaipbl_api_settings_section', __('External API Settings', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_geolocation_provider', __('Geolocation Provider', 'advanced-ip-blocker'), [$this, 'geolocation_provider_callback'], $page, 'advaipbl_api_settings_section'); // --- CÓDIGO CORREGIDO --- add_settings_field('advaipbl_api_key_ip_apicom', 'ip-api.com ' . __('API Key', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_api_settings_section', ['name' => 'api_key_ip_apicom', 'description' => __('Optional key for HTTPS access.', 'advanced-ip-blocker'), 'class' => 'api-key-field', 'data_provider' => 'ip-api.com']); add_settings_field('advaipbl_api_key_ipinfocom', 'ipinfo.io ' . __('API Key', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_api_settings_section', ['name' => 'api_key_ipinfocom', 'description' => __('API key is recommended for higher limits.', 'advanced-ip-blocker'), 'class' => 'api-key-field', 'data_provider' => 'ipinfo.io']); add_settings_field('advaipbl_api_key_ipapicom', 'ipapi.com ' . __('API Key', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_api_settings_section', ['name' => 'api_key_ipapicom', 'description' => __('API Key is required.', 'advanced-ip-blocker'), 'class' => 'api-key-field', 'data_provider' => 'ipapi.com']); add_settings_field('advaipbl_api_key_ipstackcom', 'ipstack.com ' . __('API Key', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_api_settings_section', ['name' => 'api_key_ipstackcom', 'description' => __('API Key is required.', 'advanced-ip-blocker'), 'class' => 'api-key-field', 'data_provider' => 'ipstack.com']); add_settings_field('advaipbl_clear_location_cache_button', __('Geolocation Cache', 'advanced-ip-blocker'), [$this, 'clear_cache_button_callback'], $page, 'advaipbl_api_settings_section'); add_settings_section('advaipbl_notifications_section', __('Email Notifications', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_enable_email_notifications', __('Enable Email Notifications', 'advanced-ip-blocker'), [$this, 'checkbox_field_callback'], $page, 'advaipbl_notifications_section', ['name' => 'enable_email_notifications', 'label' => __('Send an email when an IP is blocked.', 'advanced-ip-blocker')]); add_settings_field('advaipbl_notification_frequency', __('Notification Frequency', 'advanced-ip-blocker'), [$this, 'notification_frequency_callback'], $page, 'advaipbl_notifications_section'); add_settings_field('advaipbl_notification_email', __('Notification Email', 'advanced-ip-blocker'), [$this, 'email_field_callback'], $page, 'advaipbl_notifications_section', ['name' => 'notification_email', 'label' => __('Leave empty to use the admin email.', 'advanced-ip-blocker')]); add_settings_section('advaipbl_honeypot_settings_section', __('Honeypot Blocking', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_duration_honeypot', __('Block Duration (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_honeypot_settings_section', ['name' => 'duration_honeypot', 'default' => 1440, 'description' => __('Block duration for IPs that fall into a honeypot URL.', 'advanced-ip-blocker')]); add_settings_section('advaipbl_user_agent_settings_section', __('User-Agent Blocking', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_duration_user_agent', __('Block Duration (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_user_agent_settings_section', ['name' => 'duration_user_agent', 'default' => 1440, 'description' => __('Block duration for IPs whose User-Agent is on the blacklist.', 'advanced-ip-blocker')]); add_settings_section('advaipbl_404_settings_section', __('404 Error Blocking', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_threshold_404', __('Error Threshold', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_404_settings_section', ['name' => 'threshold_404', 'default' => 10]); add_settings_field('advaipbl_transient_expiration_404', __('Time Window (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_404_settings_section', ['name' => 'transient_expiration_404', 'default' => 60]); add_settings_field('advaipbl_duration_404', __('Block Duration (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_404_settings_section', ['name' => 'duration_404', 'default' => 120]); add_settings_section('advaipbl_403_settings_section', __('403 Error Blocking', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_threshold_403', __('Error Threshold', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_403_settings_section', ['name' => 'threshold_403', 'default' => 5]); add_settings_field('advaipbl_transient_expiration_403', __('Time Window (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_403_settings_section', ['name' => 'transient_expiration_403', 'default' => 30]); add_settings_field('advaipbl_duration_403', __('Block Duration (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_403_settings_section', ['name' => 'duration_403', 'default' => 60]); add_settings_section('advaipbl_login_settings_section', __('Failed Login Blocking', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_threshold_login', __('Failure Threshold', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_login_settings_section', ['name' => 'threshold_login', 'default' => 5]); add_settings_field('advaipbl_transient_expiration_login', __('Time Window (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_login_settings_section', ['name' => 'transient_expiration_login', 'default' => 60]); add_settings_field('advaipbl_duration_login', __('Block Duration (min)', 'advanced-ip-blocker'), [$this, 'text_field_callback'], $page, 'advaipbl_login_settings_section', ['name' => 'duration_login', 'default' => 120]); add_settings_section('advaipbl_uninstall_section', __('Uninstallation', 'advanced-ip-blocker'), null, $page); add_settings_field('advaipbl_delete_data_on_uninstall', __('Delete Data on Uninstall', 'advanced-ip-blocker'), [$this, 'checkbox_field_callback'], $page, 'advaipbl_uninstall_section', ['name' => 'delete_data_on_uninstall', 'label' => __('Check to delete all data from this plugin when it is deleted.', 'advanced-ip-blocker')]); } public function clear_cache_button_callback() { $nonce_url = wp_nonce_url( admin_url( 'admin-post.php?action=advaipbl_clear_location_cache_action' ), // Usamos un admin-post para la acción 'advaipbl_clear_location_cache_nonce' ); ?>

get_default_settings(); $numeric_fields = [ 'log_retention_days', 'threshold_404', 'duration_404', 'transient_expiration_404', 'threshold_403', 'duration_403', 'transient_expiration_403', 'threshold_login', 'duration_login', 'transient_expiration_login', 'duration_honeypot', 'duration_user_agent' ]; foreach ($numeric_fields as $field) { $new_input[$field] = isset($input[$field]) ? absint($input[$field]) : $defaults[$field]; } $checkbox_fields = [ 'enable_logging', 'delete_data_on_uninstall', 'enable_email_notifications' ]; foreach ($checkbox_fields as $field) { $new_input[$field] = (isset($input[$field]) && $input[$field] === '1') ? '1' : '0'; } $new_input['notification_frequency'] = isset($input['notification_frequency']) && in_array($input['notification_frequency'], ['disabled', 'instant', 'daily', 'weekly']) ? $input['notification_frequency'] : $defaults['notification_frequency']; $new_input['custom_block_message'] = isset($input['custom_block_message']) ? sanitize_textarea_field($input['custom_block_message']) : $defaults['custom_block_message']; $new_input['excluded_error_urls'] = isset($input['excluded_error_urls']) ? sanitize_textarea_field($input['excluded_error_urls']) : $defaults['excluded_error_urls']; $new_input['notification_email'] = isset($input['notification_email']) ? sanitize_email($input['notification_email']) : $defaults['notification_email']; $api_keys = ['api_key_ipapicom', 'api_key_ipstackcom', 'api_key_ipinfocom', 'api_key_ip_apicom']; foreach($api_keys as $key) { $new_input[$key] = isset($input[$key]) ? sanitize_text_field($input[$key]) : ''; } $new_input['geolocation_provider'] = isset($input['geolocation_provider']) && in_array($input['geolocation_provider'], ['ip-api.com', 'geoiplookup.net', 'ipinfo.io', 'ipapi.com', 'ipstack.com']) ? $input['geolocation_provider'] : $defaults['geolocation_provider']; if (isset($input['log_timezone']) && in_array($input['log_timezone'], timezone_identifiers_list(), true)) { $new_input['log_timezone'] = $input['log_timezone']; } else { $new_input['log_timezone'] = $defaults['log_timezone']; } return $new_input; } public function text_field_callback($args){ $value = $this->options[$args['name']] ?? $args['default'] ?? ''; $class = isset($args['class']) ? $args['class'] : ''; $type = 'text'; if ( strpos($args['name'], 'duration') !== false || strpos($args['name'], 'threshold') !== false || strpos($args['name'], 'retention') !== false ) { $type = 'number'; } $min_attr = ( 'number' === $type ) ? 'min="0"' : ''; $data_attr = ! empty( $args['data_provider'] ) ? 'data-provider="' . esc_attr( $args['data_provider'] ) . '"' : ''; // Construimos el HTML y lo imprimimos con echo para escapar cada atributo de forma segura. $html = sprintf( '', esc_attr( $type ), esc_attr( $args['name'] ), esc_attr( 'advaipbl_settings[' . $args['name'] . ']' ), esc_attr( $value ), $min_attr, // $min_attr es seguro, es 'min="0"' o ''. esc_attr( $class ), $data_attr // $data_attr ya está escapado. ); echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped if ( isset($args['description']) ) { echo '

' . esc_html($args['description']) . '

'; } } public function checkbox_field_callback($args){ $checked = checked( '1', $this->options[$args['name']] ?? '0', false ); // Construimos el HTML y lo imprimimos con echo para mayor claridad. $html = sprintf( '', esc_attr( 'advaipbl_settings[' . $args['name'] . ']' ), $checked, // La función checked() de WordPress ya devuelve una cadena segura. esc_html( $args['label'] ) ); echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } public function textarea_field_callback($args){ $value = $this->options[$args['name']] ?? ''; printf( '

%3$s

', esc_attr( 'advaipbl_settings[' . $args['name'] . ']' ), esc_textarea( $value ), esc_html( $args['label'] ) ); } public function email_field_callback($args){ $value = $this->options[$args['name']] ?? ''; printf( '', esc_attr( 'advaipbl_settings[' . $args['name'] . ']' ), esc_attr( $value ), esc_attr( get_option('admin_email') ) ); if ( isset($args['label']) ) { printf( '

%s

', esc_html($args['label']) ); } } public function timezone_select_callback() { $name_attr = 'advaipbl_settings[log_timezone]'; $current_timezone = $this->options['log_timezone'] ?? wp_timezone_string(); echo ''; echo '

' . esc_html__('Select the timezone to display in the logs.', 'advanced-ip-blocker') . '

'; } public function notification_frequency_callback() { $value = $this->options['notification_frequency'] ?? 'disabled'; $frequencies = [ 'disabled' => __('Disabled', 'advanced-ip-blocker'), 'instant' => __('Instant', 'advanced-ip-blocker'), 'daily' => __('Daily Summary', 'advanced-ip-blocker'), 'weekly' => __('Weekly Summary', 'advanced-ip-blocker') ]; echo ''; echo '

' . esc_html__('Choose how often you want to receive alert emails.', 'advanced-ip-blocker') . '

'; } public function geolocation_provider_callback() { $value = $this->options['geolocation_provider'] ?? 'ip-api.com'; $providers = [ 'ip-api.com' => __('ip-api.com (Default, no key for HTTP)', 'advanced-ip-blocker'), 'geoiplookup.net' => __('geoiplookup.net (Free, no key)', 'advanced-ip-blocker'), 'ipinfo.io' => __('ipinfo.io (API Key recommended)', 'advanced-ip-blocker'), 'ipapi.com' => __('ipapi.com (API Key required)', 'advanced-ip-blocker'), 'ipstack.com' => __('ipstack.com (API Key required)', 'advanced-ip-blocker') ]; printf( ''; } }