""){ if (file_exists('/usr/local/pkg/countryblock/'.$iso.'.txt')) $ips.=file_get_contents('/usr/local/pkg/countryblock/'.$iso.'.txt'); } } #create all ip block lists based on gui file_put_contents('/usr/local/pkg/cb.txt',$ips, LOCK_EX); #write white_list to filesystem file_put_contents('/usr/local/pkg/cbw.txt',cb_text_area_decode($countryblock_config['whitelist']), LOCK_EX); #edit or assign alias "Countryblock" and "CountryblockWL" $aliases=$config['aliases']['alias']; #print "
";
	$new_aliases=array();
	if ($ips != ""){
		#create or reaply alias
		$new_aliases[]=array("name"=> 'Countryblock',
					  		 "url"=> $web_local.'?cb=1',
					  		 "updatefreq"=> "7",
					  		 "address"=>"",
					  		 "descr"=> "Countryblock deny list",
					  		 "type"=> "urltable",
					  		 "detail"=> "DO NOT EDIT THIS ALIAS");
		#force alias file update
		if (! is_dir('/var/db/aliastables/'))
			mkdir ('/var/db/aliastables/',0755);
		if (file_exists('/var/db/aliastables/Countryblock.txt'))
			file_put_contents('/var/db/aliastables/Countryblock.txt',$ips, LOCK_EX);
		}
	else{
		#remove previous aliastable if exist
		if (file_exists('/var/db/aliastables/Countryblock.txt'))
			unlink('/var/db/aliastables/Countryblock.txt');
	}
	
	if (cb_text_area_decode($countryblock_config['whitelist']) != ""){
		#create or reaply alias
		$new_aliases[]=array("name"=> 'CountryblockWL',
						  	 "url"=> $web_local.'?cbw=1',
						  	 "updatefreq"=> "7",
						  	 "address"=>"",
						  	 "descr"=> "Countryblock white list",
						  	 "type"=> "urltable",
						  	 "detail"=> "DO NOT EDIT THIS ALIAS");
		#force alias file update
		if (! is_dir('/var/db/aliastables/'))
			mkdir ('/var/db/aliastables/',0755);
		if (file_exists('/var/db/aliastables/CountryblockWL.txt'))
			file_put_contents('/var/db/aliastables/CountryblockWL.txt',cb_text_area_decode($countryblock_config['whitelist']), LOCK_EX);
		}
	else{
		#remove previous aliastable if exist
		if (file_exists('/var/db/aliastables/CountryblockWL.txt'))
			unlink('/var/db/aliastables/CountryblockWL.txt');
	}
	
	if (is_array($aliases))
	  foreach($aliases as $cbalias){
		if (! preg_match("/Countryblock.*list/",$cbalias['descr']))
			$new_aliases[]=	$cbalias;
	}
	$config['aliases']['alias']=$new_aliases;
	# check contryblock filter options
	$rules=$config['filter']['rule'];
	$ifaces = $countryblock_config['inbound_interface'];
    foreach (explode(",", $ifaces) as $i => $iface) {
    	if (cb_text_area_decode($countryblock_config['whitelist']) != ""){
			${$iface}[0]=array("id" => "",
					"type"=>"pass",
					"tag"=>	"",
					"interface" => $iface,
					"tagged"=> "",
					"max"=>	 "",
					"max-src-nodes"=>"",
					"max-src-conn"=> "",
					"max-src-states"=>"",
					"statetimeout"=>"",
					"statetype"=>"keep state",
					"os"=> "",
					"source"=>array("address"=>"CountryblockWL"),
    				"destination"=>array("any"=>""),
    				"descr"=>"Countryblock inbound whitelist rule");

			if ($countryblock_config['enable_log'])
				${$iface}[0]["log"]="";
    	}
		if ($ips != ""){
			${$iface}[1]=array(	"id" => "",
							"type"=>"block",
							"tag"=>	"",
							"interface" => $iface,
							"tagged"=> "",
							"max"=>	 "",
							"max-src-nodes"=>"",
							"max-src-conn"=> "",
							"max-src-states"=>"",
							"statetimeout"=>"",
						    "statetype"=>"keep state",
							"os"=> "",
							"source"=>array("address"=>"Countryblock"),
    						"destination"=>array("any"=>""),
    						"descr"=>"Countryblock inbound deny rule");

			if ($countryblock_config['enable_log'])
				${$iface}[1]["log"]="";
		}
	}
	$ifaces = $countryblock_config['outbound_interface'];
    foreach (explode(",", $ifaces) as $i => $iface) {
    	if (cb_text_area_decode($countryblock_config['whitelist']) != ""){
			${$iface}[2]=array(	"id" => "",
							"type"=>"pass",
							"tag"=>	"",
							"interface" => $iface,
							"tagged"=> "",
							"max"=>	 "",
							"max-src-nodes"=>"",
							"max-src-conn"=> "",
							"max-src-states"=>"",
							"statetimeout"=>"",
							"statetype"=>"keep state",
							"os"=> "",
    						"source"=>array("any"=>""),
    						"destination"=>array("address"=>"CountryblockWL"),
    						"descr"=>"Countryblock outbound whitelist rule");
		if ($countryblock_config['enable_log'])
				${$iface}[2]["log"]="";			
    	}
		if ($ips != ""){
			${$iface}[3]= array("id" => "",
							"type"=>"block",
							"tag"=>	"",
							"interface" => $iface,
							"tagged"=> "",
							"max"=>	 "",
							"max-src-nodes"=>"",
							"max-src-conn"=> "",
							"max-src-states"=>"",
							"statetimeout"=>"",
							"statetype"=>"keep state",
							"os"=> "",
    						"source"=>array("any"=>""),
    						"destination"=>array("address"=>"Countryblock"),
    						"descr"=>"Countryblock inbound deny rule");
			if ($countryblock_config['enable_log'])
				${$iface}[3]["log"]="";
			
		}

	}
	$last_iface="";
	foreach ($rules as $rule){
		if ($rule['interface'] <> $last_iface){
			$last_iface = $rule['interface'];
			#apply countryblock rules if enabled
			if ($config['installedpackages']['countryblock']['config'][0]['enable_cb'] == "on" && is_array(${$rule['interface']}))
				foreach (${$rule['interface']} as $cb_rules)
					$new_rules[]=$cb_rules;
		}
		if (!preg_match("/Countryblock.*rule/",$rule['descr']))
			$new_rules[]=$rule;	
	}
	$config['filter']['rule']=$new_rules;

	#save and apply all changes
	write_config();
	filter_configure();
		
	countryblock_sync_on_changes();
}

function countryblock_validate_input($post, &$input_errors) {
	foreach ($post as $key => $value) {
		if (empty($value))
			continue;
		if($key == "greet_time" && !preg_match("/(\d+),(\d+)(s|m|h|w)/",$value))
				$input_errors[] = "Wrong greet time sintax.";			
		if($key == "message_size_limit" && !is_numeric($value))
				$input_errors[] = "Message size limit must be numeric.";
		if($key == "process_limit" && !is_numeric($value))
				$input_errors[] = "Process limit must be numeric.";	
		if($key == "freq" && (!preg_match("/^\d+(h|m|d)$/",$value) || $value == 0))
				$input_errors[] = "A valid number with a time reference is required for the field 'Frequency'";
		if (substr($key, 0, 2) == "dc" && !is_hostname($value))
				$input_errors[] = "{$value} is not a valid host name.";
		if (substr($key, 0, 6) == "domain" && is_numeric(substr($key, 6))) {
			if (!is_domain($value))
				$input_errors[] = "{$value} is not a valid domain name.";
		} else if (substr($key, 0, 12) == "mailserverip" && is_numeric(substr($key, 12))) {
			if (empty($post['domain' . substr($key, 12)]))
				$input_errors[] = "Domain for {$value} cannot be blank.";
			if (!is_ipaddr($value) && !is_hostname($value))
				$input_errors[] = "{$value} is not a valid IP address or host name.";
		}
	}
}

function countryblock_php_install_command() {
	include_once '/usr/local/www/countryblock.php';
	countryblock_get_countries();
	sync_package_countryblock();
}

function countryblock_php_deinstall_command() {
	global $config;
	$config['installedpackages']['countryblock']['config'][0]['enable_cb']="";
	write_config();
	sync_package_countryblock();
}

/* Uses XMLRPC to synchronize the changes to a remote node */
function countryblock_sync_on_changes() {
	global $config, $g;
	log_error("[countryblock] countryblock_xmlrpc_sync.php is starting.");
	$synconchanges = $config['installedpackages']['countryblocksync']['config'][0]['synconchanges'];	
	if(!$synconchanges) 
		return;
	foreach ($config['installedpackages']['countryblocksync']['config'] as $rs ){
		foreach($rs['row'] as $sh){
		$sync_to_ip = $sh['ipaddress'];
		$password   = $sh['password'];
		if($password && $sync_to_ip)
			countryblock_do_xmlrpc_sync($sync_to_ip, $password);
		}
	}
	log_error("[countryblock] countryblock_xmlrpc_sync.php is ending.");
}

/* Do the actual XMLRPC sync */
function countryblock_do_xmlrpc_sync($sync_to_ip, $password) {
	global $config, $g;

	if(!$password)
		return;

	if(!$sync_to_ip)
		return;

	$xmlrpc_sync_neighbor = $sync_to_ip;
    if($config['system']['webgui']['protocol'] != "") {
		$synchronizetoip = $config['system']['webgui']['protocol'];
		$synchronizetoip .= "://";
    }
    $port = $config['system']['webgui']['port'];
    /* if port is empty lets rely on the protocol selection */
    if($port == "") {
		if($config['system']['webgui']['protocol'] == "http") 
			$port = "80";
		else 
			$port = "443";
    }
	$synchronizetoip .= $sync_to_ip;

	/* xml will hold the sections to sync */
	$xml = array();
	$xml['countryblock'] = $config['installedpackages']['countryblock'];
	$xml['countryblockafrica'] = $config['installedpackages']['countryblockafrica'];
	$xml['countryblockantartica'] = $config['installedpackages']['countryblockantartica'];
	$xml['countryblockasia'] = $config['installedpackages']['countryblockasia'];
	$xml['countryblockeurope'] = $config['installedpackages']['countryblockeurope'];
	$xml['countryblocknorthamerica'] = $config['installedpackages']['countryblocknorthamerica'];
	$xml['countryblockoceania'] = $config['installedpackages']['countryblockoceania'];
	$xml['countryblocksouthamerica'] = $config['installedpackages']['countryblocksouthamerica'];
	/* assemble xmlrpc payload */
	$params = array(
		XML_RPC_encode($password),
		XML_RPC_encode($xml)
	);

	/* set a few variables needed for sync code borrowed from filter.inc */
	$url = $synchronizetoip;
	log_error("Beginning countryblock XMLRPC sync to {$url}:{$port}.");
	$method = 'pfsense.merge_installedpackages_section_xmlrpc';
	$msg = new XML_RPC_Message($method, $params);
	$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
	$cli->setCredentials('admin', $password);
	if($g['debug'])
		$cli->setDebug(1);
	/* send our XMLRPC message and timeout after 250 seconds */
	$resp = $cli->send($msg, "250");
	if(!$resp) {
		$error = "A communications error occurred while attempting countryblock XMLRPC sync with {$url}:{$port}.";
		log_error($error);
		file_notice("sync_settings", $error, "countryblock Settings Sync", "");
	} elseif($resp->faultCode()) {
		$cli->setDebug(1);
		$resp = $cli->send($msg, "250");
		$error = "An error code was received while attempting countryblock XMLRPC sync with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
		log_error($error);
		file_notice("sync_settings", $error, "countryblock Settings Sync", "");
	} else {
		log_error("countryblock XMLRPC sync successfully completed with {$url}:{$port}.");
	}
	
	/* tell countryblock to reload our settings on the destionation sync host. */
	$method = 'pfsense.exec_php';
	$execcmd  = "require_once('/usr/local/pkg/countryblock.inc');\n";
	$execcmd .= "sync_package_countryblock();";
	
	/* assemble xmlrpc payload */
	$params = array(
		XML_RPC_encode($password),
		XML_RPC_encode($execcmd)
	);

	log_error("countryblock XMLRPC reload data {$url}:{$port}.");
	$msg = new XML_RPC_Message($method, $params);
	$cli = new XML_RPC_Client('/xmlrpc.php', $url, $port);
	$cli->setCredentials('admin', $password);
	$resp = $cli->send($msg, "250");
	if(!$resp) {
		$error = "A communications error occurred while attempting countryblock XMLRPC sync with {$url}:{$port} (pfsense.exec_php).";
		log_error($error);
		file_notice("sync_settings", $error, "countryblock Settings Sync", "");
	} elseif($resp->faultCode()) {
		$cli->setDebug(1);
		$resp = $cli->send($msg, "250");
		$error = "An error code was received while attempting countryblock XMLRPC exec with {$url}:{$port} - Code " . $resp->faultCode() . ": " . $resp->faultString();
		log_error($error);
		file_notice("sync_settings", $error, "countryblock Settings Sync", "");
	} else {
		log_error("countryblock XMLRPC reload data success with {$url}:{$port} (pfsense.exec_php).");
	}

}

?>