Newer
Older
Digital_Repository / Repositories / statistics / scripts / fix-countries_src.php
<?php

/*
	Scan through the entire stats database and update all country details.
	Do this once a month when you download the latest country database for
	GeoIP from MaxMind.
*/

include("geoip.inc");

$gi = geoip_open("##GEOIP_DATABASE##",GEOIP_STANDARD);

// eprintstats db
$sqlserver = 'localhost';
$sqluser = 'eprintstatspriv';
$sqlpass = 'AuldGrizzel';
$sqldatabase = 'eprintstats';

// IP ranges for your local Intranet. Each pair represents the lower
// and upper bound of the range, respectively.
$local_name = 'Otago Intranet';
$local_IPs = array(
	array(
		'lower' => ip2long('139.80.0.0'),
		'upper' => ip2long('139.80.127.255'),
	),
);

###########################################
##
## No configuration required below here.
##
###########################################

$connect = mysql_connect ($sqlserver,$sqluser,$sqlpass);
$db = mysql_select_db($sqldatabase,$connect) or die("Could not connect");

$query = "select id, ip, country_code from view";
$result = mysql_query($query, $connect);
while ($row = mysql_fetch_assoc($result))
{
	$id = $row['id'];
	$ip = $row['ip'];
	$stored_country = $row['country_code'];
	$long_ip = ip2long($ip);

	// Determine country code and name.
	// If the number falls into the local intranet range, then
	// use that instead of GeoIP.
	$ip_long = ip2long($ip);
	foreach ($local_IPs as $key => $range)
	{
		if (($ip_long >= $range['lower']) && ($ip_long <= $range['upper']))
		{
			$country_code = 'T5';
			$country_name = $local_name;
		}
		else
		{
			$country_code = geoip_country_code_by_addr($gi, $ip);
			$country_name = geoip_country_name_by_addr($gi, $ip);
		}
	}
	
	// Only update the row if its country has changed.
	if ($stored_country != $country_code)
	{
		$update = "update view set country_code='" . $country_code . "', country_name='" . $country_name . "' where id=" . $id;
		$result2 = mysql_query($update, $connect);
	}
}

	/*
		Keep track of where we are. Should avoid duplication of results
		if the script is run more than once on the same log file
	*/

$query = "INSERT into lastproc (lastproc) values('".$request_date."')";
$result = mysql_query($query,$connect);

#print "Records counted: $counter\n";
#print "Last count: $request_date\n";
mysql_close($connect);

?>