#!/usr/local/bin/php
<?php

require_once 'DB.php';

/*
 *
 * CREATE TABLE `ip_map` (
 *  `code` char(2) NOT NULL default '',
 *  `registry` varchar(10) NOT NULL default '',
 *  `ip_from` int(10) unsigned NOT NULL default '0',
 *  `ip_to` int(10) unsigned NOT NULL default '0',
 *  KEY `code` (`code`)
 * ) TYPE=MyISAM;
 *
 */

$dsn "mysql://user:pass@host/ip2country";
$dbh DB::connect($dsntrue);

if (
DB::isError($dbh)) {
    die (
$dbh->getMessage());
}

$registries = array("apnic"   => "ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest",
                    
"arin"    => "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-latest",
                    
"lacnic"  => "ftp://lacnic.net/pub/stats/lacnic/delegated-lacnic-latest",
                    
"ripencc" => "ftp://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-latest");

/*
 *
 * RIR-format:
 * registry|cc|type|start|value|date|status[|extensions...]
 *
 */

$dbh->query("DELETE FROM ip_map");

foreach (
$registries as $registry => $url) {
    
$list file($url);
    foreach (
$list as $line_num => $line) {
        if (
preg_match("/^[a-z]+\|[a-zA-Z]{2}\|ipv4\|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\|/"$line)) {
            list(
$registry$countrycode$type$ip$ipcount$date$status) = explode('|'$line);
            if (
ip2long($ip) != -1) {
                
$start_ip sprintf('%u'ip2long($ip));
                
$end_ip   sprintf('%u'ip2long($ip) + ($ipcount 1));
                
$query    "INSERT INTO ip_map (code, registry, ip_from, ip_to) VALUES ('"$countrycode ."', '"$registry ."', '"$start_ip ."', '"$end_ip ."')";
                
$dbh->query($query);
            }
        }
    }
}