<?php

use Battles\Database\Db;
use Battles\Template;
use Battles\User;

require_once 'functions.php';
Db::getInstance()->execute('update online set real_time = ? where user_id = ?', [time(), User::getInstance()->getId()]);

if (isset($_GET['online']) && $_GET['online'] != null) {
    if ($_GET['room'] && (int)$_GET['room'] < 500) {
        User::getInstance()->setRoom($_GET['room']);
    }
    if ($u->i()['caveleader'] > 0) {
        $data = db::c()->query('
          SELECT 
            `align`, 
            `u`.`id`, 
            `klan`, 
            `level`, 
            `login`, 
            `u`.`battle` AS `in_battle`, 
            `o`.login_time, 
            `u`.`invis`, 
            (SELECT `id` FROM `effects` WHERE `type` = 2 AND `owner` = `u`.`id` LIMIT 1) AS `slp`, 
            (SELECT `id` FROM `effects` WHERE (`type` = 11 OR `type` = 12 OR `type` = 13  OR `type` = 14) AND `owner` = `u`.`id` LIMIT 1) AS `trv` 
          FROM 
            `online` AS `o`, 
            `users` AS `u` 
          WHERE 
            `o`.`id` = `u`.`id` AND 
            (`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND 
            `o`.`room` = "' . $u->i()['room'] . '" AND 
            `u`.`caveleader` = "' . $u->i()['caveleader'] . '" 
          ORDER BY 
            `u`.`login`
        ');
        $ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>";
        $ch1 = '_active';
        $ch2 = '_passive';
        $ch3 = '_passive';
        $ch4 = '_passive';
        $ch5 = '_passive';
    } elseif (User::getInstance()->getRoom() == 760) {
        $forest = db::c()->query('SELECT `id`, `room`, `time`, `user`, `data` FROM `forest` WHERE `user` = "' . $user['id'] . '" LIMIT 1')->fetch_assoc();
        $sp = db::c()->query('SELECT `id`, `room`, `user` FROM `forest` WHERE `room` = "' . $forest['room'] . '"');
        while ($pl = $sp->fetch_assoc()) {
            $uss .= ', ';
            $uss .= $pl['user'];
        }
        if ($uss != '') {
            $uss = ltrim($uss, ', ');
        }
        $data = db::c()->query('
          SELECT 
            `align`, 
            `u`.`id`, 
            `klan`, 
            `action`, 
            `level`, 
            `login`, 
            `u`.`battle` AS `in_battle`, 
            `o`.login_time, 
            `u`.`invis`, 
            (SELECT `id` FROM `effects` WHERE `type` = 2 AND `owner` = `u`.`id` LIMIT 1) AS `slp`, 
            (SELECT `id` FROM `effects` WHERE (`type` = 11 OR `type` = 12 OR `type` = 13  OR `type` = 14) AND `owner` = `u`.`id` LIMIT 1) AS `trv` 
          FROM 
            `online` AS `o`, 
            `users` AS `u` 
          WHERE 
            `o`.`id` = `u`.`id` AND 
            (`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND 
            `u`.`id` IN (' . $uss . ') 
          ORDER BY 
            `u`.`login`
        ');
        $ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $var_map[$forest['room']] . " (" . mysql_num_rows($data) . ")</b></span>";
        $ch1 = '_active';
        $ch2 = '_passive';
        $ch3 = '_passive';
        $ch4 = '_passive';
        $ch5 = '_passive';
    } else {
        $data = db::c()->query('
          SELECT 
            `align`, 
            `u`.`id`, 
            `klan`, 
            `action`, 
            `level`, 
            `login`, 
            `u`.`battle` AS `in_battle`, 
            `o`.login_time, 
            `u`.`invis`, 
            (SELECT `id` FROM `effects` WHERE `type` = 2 AND `owner` = `u`.`id` LIMIT 1) AS `slp`, 
            (SELECT `id` FROM `effects` WHERE (`type` = 11 OR `type` = 12 OR `type` = 13  OR `type` = 14) AND `owner` = `u`.`id` LIMIT 1) AS `trv` 
          FROM 
            `online` AS `o`, 
            `users` AS `u` 
          WHERE 
            `o`.`id` = `u`.`id` AND 
            (`o`.login_time >= ' . (time() - 90) . ' OR `u`.`in_tower` = 1) AND 
            `o`.`room` = "' . User::getInstance()->getRoom() . '" 
          ORDER BY 
            `u`.`login`
        ');
        $ttl = "<span style=\"color: #8f0000; font-size: 10pt;\"><b>" . $rooms[User::getInstance()->getRoom()] . " (" . mysql_num_rows($data) . ")</b></span>";
        $ch1 = '_active';
        $ch2 = '_passive';
        $ch3 = '_passive';
        $ch4 = '_passive';
        $ch5 = '_passive';
    }
    Template::header(sprintf('%s (%s)', $rooms[User::getInstance()->getRoom()], mysql_num_rows($data)));
    ?>
        <script>
            function fastshow(content) {
                var el = document.getElementById("mmoves");
                var o = window.event.srcElement;
                if (content != '' && el.style.visibility != "visible") {
                    el.innerHTML = '<small>' + content + '</small>';
                }
                var x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft + 3;
                var y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop + 5;
                el.style.left = x + "px";
                el.style.top = y + "px";
                if (el.style.visibility != "visible") {
                    el.style.visibility = "visible";
                }
            }

            function hideshow() {
                document.getElementById("mmoves").style.visibility = 'hidden';
            }

            function w(name, in_battle, align, klan, act, level, slp, trv, name2) {
                if (align.length > 0) {
                    align = '<img src="i/align_' + align + '.gif" title="Склонность персонажа" width=12 height=15>';
                }

                style = '';
                if (!name2) name2 = name;
                if (klan.length > 0) {
                    klan = '<img src="i/clan/' + klan + '.png" title="' + klan + '">';
                }
                document.write('<A HREF="javascript:top.AddToPrivate(\'' + name + '\', top.CtrlPress)" target=refreshed><img src="i/');
                if (in_battle > 0) {
                    document.write('lock2.gif');
                } else {
                    document.write('lock.gif');
                }
                document.write('" title="Приват"></A>' + align + '<a href="(\'' + name + '\',true)"></a>' + klan + '' + act + '<a href="javascript:top.AddTo(\'' + name + '\')" target=refreshed style=\'' + style + '\'>' + name2 + '</a>[' + level + ']<a href="inf.php?' + name + '" target=_blank title="Инф. о ' + name + '">' + '<IMG SRC="i/inf.gif" WIDTH=12 HEIGHT=11 BORDER=0 ALT="Инф. о ' + name + '"></a>');

                if (slp > 0) {
                    document.write(' <IMG SRC="i/sleep2.gif" WIDTH=24 HEIGHT=15 BORDER=0 ALT="Наложено заклятие молчания">');
                }
                if (trv > 0) {
                    document.write(' <IMG SRC="i/travma2.gif" WIDTH=24 HEIGHT=15 BORDER=0 ALT="Инвалидность">');
                }
                if (in_battle > 0) {
                    document.write(' <IMG SRC="i/b.jpg" WIDTH=15 HEIGHT=15 BORDER=0 title="Персонаж в поединке"></a>');
                }
                document.write('<BR>');
            }

            top.rld();
        </script>

    <div>
        <? if (!$_GET['rms']) { ?>
            <div id="fixednew" style="position: fixed; margin: 0; padding: 0; z-index: 9; width: 100%; text-align: center; overflow: auto;">
                <table border="0" cellpadding="0" cellspacing="0">
                    <tbody>
                    <tr>
                        <td><img align="left"
                                 onclick="this.src='i/buttons/ch1_passive.jpg'; location.href='ch.php?online='+Math.random();"
                                 src="i/buttons/ch1<?= $ch1; ?>.jpg"/>
                        <? if (!empty($user['klan'])) { ?>
                            <td><img align="left" title="Соклановцы" style="cursor: pointer;"
                                     onclick="location.href='ch.php?online='+Math.random()+'&amp;chview=5';"
                                     src="i/buttons/ch5<?= $ch5; ?>.jpg"/>
                        <? } ?>
                    </tbody>
                </table>
            </div>
            <br><br><br>
        <? } ?>
        <div id="mmoves"
             style="background-color: #FFFFCC; visibility:hidden; overflow: visible; position: absolute; border-color: #666666; border-style: solid; border-width: 0; padding: 0; white-space: nowrap; display: block; vertical-align: middle; word-wrap: break-word;"></div>
        <?
        if (!$_GET['room']) {
            if (!isset($_GET['chview']) || $_GET['chview'] == 1) {
                echo '<input type=\'button\' onclick=\'location.href="ch.php?online=' . rand(100000, 9999999) . '";\' value=\'Обновить\' />';
            } else {
                echo '<input type=\'button\' onclick=\'location.href="ch.php?online=' . rand(100000, 9999999) . '&chview=' . (int)$_GET['chview'] . '";\' value=\'Обновить\' />';
            }
        }
        ?>
        <? echo '<br />' . $ttl . '<br />'; ?>
    </div>
    <div>
        <script>
            <?php
            while ($row = $data->fetch_assoc()) {
                if ($row['in_battle'] > 0) {
                    $in_battle = 1;
                } else {
                    $in_battle = 0;
                }
                if ($row['invis'] > 0 && $row['id'] == $_SESSION['uid']) {
                    $row['login2'] = $row['login'] . "</a> (невидимка)";
                }
                if ($row['invis'] == 0 || $row['id'] == $_SESSION['uid']) {
                    if (!empty($row['action'])) {
                        function stripslashes_deep($text)
                        {
                            while (strstr($text, "\\")) {
                                $text = stripslashes($text);
                            }
                            return $text;
                        }

                        $rrr = $row['action'];
                        $act = explode("<>:<>", $rrr);
                        $aa = htmlspecialchars(stripslashes_deep($act[1]));
                        $aa = preg_replace("/afk ", "", $aa)
                                $aa = preg_replace("/dnd ", "", $aa);
                                $aa = preg_replace("/buy ", "", $aa);
                                $aa = preg_replace("/sell ", "", $aa);
                                $act_line = " <span onmouseover=\"fastshow(\'$aa\')\" onmouseout=\"hideshow()\"><b><small>{$act[0]}</small></b></span> ";
                            } else $act_line = '';
                    echo 'w(\'', $row['login'], '\',', $row['id'], ',', $in_battle, ',\'', $row['align'], '\',\'' . $row['klan'] . '\', \'' . $act_line . '\',\'', $row['level'], '\',\'', $row['slp'], '\',\'', $row['trv'], '\',\'', '\',\'', $row['login2'], '\');';
                }
            }
            ?>
        </script>
    </div>

    <?php
    if (!$_GET['room']) {
        ?>
        <SCRIPT>document.write('<INPUT TYPE=checkbox onclick="if(this.checked == true) { top.OnlineStop = false; } else { top.OnlineStop = true; }" ' + (top.OnlineStop ? '' : 'checked') + '> Обновлять автомат.')
        </SCRIPT>
        <?php
        exit;
    }
} elseif (@$_GET['show'] != null) {
    if ($_SESSION['sid'] != $user['sid']) {
        $_SESSION['uid'] = null;
        die ("<script>top.location.href='index.php';</script>");
    }
    $cha = file("tmp/chat.txt");
    header('Content-Type: text/html; charset=utf-8');
    echo "<script>";
    $ks = 0;
    foreach ($cha as $k => $v) {
        preg_match("/:\[(.*)\]:\[(.*)\]:\[(.*)]:\[(.*)\]/", $v, $math);
        if ($math[1] > time() - 60) {
            $math[3] = stripslashes($math[3]);
            //echo "console.log($math[1]|$math[2]|$math[3]);";
            if (($math[2] == '{[]}' . $user['login'] . '{[]}') && ($math[1] >= $user['chattime'])) {
                echo "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                echo "top.frames['chat'].document.all(\"mes_system\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                echo "top.show_new(\"wtab1\"); top.show_new(\"wtab5\");";
                $ks++;
                $lastpost = $math[1];
            } elseif (substr($math[2], 0, 4) == '{[]}' && ($math[1] >= $user['chattime'])) {
                //exit;
            } elseif (($math[2] == '!sys!!') && ($math[1] >= @$user['chattime']) && $_GET['om'] != 1) {
                if ($_GET['sys'] == 1 || strpos($math[3], "<img src=i/magic/") !== FALSE) {
                    echo "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                    echo "top.frames['chat'].document.all(\"mes_system\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                    echo "top.show_new(\"wtab5\");";
                    $ks++;
                    $lastpost = $math[1];
                }
            } elseif ($math[2] == '!sys2all!!' && @$math[1] >= $user['chattime']) {
                echo "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                echo "top.frames['chat'].document.all(\"mes_system\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . "<BR>';";
                echo "top.show_new(\"wtab5\");";
                $ks++;
                $lastpost = $math[1];
            } elseif (($math[2] == '!cavesys!!') && ($math[1] >= $user['chattime']) && ($user['caveleader'] == $math[4])) {
                echo "top.frames['chat'].document.getElementById(\"mes\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . " <BR>';";
                echo "top.frames['chat'].document.all(\"mes_system\").innerHTML += '<span class=date>" . date("H:i", $math[1]) . "</span> " . $math[3] . "<BR>';";
                echo "top.show_new(\"wtab5\");";
                $ks++;
                $lastpost = $math[1];
            } elseif ($math[1] >= @$user['chattime']) {
                if (strpos($math[3], "private [klan-{$user['klan']}-") !== FALSE) {
                    $pos = strpos($math[3], "[klan-{$user['klan']}-") + strlen($user['klan']) + 7;
                } elseif (((strpos($math[3], "private [help]") !== FALSE))) {
                    $math[3] = preg_replace("/private \[help]/Ue", "", $math[3]);
                    echo "top.frames['chat'].document.all(\"mes_help\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . " <BR>';";
                    if ($math[2] != $user['login'] && $user['align'] == 2.99) {
                        echo "top.show_new(\"wtab6\");";
                    }
                    $ks++;
                    $lastpost = $math[1];
                } elseif (((strpos($math[3], "private [trade]") !== FALSE))) {
                    $math[3] = preg_replace("/private \[trade]/Ue", "", $math[3]);
                    echo "top.frames['chat'].document.all(\"mes_trade\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . " <BR>';";
                    if ($math[2] != $user['login']) {
                        echo "top.show_new(\"wtab8\");";
                    }
                    $ks++;
                    $lastpost = $math[1];
                } elseif (strpos($math[3], "private [pal]") !== FALSE) {
                    if ((int)$user['align'] == 1 || $user['admin'] == 1) {
                        $math[3] = preg_replace("/private \[pal]/Ue", "", $math[3]);
                        echo "top.frames['chat'].document.all(\"mes_pal\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . " <BR>';";
                        $ks++;
                        $lastpost = $math[1];
                    }
                } elseif (((strpos($math[3], "private [klan-{$user['klan']}]") !== FALSE))) {
                    if ($user['klan'] != '') {
                        $math[3] = preg_replace("/private \[klan\-{$user['klan']}\]/Ue", "", $math[3]);
                        echo "top.frames['chat'].document.all(\"mes_klan\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . " <BR>';";
                        if ($math[2] != $user['login']) {
                            echo "top.show_new(\"wtab3\");";
                        }
                        $ks++;
                        $lastpost = $math[1];
                    }
                } elseif (((strpos($math[3], "private [{$user['login']}]") !== FALSE))) {
                    $sound = false;
                    preg_match_all("/private \[(.*)\]/siU", $math[3], $mmm, PREG_PATTERN_ORDER);
                    foreach ($mmm[1] as $res) {
                        $res = trim($res);
                        $res = iconv("utf-8", "utf-8", $res);
                        if ($sound == false) $sound = ($res == $user['login']) ? true : false;
                        if (strlen($res) < 3 || strlen($res) > 120 || !preg_match("/^[ёa-zA-Zа-яА-Я0-9-][ёa-zA-Zа-яА-Я0-9_ -]+[a-zA-Zа-яА-Я0-9ё-]$/", $res) || preg_match("/__/", $res) || preg_match("/--/", $res) || preg_match("/  /", $res) || preg_match("/(.)\\1\\1\\1/", $res)) {
                            $math[3] = str_replace($res, $user['login'], $math[3]);
                        }
                    }
                    $math[3] = preg_replace("/private \[(.*)\]/Ue", "'<a href='.chr(92).'\'javascript:top.AddToPrivate(\"'.(('\\1' != '" . $user['login'] . "')?'\\1':'" . $math[2] . "').'\",false)'.chr(92).'\' class=private>private [ <span oncontextmenu=\"return OpenMenu(event," . $user['level'] . ")\">\\1</span> ]</a>'", $math[3]);
                    $sssss = "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . "<BR>';";
                    echo "top.frames['chat'].document.all(\"mes_private\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . " <BR>';";

                    if ($sound == true) {
                        $sssss .= "top.soundD();";
                    }
                    echo $sssss;
                    $ks++;
                    $lastpost = $math[1];
                    unset($math[3]);
                } elseif ($math[2] == $user['login']) {
                    $sound = false;
                    preg_match_all("/private \[(.*)\]/siU", $math[3], $mmm, PREG_PATTERN_ORDER);
                    foreach ($mmm[1] as $res) {
                        $res = trim($res);
                        $res = iconv("utf-8", "utf-8", $res);
                        if ($sound == false) $sound = ($res == $user['login']) ? true : false;
                        if (strlen($res) < 3 || strlen($res) > 120 || !preg_match("/^[ёa-zA-Zа-яА-Я0-9-][ёa-zA-Zа-яА-Я0-9_ -]+[a-zA-Zа-яА-Я0-9ё-]$/", $res) || preg_match("/__/", $res) || preg_match("/--/", $res) || preg_match("/  /", $res) || preg_match("/(.)\\1\\1\\1/", $res)) {
                            $math[3] = str_replace($res, $user['login'], $math[3]);
                        }
                    }
                    $math[3] = preg_replace("/private \[(.*)\]/Ue", "'<a href='.chr(92).'\'javascript:top.AddToPrivate(\"'.(('\\1' != '" . $user['login'] . "')?'\\1':'" . $math[2] . "').'\",false)'.chr(92).'\' class=private>private [ <span oncontextmenu=\"return OpenMenu(event," . $user['level'] . ")\">\\1</span> ]</a>'", $math[3]);
                    $sssss = "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . "<BR>';";
                    $sssss .= "top.frames['chat'].document.all(\"mes_private\").innerHTML += '<span class=date2>" . date("H:i", $math[1]) . "</span> [<a href=\'javascript:top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . "<BR>';";

                    if ($sound == true) {
                        $sssss .= "top.soundD();";
                    }
                    echo $sssss;
                    $ks++;
                    $lastpost = $math[1];
                    unset($math[3]);
                } elseif ((strpos($math[3], "private") === FALSE) /*&& (User::getInstance()->getRoom() == $math[4])*/) {
                    $times = '';
                    $soundON = '';
                    if ((strpos($math[3], "[" . $user['login'] . "]") > 0) || ($math[2] == $user['login'])) {
                        $times = 'date2';
                        $math[3] = str_replace("to [" . $user['login'] . "]", "<b>to [" . $user['login'] . "]</b>", $math[3]);
                        $soundON = 'top.soundD();';
                    } elseif ($_GET['om'] != 1) {
                        $times = 'date';
                    }
                    if ($_GET['om'] != 1 || $times == 'date2') {
                        echo $soundON . "top.frames['chat'].document.all(\"mes\").innerHTML += '<span class={$times}>" . date("H:i", $math[1]) . "</span> [<a href=\'top.AddTo(\"{$math[2]}\")\'><span oncontextmenu=\'return OpenMenu(event," . $user['level'] . ")\'>{$math[2]}</span></a>] " . $math[3] . "<BR>';";
                        $ks++;
                        $lastpost = $math[1];
                    }
                }
            }
        }
    }
    if ($ks > 0) {
        db::c()->query("UPDATE `users` SET `chattime` = '" . ($lastpost + 1) . "' WHERE `id` = {$user['id']} LIMIT 1");
    }
    echo "</script><script>top.srld();</script>";
    db::c()->query("UPDATE `online` SET login_time = " . time() . " WHERE `id` = {$user['id']} LIMIT 1");
    exit;
} else {
    if (strpos($_GET['text'], "private") !== FALSE && $user['level'] < 1) {
        preg_match_all("/\[(.*)\]/U", $_GET['text'], $matches);
        for ($ii = 0; $ii < count($matches[1]); $ii++) {
            $dde = db::c()->query("SELECT `id` FROM `users` WHERE ((`align`>1 AND `align`<2)) AND `login` = '" . trim($matches[1][$ii]) . "' LIMIT 1 ;")->fetch_assoc();
            if (!$dde['id']) {
                exit();
            }
        }
    }
    if (@trim($_GET['text']) != null) {
        $rr = db::c()->query("SELECT `id` FROM `effects` WHERE `type` = 2 AND `owner` = {$user['id']};")->fetch_assoc();


        # Ограничения на ввод символов в чат!
        if (!isset($rr['id'])) {
            $_GET['text'] = substr($_GET['text'], 0, 1024); // Ограничние на символы в чате!
            $_GET['text'] = str_replace('<', '&lt;', $_GET['text']);
            $_GET['text'] = str_replace(']:[', '] : [', $_GET['text']);
            $_GET['text'] = str_replace('>', '&gt;', $_GET['text']);

            $_GET['text'] = preg_replace('/private \[klan-([a-zA-Z]*)\]/', '', $_GET['text']);

            if (empty(User::getInstance()->getClan())) {
                $_GET['text'] = str_replace('private [klan]', '', $_GET['text']);
                $_GET['text'] = str_replace('private [klan]', 'private [klan-' . $user['klan'] . ']', $_GET['text']);
            } else {
                $_GET['text'] = str_replace('private [klan]', 'private [klan-' . $user['klan'] . ']', $_GET['text']);
                $_GET['text'] = preg_replace('/private \[klan-([1-9])\]/', 'private [klan-' . $user['klan'] . ']', $_GET['text']);
                $pos = strpos($_GET['text'], "[klan-{$user['klan']}") + strlen($user['klan']) + 7;
            }

            if ($_GET['chtype'] == 6 && stristr($_GET['text'], 'private') === FALSE) {
                $_GET['text'] = 'private [help] ' . $_GET['text'];
            } elseif ($_GET['chtype'] == 8 && stristr($_GET['text'], 'private') === FALSE) {
                $_GET['text'] = 'private [trade] ' . $_GET['text'];
            } elseif ($_GET['chtype'] == 3 && $user['klan'] != '') {
                $_GET['text'] = 'private [klan-' . $user['klan'] . '] ' . $_GET['text'];
            } elseif ($_GET['chtype'] == 4 && (((int)$user['align'] == 1) || $user['admin'] == 1)) {
                $_GET['text'] = 'private [pal] ' . $_GET['text'];
            }


            if ((int)$user['align'] != 1 && $user['admin'] != 1) {
                $_GET['text'] = str_replace('private [pal]', '', $_GET['text']);
            }

            unset($tmp);
            # Упростил тот Адъ и Израиль до одной нормальной строчки, которая вырежет все ссылки.
            if (!preg_match(GAMEDOMAIN, $_GET['text']) || !preg_match("/imgur.com/", $_GET['text'])) {
                $_GET['text'] = preg_replace("@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@", '<i style="color:silver;"><РАП/РВС></i>', $_GET['text']);
            }

            $smiles = ["/:susel:/", "/:ponder:/"];
            $smiles2 = ["<img style=\"cursor:pointer;\" onclick=S(\"susel\") src=i/smile/susel.gif>", "<img style=\"cursor:pointer;\" onclick=S(\"ponder\") src=i/smile/ponder.gif>"];

            preg_match_all("/\[(.*)\]/U", $_GET['text'], $matches);

            $_GET['text'] = preg_replace($smiles, $smiles2, $_GET['text'], 3);
            $_GET['text'] = tolink($_GET['text']);

            if ($user['invis'] == 1) {
                $tme = db::c()->query("SELECT `time` FROM `effects` WHERE `owner` = '$user[id]' AND `type` = '1022'")->fetch_assoc();
                $user['login'] = '</a><b><i>невидимка ' . substr($tme[0], strlen($tme[0]) - 4) . '</i></b>';
            }

            # Понять бы какого чёрта условия два… Инс.
            if ($action != 1) {
                $file = 'tmp/chat.txt';
                if (filesize("tmp/chat.txt") > 100 * 1024) {
                    $line = "\r\n:[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . User::getInstance()->getRoom() . "]\r\n";
                    // Пишем содержимое в файл,
                    // используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
                    // и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
                    // а то заебали устаревшие функции использовать. Инс.
                    file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
                    echo "1";
                } else {
                    $line = ":[" . time() . "]:[{$user['login']}]:[<font color=\"" . (($user['color']) ? $user['color'] : "#000000") . "\">" . ($_GET['text']) . "</font>]:[" . User::getInstance()->getRoom() . "]\r\n";
                    file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
                    echo "2";
                }
            }
        }
        die ("<script>top.CLR1(); top.RefreshChat();</script>");
    }
}