<?php

class MainWP_ITSEC_Ban_Users_Validator extends MainWP_ITSEC_Validator {
	public function get_id() {
		return 'ban-users';
	}
	
	protected function sanitize_settings() {
		$this->sanitize_setting( 'bool', 'default', __( 'Default Blacklist', 'l10n-mainwp-ithemes-security-extension' ) );
		$this->sanitize_setting( 'bool', 'enable_ban_lists', __( 'Ban Lists', 'l10n-mainwp-ithemes-security-extension' ) );
		
		$this->sanitize_setting( 'newline-separated-ips', 'host_list', __( 'Ban Hosts', 'l10n-mainwp-ithemes-security-extension' ) );
		
		if ( is_array( $this->settings['host_list'] ) ) {
			require_once( MainWP_ITSEC_Core::get_core_dir() . '/lib/class-itsec-lib-ip-tools.php' );
			
			$whitelisted_hosts = array();
			$current_ip = MainWP_ITSEC_Lib::get_ip();
			
			foreach ( $this->settings['host_list'] as $host ) {
				if ( is_user_logged_in() && MainWP_ITSEC_Lib_IP_Tools::intersect( $current_ip, MainWP_ITSEC_Lib_IP_Tools::ip_wild_to_ip_cidr( $host ) ) ) {
					$this->set_can_save( false );
					
					/* translators: 1: input name, 2: invalid host */
					$this->add_error( sprintf( __( 'The following host in %1$s matches your current IP and cannot be banned: %2$s', 'l10n-mainwp-ithemes-security-extension' ), __( 'Ban Hosts', 'l10n-mainwp-ithemes-security-extension' ), $host ) );
					
					continue;
				}
				
				if ( MainWP_ITSEC_Lib::is_ip_whitelisted( $host ) ) {
					$whitelisted_hosts[] = $host;
				}
			}
			
			if ( ! empty( $whitelisted_hosts ) ) {
				$this->set_can_save( false );
				
				/* translators: 1: input name, 2: invalid host list */
				$this->add_error( wp_sprintf( _n( 'The following IP in %1$s is whitelisted and cannot be banned: %2$l', 'The following IPs in %1$s are whitelisted and cannot be banned: %2$l', count( $whitelisted_hosts ), 'l10n-mainwp-ithemes-security-extension' ), __( 'Ban Hosts', 'l10n-mainwp-ithemes-security-extension' ), $whitelisted_hosts ) );
			}
		}
		
		$this->sanitize_setting( array( $this, 'sanitize_agent_list_entry' ), 'agent_list', __( 'Ban User Agents', 'l10n-mainwp-ithemes-security-extension' ) );
	}
	
	protected function sanitize_agent_list_entry( $entry ) {
		return trim( sanitize_text_field( $entry ) );
	}
	
	protected function validate_settings() {
		if ( ! $this->can_save() ) {
			return;
		}
		
		
		$previous_settings = MainWP_ITSEC_Modules::get_settings( $this->get_id() );
		
		foreach ( $this->settings as $key => $val ) {
			if ( ! isset( $previous_settings[$key] ) || $previous_settings[$key] != $val ) {
				MainWP_ITSEC_Response::regenerate_server_config();
				break;
			}
		}
	}
}

MainWP_ITSEC_Modules::register_validator( new MainWP_ITSEC_Ban_Users_Validator() );
