<?php
    $GLOBALS['mysql']['location'] = @mysqli_connect("127.0.0.1", "location", "f0nwv8MW6vZMkxkXtNpp", "location");
    
    function ip2country($ip = '')
    {
        if ($GLOBALS['mysql']['location'])
        {
            if (!$ip)
            {
                $ip = server('HTTP_X_FORWARDED_FOR') ? server('HTTP_X_FORWARDED_FOR') : (server('REMOTE_ADDR') ? server('REMOTE_ADDR') : '127.0.0.1');
            }
            if (!is_numeric($ip))
            {
                $ip = ip_encode($ip);
            }
            $maxmind_countries = mysqli_query($GLOBALS['mysql']['location'], "SELECT country FROM ip2location WHERE ip_to >= '" . $ip . "' ORDER BY ip_to LIMIT 1");
            if ($maxmind_countries_row = mysqli_fetch_array($maxmind_countries, MYSQLI_ASSOC))
            {
                return $maxmind_countries_row['country'];
            }
        }
        return '';
    }
    
    function ip2flag($ip = '')
    {
        if ($GLOBALS['mysql']['location'])
        {
            if (!$ip)
            {
                $ip = server('HTTP_X_FORWARDED_FOR') ? server('HTTP_X_FORWARDED_FOR') : (server('REMOTE_ADDR') ? server('REMOTE_ADDR') : '127.0.0.1');
            }
            if (!is_numeric($ip))
            {
                $ip = ip_encode($ip);
            }
            $maxmind_countries = mysqli_query($GLOBALS['mysql']['location'], "SELECT country, country_name FROM ip2location WHERE ip_to >= '" . $ip . "' ORDER BY ip_to LIMIT 1");
            if ($maxmind_countries_row = mysqli_fetch_array($maxmind_countries, MYSQLI_ASSOC))
            {
                if (is_file('images/flags/' . $maxmind_countries_row['country'] . '.png'))
                {
                    return '<img src="' . DOMAIN . 'images/flags/' . $maxmind_countries_row['country'] . '.png" title="' . htmlspecialchars($maxmind_countries_row['country_name']) . '" />';
                }
            }
        }
        return '<img src="' . DOMAIN . 'images/flags/unknown.png" title="Unknown" />';
    }
    
    function maxmind_download()
    {
        if (0)
        {
            echo_flush('Download: http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip');
            $contents = file_get_contents('http://www.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip');
            file_put_contents('data/GeoIPCountryCSV.zip', $contents);
            $contents = '';
            $i = 1;
            while (!$contents)
            {
                echo_flush('http://www.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_' . date('Y') . date('m') . '0' . $i . '.zip');
                $contents = @file_get_contents('http://www.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_' . date('Y') . date('m') . '0' . $i . '.zip');
                $i++;
                if ($i == 7)
                {
                    break;
                }
            }
            $i = 1;
            while (!$contents)
            {
                echo_flush('http://www.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_' . date('Y', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'))) . date('m', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'))) . '0' . $i . '.zip');
                $contents = @file_get_contents('http://www.maxmind.com/download/geoip/database/GeoLiteCity_CSV/GeoLiteCity_' . date('Y', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'))) . date('m', mktime(0, 0, 0, date('m') - 1, date('d'), date('Y'))) . '0' . $i . '.zip');
                $i++;
                if ($i == 7)
                {
                    break;
                }
            }
            file_put_contents('data/GeoLiteCity.zip', $contents);
        }
    }
    
    function maxmind_unzip()
    {
        if (0)
        {
            $array = array('GeoIPCountryCSV.zip', 'GeoLiteCity.zip');
            foreach ($array as $value)
            {
                $za = new ZipArchive();
                $res = $za->open('data/' . $value);
                if ($res === TRUE)
                {
                    for ($i = 0; $i < $za->numFiles; $i++)
                    {
                        $info = $za->statIndex($i);
                        file_put_contents('data/' . basename($info['name']), $za->getFromIndex($i));
                    }
                    $za->close();
                }
                else
                {
                    echo_flush('Error: ' . zipFileErrMsg($zip));
                    die;
                }
            }
        }
    }
    
    function maxmind_update()
    {
        if (1)
        {
            echo_flush("Processing: GeoIPCountryWhois.csv");
            if (($fp = fopen('data/GeoIPCountryWhois.csv', 'r')) !== false)
            {
                mysqli_query($GLOBALS['mysql']['location'], "CREATE TABLE maxmind_countries_replace (i_from char(15) NOT NULL, i_to char(15) NOT NULL, ip" . IP_BITS . " " . (IP_BITS < 16 ? "smallint(5)" : "int(10)") . " UNSIGNED NOT NULL, ip_from int(10) UNSIGNED NOT NULL, ip_to int(10) UNSIGNED NOT NULL, country_code2 char(2) NOT NULL, country_name varchar(50) NOT NULL, KEY IP" . IP_BITS . " (IP" . IP_BITS . ")) ENGINE=MyISAM DEFAULT CHARSET=utf8");
                mysqli_query($GLOBALS['mysql']['location'], "TRUNCATE TABLE maxmind_countries_replace");
                $completed_old = '';
                while (!feof($fp))
                {
                    $completed_new = number_format((ftell($fp) / filesize('data/GeoIPCountryWhois.csv')) * 100, 1);
                    if ($completed_old != $completed_new)
                    {
                        echo_flush("Completed: " . $completed_new . "%");
                        $completed_old = $completed_new;
                    }
                    $buf = fgets($fp);
                    if (!empty($buf))
                    {
                        $work = explode('","', trim($buf, " \t\n\r\0\x0B\""));
                        //$result = mysqli_query($GLOBALS['mysql']['location'], "SELECT " . $work[2] . ">>" . SHIFTBITS . " AS low," . $work[3] . ">>" . SHIFTBITS . " AS high");
                        $low = bcdiv($work[2], bcpow(2, SHIFTBITS));
                        $high = bcdiv($work[3], bcpow(2, SHIFTBITS));
                        for ($i = $low; $i <= $high; $i++)
                        {
                            mysqli_query($GLOBALS['mysql']['location'], "INSERT INTO maxmind_countries_replace SET i_from = '" . safe_string(isset($work[0]) ? $work[0] : '') . "', i_to = '" . safe_string(isset($work[1]) ? $work[1] : '') . "', ip" . IP_BITS . " = '" . safe_string($i) . "', ip_from = '" . safe_string(isset($work[2]) ? $work[2] : '') . "', ip_to = '" . safe_string(isset($work[3]) ? $work[3] : '') . "', country_code2 = '" . safe_string(isset($work[4]) ? $work[4] : '') . "', country_name = '" . safe_string(isset($work[5]) ? $work[5] : '') . "'");
                        }
                    }
                }
                mysqli_query($GLOBALS['mysql']['location'], "DROP TABLE maxmind_countries");
                mysqli_query($GLOBALS['mysql']['location'], "RENAME TABLE maxmind_countries_replace TO maxmind_countries");
            }
            echo_flush("Processing: GeoLiteCity-Location.csv");
            if (($fp = fopen('data/GeoLiteCity-Location.csv', 'r')) !== false)
            {
                $completed_old = '';
                while (!feof($fp))
                {
                    $completed_new = number_format((ftell($fp) / filesize('data/GeoLiteCity-Location.csv')) * 100, 1);
                    if ($completed_old != $completed_new)
                    {
                        echo_flush("Completed: " . $completed_new . "%");
                        $completed_old = $completed_new;
                    }
                    $buf = fgets($fp);
                    if (!empty($buf))
                    {
                        $work = explode(',', trim($buf));
                        foreach ($work as $key => $value)
                        {
                            if (substr($work[$key], 0, 1) == '"')
                            {
                                $work[$key] = substr($work[$key], 1);
                            }
                            if (substr($work[$key], -1, 1) == '"')
                            {
                                $work[$key] = substr($work[$key], 0, strlen($work[$key]) - 1);
                            }
                        }
                        if (is_numeric($work[0]))
                        {
                            mysqli_query($GLOBALS['mysql']['location'], "REPLACE INTO maxmind_location SET locId = '" . safe_string(isset($work[0]) ? $work[0] : '') . "', country = '" . safe_string(isset($work[1]) ? $work[1] : '') . "', region = '" . safe_string(isset($work[2]) ? $work[2] : '') . "', city = '" . safe_string(isset($work[3]) ? $work[3] : '') . "', postalCode = '" . safe_string(isset($work[4]) ? $work[4] : '') . "', latitude = '" . safe_string(isset($work[5]) ? $work[5] : '') . "', longitude = '" . safe_string(isset($work[6]) ? $work[6] : '') . "', metroCode = '" . safe_string(isset($work[7]) ? $work[7] : '') . "', areaCode = '" . safe_string(isset($work[8]) ? $work[8] : '') . "'");
                        }
                    }
                }
            }
        }
        echo_flush("Processing: GeoLiteCity-Blocks.csv");
        if (($fp = fopen('data/GeoLiteCity-Blocks.csv', 'r')) !== false)
        {
            mysqli_query($GLOBALS['mysql']['location'], "CREATE TABLE maxmind_location_blocks_replace (ip" . IP_BITS . " " . (IP_BITS < 16 ? "smallint(5)" : "int(10)") . " UNSIGNED NOT NULL, ip_from int(10) UNSIGNED NOT NULL, ip_to int(10) UNSIGNED NOT NULL, locId int(10) UNSIGNED NOT NULL, KEY IP" . IP_BITS . " (IP" . IP_BITS . ")) ENGINE=MyISAM DEFAULT CHARSET=utf8");
            mysqli_query($GLOBALS['mysql']['location'], "TRUNCATE TABLE maxmind_location_blocks_replace");
            $completed_old = '';
            while (!feof($fp))
            {
                $completed_new = number_format((ftell($fp) / filesize('data/GeoLiteCity-Blocks.csv')) * 100, 1);
                if ($completed_old != $completed_new)
                {
                    echo_flush("Completed: " . $completed_new . "%");
                    $completed_old = $completed_new;
                }
                $buf = fgets($fp);
                if (!empty($buf))
                {
                    $work = explode('","', trim($buf, " \t\n\r\0\x0B\""));
                    if (is_numeric($work[0]))
                    {
                        //$result = mysqli_query($GLOBALS['mysql']['location'], "SELECT " . $work[0] . ">>" . SHIFTBITS . " AS low," . $work[1] . ">>" . SHIFTBITS . " AS high");
                        $low = bcdiv($work[0], bcpow(2, SHIFTBITS));
                        $high = bcdiv($work[1], bcpow(2, SHIFTBITS));
                        for ($i = $low; $i <= $high; $i++)
                        {
                            mysqli_query($GLOBALS['mysql']['location'], "INSERT INTO maxmind_location_blocks_replace SET ip" . IP_BITS . " = '" . safe_string($i) . "', ip_from = '" . safe_string(isset($work[0]) ? $work[0] : '') . "', ip_to = '" . safe_string(isset($work[1]) ? $work[1] : '') . "', locId = '" . safe_string(isset($work[2]) ? $work[2] : '') . "'");
                        }
                    }
                }
            }
            mysqli_query($GLOBALS['mysql']['location'], "DROP TABLE maxmind_location_blocks");
            mysqli_query($GLOBALS['mysql']['location'], "RENAME TABLE maxmind_location_blocks_replace TO maxmind_location_blocks");
        }
    }
    
    function echo_flush($text)
    {
        echo $text . '<br />';
        flush();
    }
    
    function zipFileErrMsg($errno)
    {
        $zipFileFunctionsErrors = array(
            'ZIPARCHIVE::ER_MULTIDISK' => 'Multi-disk zip archives not supported.',
            'ZIPARCHIVE::ER_RENAME' => 'Renaming temporary file failed.',
            'ZIPARCHIVE::ER_CLOSE' => 'Closing zip archive failed',
            'ZIPARCHIVE::ER_SEEK' => 'Seek error',
            'ZIPARCHIVE::ER_READ' => 'Read error',
            'ZIPARCHIVE::ER_WRITE' => 'Write error',
            'ZIPARCHIVE::ER_CRC' => 'CRC error',
            'ZIPARCHIVE::ER_ZIPCLOSED' => 'Containing zip archive was closed',
            'ZIPARCHIVE::ER_NOENT' => 'No such file.',
            'ZIPARCHIVE::ER_EXISTS' => 'File already exists',
            'ZIPARCHIVE::ER_OPEN' => 'Can\'t open file',
            'ZIPARCHIVE::ER_TMPOPEN' => 'Failure to create temporary file.',
            'ZIPARCHIVE::ER_ZLIB' => 'Zlib error',
            'ZIPARCHIVE::ER_MEMORY' => 'Memory allocation failure',
            'ZIPARCHIVE::ER_CHANGED' => 'Entry has been changed',
            'ZIPARCHIVE::ER_COMPNOTSUPP' => 'Compression method not supported.',
            'ZIPARCHIVE::ER_EOF' => 'Premature EOF',
            'ZIPARCHIVE::ER_INVAL' => 'Invalid argument',
            'ZIPARCHIVE::ER_NOZIP' => 'Not a zip archive',
            'ZIPARCHIVE::ER_INTERNAL' => 'Internal error',
            'ZIPARCHIVE::ER_INCONS' => 'Zip archive inconsistent',
            'ZIPARCHIVE::ER_REMOVE' => 'Can\'t remove file',
            'ZIPARCHIVE::ER_DELETED' => 'Entry has been deleted',
        );
        $errmsg = 'unknown';
        foreach ($zipFileFunctionsErrors as $constName => $errorMessage)
        {
            if (defined($constName) and constant($constName) === $errno)
            {
                return 'Zip File Function error: ' . $errorMessage;
            }
        }
        return 'Zip File Function error: unknown';
    }
?>