settings = Plugin::get_settings( 'security' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] );
self::$is_cloudflare_enabled = Utils::is_cloudflare_enabled();
self::$is_geoip_enabled = Utils::is_geoip_enabled();
self::$is_blocking_countries_enabled = ( self::$is_cloudflare_enabled || self::$is_geoip_enabled );
add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] );
if( !self::$is_blocking_countries_enabled ) {
return;
}
if( !empty( $this->settings['block_specific_countries_enabled'] ) && !Utils::is_apache_compatible() ) {
add_action( 'init', [ $this, 'php_block_countries' ], 1 );
}
}
/**
* Generates and updates the settings fields for configuring security options.
* Specifically includes fields for blocking visitors from specific countries.
*
* @param array $fields An associative array of existing settings fields with their configurations.
*
* @return array The modified array of settings fields with the added configuration for blocking specific countries.
*/
public function adminease_settings_fields( array $fields ): array {
$countries = Utils::get_countries_iso();
$visitor_country_code = Utils::get_client_country();
if( isset( $countries[ $visitor_country_code ] ) ) {
unset( $countries[ $visitor_country_code ] );
}
$fields['security']['fields'][] = [
'type' => 'switch',
'id' => 'block-specific-countries-enabled',
'name' => 'adminease[security][block_specific_countries_enabled]',
'value' => $this->settings['block_specific_countries_enabled'] ?? false,
'label_class' => 'pwp-switch',
'input_class' => 'pwp-field-input toggle-field',
'label' => __( 'Enable country blocking', 'adminease' ),
'risk' => 'careful',
'breaks' => __( 'Visitors from the chosen countries cannot reach your site.', 'adminease' ),
'field_description' => $this->get_enable_field_description(),
'child_fields' => [
[
'type' => 'select',
'id' => 'block-specific-countries',
'name' => 'adminease[security][block_specific_countries][]',
'value' => $this->settings['block_specific_countries'] ?? '',
'options' => $countries,
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input adminease-choices',
'wrapper_class' => 'form-group-child',
'label' => __( 'Block specific countries', 'adminease' ),
'attributes' => [
'data-parent' => 'block-specific-countries-enabled',
'multiple' => 'multiple',
'data-allow_clear' => true,
'data-allow_select_all' => true,
],
],
[
'type' => 'textarea',
'id' => 'block-specific-countries-excluded-paths',
'name' => 'adminease[security][block_specific_countries_excluded_paths]',
'value' => $this->settings['block_specific_countries_excluded_paths'] ?? '',
'label_class' => 'pwp-field-label',
'input_class' => 'pwp-field-input',
'wrapper_class' => 'form-group-child',
'label' => __( 'Exclude paths from country blocking', 'adminease' ),
'description' => __( 'Enter URL path prefixes (one per line) that should bypass the country block - useful for REST API callbacks, webhooks, AJAX, and cron. Examples: /wp-json/, /wp-admin/, /wp-cron.php', 'adminease' ),
'attributes' => [
'data-parent' => 'block-specific-countries-enabled',
'rows' => '5',
'placeholder' => "/wp-json/\n/wp-admin/admin-ajax.php\n/wp-cron.php",
],
],
],
];
return $fields;
}
/**
* Build the description shown under the parent toggle.
* Reports how the block will actually be enforced on this particular site, since that
* depends on whether the server reads .htaccess at all.
*
* @return string
*/
private function get_enable_field_description(): string {
if( !self::$is_blocking_countries_enabled ) {
return sprintf(
'%s',
sprintf(
/* translators: %s: link reading "see what it requires", pointing at the feature's help section further down the page. */
__( 'Unfortunately your server does not support this feature - %s.', 'adminease' ),
sprintf(
'%s',
esc_html__( 'see what it requires', 'adminease' )
)
)
);
}
$description = __( 'Block visitors from specific countries based on geolocation.', 'adminease' );
$php_notice = Utils::get_php_enforcement_notice();
if( '' !== $php_notice ) {
$description .= '
' . $php_notice;
}
return $description;
}
/**
* Processes and saves settings specific to blocking visitors from certain countries
* based on different compatibility modules (Cloudflare, MaxMind, GeoIP).
*
* @param array $sanitized_settings The array of settings, including the 'security' section which defines the countries to block.
*
* @return void
*/
public function adminease_settings_saved( array $sanitized_settings ): void {
if( !Utils::is_apache_compatible() ) {
if( file_exists( ABSPATH . '.htaccess' ) ) {
FileHandler::get_instance()->stack_htaccess_rule( 'BLOCK_SPECIFIC_COUNTRIES', '' );
}
return;
}
$block_specific_bots_enabled = $sanitized_settings['security']['block_specific_countries_enabled'] ?? false;
$block_specific_countries = $sanitized_settings['security']['block_specific_countries'] ?? [];
$excluded_paths_raw = $sanitized_settings['security']['block_specific_countries_excluded_paths'] ?? '';
$excluded_paths = $this->parse_excluded_paths( (string) $excluded_paths_raw );
$code = '';
if( $block_specific_bots_enabled ) {
if( !empty( $block_specific_countries ) && self::$is_cloudflare_enabled ) {
$code = "\n";
$code .= "\tRewriteEngine On\n\n";
$code .= "\t# Cloudflare compatibility\n";
foreach( $excluded_paths as $path ) {
$code .= "\tRewriteCond %{REQUEST_URI} !^" . $path . "\n";
}
foreach( $block_specific_countries as $index => $country ) {
$or_flag = ( $index < count( $block_specific_countries ) - 1 ) ? ' [OR]' : '';
$code .= "\tRewriteCond %{HTTP:CF-IPCountry} ^{$country}$" . $or_flag . "\n";
}
$code .= "\tRewriteRule ^(.*)$ - [F,L]\n";
$code .= "\n";
}
if( !empty( $block_specific_countries ) && self::$is_geoip_enabled ) {
$countries_pipe = implode( '|', $block_specific_countries );
$code .= "\n\n";
$code .= "\tGeoIPEnable On\n";
foreach( $excluded_paths as $path ) {
$code .= "\tSetEnvIfNoCase Request_URI \"^" . $path . "\" AllowedPath\n";
}
$code .= "\tSetEnvIf GEOIP_COUNTRY_CODE ^($countries_pipe)$ BlockCountry\n";
$code .= "\tOrder Allow,Deny\n";
$code .= "\tAllow from all\n";
$code .= "\tDeny from env=BlockCountry\n";
if( !empty( $excluded_paths ) ) {
$code .= "\tAllow from env=AllowedPath\n";
}
$code .= "\n";
}
}
$code = apply_filters( 'adminease_block_specific_countries_code', $code, $sanitized_settings );
FileHandler::get_instance()->stack_htaccess_rule( 'BLOCK_SPECIFIC_COUNTRIES', $code );
}
/**
* PHP-layer country gate for servers that do not read .htaccess.
*
* Mirrors the rewrite rules: the visitor's country is resolved from the same
* Cloudflare / GeoIP data the directives read, the same path exclusions are honoured,
* and anything left over from a blocked country is refused with a 403.
*
* Deliberately does not exempt logged-in users or administrators, because the
* .htaccess path runs before PHP and cannot know about them. Adding the exemption on
* one server type only would mean the same settings behave differently depending on
* the host, which is worse than the lockout risk it would remove. Path exclusions are
* the supported way to keep an entry point reachable.
*
* Runs at priority 1 to match BlockSpecificBots::php_block_bots().
*
* @return void
*/
public function php_block_countries(): void {
if( wp_doing_cron() ) {
return;
}
if( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
$countries = $this->settings['block_specific_countries'] ?? [];
if( empty( $countries ) || !is_array( $countries ) ) {
return;
}
$country = Utils::get_client_country();
if( '' === $country || !in_array( $country, $countries, true ) ) {
return;
}
if( $this->is_request_excluded() ) {
return;
}
if( true === apply_filters( 'adminease_block_specific_countries_allow_request', false ) ) {
return;
}
nocache_headers();
header( 'Content-Type: text/plain; charset=utf-8' );
status_header( 403 );
echo 'Forbidden';
exit;
}
/**
* Checks the current request URI against the configured path exclusions.
*
* parse_excluded_paths() escapes each path with preg_quote() using '#' as the
* delimiter, so the same list can be matched here with an anchored, case-insensitive
* prefix test - the PHP equivalent of the `RewriteCond %{REQUEST_URI} !^...` and
* `SetEnvIfNoCase Request_URI "^..."` directives the Apache path writes.
*
* @return bool True when the request must bypass the country block.
*/
private function is_request_excluded(): bool {
$excluded_paths = self::parse_excluded_paths( (string) ( $this->settings['block_specific_countries_excluded_paths'] ?? '' ) );
if( empty( $excluded_paths ) ) {
return false;
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
if( '' === $request_uri ) {
return false;
}
foreach( $excluded_paths as $path ) {
if( 1 === preg_match( '#^' . $path . '#i', $request_uri ) ) {
return true;
}
}
return false;
}
/**
* Parses the excluded-paths textarea value into a normalised, regex-escaped list.
* - Trims whitespace, skips empty lines and lines starting with '#'.
* - Ensures each path begins with '/'.
* - Escapes regex metacharacters so dots and other specials match literally in Apache.
*
* @param string $raw The raw textarea value (one path per line).
*
* @return array List of regex-escaped path prefixes, ready to embed after `^` in RewriteCond / SetEnvIf.
*/
public static function parse_excluded_paths( string $raw ): array {
$paths = [];
foreach( preg_split( '/\r\n|\r|\n/', $raw ) as $line ) {
$line = trim( $line );
if( '' === $line || 0 === strpos( $line, '#' ) ) {
continue;
}
if( '/' !== $line[0] ) {
$line = '/' . $line;
}
$paths[] = preg_quote( $line, '#' );
}
return array_values( array_unique( $paths ) );
}
}