<?php
$servername = "localhost:3306";
$username = "rlmgloba_cotg";
$password = "pjWKw3r8&ZbzC5qm";
$dbname = "rlmgloba_cotg";
$version = "1-0-0a";

/* http://louopt.codebits.org/2ZjDY1447 */
/* http://city.louopt.com/2ZjDY1447 */


if (isset($_REQUEST['ab'])) {
    /* 
        CREATE TABLE adblock (
            hit_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 
            ip varchar(32) NOT NULL,
            user_agent VARCHAR(128) NOT NULL,
            adblock BOOL NOT NULL
        );

     */

    if (0) {
        mysql_pconnect($serername, $username, $password) || die(mysql_error());
        mysql_select_db($dbname) || die(mysql_error());

        $adblock = intval($_REQUEST['ab']);
        $ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
        $ua = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);

        mysql_query("INSERT INTO adblock (ip, user_agent, adblock) VALUES (\"$ip\", \"$ua\", $adblock);");
    }
    exit;
}


if (isset($_REQUEST['short']) || isset($_REQUEST['write'])) {
    mysql_pconnect($servername, $username, $password) || die(mysql_error());
    mysql_select_db($dbname) || die(mysql_error());

    if (0) {
        mysql_query(<<<SQL
            CREATE TABLE IF NOT EXISTS maps (
                id    BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                short VARCHAR(16) NULL,
                map   TEXT NOT NULL,
                last_read DATETIME NULL,
                created   TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

                UNIQUE(short),
                INDEX(last_read)
            );
SQL
    ) || die(mysql_error());
    }


    function encode($n) {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $ret = "";
        while ($n > 0) {
            $ret .= $alphabet[$n%strlen($alphabet)];
            $n = floor($n/strlen($alphabet));
        }
        return $ret;
    }

    function decode($str) {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $n = 0;
        $mul = 1;
        for ($i=strlen($str)-1; $i >= 0; --$i) {
            if (($idx = strpos($alphabet, $str[$i])) === FALSE) {
                die("Invalid character {$str[$i]}");
            }

            $n += pow(strlen($alphabet), $i) * $idx;
        }

        return $n;
    }


    if (isset($_REQUEST['write'])) {
        $str = mysql_real_escape_string($_REQUEST['write']);

        if (strlen($str) > 294) {
            die("String too long.");
        }

        mysql_query("INSERT INTO maps(map) VALUES (\"$str\");") || die (mysql_error());
        $id = mysql_insert_id();
        header("Content-Type: text/plain");
        die(encode($id));
    }

    if (isset($_REQUEST['short'])) {
        /* If url is city.louopt.com .. use short field, else decode num and use id */
        header("hmm");
        $id = decode($_REQUEST['short']);
        $short = mysql_real_escape_string($_REQUEST['short']);
        header("Content-Type: text/plain");
        $res = mysql_query("SELECT id, map FROM maps WHERE id=$id OR short=\"$short\" ORDER BY id DESC LIMIT 1");

        if ($res === FALSE) {
            die(mysql_error());
        }

        while ($row = mysql_fetch_assoc($res)) {
            $map = $row['map'];
            $res = mysql_query("UPDATE maps SET last_read=NOW() WHERE id={$row['id']}");
            header("Location: http://{$_SERVER['SERVER_NAME']}/?map=$map");
            exit;
        }


        if (0) { /* go out to our old service and see if the string is there */
            $ch = curl_init("http://ghs.google.com/$short");

            $headers = array("Host: city.louopt.com");
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            curl_close($ch);

            if (preg_match("/Location: http:\/\/city.louopt.com\/[?]map=([a-zA-Z0-9]+)/m", $output, $m)) {
                error_log("Resolved map via refrence back to google");
                $map = mysql_real_escape_string($m[1]);
                mysql_query("INSERT INTO maps(map, last_read, short) VALUES (\"$map\", NOW(), \"$short\");") || die (mysql_error());

                header("Location: http://{$_SERVER['SERVER_NAME']}/?map=$map");
                exit;
            }
        }



        die("No city found by that string");
        exit;
    }
}
?>
