settings = Plugin::get_settings( 'security' );
add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ], 20 );
add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] );
// Register PHP-layer bot blocking for non-Apache servers
if( !empty( $this->settings['block_specific_bots_enabled'] ) && !$this->is_apache_compatible() ) {
add_action( 'init', [ $this, 'php_block_bots' ], 1 );
}
}
/**
* Modifies and returns an array of settings fields to include bot blocking configuration options.
*
* @param array $fields The current fields array to be modified with additional settings.
*
* @return array The modified fields array including new bot blocking configuration options.
*/
public function adminease_settings_fields( array $fields ): array {
$fields['security']['fields'][] = [
'type' => 'switch',
'id' => 'block-specific-bots-enabled',
'name' => 'adminease[security][block_specific_bots_enabled]',
'value' => $this->settings['block_specific_bots_enabled'] ?? '',
'label_class' => 'adminease-switch',
'input_class' => 'form-control toggle-field',
'label' => __( 'Enable bots blocking', 'adminease' ),
'description' => __( "Block malicious or unwanted bots from accessing your site. Protect your server resources from aggressive crawlers, prevent content scraping, reduce bandwidth waste, and improve site performance by filtering out automated traffic that doesn't serve your business goals. Control which bots can access your content with precision.", 'adminease' ),
'field_description' => __( 'Select common bots to block from accessing your site', 'adminease' ),
'child_fields' => [
[
'type' => 'select',
'id' => 'block-specific-bots',
'name' => 'adminease[security][block_specific_bots][]',
'value' => $this->settings['block_specific_bots'] ?? [],
'options' => Utils::get_bots_list(),
'has_optgroups' => true,
'label_class' => 'adminease-label',
'input_class' => 'form-control adminease-choices',
'wrapper_class' => 'form-group-child',
'label' => __( 'Block common bots', 'adminease' ),
'field_description' => __( 'Select common bots to block from accessing your site', 'adminease' ),
'attributes' => [
'data-parent' => 'block-specific-bots-enabled',
'multiple' => 'multiple',
'data-allow_clear' => true,
'data-allow_select_all' => true,
],
],
[
'type' => 'textarea',
'id' => 'block-specific-bots-custom',
'name' => 'adminease[security][block_specific_bots_custom]',
'value' => str_replace( ' ', "\n", ( $this->settings['block_specific_bots_custom'] ?? '' ) ),
'label_class' => 'adminease-label',
'input_class' => 'form-control',
'wrapper_class' => 'form-group-child',
'label' => __( 'Block specific bots', 'adminease' ),
'field_description' => __( 'List of custom bot user agents to block, one per line. You can use the Network Viewer Log feature to view bot traffic.
Example:
BadBot
SpamBot3000
EvilScraper', 'adminease' ),
'attributes' => [
'data-parent' => 'block-specific-bots-enabled',
],
],
],
];
return $fields;
}
/**
* PHP-layer bot blocking for non-Apache servers (Nginx, LiteSpeed native, etc.)
* Runs at priority 1 on 'init' to block bots before WordPress processes the request.
*
* @return void
*/
public function php_block_bots(): void {
$blocked_bots = get_option( 'adminease_blocked_bots', [] );
if( empty( $blocked_bots ) ) {
return;
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below
$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
if( empty( $user_agent ) ) {
return;
}
foreach( $blocked_bots as $bot ) {
if( stripos( $user_agent, $bot ) !== false ) {
http_response_code( 403 );
exit;
}
}
}
/**
* Generate .htaccess rules for blocking bots (Apache / LiteSpeed with .htaccess support)
*
* @param array $bots Array of bot user agents to block
*
* @return string
*/
private function generate_bot_blocking_rules( array $bots ): string {
if( empty( $bots ) ) {
return '';
}
$code = "\n";
$code .= "\tRewriteEngine On\n\n";
$code .= "\t# Block specific bots\n";
$chunks = array_chunk( $bots, 10 );
$last_index = count( $chunks ) - 1;
foreach( $chunks as $index => $chunk ) {
$bot_pattern = implode( '|', array_map( [ $this, 'escape_bot_for_apache_regex' ], $chunk ) );
if( $index < $last_index ) {
$code .= "\tRewriteCond %{HTTP_USER_AGENT} ({$bot_pattern}) [NC,OR]\n";
} else {
$code .= "\tRewriteCond %{HTTP_USER_AGENT} ({$bot_pattern}) [NC]\n";
}
}
$code .= "\tRewriteRule ^(.*)$ - [F,L]\n";
$code .= "\n";
return $code;
}
/**
* Escape a bot name for use in an Apache RewriteCond regex pattern.
*
* @param string $bot The bot name to escape.
*
* @return string
*/
private function escape_bot_for_apache_regex( string $bot ): string {
return str_replace(
[ ' ', '.', '(', ')', '[', ']', '+', '*', '?', '{', '}', '$', '^' ],
[ '\s', '\.', '\(', '\)', '\[', '\]', '\+', '\*', '\?', '\{', '\}', '\$', '\^' ],
$bot
);
}
/**
* Get combined list of blocked bots from common and custom selections.
* Both sources are sanitized to the same standard.
*
* @param array $common_bots
* @param string $custom_bots
*
* @return array
*/
private function get_blocked_bots( array $common_bots, string $custom_bots ): array {
$blocked_bots = [];
// Add selected common bots with the same sanitization applied to custom bots
if( !empty( $common_bots ) ) {
$common_bots = array_filter( array_map( [ $this, 'sanitize_bot_name' ], $common_bots ) );
$blocked_bots = array_merge( $blocked_bots, $common_bots );
}
// Add custom bots with validation
if( !empty( $custom_bots ) ) {
$custom_bot_list = preg_split( '/[\s\n\r]+/', trim( $custom_bots ) ) ? : [];
$custom_bot_list = array_filter( array_map( [ $this, 'sanitize_bot_name' ], $custom_bot_list ) );
$blocked_bots = array_merge( $blocked_bots, $custom_bot_list );
}
$blocked_bots = array_filter( array_unique( $blocked_bots ) );
// Limit total number of bots to prevent performance issues
if( count( $blocked_bots ) > 200 ) {
$blocked_bots = array_slice( $blocked_bots, 0, 200 );
}
return array_values( $blocked_bots );
}
/**
* Sanitize a single bot name.
* Strips disallowed characters and enforces a maximum length.
*
* @param string $bot Raw bot name.
*
* @return string Sanitized bot name.
*/
private function sanitize_bot_name( string $bot ): string {
$bot = trim( $bot );
// Only allow alphanumeric, spaces, hyphens, underscores, and dots
$bot = preg_replace( '/[^a-zA-Z0-9\s\-_.]/', '', $bot );
// Limit length to prevent abuse
if( strlen( $bot ) > 100 ) {
$bot = substr( $bot, 0, 100 );
}
return $bot;
}
/**
* Determine whether the current server supports .htaccess-based bot blocking.
* Returns true for Apache and LiteSpeed running in Apache-compatibility mode.
*
* @return bool
*/
private function is_apache_compatible(): bool {
if( !isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
return false;
}
$server = strtolower( sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) );
if( false !== strpos( $server, 'apache' ) ) {
return true;
}
// LiteSpeed with Apache-compatibility mode exposes apache_get_modules()
if( false !== strpos( $server, 'litespeed' ) && function_exists( 'apache_get_modules' ) ) {
return true;
}
return false;
}
/**
* Process settings after save.
* On Apache/LiteSpeed: writes .htaccess rules.
* On Nginx/other: stores the bot list in a WP option for PHP-layer blocking.
*
* @param array $settings
*/
public function adminease_settings_saved( array $settings ): void {
if( !current_user_can( 'manage_options' ) ) {
return;
}
$block_specific_bots_enabled = $settings['security']['block_specific_bots_enabled'] ?? false;
$block_specific_bots = $settings['security']['block_specific_bots'] ?? [];
$block_specific_bots_custom = $settings['security']['block_specific_bots_custom'] ?? '';
$blocked_bots = [];
if( $block_specific_bots_enabled ) {
$blocked_bots = $this->get_blocked_bots( $block_specific_bots, $block_specific_bots_custom );
}
if( $this->is_apache_compatible() ) {
// Apache / LiteSpeed: write .htaccess rules
$code = '';
if( !empty( $blocked_bots ) ) {
$code = $this->generate_bot_blocking_rules( $blocked_bots );
}
FileHandler::get_instance()->stack_htaccess_rule( 'BLOCK_SPECIFIC_BOTS', $code );
} else {
// Nginx / other: store bot list for PHP-layer blocking on 'init'
if( !empty( $blocked_bots ) ) {
update_option( 'adminease_blocked_bots', $blocked_bots );
} else {
delete_option( 'adminease_blocked_bots' );
}
}
}
}