'Select a country',
'AF' => 'Afghanistan',
'AL' => 'Albania',
'DZ' => 'Algeria',
'AS' => 'American Samoa',
'AD' => 'Andorra',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AQ' => 'Antarctica',
'AG' => 'Antigua and Barbuda',
'AR' => 'Argentina',
'AM' => 'Armenia',
'AW' => 'Aruba',
'AU' => 'Australia',
'AT' => 'Austria',
'AZ' => 'Azerbaijan',
'BS' => 'Bahamas',
'BH' => 'Bahrain',
'BD' => 'Bangladesh',
'BB' => 'Barbados',
'BY' => 'Belarus',
'BE' => 'Belgium',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermuda',
'BT' => 'Bhutan',
'BO' => 'Bolivia',
'BA' => 'Bosnia and Herzegovina',
'BW' => 'Botswana',
'BR' => 'Brazil',
'BN' => 'Brunei',
'BG' => 'Bulgaria',
'BF' => 'Burkina Faso',
'BI' => 'Burundi',
'KH' => 'Cambodia',
'CM' => 'Cameroon',
'CA' => 'Canada',
'CV' => 'Cape Verde',
'KY' => 'Cayman Islands',
'CF' => 'Central African Republic',
'TD' => 'Chad',
'CL' => 'Chile',
'CN' => 'China',
'CO' => 'Colombia',
'KM' => 'Comoros',
'CG' => 'Congo - Brazzaville',
'CD' => 'Congo - Kinshasa',
'CR' => 'Costa Rica',
'CI' => 'Côte d’Ivoire',
'HR' => 'Croatia',
'CU' => 'Cuba',
'CY' => 'Cyprus',
'CZ' => 'Czech Republic',
'DK' => 'Denmark',
'DJ' => 'Djibouti',
'DM' => 'Dominica',
'DO' => 'Dominican Republic',
'EC' => 'Ecuador',
'EG' => 'Egypt',
'SV' => 'El Salvador',
'GQ' => 'Equatorial Guinea',
'ER' => 'Eritrea',
'EE' => 'Estonia',
'ET' => 'Ethiopia',
'FJ' => 'Fiji',
'FI' => 'Finland',
'FR' => 'France',
'GF' => 'French Guiana',
'PF' => 'French Polynesia',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GE' => 'Georgia',
'DE' => 'Germany',
'GH' => 'Ghana',
'GI' => 'Gibraltar',
'GR' => 'Greece',
'GL' => 'Greenland',
'GD' => 'Grenada',
'GP' => 'Guadeloupe',
'GU' => 'Guam',
'GT' => 'Guatemala',
'GG' => 'Guernsey',
'GN' => 'Guinea',
'GW' => 'Guinea-Bissau',
'GY' => 'Guyana',
'HT' => 'Haiti',
'HN' => 'Honduras',
'HK' => 'Hong Kong',
'HU' => 'Hungary',
'IS' => 'Iceland',
'IN' => 'India',
'ID' => 'Indonesia',
'IR' => 'Iran',
'IQ' => 'Iraq',
'IE' => 'Ireland',
'IM' => 'Isle of Man',
'IL' => 'Israel',
'IT' => 'Italy',
'JM' => 'Jamaica',
'JP' => 'Japan',
'JE' => 'Jersey',
'JO' => 'Jordan',
'KZ' => 'Kazakhstan',
'KE' => 'Kenya',
'KI' => 'Kiribati',
'KP' => 'North Korea',
'KR' => 'South Korea',
'KW' => 'Kuwait',
'KG' => 'Kyrgyzstan',
'LA' => 'Laos',
'LV' => 'Latvia',
'LB' => 'Lebanon',
'LS' => 'Lesotho',
'LR' => 'Liberia',
'LY' => 'Libya',
'LI' => 'Liechtenstein',
'LT' => 'Lithuania',
'LU' => 'Luxembourg',
'MO' => 'Macao',
'MK' => 'North Macedonia',
'MG' => 'Madagascar',
'MW' => 'Malawi',
'MY' => 'Malaysia',
'MV' => 'Maldives',
'ML' => 'Mali',
'MT' => 'Malta',
'MH' => 'Marshall Islands',
'MQ' => 'Martinique',
'MR' => 'Mauritania',
'MU' => 'Mauritius',
'MX' => 'Mexico',
'FM' => 'Micronesia',
'MD' => 'Moldova',
'MC' => 'Monaco',
'MN' => 'Mongolia',
'ME' => 'Montenegro',
'MA' => 'Morocco',
'MZ' => 'Mozambique',
'MM' => 'Myanmar (Burma)',
'NA' => 'Namibia',
'NR' => 'Nauru',
'NP' => 'Nepal',
'NL' => 'Netherlands',
'NC' => 'New Caledonia',
'NZ' => 'New Zealand',
'NI' => 'Nicaragua',
'NE' => 'Niger',
'NG' => 'Nigeria',
'NO' => 'Norway',
'OM' => 'Oman',
'PK' => 'Pakistan',
'PW' => 'Palau',
'PS' => 'Palestinian Territories',
'PA' => 'Panama',
'PG' => 'Papua New Guinea',
'PY' => 'Paraguay',
'PE' => 'Peru',
'PH' => 'Philippines',
'PL' => 'Poland',
'PT' => 'Portugal',
'QA' => 'Qatar',
'RO' => 'Romania',
'RU' => 'Russia',
'RW' => 'Rwanda',
'SM' => 'San Marino',
'SA' => 'Saudi Arabia',
'SN' => 'Senegal',
'RS' => 'Serbia',
'SC' => 'Seychelles',
'SL' => 'Sierra Leone',
'SG' => 'Singapore',
'SK' => 'Slovakia',
'SI' => 'Slovenia',
'SB' => 'Solomon Islands',
'SO' => 'Somalia',
'ZA' => 'South Africa',
'ES' => 'Spain',
'LK' => 'Sri Lanka',
'SD' => 'Sudan',
'SR' => 'Suriname',
'SE' => 'Sweden',
'CH' => 'Switzerland',
'SY' => 'Syria',
'TW' => 'Taiwan',
'TJ' => 'Tajikistan',
'TZ' => 'Tanzania',
'TH' => 'Thailand',
'TL' => 'Timor-Leste',
'TG' => 'Togo',
'TO' => 'Tonga',
'TT' => 'Trinidad and Tobago',
'TN' => 'Tunisia',
'TR' => 'Turkey',
'TM' => 'Turkmenistan',
'UG' => 'Uganda',
'UA' => 'Ukraine',
'AE' => 'United Arab Emirates',
'GB' => 'United Kingdom',
'US' => 'United States',
'UY' => 'Uruguay',
'UZ' => 'Uzbekistan',
'VU' => 'Vanuatu',
'VE' => 'Venezuela',
'VN' => 'Vietnam',
'YE' => 'Yemen',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe'
);
}
/**
* Plugin Activation:
* 1) Detect the activating admin’s IP and set that country in the country list.
* 2) Create a custom DB table to log blocked attempts.
* 3) Set default options including the filtering mode and logging.
*/
register_activation_hook( __FILE__, 'advcb_plugin_activation' );
function advcb_plugin_activation() {
// Set the activating admin's country (fallback is RS)
$admin_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
$country_code = 'RS';
if ( ! empty( $admin_ip ) ) {
$detected_country = advcb_get_country_code_for_ip( $admin_ip );
if ( ! empty( $detected_country ) ) {
$country_code = $detected_country;
}
}
// In allow mode, the admin’s country is the only allowed country.
update_option( 'advcb_allowed_countries', array( $country_code ) );
// Create DB table for logs.
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
ip varchar(100) NOT NULL,
country_code varchar(5) DEFAULT '' NOT NULL,
blocked_time datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
reason varchar(255) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
// Set default options.
add_option( 'advcb_secret_key', wp_generate_password( 24, false, false ) );
add_option( 'advcb_blacklisted_ips', array() );
add_option( 'advcb_trusted_ips', array() );
add_option( 'advcb_send_email_alerts', false );
add_option( 'advcb_alert_email', get_option( 'admin_email' ) );
add_option( 'advcb_mode', 'allow' );
// New option: enable logging (default true).
add_option( 'advcb_enable_logs', true );
add_option( 'advcb_block_page_title', 'Access Restricted' );
add_option( 'advcb_block_message', 'We’re sorry, but your location is not allowed to view this site.' );
add_option( 'advcb_enable_redirect', false );
add_option( 'advcb_redirect_url', '' );
add_option( 'advcb_redirect_status_code', 302 );
add_option( 'advcb_http_status_code', 403 );
add_option( 'advcb_log_retention_days', 30 );
add_option( 'advcb_geoip_source', 'api' );
add_option( 'advcb_geoip_db_path', '' );
// CAPTCHA challenge options.
add_option( 'advcb_enable_captcha', false );
add_option( 'advcb_captcha_provider', 'recaptcha_v2' );
add_option( 'advcb_captcha_site_key', '' );
add_option( 'advcb_captcha_secret_key', '' );
add_option( 'advcb_captcha_duration', 24 ); // Hours
add_option( 'advcb_captcha_threshold', 0.5 ); // For reCAPTCHA v3
if ( ! wp_next_scheduled( 'advcb_cleanup_logs_event' ) ) {
wp_schedule_event( time(), 'daily', 'advcb_cleanup_logs_event' );
}
}
register_deactivation_hook( __FILE__, 'advcb_plugin_deactivation' );
function advcb_plugin_deactivation() {
wp_clear_scheduled_hook( 'advcb_cleanup_logs_event' );
}
add_action( 'init', 'advcb_ensure_cleanup_schedule' );
function advcb_ensure_cleanup_schedule() {
if ( ! wp_next_scheduled( 'advcb_cleanup_logs_event' ) ) {
wp_schedule_event( time(), 'daily', 'advcb_cleanup_logs_event' );
}
}
/**
* Admin notice: Warn if the bypass secret key is still the insecure default.
* Addresses CVE-2026-1675.
*/
add_action( 'admin_notices', 'advcb_insecure_secret_key_notice' );
function advcb_insecure_secret_key_notice() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$secret_key = get_option( 'advcb_secret_key', '' );
if ( empty( $secret_key ) || 'OpenSesame' === $secret_key ) {
$settings_url = admin_url( 'admin.php?page=advcb_settings' );
echo '
';
echo '' . esc_html__( 'Advanced Country Blocker - Security Warning:', 'advanced-country-blocker' ) . ' ';
if ( 'OpenSesame' === $secret_key ) {
printf(
/* translators: %s: link to settings page */
esc_html__( 'Your bypass secret key is set to the insecure default value. The URL bypass feature is disabled until you change it. Please %s to set a unique secret key.', 'advanced-country-blocker' ),
'' . esc_html__( 'update your settings', 'advanced-country-blocker' ) . ''
);
} else {
printf(
/* translators: %s: link to settings page */
esc_html__( 'Your bypass secret key is empty. The URL bypass feature is disabled until you set one. Please %s to configure a secret key.', 'advanced-country-blocker' ),
'' . esc_html__( 'update your settings', 'advanced-country-blocker' ) . ''
);
}
echo '
';
}
}
/**
* MAIN BLOCKING LOGIC
*/
function advcb_block_non_allowed_countries() {
// Allow admins to bypass the blocking logic.
if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
return;
}
// Allow CAPTCHA verification AJAX requests to pass through.
if ( wp_doing_ajax() && isset( $_REQUEST['action'] ) && 'advcb_verify_captcha' === $_REQUEST['action'] ) {
return;
}
// Retrieve settings.
$allowed_countries = get_option( 'advcb_allowed_countries', array() );
$secret_key = get_option( 'advcb_secret_key', '' );
$temporary_access_duration = HOUR_IN_SECONDS;
// Refuse bypass if the secret key is empty or still the insecure default (CVE-2026-1675).
$secret_key_is_secure = ! empty( $secret_key ) && $secret_key !== 'OpenSesame';
$blacklisted_ips = get_option( 'advcb_blacklisted_ips', array() );
$trusted_ips = get_option( 'advcb_trusted_ips', array() );
$send_email_alerts = get_option( 'advcb_send_email_alerts', false );
$alert_email = get_option( 'advcb_alert_email', get_option( 'admin_email' ) );
$mode = get_option( 'advcb_mode', 'allow' ); // 'allow' or 'block'
// Get visitor's IP address, properly handling proxy headers.
// Uses WordPress function which respects trusted proxies and prevents spoofing.
if ( function_exists( 'wp_http_get_original_ip' ) ) {
$ip = wp_http_get_original_ip();
} else {
// Fallback for older WordPress versions.
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
}
// Validate IP format to prevent invalid IPs from being processed.
if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
$ip = 'unknown';
}
if ( ! is_array( $blacklisted_ips ) ) {
$blacklisted_ips = explode( ',', $blacklisted_ips );
}
if ( ! is_array( $trusted_ips ) ) {
$trusted_ips = explode( ',', $trusted_ips );
}
$blacklisted_ips = array_map( 'trim', $blacklisted_ips );
$trusted_ips = array_map( 'trim', $trusted_ips );
// 1) Check if IP is whitelisted explicitly.
if ( in_array( $ip, $trusted_ips, true ) ) {
return;
}
// 2) Check if IP is blacklisted.
if ( in_array( $ip, $blacklisted_ips, true ) ) {
$reason = __( 'Blacklisted IP', 'advanced-country-blocker' );
advcb_record_block( $ip, 'XX', $reason, $send_email_alerts, $alert_email );
advcb_show_block_page( array(
'ip' => $ip,
'country_code' => 'XX',
'reason' => $reason,
) );
exit;
}
// 3) Check if IP is in the temporary whitelist.
$whitelisted_ips = get_transient( 'advcb_whitelisted_ips' );
if ( is_array( $whitelisted_ips ) && in_array( $ip, $whitelisted_ips ) ) {
return; // temporary access granted
}
// 3.5) Check if IP has passed CAPTCHA challenge.
if ( advcb_is_captcha_verified( $ip ) ) {
return;
}
// 4) Determine visitor's country code.
$country_cache_key = 'advcb_country_' . md5( $ip );
$country_code = get_transient( $country_cache_key );
if ( ! $country_code ) {
$country_code = advcb_get_country_code_for_ip( $ip );
if ( $country_code ) {
set_transient( $country_cache_key, $country_code, DAY_IN_SECONDS );
} else {
// If we cannot determine the visitor's country, allow access to avoid blocking legitimate users.
return;
}
}
/*
* 5) Country Filtering Logic:
* In "allow" mode: if the visitor’s country is NOT in the list, then block.
* In "block" mode: if the visitor’s country IS in the list, then block.
* In both cases, if the secret key parameter is provided, grant temporary access.
*/
if ( $country_code ) {
if ( $mode === 'allow' && ! in_array( $country_code, $allowed_countries ) ) {
// Check if the secret key parameter exists and has a truthy value.
if ( $secret_key_is_secure && isset( $_GET[ $secret_key ] ) && '1' === $_GET[ $secret_key ] ) {
// Grant temporary access.
if ( ! is_array( $whitelisted_ips ) ) {
$whitelisted_ips = array();
}
$whitelisted_ips[] = $ip;
$whitelisted_ips = array_unique( $whitelisted_ips );
set_transient( 'advcb_whitelisted_ips', $whitelisted_ips, $temporary_access_duration );
// Optional: enqueue a redirect alert.
add_action( 'wp_enqueue_scripts', function() use ( $secret_key ) {
wp_enqueue_script( 'advcb-alert', plugin_dir_url( __FILE__ ) . 'advcb-alert.js', array(), '1.0', true );
wp_localize_script( 'advcb-alert', 'advcb_redirect', array(
'url' => esc_url( remove_query_arg( $secret_key ) ),
) );
} );
return;
}
$reason = __( 'Country not allowed', 'advanced-country-blocker' );
advcb_record_block( $ip, $country_code, $reason, $send_email_alerts, $alert_email );
// Check if CAPTCHA challenge is enabled - if so, show CAPTCHA instead of block page.
$captcha_enabled = get_option( 'advcb_enable_captcha', false );
if ( $captcha_enabled ) {
advcb_show_captcha_challenge( array(
'ip' => $ip,
'country_code' => $country_code,
'reason' => $reason,
) );
exit;
}
advcb_show_block_page( array(
'ip' => $ip,
'country_code' => $country_code,
'reason' => $reason,
) );
exit;
} elseif ( $mode === 'block' && in_array( $country_code, $allowed_countries ) ) {
// Check if the secret key parameter exists and has a truthy value.
if ( $secret_key_is_secure && isset( $_GET[ $secret_key ] ) && '1' === $_GET[ $secret_key ] ) {
// Grant temporary access.
if ( ! is_array( $whitelisted_ips ) ) {
$whitelisted_ips = array();
}
$whitelisted_ips[] = $ip;
$whitelisted_ips = array_unique( $whitelisted_ips );
set_transient( 'advcb_whitelisted_ips', $whitelisted_ips, $temporary_access_duration );
add_action( 'wp_enqueue_scripts', function() use ( $secret_key ) {
wp_enqueue_script( 'advcb-alert', plugin_dir_url( __FILE__ ) . 'advcb-alert.js', array(), '1.0', true );
wp_localize_script( 'advcb-alert', 'advcb_redirect', array(
'url' => esc_url( remove_query_arg( $secret_key ) ),
) );
} );
return;
}
$reason = __( 'Country blocked', 'advanced-country-blocker' );
advcb_record_block( $ip, $country_code, $reason, $send_email_alerts, $alert_email );
// Check if CAPTCHA challenge is enabled - if so, show CAPTCHA instead of block page.
$captcha_enabled = get_option( 'advcb_enable_captcha', false );
if ( $captcha_enabled ) {
advcb_show_captcha_challenge( array(
'ip' => $ip,
'country_code' => $country_code,
'reason' => $reason,
) );
exit;
}
advcb_show_block_page( array(
'ip' => $ip,
'country_code' => $country_code,
'reason' => $reason,
) );
exit;
}
}
}
add_action( 'init', 'advcb_block_non_allowed_countries' );
/**
* RECORD BLOCKED ATTEMPT IN DATABASE & (optionally) SEND EMAIL
*/
function advcb_record_block( $ip, $country_code, $reason, $send_email_alerts, $alert_email ) {
// Check if logging is enabled.
if ( ! get_option( 'advcb_enable_logs', true ) ) {
// Logging is disabled; optionally still send an email alert.
if ( $send_email_alerts && ! empty( $alert_email ) ) {
$subject = 'Country Blocker Alert: A visitor was blocked';
$message = sprintf(
"A visitor from IP: %s (country: %s) was blocked.\nReason: %s\nTime: %s",
$ip,
$country_code,
$reason,
current_time( 'mysql' )
);
wp_mail( $alert_email, $subject, $message );
}
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$wpdb->insert( $table_name, array(
'ip' => $ip,
'country_code' => $country_code ?: '',
'reason' => $reason,
), array( '%s', '%s', '%s' ) );
if ( $send_email_alerts && ! empty( $alert_email ) ) {
$subject = 'Country Blocker Alert: A visitor was blocked';
$message = sprintf(
"A visitor from IP: %s (country: %s) was blocked.\nReason: %s\nTime: %s",
$ip,
$country_code,
$reason,
current_time( 'mysql' )
);
wp_mail( $alert_email, $subject, $message );
}
}
/**
* SHOW A CUSTOM BLOCK PAGE (instead of default 403).
*/
function advcb_show_block_page( $context = array() ) {
$redirect_enabled = (bool) get_option( 'advcb_enable_redirect', false );
$redirect_url = get_option( 'advcb_redirect_url', '' );
if ( $redirect_enabled && ! empty( $redirect_url ) ) {
$redirect_status = (int) get_option( 'advcb_redirect_status_code', 302 );
$allowed_redirect_statuses = array( 301, 302, 307, 308 );
if ( ! in_array( $redirect_status, $allowed_redirect_statuses, true ) ) {
$redirect_status = 302;
}
wp_safe_redirect( esc_url_raw( $redirect_url ), $redirect_status );
exit;
}
$title = get_option( 'advcb_block_page_title', 'Access Restricted' );
$message = get_option( 'advcb_block_message', 'We’re sorry, but your location is not allowed to view this site.' );
$status_code = (int) get_option( 'advcb_http_status_code', 403 );
$message = advcb_replace_placeholders( $message, $context );
$status_code = in_array( $status_code, apply_filters( 'advcb_allowed_http_status_codes', array( 403, 410, 451 ) ), true )
? $status_code
: 403;
$content = '' . esc_html( $title ) . '
' . wpautop( wp_kses_post( $message ) );
wp_die(
wp_kses_post( $content ),
esc_html( $title ),
array( 'response' => absint( $status_code ) )
);
}
/**
* REGISTER/INITIALIZE SETTINGS
*/
function advcb_register_settings() {
// Register and sanitize the country codes list.
register_setting( 'advcb_options_group', 'advcb_allowed_countries', array(
'sanitize_callback' => 'advcb_sanitize_allowed_countries',
) );
// Register and sanitize secret key.
register_setting( 'advcb_options_group', 'advcb_secret_key', array(
'sanitize_callback' => 'advcb_sanitize_secret_key',
) );
// Register and sanitize blacklisted IPs.
register_setting( 'advcb_options_group', 'advcb_blacklisted_ips', array(
'sanitize_callback' => 'advcb_sanitize_blacklisted_ips',
) );
register_setting( 'advcb_options_group', 'advcb_trusted_ips', array(
'sanitize_callback' => 'advcb_sanitize_blacklisted_ips',
) );
// Register and sanitize email alert toggle.
register_setting( 'advcb_options_group', 'advcb_send_email_alerts', array(
'sanitize_callback' => 'advcb_sanitize_boolean',
) );
// Register and sanitize alert email.
register_setting( 'advcb_options_group', 'advcb_alert_email', array(
'sanitize_callback' => 'sanitize_email',
) );
// Register and sanitize the filtering mode.
register_setting( 'advcb_options_group', 'advcb_mode', array(
'sanitize_callback' => 'advcb_sanitize_mode',
) );
// Register and sanitize the logging option.
register_setting( 'advcb_options_group', 'advcb_enable_logs', array(
'sanitize_callback' => 'advcb_sanitize_boolean',
) );
register_setting( 'advcb_options_group', 'advcb_block_page_title', array(
'sanitize_callback' => 'sanitize_text_field',
) );
register_setting( 'advcb_options_group', 'advcb_block_message', array(
'sanitize_callback' => 'advcb_sanitize_textarea',
) );
register_setting( 'advcb_options_group', 'advcb_http_status_code', array(
'sanitize_callback' => 'advcb_sanitize_http_status',
) );
register_setting( 'advcb_options_group', 'advcb_enable_redirect', array(
'sanitize_callback' => 'advcb_sanitize_boolean',
) );
register_setting( 'advcb_options_group', 'advcb_redirect_url', array(
'sanitize_callback' => 'advcb_sanitize_url',
) );
register_setting( 'advcb_options_group', 'advcb_redirect_status_code', array(
'sanitize_callback' => 'advcb_sanitize_redirect_status',
) );
register_setting( 'advcb_options_group', 'advcb_log_retention_days', array(
'sanitize_callback' => 'advcb_sanitize_positive_int',
) );
register_setting( 'advcb_options_group', 'advcb_geoip_source', array(
'sanitize_callback' => 'advcb_sanitize_geoip_source',
) );
register_setting( 'advcb_options_group', 'advcb_geoip_db_path', array(
'sanitize_callback' => 'advcb_sanitize_file_path',
) );
// Register CAPTCHA challenge settings.
register_setting( 'advcb_options_group', 'advcb_enable_captcha', array(
'sanitize_callback' => 'advcb_sanitize_boolean',
) );
register_setting( 'advcb_options_group', 'advcb_captcha_provider', array(
'sanitize_callback' => 'advcb_sanitize_captcha_provider',
) );
register_setting( 'advcb_options_group', 'advcb_captcha_site_key', array(
'sanitize_callback' => 'sanitize_text_field',
) );
register_setting( 'advcb_options_group', 'advcb_captcha_secret_key', array(
'sanitize_callback' => 'advcb_sanitize_captcha_secret_key',
) );
register_setting( 'advcb_options_group', 'advcb_captcha_duration', array(
'sanitize_callback' => 'advcb_sanitize_positive_int',
) );
register_setting( 'advcb_options_group', 'advcb_captcha_threshold', array(
'sanitize_callback' => 'advcb_sanitize_captcha_threshold',
) );
// Register registration-specific country blocking settings.
register_setting( 'advcb_options_group', 'advcb_block_registration_by_country', array(
'sanitize_callback' => 'advcb_sanitize_boolean',
) );
register_setting( 'advcb_options_group', 'advcb_registration_mode', array(
'sanitize_callback' => 'advcb_sanitize_mode',
) );
register_setting( 'advcb_options_group', 'advcb_registration_countries', array(
'sanitize_callback' => 'advcb_sanitize_allowed_countries',
) );
register_setting( 'advcb_options_group', 'advcb_registration_blocked_message', array(
'sanitize_callback' => 'sanitize_text_field',
) );
}
add_action( 'admin_init', 'advcb_register_settings' );
/**
* Clean up log entries based on retention setting.
*/
function advcb_cleanup_logs() {
$retention_days = absint( get_option( 'advcb_log_retention_days', 30 ) );
if ( $retention_days <= 0 ) {
return;
}
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$threshold = gmdate( 'Y-m-d H:i:s', time() - ( $retention_days * DAY_IN_SECONDS ) );
$wpdb->query( $wpdb->prepare( "DELETE FROM $table_name WHERE blocked_time < %s", $threshold ) );
}
add_action( 'advcb_cleanup_logs_event', 'advcb_cleanup_logs' );
/**
* Block/allow user registration based on country.
*/
function advcb_restrict_registration_by_country( $errors, $sanitized_user_login, $user_email ) {
// Check if feature is enabled
if ( ! get_option( 'advcb_block_registration_by_country', false ) ) {
return $errors;
}
// Get configured countries
$countries = get_option( 'advcb_registration_countries', array() );
if ( empty( $countries ) ) {
return $errors;
}
// Get mode and user's country code
$mode = get_option( 'advcb_registration_mode', 'block' );
$country_code = advcb_get_country_code_for_ip( advcb_get_visitor_ip() );
$should_block = false;
if ( 'block' === $mode ) {
// Block mode: block if country is in the list
$should_block = in_array( $country_code, $countries, true );
} else {
// Allow mode: block if country is NOT in the list
$should_block = ! in_array( $country_code, $countries, true );
}
if ( $should_block ) {
$error_message = get_option( 'advcb_registration_blocked_message',
__( 'Registrations from your location are not allowed.', 'advanced-country-blocker' )
);
$error_message = apply_filters( 'advcb_registration_blocked_message', $error_message, $country_code );
$errors->add( 'country_blocked', $error_message );
}
return $errors;
}
add_filter( 'registration_errors', 'advcb_restrict_registration_by_country', 10, 3 );
/**
* Log blocked registration attempt.
* Runs before user is created, captures the attempt at validation time.
*/
function advcb_log_blocked_registration_attempt( $errors, $sanitized_user_login, $user_email ) {
// Only log if this is a country block error
if ( ! in_array( 'country_blocked', $errors->get_error_codes(), true ) ) {
return $errors;
}
if ( ! get_option( 'advcb_enable_logs', false ) ) {
return $errors;
}
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$country_code = advcb_get_country_code_for_ip( advcb_get_visitor_ip() );
$wpdb->insert(
$table_name,
array(
'ip_address' => advcb_get_visitor_ip(),
'country_code' => $country_code,
'block_reason' => 'Registration attempt blocked: ' . $sanitized_user_login,
'blocked_time' => current_time( 'mysql' ),
)
);
return $errors;
}
add_filter( 'registration_errors', 'advcb_log_blocked_registration_attempt', 11, 3 );
/**
* ADD MENU PAGE
*/
function advcb_register_options_page() {
add_menu_page(
'Country Blocker',
'Country Blocker',
'manage_options',
'advcb_settings',
'advcb_options_page',
'dashicons-location-alt',
60
);
// Add a sub-page for logs.
add_submenu_page(
'advcb_settings',
'Block Logs',
'Block Logs',
'manage_options',
'advcb_block_logs',
'advcb_block_logs_page'
);
// Add a sub-page for analytics dashboard.
add_submenu_page(
'advcb_settings',
'Analytics Dashboard',
'Analytics',
'manage_options',
'advcb_analytics',
'advcb_analytics_dashboard_page'
);
// Add a sub-page for real-time activity monitor.
add_submenu_page(
'advcb_settings',
'Real-Time Monitor',
'Live Monitor',
'manage_options',
'advcb_live_monitor',
'advcb_live_monitor_page'
);
}
add_action( 'admin_menu', 'advcb_register_options_page' );
/**
* MAIN SETTINGS PAGE with Dynamic Country Select Boxes
*/
function advcb_options_page() {
// Get current filtering mode to adjust labels.
$mode = get_option( 'advcb_mode', 'allow' );
$list_label = ( $mode === 'block' ) ? 'Blocked Country Codes' : 'Allowed Country Codes';
$list_desc = ( $mode === 'block' )
? 'Select ISO country codes that should be blocked from accessing the site. Everyone else will be allowed automatically.'
: 'Select ISO country codes that are allowed to access the site. Visitors from all other countries will be blocked.';
// Retrieve the saved countries. Ensure we have an array.
$selected_countries = get_option( 'advcb_allowed_countries', array() );
if ( ! is_array( $selected_countries ) ) {
$selected_countries = explode( ',', $selected_countries );
}
// Always display at least one select box.
if ( empty( $selected_countries ) ) {
$selected_countries = array( '' );
}
// Get the complete list of countries.
$countries = advcb_get_countries();
$trusted_ips = get_option( 'advcb_trusted_ips', array() );
if ( is_array( $trusted_ips ) ) {
$trusted_ips = implode( ',', array_filter( array_map( 'trim', $trusted_ips ) ) );
}
$geoip_source = get_option( 'advcb_geoip_source', 'api' );
$geoip_db_path = advcb_get_geoip_database_path();
$geoip_db_readable = $geoip_db_path && file_exists( $geoip_db_path ) && is_readable( $geoip_db_path );
$geoip_storage_dir = advcb_get_geoip_storage_dir();
$block_page_title = get_option( 'advcb_block_page_title', 'Access Restricted' );
$block_message = get_option( 'advcb_block_message', 'We\'re sorry, but your location is not allowed to view this site.' );
$http_status_code = (int) get_option( 'advcb_http_status_code', 403 );
$enable_redirect = (bool) get_option( 'advcb_enable_redirect', false );
$redirect_url = get_option( 'advcb_redirect_url', '' );
$redirect_status = (int) get_option( 'advcb_redirect_status_code', 302 );
$log_retention_days = absint( get_option( 'advcb_log_retention_days', 30 ) );
// Get current secret key for display.
$current_secret_key = get_option( 'advcb_secret_key', '' );
// CAPTCHA settings.
$captcha_enabled = get_option( 'advcb_enable_captcha', false );
$captcha_provider = get_option( 'advcb_captcha_provider', 'recaptcha_v2' );
$captcha_site_key = get_option( 'advcb_captcha_site_key', '' );
$captcha_duration = get_option( 'advcb_captcha_duration', 24 );
$captcha_threshold = get_option( 'advcb_captcha_threshold', 0.5 );
// Registration blocking settings.
$reg_block_enabled = get_option( 'advcb_block_registration_by_country', false );
$reg_mode = get_option( 'advcb_registration_mode', 'block' );
$reg_selected_countries = get_option( 'advcb_registration_countries', array() );
$reg_blocked_message = get_option( 'advcb_registration_blocked_message', __( 'Registrations from your location are not allowed.', 'advanced-country-blocker' ) );
?>
prefix . 'advcb_block_logs';
advcb_cleanup_logs();
// Check for a truncate action and validate nonce.
if ( isset( $_GET['action'] ) && $_GET['action'] === 'truncate_logs' && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'truncate_logs' ) ) {
$wpdb->query( "TRUNCATE TABLE $table_name" );
echo '';
}
$paged = isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
$limit = 20;
$offset = ( $paged - 1 ) * $limit;
$results = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM $table_name ORDER BY blocked_time DESC LIMIT %d OFFSET %d",
$limit,
$offset
) );
$total = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
$total_pages = ceil( $total / $limit );
?>
Blocked Attempts Log
0 ) {
/* translators: %d: number of days */
printf( esc_html__( 'Entries older than %d day(s) are removed automatically.', 'advanced-country-blocker' ), absint( $retention_days ) );
} else {
esc_html_e( 'Automatic log cleanup is currently disabled.', 'advanced-country-blocker' );
}
?>
Clear Logs
| ID |
IP |
Country Code |
Reason |
Time |
| id ); ?> |
ip ); ?> |
country_code ); ?> |
reason ); ?> |
blocked_time ); ?> |
1 ) : ?>
10 ) {
if ( $paged <= 6 ) {
$start = 1;
$end = 10;
} elseif ( $paged > $total_pages - 5 ) {
$start = $total_pages - 9;
$end = $total_pages;
} else {
$start = $paged - 5;
$end = $paged + 4;
}
} else {
$start = 1;
$end = $total_pages;
}
// Optionally, add a "Previous" button.
if ( $paged > 1 ) {
echo '
« Prev ';
}
for ( $i = $start; $i <= $end; $i++ ) {
$class = ( $i == $paged ) ? ' class="button button-primary disabled"' : ' class="button"';
echo '
' . esc_html( $i ) . ' ';
}
// Optionally, add a "Next" button.
if ( $paged < $total_pages ) {
echo '
Next »';
}
?>
No blocked attempts logged yet.
array(),
'blocks' => array(),
'statistics' => array(
'today_visitors' => 0,
'today_blocks' => 0,
'active_now' => 0,
),
);
}
$current_time = current_time( 'mysql' );
$timestamp = time();
// Update or add visitor.
$found = false;
foreach ( $activity['visitors'] as &$visitor ) {
if ( $visitor['ip'] === $ip ) {
$visitor['last_seen'] = $current_time;
$visitor['timestamp'] = $timestamp;
$visitor['requests']++;
$found = true;
break;
}
}
unset( $visitor );
if ( ! $found ) {
// Get visitor country.
$country_code = advcb_get_country_code_for_ip( $ip );
$country_name = advcb_get_country_name( $country_code );
$activity['visitors'][] = array(
'ip' => $ip,
'country_code' => $country_code ?: 'XX',
'country_name' => $country_name ?: 'Unknown',
'first_seen' => $current_time,
'last_seen' => $current_time,
'timestamp' => $timestamp,
'requests' => 1,
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 100 ) : '',
'request_uri' => isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '',
'method' => isset( $_SERVER['REQUEST_METHOD'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) : 'GET',
);
$activity['statistics']['today_visitors']++;
}
// Clean up old visitors (inactive for 5 minutes) and old blocks (older than 1 hour).
$activity['visitors'] = array_filter( $activity['visitors'], function( $v ) use ( $timestamp ) {
return ( $timestamp - $v['timestamp'] ) < 300; // 5 minutes
} );
$activity['blocks'] = array_filter( $activity['blocks'], function( $b ) use ( $timestamp ) {
return ( $timestamp - $b['timestamp'] ) < 3600; // 1 hour
} );
// Re-index arrays.
$activity['visitors'] = array_values( $activity['visitors'] );
$activity['blocks'] = array_values( $activity['blocks'] );
// Update statistics.
$activity['statistics']['active_now'] = count( $activity['visitors'] );
$activity['statistics']['today_blocks'] = count( $activity['blocks'] );
// Store activity data with 5-minute expiration.
set_transient( 'advcb_live_activity', $activity, 5 * MINUTE_IN_SECONDS );
}
add_action( 'init', 'advcb_track_visitor_activity', 5 ); // Run early but after plugins loaded.
/**
* Record a block for the live monitor.
* Hook into the blocking process.
*/
function advcb_record_live_block( $ip, $country_code, $reason ) {
$activity = get_transient( 'advcb_live_activity' );
if ( ! is_array( $activity ) ) {
$activity = array(
'visitors' => array(),
'blocks' => array(),
'statistics' => array(
'today_visitors' => 0,
'today_blocks' => 0,
'active_now' => 0,
),
);
}
// Add block entry.
$country_name = advcb_get_country_name( $country_code );
$activity['blocks'][] = array(
'ip' => $ip,
'country_code' => $country_code,
'country_name' => $country_name ?: 'Unknown',
'reason' => $reason,
'timestamp' => time(),
'time' => current_time( 'mysql' ),
'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 100 ) : '',
);
set_transient( 'advcb_live_activity', $activity, 5 * MINUTE_IN_SECONDS );
}
add_action( 'advcb_block_recorded', 'advcb_record_live_block', 10, 3 );
/**
* Hook to trigger block recording after a block is logged.
*/
function advcb_trigger_block_record_hook( $ip, $country_code, $reason, $send_email_alerts, $alert_email ) {
do_action( 'advcb_block_recorded', $ip, $country_code, $reason );
}
add_action( 'advcb_record_block', 'advcb_trigger_block_record_hook', 10, 5 );
/**
* AJAX handler for getting live monitor data.
*/
function advcb_get_live_monitor_data() {
check_ajax_referer( 'advcb_live_monitor_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( array( 'message' => 'Permission denied' ) );
}
$activity = get_transient( 'advcb_live_activity' );
if ( ! is_array( $activity ) ) {
$activity = array(
'visitors' => array(),
'blocks' => array(),
'statistics' => array(
'today_visitors' => 0,
'today_blocks' => 0,
'active_now' => 0,
),
);
}
// Get additional stats.
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$today_blocks = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE DATE(blocked_time) = CURDATE()"
)
);
$activity['statistics']['today_blocks'] = (int) $today_blocks;
// Get top countries from all-time logs.
$top_countries_all_time = $wpdb->get_results(
"SELECT country_code, COUNT(*) as count FROM $table_name WHERE country_code != '' GROUP BY country_code ORDER BY count DESC LIMIT 10",
ARRAY_A
);
$activity['top_countries'] = $top_countries_all_time;
wp_send_json_success( $activity );
}
add_action( 'wp_ajax_advcb_get_live_monitor_data', 'advcb_get_live_monitor_data' );
/**
* Get country name from code.
*/
function advcb_get_country_name( $code ) {
if ( empty( $code ) || 'XX' === $code ) {
return 'Unknown';
}
$countries = advcb_get_countries();
return isset( $countries[ $code ] ) ? $countries[ $code ] : $code;
}
/**
* Get country flag emoji from code.
*/
function advcb_get_country_flag( $code ) {
if ( empty( $code ) || strlen( $code ) !== 2 ) {
return '';
}
// Regional indicator symbols.
$offset = 0x1F1E6;
$flag = '';
for ( $i = 0; $i < 2; $i++ ) {
$char = ord( strtoupper( $code[ $i ] ) ) - ord( 'A' );
if ( $char >= 0 && $char <= 25 ) {
$flag .= mb_chr( $offset + $char );
}
}
return $flag;
}
/**
* Render the Real-Time Activity Monitor page.
*/
function advcb_live_monitor_page() {
?>
__( 'CAPTCHA not configured.', 'advanced-country-blocker' ) ) );
}
$captcha_response = isset( $_POST['captcha_response'] ) ? sanitize_text_field( wp_unslash( $_POST['captcha_response'] ) ) : '';
if ( empty( $captcha_response ) ) {
wp_send_json_error( array( 'message' => __( 'Please complete the CAPTCHA.', 'advanced-country-blocker' ) ) );
}
$verified = false;
$error_message = '';
switch ( $provider ) {
case 'recaptcha_v2':
case 'recaptcha_v3':
$response = wp_remote_post( 'https://www.google.com/recaptcha/api/siteverify', array(
'body' => array(
'secret' => $secret_key,
'response' => $captcha_response,
'remoteip' => advcb_get_visitor_ip(),
),
'timeout' => 10,
) );
if ( is_wp_error( $response ) ) {
$error_message = __( 'Failed to verify CAPTCHA.', 'advanced-country-blocker' );
} else {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( isset( $body['success'] ) && $body['success'] ) {
if ( 'recaptcha_v3' === $provider ) {
$threshold = floatval( get_option( 'advcb_captcha_threshold', 0.5 ) );
$score = isset( $body['score'] ) ? floatval( $body['score'] ) : 0;
if ( $score >= $threshold ) {
$verified = true;
} else {
$error_message = __( 'Verification failed. Please try again.', 'advanced-country-blocker' );
}
} else {
$verified = true;
}
} else {
$error_message = __( 'CAPTCHA verification failed.', 'advanced-country-blocker' );
}
}
break;
case 'hcaptcha':
$response = wp_remote_post( 'https://api.hcaptcha.com/siteverify', array(
'body' => array(
'secret' => $secret_key,
'response' => $captcha_response,
'remoteip' => advcb_get_visitor_ip(),
),
'timeout' => 10,
) );
if ( is_wp_error( $response ) ) {
$error_message = __( 'Failed to verify CAPTCHA.', 'advanced-country-blocker' );
} else {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( isset( $body['success'] ) && $body['success'] ) {
$verified = true;
} else {
$error_message = __( 'CAPTCHA verification failed.', 'advanced-country-blocker' );
}
}
break;
case 'turnstile':
$response = wp_remote_post( 'https://challenges.cloudflare.com/turnstile/v0/siteverify', array(
'body' => array(
'secret' => $secret_key,
'response' => $captcha_response,
'remoteip' => advcb_get_visitor_ip(),
),
'timeout' => 10,
) );
if ( is_wp_error( $response ) ) {
$error_message = __( 'Failed to verify CAPTCHA.', 'advanced-country-blocker' );
} else {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( isset( $body['success'] ) && $body['success'] ) {
$verified = true;
} else {
$error_message = __( 'CAPTCHA verification failed.', 'advanced-country-blocker' );
}
}
break;
}
if ( $verified ) {
$ip = advcb_get_visitor_ip();
advcb_add_captcha_verified_ip( $ip );
wp_send_json_success( array(
'message' => __( 'Verification successful! Redirecting...', 'advanced-country-blocker' ),
'redirect' => home_url( '/' ),
) );
} else {
wp_send_json_error( array( 'message' => $error_message ) );
}
}
add_action( 'wp_ajax_advcb_verify_captcha', 'advcb_verify_captcha_challenge' );
add_action( 'wp_ajax_nopriv_advcb_verify_captcha', 'advcb_verify_captcha_challenge' );
/**
* Get visitor IP address (centralized function).
*/
function advcb_get_visitor_ip() {
if ( function_exists( 'wp_http_get_original_ip' ) ) {
return wp_http_get_original_ip();
}
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
$ip = 'unknown';
}
return $ip;
}
/**
* Show CAPTCHA challenge page.
*/
function advcb_show_captcha_challenge( $context = array() ) {
$provider = get_option( 'advcb_captcha_provider', 'recaptcha_v2' );
$site_key = get_option( 'advcb_captcha_site_key', '' );
if ( empty( $site_key ) ) {
advcb_show_block_page( $context );
return;
}
// Get scripts based on provider.
$script_url = '';
$inline_script = '';
switch ( $provider ) {
case 'recaptcha_v2':
$script_url = 'https://www.google.com/recaptcha/api.js';
$inline_script = '';
break;
case 'recaptcha_v3':
$script_url = 'https://www.google.com/recaptcha/api.js?render=' . rawurlencode( $site_key );
$inline_script = '';
break;
case 'hcaptcha':
$script_url = 'https://hcaptcha.com/1/api.js';
$inline_script = '';
break;
case 'turnstile':
$script_url = 'https://challenges.cloudflare.com/turnstile/v0/api.js';
$inline_script = '';
break;
}
$title = get_option( 'advcb_block_page_title', 'Access Restricted' );
$country_code = isset( $context['country_code'] ) ? $context['country_code'] : '';
?>
>
'Permission denied' ) );
}
global $wpdb;
$table_name = $wpdb->prefix . 'advcb_block_logs';
$range = isset( $_POST['range'] ) ? sanitize_text_field( wp_unslash( $_POST['range'] ) ) : '7';
// Calculate date range based on selection.
$intervals = array(
'1' => DAY_IN_SECONDS,
'7' => 7 * DAY_IN_SECONDS,
'30' => 30 * DAY_IN_SECONDS,
'90' => 90 * DAY_IN_SECONDS,
'365' => 365 * DAY_IN_SECONDS,
);
$interval = isset( $intervals[ $range ] ) ? $intervals[ $range ] : 7 * DAY_IN_SECONDS;
$start_date = gmdate( 'Y-m-d H:i:s', time() - $interval );
// Get total blocks in range.
$total_blocks = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE blocked_time >= %s",
$start_date
)
);
// Get unique IPs blocked.
$unique_ips = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(DISTINCT ip) FROM $table_name WHERE blocked_time >= %s",
$start_date
)
);
// Get unique countries.
$unique_countries = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(DISTINCT country_code) FROM $table_name WHERE blocked_time >= %s",
$start_date
)
);
// Get blocks per day for the chart.
$group_by = '1' === $range ? 'HOUR' : 'DAY';
$date_format = '1' === $range ? '%Y-%m-%d %H:00' : '%Y-%m-%d';
$time_series = $wpdb->get_results(
$wpdb->prepare(
"SELECT DATE_FORMAT(blocked_time, %s) as period, COUNT(*) as count
FROM $table_name
WHERE blocked_time >= %s
GROUP BY period
ORDER BY period ASC",
$date_format,
$start_date
),
ARRAY_A
);
// Get top countries.
$top_countries = $wpdb->get_results(
$wpdb->prepare(
"SELECT country_code, COUNT(*) as count
FROM $table_name
WHERE blocked_time >= %s AND country_code != ''
GROUP BY country_code
ORDER BY count DESC
LIMIT 10",
$start_date
),
ARRAY_A
);
// Get block reasons breakdown.
$block_reasons = $wpdb->get_results(
$wpdb->prepare(
"SELECT reason, COUNT(*) as count
FROM $table_name
WHERE blocked_time >= %s
GROUP BY reason
ORDER BY count DESC",
$start_date
),
ARRAY_A
);
// Sanitize block reasons for safe JavaScript output.
foreach ( $block_reasons as &$reason ) {
$reason['reason'] = sanitize_text_field( $reason['reason'] );
}
unset( $reason );
// Get top blocked IPs.
$top_ips = $wpdb->get_results(
$wpdb->prepare(
"SELECT ip, country_code, COUNT(*) as count, MAX(blocked_time) as last_seen
FROM $table_name
WHERE blocked_time >= %s
GROUP BY ip, country_code
ORDER BY count DESC
LIMIT 20",
$start_date
),
ARRAY_A
);
// Get all-time stats.
$all_time_total = $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );
$all_time_unique = $wpdb->get_var( "SELECT COUNT(DISTINCT ip) FROM $table_name" );
wp_send_json_success( array(
'total_blocks' => (int) $total_blocks,
'unique_ips' => (int) $unique_ips,
'unique_countries' => (int) $unique_countries,
'time_series' => $time_series,
'top_countries' => $top_countries,
'block_reasons' => $block_reasons,
'top_ips' => $top_ips,
'all_time_total' => (int) $all_time_total,
'all_time_unique' => (int) $all_time_unique,
) );
}
add_action( 'wp_ajax_advcb_get_dashboard_stats', 'advcb_get_dashboard_stats' );
/**
* Render the analytics dashboard page.
*/
function advcb_analytics_dashboard_page() {
wp_enqueue_script( 'advcb-chartjs', plugin_dir_url( __FILE__ ) . 'assets/js/chart.umd.js', array(), '4.4.1', true );
// Get available countries for flag display.
$countries = advcb_get_countries();
?>
$type,
'message' => $message,
),
MINUTE_IN_SECONDS
);
}
function advcb_geoip_admin_notices() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$notice = get_transient( advcb_geoip_notice_key() );
if ( false === $notice ) {
return;
}
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
if ( $screen && ! in_array( $screen->id, array( 'toplevel_page_advcb_settings', 'country-blocker_page_advcb_block_logs', 'country-blocker_page_advcb_analytics' ), true ) ) {
return;
}
delete_transient( advcb_geoip_notice_key() );
$type = isset( $notice['type'] ) ? $notice['type'] : 'success';
$class = 'notice notice-' . sanitize_html_class( $type );
echo '' . esc_html( $notice['message'] ) . '
';
}
add_action( 'admin_notices', 'advcb_geoip_admin_notices' );
function advcb_geoip_redirect_to_settings() {
$redirect = admin_url( 'admin.php?page=advcb_settings' );
wp_safe_redirect( $redirect );
exit;
}
function advcb_save_geoip_database_content( $content, $filename = 'GeoLite2-Country.mmdb' ) {
if ( ! function_exists( 'wp_mkdir_p' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$storage_dir = advcb_get_geoip_storage_dir();
if ( ! $storage_dir ) {
return new WP_Error( 'advcb_geoip_storage', __( 'Unable to determine the GeoIP storage directory.', 'advanced-country-blocker' ) );
}
if ( ! wp_mkdir_p( $storage_dir ) ) {
return new WP_Error( 'advcb_geoip_storage', __( 'Unable to create the GeoIP storage directory.', 'advanced-country-blocker' ) );
}
$filename = sanitize_file_name( $filename );
if ( '' === $filename ) {
$filename = 'GeoLite2-Country.mmdb';
}
if ( 'mmdb' !== strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) ) {
$filename .= '.mmdb';
}
$destination = trailingslashit( $storage_dir ) . $filename;
$written = file_put_contents( $destination, $content );
if ( false === $written ) {
return new WP_Error( 'advcb_geoip_write', __( 'Failed to save the GeoIP database file.', 'advanced-country-blocker' ) );
}
// Set secure file permissions using WP_Filesystem.
global $wp_filesystem;
if ( ! function_exists( 'WP_Filesystem' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
WP_Filesystem();
if ( $wp_filesystem ) {
$wp_filesystem->chmod( $destination, 0644 );
}
update_option( 'advcb_geoip_db_path', $filename );
return array(
'path' => $destination,
'filename' => $filename,
'bytes' => $written,
);
}
function advcb_handle_geoip_download() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'advanced-country-blocker' ) );
}
check_admin_referer( 'advcb_geoip_download' );
$url = isset( $_POST['advcb_geoip_url'] ) ? wp_unslash( $_POST['advcb_geoip_url'] ) : '';
$url = esc_url_raw( trim( $url ) );
if ( empty( $url ) ) {
advcb_add_geoip_notice( __( 'Please provide a valid download URL.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Validate URL and prevent SSRF attacks - only allow HTTPS from trusted domains.
$parsed_url = wp_parse_url( $url );
if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
advcb_add_geoip_notice( __( 'Invalid URL provided.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Only allow HTTPS URLs (prevent internal network access).
if ( isset( $parsed_url['scheme'] ) && 'https' !== $parsed_url['scheme'] ) {
advcb_add_geoip_notice( __( 'Only HTTPS URLs are allowed for security reasons.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Block private/reserved IP addresses in the host (prevent SSRF).
$host = strtolower( $parsed_url['host'] );
if ( preg_match( '/^(127\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.|localhost|::1|fe80::|fc00::)/i', $host ) ) {
advcb_add_geoip_notice( __( 'Access to internal/private network addresses is not allowed.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Additional allowed domains filter.
$allowed_domains = apply_filters( 'advcb_allowed_geoip_download_domains', array(
'github.com',
'githubusercontent.com',
'git.io',
'p3terx.com',
) );
$host_domain = $host;
// Remove 'www.' prefix for comparison.
$host_domain = preg_replace( '/^www\./', '', $host_domain );
$is_allowed_domain = false;
foreach ( $allowed_domains as $allowed_domain ) {
if ( $host_domain === $allowed_domain || str_ends_with( $host_domain, '.' . $allowed_domain ) ) {
$is_allowed_domain = true;
break;
}
}
if ( ! $is_allowed_domain ) {
advcb_add_geoip_notice( __( 'Downloads are only allowed from trusted GeoIP database sources.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
$response = wp_safe_remote_get(
$url,
array(
'timeout' => 60,
'stream' => false,
)
);
if ( is_wp_error( $response ) ) {
/* translators: %s: error message */
advcb_add_geoip_notice( sprintf( __( 'Download failed: %s', 'advanced-country-blocker' ), $response->get_error_message() ), 'error' );
advcb_geoip_redirect_to_settings();
}
$status_code = (int) wp_remote_retrieve_response_code( $response );
if ( 200 !== $status_code ) {
/* translators: %d: HTTP status code */
advcb_add_geoip_notice( sprintf( __( 'Download failed with status code %d.', 'advanced-country-blocker' ), $status_code ), 'error' );
advcb_geoip_redirect_to_settings();
}
$body = wp_remote_retrieve_body( $response );
// Enforce maximum file size limit (100MB) to prevent DoS.
$max_file_size = apply_filters( 'advcb_max_geoip_file_size', 100 * MB_IN_BYTES );
if ( strlen( $body ) > $max_file_size ) {
/* translators: %s: maximum file size */
advcb_add_geoip_notice( sprintf( __( 'The downloaded file is too large. Maximum size is %s.', 'advanced-country-blocker' ), size_format( $max_file_size ) ), 'error' );
advcb_geoip_redirect_to_settings();
}
if ( empty( $body ) ) {
advcb_add_geoip_notice( __( 'The downloaded file appears to be empty.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Validate MaxMind database header (must start with the MaxMind database signature).
if ( strlen( $body ) < 2 || substr( $body, 0, 2 ) !== "\x00\x00" ) {
// Try to detect if this is a gzip file.
if ( strlen( $body ) < 2 || substr( $body, 0, 2 ) !== "\x1f\x8b" ) {
advcb_add_geoip_notice( __( 'The downloaded file does not appear to be a valid MaxMind database file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
}
$filename = isset( $parsed_url['path'] ) ? basename( $parsed_url['path'] ) : 'GeoLite2-Country.mmdb';
// Sanitize filename to prevent any path traversal or malicious filenames.
$filename = sanitize_file_name( $filename );
if ( empty( $filename ) || '.mmdb' !== strtolower( substr( $filename, -5 ) ) ) {
$filename = 'GeoLite2-Country.mmdb';
}
$result = advcb_save_geoip_database_content( $body, $filename );
if ( is_wp_error( $result ) ) {
advcb_add_geoip_notice( $result->get_error_message(), 'error' );
} else {
/* translators: %s: filename */
advcb_add_geoip_notice( sprintf( __( 'GeoIP database saved as %s.', 'advanced-country-blocker' ), $result['filename'] ), 'success' );
}
advcb_geoip_redirect_to_settings();
}
add_action( 'admin_post_advcb_geoip_download', 'advcb_handle_geoip_download' );
function advcb_handle_geoip_upload() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to perform this action.', 'advanced-country-blocker' ) );
}
check_admin_referer( 'advcb_geoip_upload' );
if ( empty( $_FILES['advcb_geoip_file'] ) || ! is_array( $_FILES['advcb_geoip_file'] ) ) {
advcb_add_geoip_notice( __( 'No file was uploaded.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
$file = $_FILES['advcb_geoip_file'];
if ( ! empty( $file['error'] ) && UPLOAD_ERR_OK !== (int) $file['error'] ) {
advcb_add_geoip_notice( __( 'There was an error uploading the file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
$filename = isset( $file['name'] ) ? sanitize_file_name( wp_unslash( $file['name'] ) ) : '';
if ( '' === $filename ) {
$filename = 'GeoLite2-Country.mmdb';
}
if ( ! function_exists( 'wp_check_filetype_and_ext' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$file_type = wp_check_filetype_and_ext( $file['tmp_name'], $filename, array( 'mmdb' => 'application/octet-stream' ) );
if ( isset( $file_type['ext'] ) && 'mmdb' !== $file_type['ext'] ) {
advcb_add_geoip_notice( __( 'Please upload a valid .mmdb database file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
if ( ! is_uploaded_file( $file['tmp_name'] ) ) {
advcb_add_geoip_notice( __( 'The uploaded file could not be validated.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Enforce maximum file size limit (100MB) to prevent DoS.
$max_file_size = apply_filters( 'advcb_max_geoip_file_size', 100 * MB_IN_BYTES );
$file_size = filesize( $file['tmp_name'] );
if ( false === $file_size || $file_size > $max_file_size ) {
wp_delete_file( $file['tmp_name'] );
/* translators: %s: maximum file size */
advcb_add_geoip_notice( sprintf( __( 'The uploaded file is too large. Maximum size is %s.', 'advanced-country-blocker' ), size_format( $max_file_size ) ), 'error' );
advcb_geoip_redirect_to_settings();
}
$storage_dir = advcb_get_geoip_storage_dir();
if ( ! $storage_dir ) {
advcb_add_geoip_notice( __( 'Unable to determine the GeoIP storage directory.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
if ( ! function_exists( 'wp_mkdir_p' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
if ( ! wp_mkdir_p( $storage_dir ) ) {
advcb_add_geoip_notice( __( 'Unable to create the GeoIP storage directory.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
if ( 'mmdb' !== strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) ) {
$filename .= '.mmdb';
}
$destination = trailingslashit( $storage_dir ) . $filename;
// Read file content to validate it's a valid MaxMind database.
$file_content = file_get_contents( $file['tmp_name'] );
if ( false === $file_content ) {
wp_delete_file( $file['tmp_name'] );
advcb_add_geoip_notice( __( 'Failed to read the uploaded file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Validate MaxMind database header (must start with the MaxMind database signature).
if ( strlen( $file_content ) < 4 || substr( $file_content, 0, 4 ) !== "\x00\x00\x00\x00" ) {
// Try to detect if this is a gzip file.
if ( strlen( $file_content ) < 2 || substr( $file_content, 0, 2 ) !== "\x1f\x8b" ) {
wp_delete_file( $file['tmp_name'] );
advcb_add_geoip_notice( __( 'The uploaded file does not appear to be a valid MaxMind database file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
}
// Move uploaded file using WP_Filesystem.
global $wp_filesystem;
if ( ! function_exists( 'WP_Filesystem' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
WP_Filesystem();
if ( ! $wp_filesystem || ! $wp_filesystem->move( $file['tmp_name'], $destination, true ) ) {
advcb_add_geoip_notice( __( 'Failed to move the uploaded file.', 'advanced-country-blocker' ), 'error' );
advcb_geoip_redirect_to_settings();
}
// Set secure file permissions.
$wp_filesystem->chmod( $destination, 0644 );
update_option( 'advcb_geoip_db_path', $filename );
/* translators: %s: filename */
advcb_add_geoip_notice( sprintf( __( 'GeoIP database uploaded as %s.', 'advanced-country-blocker' ), $filename ), 'success' );
advcb_geoip_redirect_to_settings();
}
add_action( 'admin_post_advcb_geoip_upload', 'advcb_handle_geoip_upload' );
/**
* SANITIZE INPUTS
*/
function advcb_sanitize_allowed_countries( $input ) {
$countries = is_array( $input ) ? $input : explode( ',', $input );
return array_map( 'sanitize_text_field', array_map( 'trim', $countries ) );
}
function advcb_sanitize_blacklisted_ips( $input ) {
$ips = is_array( $input ) ? $input : explode( ',', $input );
return array_map( 'sanitize_text_field', array_map( 'trim', $ips ) );
}
function advcb_sanitize_boolean( $input ) {
return (bool) $input;
}
function advcb_sanitize_mode( $input ) {
return ( $input === 'block' ) ? 'block' : 'allow';
}
function advcb_sanitize_textarea( $input ) {
return wp_kses_post( $input );
}
function advcb_sanitize_http_status( $input ) {
$allowed = array( 403, 410, 451 );
$input = (int) $input;
return in_array( $input, $allowed, true ) ? $input : 403;
}
function advcb_sanitize_url( $input ) {
return esc_url_raw( trim( $input ) );
}
function advcb_sanitize_redirect_status( $input ) {
$allowed = array( 301, 302, 307, 308 );
$input = (int) $input;
return in_array( $input, $allowed, true ) ? $input : 302;
}
function advcb_sanitize_positive_int( $input ) {
return absint( $input );
}
function advcb_sanitize_file_path( $input ) {
if ( is_array( $input ) ) {
return '';
}
$input = is_string( $input ) ? wp_unslash( $input ) : '';
$input = trim( $input );
if ( '' === $input ) {
return '';
}
$normalized = wp_normalize_path( $input );
if ( function_exists( 'path_is_absolute' ) && path_is_absolute( $normalized ) ) {
return sanitize_text_field( $normalized );
}
if ( preg_match( '#^[a-zA-Z]:/#', $normalized ) ) {
return sanitize_text_field( $normalized );
}
return sanitize_file_name( wp_basename( $normalized ) );
}
function advcb_sanitize_geoip_source( $input ) {
if ( ! is_string( $input ) ) {
return 'api';
}
$input = strtolower( trim( $input ) );
$allowed = array( 'api', 'database' );
return in_array( $input, $allowed, true ) ? $input : 'api';
}
function advcb_sanitize_captcha_provider( $input ) {
if ( ! is_string( $input ) ) {
return 'recaptcha_v2';
}
$input = strtolower( trim( $input ) );
$allowed = array( 'recaptcha_v2', 'recaptcha_v3', 'hcaptcha', 'turnstile' );
return in_array( $input, $allowed, true ) ? $input : 'recaptcha_v2';
}
function advcb_sanitize_captcha_threshold( $input ) {
$threshold = floatval( $input );
if ( $threshold < 0 ) {
return 0.1;
}
if ( $threshold > 1 ) {
return 1.0;
}
return round( $threshold, 2 );
}
/**
* Sanitize bypass secret key.
* Rejects the insecure default 'OpenSesame' and enforces minimum length.
* Addresses CVE-2026-1675.
*/
function advcb_sanitize_secret_key( $input ) {
$input = sanitize_text_field( $input );
// Reject the old insecure default.
if ( 'OpenSesame' === $input ) {
add_settings_error(
'advcb_secret_key',
'advcb_insecure_key',
__( 'The secret key "OpenSesame" is a known insecure default and cannot be used. Please choose a unique key.', 'advanced-country-blocker' ),
'error'
);
// Return the existing value to avoid saving the insecure key.
return get_option( 'advcb_secret_key', '' );
}
// Enforce minimum length of 8 characters.
if ( ! empty( $input ) && strlen( $input ) < 8 ) {
add_settings_error(
'advcb_secret_key',
'advcb_short_key',
__( 'The secret key must be at least 8 characters long for security.', 'advanced-country-blocker' ),
'error'
);
return get_option( 'advcb_secret_key', '' );
}
return $input;
}
/**
* Sanitize CAPTCHA secret key - keep existing value if masked placeholder is sent.
*/
function advcb_sanitize_captcha_secret_key( $input ) {
// If the input is the masked placeholder, keep the existing value.
if ( '••••••••••••••••' === $input || strspn( $input, '••••••••••' ) === strlen( $input ) ) {
return get_option( 'advcb_captcha_secret_key', '' );
}
return sanitize_text_field( $input );
}
function advcb_replace_placeholders( $message, $context = array() ) {
$placeholders = array(
'{ip}' => isset( $context['ip'] ) ? $context['ip'] : '',
'{country_code}' => isset( $context['country_code'] ) ? $context['country_code'] : '',
'{reason}' => isset( $context['reason'] ) ? $context['reason'] : '',
);
foreach ( $placeholders as $placeholder => $value ) {
$message = str_replace( $placeholder, esc_html( $value ), $message );
}
return $message;
}
?>