<?
    // При использовании обязательно дайте ссылку в одном из постов у себя на сайте.
    // Pri ispol'zovanii objazatelno dajte ssylku v odnim iz postov u sebja na sajte.
    // You've to post a hyperlink to my site when using it's content in one of your posts

    // Blogowar API v2
    // Written by Evgeny Stepanischev aka BOLK (http://bolknote.ru), 2007

    // Usage example

    $uid = 1; // <--- Blogowar USER ID

    echo <<<HTML
    <head>
        <title>Blogowar</title>
        <style type="text/css">
        <!--
            body, td, th { font-family: 'Trebuchet MS', Arial; font-size: 12px }
            th  { font-size: 20px; text-transform: uppercase }
            .c2 { font-weight: bold }
            .c1 { border-right: 2px solid #aaa; font-size: 14px }
            table { background: #ccc; padding: 20px }
            td { border-bottom: 1px solid #aaa; padding-top: 5px }
        -->
        </style>
    </head>
    <body>
    <table width="240" border="0" align="center">

HTML;

    $war = &new Bolkowar();

    if ($war->userExists($uid))
    {
        $profile = $war->userProfile($uid);
        $favicon = $war->userFavicon($uid);

        if ($favicon)
        $favicon = '<img src="http://blogowar.ru/ico/'.$uid.'.png" width="16" height="16" alt="" align="absmiddle" hspace="4" />';

        echo '<th colspan="2" align="center">', $favicon, $profile['name'], '</th>';

        unset($profile['name']);

        foreach ($profile as $name => $value)
        {
            echo '<tr><td width="100" class="c1">', ucfirst($name), '</td><td class="c2" align="right" width="100">';

            if ($name == 'cancast')
            {
                if ($value === null) echo '?'; else
                if ($value === true) echo 'now'; else
                echo date('H:i:s', $value);
            }
            elseif (is_bool($value))
            {
                echo $value ? '+' : '-';
            }
            else
            {
                    echo $value;
            }

            echo '</td></tr>';
        }

        echo '</table></body>';
    }


    // Class itself
    class Bolkowar
    {
        var $tmpdir;

        function Bolkowar()
        {
            $this->tmpdir =
                    file_exists('/tmp') && is_dir('/tmp') ?
                    '/tmp/' :
                    dirname(__FILE__).'/';

            $tmpdirs = array('TMPDIR', 'TEMP', 'TMP');
            foreach ($tmpdirs as $dir)
            {
                $dir = getenv($dir);
                if ($dir !== false)
                {
                    $this->tmpdir = $dir.'/';
                    break;
                }
            }
        }

        function userExists($id)
        {
            $data = $this->_http('HEAD', '/data/'.$id.'.png');
            if ($data === null) return null;

            return $data['CODE'] == 200;
        }

        function userProfile($id)
        {
            $cachefile = $this->tmpdir.'bolkowar-'.(int) $id;
            if (file_exists($cachefile) && abs(time() - filemtime($cachefile)) < 120)
            {
                $fp = fopen($cachefile, 'rb');
                if ($fp)
                {
                    flock($fp, LOCK_SH);
                    $content = fread($fp, filesize($cachefile));
                    fclose($fp);

                    $content = unserialize($content);
                    if ($content !== false)
                    return $content;
                }
            }

            $data = $this->_http('GET', '/soldier/'.$id);
            if ($data === null) return null;

            $data = $data['BODY'];

            $profile = array();
            $index = array
            (
                '!<b>Унц</b>:\s*(\d+)!iS' => 'untz',
                '!<b>Баксы</b>:\s+(\d+)\$!iS' => '$',
                '!<b>XP</b>:\s*(\d+)!S' => 'xp',
                '!<h1><a[^>]+>(.+?)</a></h1>!Ss' => 'name',
                '!<h1><a href=http://([^>]+)>.*?</a></h1>!Ss' => 'url',
                '!icon_heal\.gif.{0,80}Sanctuary!iSs' => 'sanctuary',
                '!icon_fire\.gif.{0,80}Fire mark!iSs' => 'firemark',
                '!a(\d+)\.gif!S' => 'armor',
                '!w(\d+)\.gif!S' => 'weapon',
            );

            foreach ($index as $reg => $key)
            {
                if (preg_match($reg, $data, $match))
                {
                    $profile[$key] = isset($match[1]) ? $match[1] : true;
                }
                else
                {
                    $profile[$key] = false;
                }
            }

            $data = $this->_http('GET', '/soldier/'.$id.'/rss');
            if ($data !== null)
            {
                if (preg_match("!magic\.php\?f=$id&s=\d+&m=\d+&t=(\d+)!sS", $data['BODY'], $match))
                {
                    $lastcast = $match[1];
                    $diff = strtotime($data['date']) - $lastcast;
                    $downtime = 2 * 60 * 60;

                    if ($diff > $downtime)
                    $profile['cancast'] = true; else
                    $profile['cancast'] = time() + $downtime - $diff;
                }
                else
                {
                    $profile['cancast'] = null;
                }
            }


               $fp = fopen($cachefile, 'ab');
               if ($fp)
               {
                   flock($fp, LOCK_EX);
                   fseek($fp, 0);
                   ftruncate($fp, 0);
                   fwrite($fp, serialize($profile));
                   fclose($fp);
            }

            return $profile;
        }

        function userFavicon($id)
        {
            $data = $this->_http('HEAD', '/ico/'.$id.'.png');
            if ($data === null) return null;
            return $data['CODE'] == 200;
        }

        function _http($method, $url)
        {
            $fp = fsockopen('blogowar.ru', 80);
            if (!$fp) return null;


            $request = "$method $url HTTP/1.0\r\n".
                       "Host: blogowar.ru\r\n".
                       "User-agent: bolkowar (http://bolknote.ru/)\r\n";

            if (function_exists('gzencode'))
            $request.= "Accept-Encoding: gzip\r\n";

            $request.= "\r\n";

            fwrite($fp, $request);

            $answer = array();
            for ($i = 0; !feof($fp); $i++)
            {
                $line = trim(fgets($fp, 1024));
                if ($line == '') break;

                if (!$i)
                {
                    list(,$answer['CODE'], $answer['MESSAGE']) = explode(' ', $line, 3);
                }
                else
                {
                    list($field, $value) = preg_split('/\s*:\s*/S', $line, 2);
                    $answer[strtolower($field)] = $value;
                }
            }

            $answer['BODY'] = '';
            while (!feof($fp))
            $answer['BODY'] .= fgets($fp, 65535);
            fclose($fp);

            if (isset($answer['content-encoding']))
            $answer['BODY'] = gzinflate(substr($answer['BODY'], 10));

            return $answer;
        }

    }
?>