<?php
session_start();
include('config.php');
if ($_SESSION['uid'] == null) header("Location: index.php");

$user = db::c()->query('SELECT * FROM `users` WHERE `id` = ?i', $_SESSION['uid'])->fetch_assoc();
$sleep = db::c()->query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', $user['id'], time())->fetch_assoc();


if (!isset($_GET['page'])) {
    $ps = 0;
} else {
    $ps = $_GET['page'];
}

$isModerator = false;
$isAdmin = false;

if (($user['align'] >= 1.1 && $user['align'] < 2)) {
    $isModerator = true;
}

if ($user['admin'] == 1) {
    $isAdmin = true;
    $isModerator = true;
}

$edit = '';
$search = '';

if (isset($_GET['do']) && $_GET['do'] != "search" && $_GET['do'] != "my_topics" && $_GET['do'] != "my_comments" && $_GET['do'] != "open" && $_GET['do'] != "close" && $_GET['do'] != "fix" && $_GET['do'] != "unfix") {
    echo '<script type="text/javascript">location.href="forum.php"</script>';
} elseif (isset($_GET['do']) && $_GET['do'] == "search") {
    $search .= '<br /><br /><br />';
}

if (isset($_POST['selectt'], $_POST['numt']) && $_POST['selectt'] != '' && $_POST['numt'] != '') {
    $AlignTop = db::c()->query('SELECT `min_align`, `max_align` FROM `forum` WHERE `id` = ?i', $_POST['selectt'])->fetch_assoc();
    db::c()->query('UPDATE `forum` SET `parent` = ?i, `min_align` = "?s", `max_align` = "?s" WHERE `id` = ?i', $_POST['selectt'], $AlignTop['min_align'], $AlignTop['max_align'], $_POST['numt']);
}

if (!isset($_GET['conf']) && !isset($_GET['topic'])) {
    $_GET['conf'] = 1;
}

$Movemess = ($isModerator == true) ? 1 : 0;
$replasepost = '';

function parse_bb_code($text)
{
    $bbCodes = array(
        // Стандартные BB коды
        '/\[(\/?)(b|i|u|s)\s*\]/' => "<$1$2>",
        '/\[(left|center|right)\]/' => '<p style="text-align:$1;">',
        '/\[\/(left|center|right)\]/' => '</p>',
        '/\[url\s?(src=)?\s?(.+?)\s?(target=(_blank|_self))?\](.+?)\[\/url\]/' => '<a href="$2" target="$4">$5</a>',
        '/\[img width=([0-9]{1,4}) height=([0-9]{1,4})\](.+?)\[\/img\]/' => '<img src="$3" width="$1" height="$2" />',
        '/\[img\](.+?)\[\/img\]/' => '<img src="$1" />',
        '/\[quote\](.+?)\[\/quote\]/' => "<blockquote>$1</blockquote>",
        '/\[code\](.+?)\[\/code\]/' => "<pre><code>$1</code></pre>",
        // Смайлы
        '/\:smile0\:/' => '<img src="i/forum/icon7.gif" />',
        '/\:baby\:/' => '<img src="i/smile/baby.gif" />',
        '/\:sniper\:/' => '<img src="i/smile/sniper.gif" />',
        '/\:trup\:/' => '<img src="i/smile/trup.gif" />',
        '/\:beggar\:/' => '<img src="i/smile/beggar.gif" />',
        '/\:rotate\:/' => '<img src="i/smile/rotate.gif" />',
        '/\:hello\:/' => '<img src="i/smile/hello.gif" />',
        '/\:sten\:/' => '<img src="i/smile/sten.gif" />',
        '/\:shuffle\:/' => '<img src="i/smile/shuffle.gif" />',
        '/\:elix\:/' => '<img src="i/smile/elix.gif" />',
        '/\:smil\:/' => '<img src="i/smile/smil.gif" />',
        '/\:mdr\:/' => '<img src="i/smile/mdr.gif" />',
        '/\:podz\:/' => '<img src="i/smile/podz.gif" />',
        '/\:dont\:/' => '<img src="i/smile/dont.gif" />',
        '/\:grust\:/' => '<img src="i/smile/grust.gif" />',
        '/\:boks\:/' => '<img src="i/smile/boks.gif" />',
        '/\:susel\:/' => '<img src="i/smile/susel.gif" />',
        '/\:dedmoroz\:/' => '<img src="i/smile/dedmoroz.gif" />',
        '/\:creator\:/' => '<img src="i/smile/creator.gif" />',
        '/\:no\:/' => '<img src="i/smile/no.gif" />',
        '/\:horse\:/' => '<img src="i/smile/horse.gif" />',
        '/\:vamp\:/' => '<img src="i/smile/vamp.gif" />',
        '/\:eek\:/' => '<img src="i/smile/eek.gif" />',
        '/\:sorry\:/' => '<img src="i/smile/sorry.gif" />',
        '/\:friday\:/' => '<img src="i/smile/friday.gif" />',
        '/\:obm\:/' => '<img src="i/smile/obm.gif" />',
        '/\:smile\:/' => '<img src="i/smile/smile.gif" />',
        '/\:nail\:/' => '<img src="i/smile/nail.gif" />',
        '/\:gent\:/' => '<img src="i/smile/gent.gif" />',
        '/\:beer\:/' => '<img src="i/smile/beer.gif" />',
        '/\:inv\:/' => '<img src="i/smile/inv.gif" />',
        '/\:fire\:/' => '<img src="i/smile/fire.gif" />',
        '/\:dance1\:/' => '<img src="i/smile/dance1.gif" />',
        '/\:maniac\:/' => '<img src="i/smile/maniac.gif" />',
        '/\:kiss4\:/' => '<img src="i/smile/kiss4.gif" />',
        '/\:confused\:/' => '<img src="i/smile/confused.gif" />',
        '/\:kiss2\:/' => '<img src="i/smile/kiss2.gif" />',
        '/\:snowfight\:/' => '<img src="i/smile/snowfight.gif" />',
        '/\:row\:/' => '<img src="i/smile/row.gif" />',
        '/\:naem\:/' => '<img src="i/smile/naem.gif" />',
        '/\:radio1\:/' => '<img src="i/smile/radio1.gif" />',
        '/\:fie\:/' => '<img src="i/smile/fie.gif" />',
        '/\:love\:/' => '<img src="i/smile/love.gif" />',
        '/\:sneeze\:/' => '<img src="i/smile/sneeze.gif" />',
        '/\:mol\:/' => '<img src="i/smile/mol.gif" />',
        '/\:showng\:/' => '<img src="i/smile/showng.gif" />',
        '/\:rocket\:/' => '<img src="i/smile/rocket.gif" />',
        '/\:dustman\:/' => '<img src="i/smile/dustman.gif" />',
        '/\:rupor\:/' => '<img src="i/smile/rupor.gif" />',
        '/\:nnn\:/' => '<img src="i/smile/nnn.gif" />',
        '/\:snegur\:/' => '<img src="i/smile/snegur.gif" />',
        '/\:dance2\:/' => '<img src="i/smile/dance2.gif" />',
        '/\:jeer\:/' => '<img src="i/smile/jeer.gif" />',
        '/\:kiss\:/' => '<img src="i/smile/kiss.gif" />',
        '/\:ponder\:/' => '<img src="i/smile/ponder.gif" />',
        '/\:drink\:/' => '<img src="i/smile/drink.gif" />',
        '/\:angel\:/' => '<img src="i/smile/angel.gif" />',
        '/\:idea\:/' => '<img src="i/smile/idea.gif" />',
        '/\:lady\:/' => '<img src="i/smile/lady.gif" />',
        '/\:gun\:/' => '<img src="i/smile/gun.gif" />',
        '/\:pif\:/' => '<img src="i/smile/pif.gif" />',
        '/\:help\:/' => '<img src="i/smile/help.gif" />',
        '/\:alch\:/' => '<img src="i/smile/alch.gif" />',
        '/\:kiss3\:/' => '<img src="i/smile/kiss3.gif" />',
        '/\:hug\:/' => '<img src="i/smile/hug.gif" />',
        '/\:lordhaos\:/' => '<img src="i/smile/lordhaos.gif" />',
        '/\:rose\:/' => '<img src="i/smile/rose.gif" />',
        '/\:radio2\:/' => '<img src="i/smile/radio2.gif" />',
        '/\:boks2\:/' => '<img src="i/smile/boks2.gif" />',
        '/\:str\:/' => '<img src="i/smile/str.gif" />',
        '/\:invis\:/' => '<img src="i/smile/invis.gif" />',
        '/\:rev\:/' => '<img src="i/smile/rev.gif" />',
        '/\:ok\:/' => '<img src="i/smile/ok.gif" />',
        '/\:alien\:/' => '<img src="i/smile/alien.gif" />',
        '/\:smash\:/' => '<img src="i/smile/smash.gif" />',
        '/\:super\:/' => '<img src="i/smile/super.gif" />',
        '/\:love2\:/' => '<img src="i/smile/love2.gif" />',
        '/\:victory\:/' => '<img src="i/smile/victory.gif" />',
        '/\:kruger\:/' => '<img src="i/smile/kruger.gif" />',
        '/\:agree\:/' => '<img src="i/smile/agree.gif" />',
        '/\:hi\:/' => '<img src="i/smile/hi.gif" />',
        '/\:privet\:/' => '<img src="i/smile/privet.gif" />',
        '/\:devil\:/' => '<img src="i/smile/devil.gif" />',
        '/\:naem2\:/' => '<img src="i/smile/naem2.gif" />',
        '/\:tongue\:/' => '<img src="i/smile/tongue.gif" />',
        '/\:red\:/' => '<img src="i/smile/red.gif" />',
        '/\:doc\:/' => '<img src="i/smile/doc.gif" />',
        '/\:icon7\:/' => '<img src="i/forum/icon7.gif" />',
        '/\:lightfly\:/' => '<img src="i/smile/lightfly.gif" />',
        '/\:owl\:/' => '<img src="i/smile/owl.gif" />',
        '/\:pirate\:/' => '<img src="i/smile/pirate.gif" />',
        '/\:sword\:/' => '<img src="i/smile/sword.gif" />',
        '/\:bye\:/' => '<img src="i/smile/bye.gif" />',
        '/\:mad\:/' => '<img src="i/smile/mad.gif" />',
        '/\:fingal\:/' => '<img src="i/smile/fingal.gif" />',
        '/\:nono\:/' => '<img src="i/smile/nono.gif" />',
        '/\:loveya\:/' => '<img src="i/smile/loveya.gif" />',
        '/\:cry\:/' => '<img src="i/smile/cry.gif" />',
        '/\:superng\:/' => '<img src="i/smile/superng.gif" />',
        '/\:yes\:/' => '<img src="i/smile/yes.gif" />',
        '/\:crying\:/' => '<img src="i/smile/crying.gif" />',
        '/\:\'\(\:/' => '<img src="i/smile/crying.gif" />',
        '/\:flowers\:/' => '<img src="i/smile/flowers.gif" />',
        '/\:tease\:/' => '<img src="i/smile/tease.gif" />',
        '/\:wink\:/' => '<img src="i/smile/wink.gif" />',
        '/\:sharp\:/' => '<img src="i/smile/sharp.gif" />',
        '/\:nunu\:/' => '<img src="i/smile/nunu.gif" />',
        '/\:angel2\:/' => '<img src="i/smile/angel2.gif" />',
        '/\:naem3\:/' => '<img src="i/smile/naem3.gif" />',
        '/\:lick\:/' => '<img src="i/smile/lick.gif" />',
        '/\:ninja\:/' => '<img src="i/smile/ninja.gif" />',
        '/\:cat\:/' => '<img src="i/smile/cat.gif" />',
        '/\:smoke\:/' => '<img src="i/smile/smoke.gif" />',
        '/\:chtoza\:/' => '<img src="i/smile/chtoza.gif" />',
        '/\:grace\:/' => '<img src="i/smile/grace.gif" />',
        '/\:tongue2\:/' => '<img src="i/smile/tongue2.gif" />',
        '/\:sorry2\:/' => '<img src="i/smile/sorry2.gif" />',
        '/\:yar\:/' => '<img src="i/smile/yar.gif" />',
        '/\:king2\:/' => '<img src="i/smile/king2.gif" />',
        '/\:carreat\:/' => '<img src="i/smile/carreat.gif" />',
        '/\:hlw\:/' => '<img src="i/smile/hlw.gif" />',
        '/\:grenade\:/' => '<img src="i/smile/grenade.gif" />',
        '/\:bow\:/' => '<img src="i/smile/bow.gif" />',
        '/\:doc2\:/' => '<img src="i/smile/doc2.gif" />',
        '/\:duel\:/' => '<img src="i/smile/duel.gif" />',
        '/\:mag\:/' => '<img src="i/smile/mag.gif" />',
        '/\:king\:/' => '<img src="i/smile/king.gif" />',
        '/\:laugh\:/' => '<img src="i/smile/laugh.gif" />',
        '/\:pal\:/' => '<img src="i/smile/pal.gif" />',
        '/\:nun\:/' => '<img src="i/smile/nun.gif" />',
        '/\:ura\:/' => '<img src="i/smile/ura.gif" />',
    );

    $text = preg_replace(array_keys($bbCodes), array_values($bbCodes), $text);
    $text = close_dangling_tags($text);

    return $text;
}

function close_dangling_tags($html)
{
    preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU", $html, $result);
    $openedtags = $result[1];
    preg_match_all("#</([a-z]+)>#iU", $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);
    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);
    for ($i = 0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            if ($openedtags[$i] != 'br') {
                $html .= '</' . $openedtags[$i] . '>';
            }
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }
    return $html;
}

if (isset($_POST['add']) && isset($user['id'])) {

    $icon = htmlentities($_POST['icon'], ENT_NOQUOTES, 'utf8');
    $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8');
    $text1 = parse_bb_code(preg_replace("/\n/", "<br />", $_POST['text']));

    $minmax = db::c()->query('SELECT `min_align`, `max_align` FROM `forum` WHERE `id` = ?i', $_GET['conf'])->fetch_assoc();
    $min_align = $minmax['min_align'];
    $max_align = $minmax['max_align'];

    rtrim($_POST['title']);
    rtrim($_POST['text']);
    if (empty($_POST['text']) || empty($_POST['title'])) {
        $error = "Заголовок или текст не могут быть пустыми!";
    } elseif (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || ($user['align'] >= $minmax['min_align'] && $user['align'] <= $minmax['max_align']) || $isAdmin) {
        if ($user['invis'] == 1) {
            $userPost = '<b>Невидимка</b>';
        } else {
            $userPost = nick::id($user['id'])->full(1);
        }
        if ($isModerator == false) $text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>');

        db::c()->query('INSERT INTO `forum` (`type`, `topic`, `text`, `parent`, `author`, `date`, `min_align`, `max_align`, `icon`) VALUES (2,"?s","?s",?i,"?s","?s","?s","?s","?s")', $text2, $text1, $_GET['conf'], $userPost, date('d.m.y H:i:s'), $min_align, $max_align, $icon);
        $topic_id = db::c()->getLastInsertId();
        unset($_POST['text']);
        print "<script>window.location='?conf=" . $_GET['conf'] . "&rnd'</script>";
        exit();
    } else {
        $error = "Вы не можете писать в этой конференции!";
    }
    unset($_POST['add']);
}

if (isset($_POST['add2']) && isset($user['id'])) {
    $text2 = htmlspecialchars($_POST['title'], ENT_NOQUOTES, 'utf8');
    $text1 = parse_bb_code(preg_replace("/\n/", "<br />", $_POST['text']));

    $minmax = db::c()->query('SELECT `min_align`,`max_align`, `close`, `parent` FROM `forum` WHERE `id` = ?i', $_GET['topic'])->fetch_assoc();
    $min_align = $minmax['min_align'];
    $max_align = $minmax['max_align'];

    rtrim($_POST['text']);
    if (empty($_POST['text'])) {
        $error = "Текст не может быть пустыми";
    } elseif (!is_numeric($_GET['topic'])) {
        $error = "Не надо так делать";
    }

    if (($minmax['min_align'] == 0 && $minmax['max_align'] == 0) || ($user['align'] >= $minmax['min_align'] && $user['align'] <= $minmax['max_align']) && $minmax['close'] == "0" || $isAdmin) {
        if ($user['invis'] == 1) {
            $userPost = '<b>Невидимка</b>';
        } else {
            $userPost = nick::id($user['id'])->full(1);
        }

        if ($isModerator == false) {
            $text1 = strip_tags($text1, '<b><i><u><code><a><br><img><div>');
        }

        db::c()->query('INSERT INTO `forum` (`type`, `topic`, `text`, `parent`, `author`, `date`, `min_align`, `max_align`) VALUES (2,"?s","?s",?i,"?s","?s","?s","?s")', $text2, $text1, $_GET['topic'], $userPost, date('d.m.y H:i:s'), $min_align, $max_align);
        db::c()->query('UPDATE `forum` SET `updated` = now() WHERE `id` = ?i', $_GET['topic']);

        unset($_POST['text']);
        if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
            $page_num = '&page=' . $_GET['page'];
        } else {
            $page_num = '&page=0';
        }
        echo '<script>location.href="?topic=' . $_GET['topic'] . '&konftop=' . $minmax['parent'] . $page_num . '&rnd#add_comment_place";</script>';
        exit();
    } else {
        $error = "Вы не можете писать в этой конференции!";
    }
    unset($_POST['add2']);
}

if (isset($_GET['dp']) && $isModerator == true) {
    if ($_GET['dp'] > 100) {
        db::c()->query('DELETE FROM `forum` WHERE `id` = ?i OR `parent` = ?i', $_GET['dp'], $_GET['dp']);
        echo "<script>window.location='?topic=" . $_GET['topic'] . "&page=" . $_GET['page'] . "'</script>";
        exit();
    }
}

if (isset($_GET['dt']) && $isModerator == true) {
    if ($_GET['dt'] > 100) {
        db::c()->query('DELETE FROM `forum` WHERE `id` = ?i OR `parent` = ?i', $_GET['dt'], $_GET['dt']);
        echo "<script>window.location='?conf=" . $_GET['conf'] . "&rnd'</script>";
        exit();
    }
}

if (isset($_GET['com']) && isset($_GET['cpr']) && $isModerator == true) {
    if ($user['invis'] == 1) {
        $addText = "<br /><b>Невидимка</b>: " . $_GET['cpr'];
    } else {
        $addText = nick::id($user['id'])->full(1) . ": " . $_GET['cpr'];
    }
    db::c()->query('UPDATE `forum` SET `text` = CONCAT(`text`,"?s") WHERE `id` = ?i', $addText, $_GET['com']);
    echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
    exit();
}

if (isset($_GET['do']) && $isModerator == true) {
    if ($_GET['do'] == "open") {
        db::c()->query('UPDATE `forum` SET `close` = 0 WHERE `id` = "?s"', $_GET['topic']);
        echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
        exit();
    }

    if ($_GET['do'] == "close") {
        $closeComment = "Обсуждение закрыл " . ($isAdmin) ? "<b>Администратор</b>" : nick::id($user['id'])->full(1);
        db::c()->query('UPDATE `forum` SET `close` = 1, `closepal` = "?s" WHERE `id` = "?s"', $closeComment, $_GET['topic']);
        echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
        exit();
    }

    if ($_GET['do'] == "fix") {
        db::c()->query('UPDATE `forum` SET `fix` = 1 WHERE `id` = "?s"', $_GET['topic']);
        echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
        exit();
    }

    if ($_GET['do'] == "unfix") {
        db::c()->query('UPDATE `forum` SET `fix` = 0 WHERE `id` = "?s"', $_GET['topic']);
        echo "<script>window.location='?topic=" . $_GET['topic'] . "&rnd'</script>";
        exit();
    }
}
?>
<!DOCTYPE HTML>
<html>
<head>
    <title>Форум</title>
    <meta charset="utf-8">
    <!--    <link rel="stylesheet" href="css/forum.css"/>-->
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/wysibb/theme/default/wbbtheme.css"/>
    <link rel='stylesheet' href="css/contact.css" media='screen'/>
    <script type="text/javascript" language="JavaScript" src="js/jquery.min.js"></script>
    <script type="text/javascript" language="JavaScript" src="js/jquery.wysibb-1.3.0.js"></script>
    <script type="text/javascript" language="JavaScript" src='js/forum.js'></script>
    <script type='text/javascript' src='js/jquery.simplemodal.js'></script>
    <script type='text/javascript' src='js/contact.js'></script>
</head>
<body>
<table width="100%" border="0">
    <tr valign="top">
        <td width="200">
            <br/>
            <?php if (isset($user['id'])) echo "Игрок : " . nick::id($user['id'])->full(1) . "<br />"; ?>
            <h4>Конференции</h4>
            <?php
            if ((isset($_GET['conf']) && is_numeric($_GET['conf'])) || (isset($_GET['konftop']) && is_numeric($_GET['konftop'])) || $Movemess == 1) {
                $data = db::c()->query('SELECT * FROM `forum` WHERE `parent` = 0 AND `type` = 1 ORDER BY `id` ASC');
                while ($row = $data->fetch_assoc()) {
                    if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) {
                        $min = $row['min_align'] == 0;
                        $max = $row['max_align'] == 0;

                        if (!isset($user['id']) || (($user['align'] < $row['min_align']) || ($user['align'] > $row['max_align']) && !$min && !$max)) {
                            echo '<nobr><b>&nbsp;&nbsp;📕';
                        } else {
                            echo '<nobr><b>&nbsp;&nbsp;📖&nbsp;';
                        }
                        echo '<a href="?conf=' . $row['id'] . '">' . $row['topic'] . '</a><br /></b></nobr>';
                    }
                }
            }
            ?>
        </td>
        <td rowspan="2" style="padding-left: 10px;">
            <?php
            if (!isset($_GET['conf'])) {
                $row = db::c()->query('SELECT * FROM `forum` WHERE `id` = "?s"', $_GET['topic'])->fetch_assoc();
                if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) {
                    $top = $row['parent'];
                    $parentCat = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $top)->fetch_assoc();
                    $icons = $row['icon'];
                    ?>
                    <h3><a href="forum.php?conf=<?= $top ?>">Конференция «<?= $parentCat['topic'] ?>»</a></h3>

                    <?php
                    if (isset($error)) err($error);

                    $par_top = db::c()->query('SELECT `closepal`, `id` FROM `forum` WHERE `id` = "?s"', $_GET['topic'])->fetch_row();
                    if (((int)$par_top[1] != 0) || ((int)$_GET['konftop'] > 0)) {
                        if ($row['close'] == 1) {
                            $close = "<a href='?topic={$_GET['topic']}&do=open'>🔓Открыть</a>";
                            $closed = 1;
                            $closepal = $row['closepal'];
                        } else {
                            $close = "<a href='?topic={$_GET['topic']}&do=close'>🔒Закрыть</a>";
                        }
                        if ($row['fix'] == 1) {
                            $fix = "<a href='?topic={$_GET['topic']}&do=unfix'>📄Открепить</a>";
                        } else {
                            $fix = "<a href='?topic={$_GET['topic']}&do=fix'>📌Прикрепить</a>";
                        }

                        if ($isModerator): ?>
                            <br>
                            <div align="right">
                                <small>
                                    <?= $close ?> | <?= $fix ?>
                                    <br><i>Перемещение тем не работает.</i>
                                </small>
                            </div>
                        <?php
                        endif;

                        $pgs = db::c()->query('SELECT count(`id`) FROM `forum` WHERE `parent` = "?s"', $_GET['topic'])->fetch_row();
                        $pgs = $pgs[0] / 20;
                        if ($pgs > 1) echo "<img src=i/ico/news.gif width=\"16\" height=\"16\" /> Страницы: ";
                        $pages_str = '';
                        $page = isset($_GET['page']) ? (((int)$_GET['page'] + 1) > $pgs ? ($pgs - 1) : (int)$_GET['page']) : 0;
                        $page = ceil($page);
                        if ($pgs > 1) {
                            for ($i = 0; $i < ceil($pgs); $i++) {
                                if (($i > ($page - 5)) && ($i <= ($page + 4))) {
                                    $pages_str .= ($i == $page ? " <b>" . ($i + 1) . "</b>" : " <a href='?topic=" . (int)$row['id'] . "&konftop=" . htmlspecialchars($_GET['konftop']) . "&page=" . ($i) . "'>" . ($i + 1) . "</a>");
                                }
                            }
                            $pages_str .= ($page < $pgs - 5 ? " ..." : "");
                            $pages_str = ($page > 4 ? "<a href='?topic=" . (int)$row['id'] . "&konftop=" . htmlspecialchars($_GET['konftop']) . "&page=" . ($page - 1) . "'> &laquo; </a> ... " : "") . $pages_str . (($page < ($pgs - 1) ? "<a href='?topic=" . (int)$row['id'] . "&page=" . ($page + 1) . "' > &raquo; </a>" : ""));
                        }
                        $FirstPage = (ceil($pgs) > 4 ? $_GET['page'] > 0 ? "<a href='?topic=" . (int)$row['id'] . "&konftop=" . htmlspecialchars($_GET['konftop']) . "&page=0'>	Первая </a>" : "" : "");
                        $LastPage = (ceil($pgs) > 4 ? (ceil($pgs) - 1) != $_GET['page'] ? "<a href='?topic=" . (int)$row['id'] . "&konftop=" . htmlspecialchars($_GET['konftop']) . "&page=" . (ceil($pgs) - 1) . "'>	Последняя </a>" : "" : "");
                        $pages_str = $FirstPage . $pages_str . $LastPage;
                        echo $pages_str;

                        ?>
                        <div id="leaf<?= $row['id'] ?>"
                             style="background-color: #ddd;margin: 2px;padding:5px;overflow-x: auto;word-wrap: break-word;box-shadow: 1px 2px 3px #ccc;">
                            <span class="topicTitle">
                                <img src="i/forum/icon<?= $icons ?>.gif"> <?= $row['topic'] ?>
                            </span>
                            <div class="auth_str">
                                <?= $row['author'] ?><span class="date">(<?= $row['date'] ?>)</span>
                                <a href='#' class='cite' onclick="add_cites(<?= $row['id'] ?>);" title="Цитата">
                                    <small>Цитировать</small>
                                </a>
                                <?php if ($isAdmin): ?>
                                    | <a href="javascript:void(0);" class="contact" id="<?= $row['id'] ?>">
                                        <small>Редактировать</small>
                                    </a>
                                <?php endif; ?>

                                <?php if ($isModerator AND (isset($_GET['conf']) OR isset($_GET['page']))): ?>
                                    <a href="?topic=<?= $_GET['topic'] ?>&konftop=<?= htmlspecialchars($_GET['conf']) ?>&page=<?= $_GET['page'] ?>&dp=<?= $row['id'] ?>">
                                        <small>Удалить</small>
                                    </a> |
                                    <a onclick="var obj; if (obj = prompt('Введите комментарий','')) { window.location='forum.php?topic=<?= $_GET['topic'] ?>&konftop=<?= htmlspecialchars($_GET['conf']) ?>&page=<?= $_GET['page'] ?>&cpr='+obj+'&com=<?= $row['id'] ?>'; }"
                                       href='#'>
                                        <small>Комментарий</small>
                                    </a>
                                <?php endif; ?>
                                <br>
                                <br>
                            </div>
                            <span><?= $row['text'] ?></span>
                        </div>
                        <?php
                        if (empty($_GET['page'])) $_GET['page'] = "";
                        $data = db::c()->query('SELECT * FROM `forum` WHERE `parent` = "?s" ORDER BY `id` ASC LIMIT ?i,20', $_GET['topic'], ($_GET['page'] * 20));
                        while ($row = $data->fetch_assoc()): ?>
                            <div id="leaf<?= $row['id'] ?>"
                                 style="background-color: #ddd;margin: 2px;padding:5px;overflow-x: auto;word-wrap: break-word;box-shadow: 1px 2px 3px #ccc;">
                                <div class="mesTopBar">
                                    <table width="100%">
                                        <tr>
                                            <td>
                                                <?= $row['author'] ?> <span class="date">(<?= $row['date'] ?>)</span>
                                                <?php if ($isModerator AND isset($_GET['conf']) AND isset($_GET['page'])): ?>
                                                    <a href="?topic=<?= $_GET['topic'] ?>&konftop=<?= htmlspecialchars($_GET['conf']) ?>&page=<?= $_GET['page'] ?>&dp=<?= $row['id'] ?>">
                                                        <small>Удалить</small>
                                                    </a>
                                                    <a onclick="var obj; if (obj = prompt('Введите комментарий','')) { window.location='forum.php?topic=<?= $_GET['topic'] ?>&konftop=<?= htmlspecialchars($_GET['conf']) ?>&page=<?= $_GET['page'] ?>&cpr='+obj+'&com=<?= $row['id'] ?>'; }"
                                                       href='#'>
                                                        |
                                                        <small>Комментарий</small>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                            <td align="right">
                                                <a href="javascript:void(0);" class="quote_btn"
                                                   onclick="return add_cites(<?= $row['id'] ?>);" title="Цитата">
                                                    <small>Цитировать</small>
                                                </a>
                                                <?php if ($isAdmin): ?>
                                                    <a href="javascript:void(0);" class="contact"
                                                       id="<?= $row['id'] ?>">
                                                        <small>Редактировать</small>
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                                <span><?= $row['text'] ?></span>
                            </div>
                        <?php
                        endwhile;
                        if ($pgs > 1) {
                            echo "<img src=i/ico/news.gif> Страницы: ";
                        }
                        echo $pages_str;

                        if ($closed == 1) {
                            echo "<br /><div align=center>" . $closepal . "</div><br /><br />";
                        } else {
                            if (!empty($user['block'])) {
                                $error = "Вы заблокированы!";
                            } elseif ($user['level'] < 2) {
                                $error = "Персонажам до 2-го уровня запрещено писать на форуме!";
                            } elseif (isset($sleep['id'])) {
                                $error = "Вы молчите!";
                            } else {
                                ?>
                                <a name="add_comment_place"></a>
                                <form method=POST
                                      action="forum.php?topic=<?= $_GET['topic'] ?>&konftop=<?= $_GET['conf'] ?>&page=<?= $_GET['page'] ?>"
                                      name="F1">

                                    <table bgcolor="F6E5B1" cellpadding="5" style="border: 1px outset;">
                                        <tr>
                                            <td colspan="2">
                                                <h4 id="response">Оставить комментарий</h4>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td colspan="2">
                                                <textarea class="inup" id="answer" rows="12" name="text"
                                                          cols="84" wrap="virtual"
                                                          onselect="storeCaret(this);"
                                                          onclick="storeCaret(this);"
                                                          onkeyup="storeCaret(this);"
                                                          onchange="storeCaret(this);"></textarea>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                <input type="submit" class="btn" value="Добавить" name="add2">
                                                <div class="page" id="<?= $ps; ?>" style="display: none;"></div>
                                            </td>
                                        </tr>
                                    </table>

                                    <input type="hidden" value="index" name="n"/>
                                    <input type="hidden" value="73991290635595" name="id"/>
                                    <input type="hidden" value="add_com" name="act"/>
                                    <input type="hidden" id="key_person_line" name="key_person_line"
                                           value="1290639545#1227576496"/>
                                    <input type="hidden" id="set_person_line" name="set_person_line"
                                           value="9c84c2b3d7e44a2b82928fd840ec97d7"/>
                                </form>
                                <?
                            }
                        }
                    } else echo "Тема удалена с форума, либо её не существует.<br>";
                }
            } else {
            if (is_numeric($_GET['conf']) && $row = db::c()->query('SELECT * FROM `forum` WHERE `id` = ?i', $_GET['conf'])->fetch_assoc()) {
            if (($row['min_align'] == 0 && $row['max_align'] == 0) || ($user['align'] >= $row['min_align'] && $user['align'] <= $row['max_align']) || $isAdmin) {
            $confname = 'Конференция «' . $row['topic'] . '»';
            $pgs = db::c()->query('SELECT count(`id`) FROM `forum` WHERE `parent` = ?i ORDER BY `fix` DESC, `updated` DESC', $_GET['conf'])->fetch_row();
            $pgs = $pgs[0] / 20;
            $pages_str = '';
            if (empty($_GET['page'])) $_GET['page'] = 0;
            $page = (int)$_GET['page'] ? (((int)$_GET['page'] + 1) > $pgs ? ($pgs - 1) : (int)$_GET['page']) : 0;
            $page = ceil($page);
            ?>
        <td rowspan="2" style="padding-left: 10px">
            <h3><?= $confname ?></h3>

            <?php
            if (isset($error)) err($error);
            if (empty($row['parent'])) echo $row['text'];

            if ($pgs > 1) {
                for ($i = 0; $i < ceil($pgs); $i++) {
                    if (($i > ($page - 5)) && ($i <= ($page + 4))) {
                        $pages_str .= ($i == $page ? " <b>" . ($i + 1) . "</b>" : " <a href='?conf=" . $_GET['conf'] . "&konftop=" . htmlspecialchars($_GET['conf']) . "&page=" . ($i) . "'>" . ($i + 1) . "</a>");
                    }
                }
                $pages_str .= ($page < $pgs - 5 ? " ..." : "");
                $pages_str = ($page > 4 ? "<a href='?conf=" . $_GET['conf'] . "&konftop=" . htmlspecialchars($_GET['conf']) . "&page=" . ($page - 1) . "'> &laquo; </a> ... " : "") . $pages_str . (($page < ($pgs - 1) ? "<a href='?conf=" . $_GET['conf'] . "&page=" . ($page + 1) . "' > &raquo;</a>" : ""));
                ?>
                <div style="width: 100%; margin: 5px;">
                    <img src="i/ico/news.gif" width="16" height="16"/> Страницы:<?= $pages_str ?>
                </div>
                <?php
            }
            $FirstPage = (ceil($pgs) > 4 ? $_GET['page'] > 0 ? "<a href='?conf=" . $_GET['conf'] . "&konftop=" . htmlspecialchars($_GET['conf']) . "&page=0'>	Первая </a>" : "" : "");
            $LastPage = (ceil($pgs) > 4 ? (ceil($pgs) - 1) != $_GET['page'] ? "<a href='?conf=" . $_GET['conf'] . "&konftop=" . htmlspecialchars($_GET['conf']) . "&page=" . (ceil($pgs) - 1) . "'>	Последняя </a>" : "" : "");
            $pages_str = $FirstPage . $pages_str . $LastPage;

            if (!empty($_GET['conf'])) {
                if (empty($_GET['page'])) $_GET['page'] = 0;
                $data = db::c()->query('SELECT * FROM `forum` WHERE `parent` = "?s" ORDER BY `fix` DESC, `updated` DESC LIMIT ?i,20', $_GET['conf'], ($_GET['page'] * 20));
                while ($row = $data->fetch_assoc()) {
                    $logi = '';
                    $userlist = '';
                    $icons = $row['icon'];
                    $data2 = db::c()->query('SELECT `author` FROM (SELECT `author`,`id` FROM `forum` WHERE `parent` = ?i ORDER BY `id` DESC LIMIT 10) AS sTable ORDER BY id DESC', $row['id']);
                    while ($row2 = $data2->fetch_row()) {
                        $userlist = strip_tags($row2[0], "");
                        list ($username, $level) = split(" \[", $userlist);
                        $logi .= $username;
                    }
                    $datacount = db::c()->query('SELECT count(*) AS CountNumber FROM `forum` WHERE `parent` = ?i', $row['id'])->fetch_assoc();
                    $count = $datacount["CountNumber"];
                    $lasttimedb = db::c()->query('SELECT `date` FROM `forum` WHERE `parent` = ?i ORDER BY `id` DESC', $row['id'])->fetch_assoc();
                    $lasttime = $lasttimedb['date'];
                    echo "<div class=\"mBodyBlock rounded rc6\" style='background-color: #ddd;margin: 2px;overflow-x: auto;word-wrap: break-word; box-shadow: 1px 2px 3px #ccc'>
                    <p class=pleft>" . ($row['fix'] ? "📌 " : "") . "<a href='?topic=" . $row['id'];
                    if (isset($_GET['conf'])) echo "&konftop=" . $_GET['conf'];

                    $pgs1 = db::c()->query('SELECT count(`id`) FROM `forum` WHERE `parent` = ?i', $row['id'])->fetch_assoc();
                    $pgs1 = $pgs1[0] / 20;
                    $pages_str1 = '';
                    $page1 = (int)$_GET['page'] > 0 ? (((int)$_GET['page'] + 1) > $pgs ? ($pgs - 1) : (int)$_GET['page']) : 0;
                    $page1 = ceil($page1);
                    if ($pgs1 > 1) {
                        for ($i = 0; $i < ceil($pgs1); $i++)
                            if (($i > ($page1 - 5)) && ($i <= ($page1 + 4)))
                                $pages_str1 .= ($i == $page1 ? "<b>" . ($i + 1) . "</b>" : "<a href='?topic=" . $row['id'] . "&konftop=" . htmlspecialchars($_GET['conf']) . "&page=" . ($i) . "'>" . ($i + 1) . "</a>");
                        $pages_str1 .= ($page1 < $pgs1 - 5 ? " ..." : "");
                    }
                    if ($pgs1 > 1) {
                        $pages_str1 = "<nobr><img src=\"i/forum/p.gif\" width=\"10\" height=\"12\" /><small class=pages><span class=pagenum>" . $pages_str1 . "</span></small></nobr>";
                    }

                    echo "'><IMG height=15 src=\"i/forum/icon{$icons}.gif\" width=15 border=0> {$row['topic']}</a> " . $pages_str1 . "<nobr>&nbsp;{$row['author']}</nobr>";

                    if ($isModerator) echo " <a href='?conf={$_GET['conf']}&dt={$row['id']}'><small>Удалить</small></a>";

                    echo "<br /><span class=date>" . $row['date'] . "</span><span class=dsc> " . strip_tags(substr($row['text'], 0, 250), "") . "</span>
								<br /><small>Ответов: <b>" . $count . "</b> <span title=\"Последний ответ: " . $logi . "\" style=\"border-bottom:1px dashed grey;cursor:help;font-size:10px;\">(" . $lasttime . ")</span></small>
							</p></div>";
                }
            }
            if ($pgs > 1) echo "<p><img src=i/ico/news.gif width=\"16\" height=\"16\" /> Страницы:";

            echo $pages_str . "</p>";

            if (!empty($user['block'])) {
                $error = "Вы заблокированы!";
            } elseif ($user['level'] < 2) {
                $error = "Персонажам до 2-го уровня запрещено писать на форуме!";
            } elseif (isset($sleep['id'])) {
                $error = "Вы молчите!";
            } else {
                ?>
                <a name="answer"></a>
                <br/>
                <form method=POST action="forum.php?conf=<?= $_GET['conf'] ?>" name="F1">
                    <table bgcolor="F6E5B1" width="100%" cellspacing="0" cellpadding="2"
                           style="border: 1px outset;">
                        <tr>
                            <td align=center>
                                <table>
                                    <tr>
                                        <td colspan="2">
                                            <h4>Добавить свой вопрос в форум</h4>
                                            <input type="text" class="inup" name="title" size="57" maxlength="65"
                                                   placeholder="Тема сообщения">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <textarea rows="8" class="inup" id="message" name="text" cols="85"
                                                      wrap="virtual"
                                                      onselect="storeCaret(this);"
                                                      onclick="storeCaret(this);"
                                                      onkeyup="storeCaret(this);"
                                                      onchange="storeCaret(this);"
                                                      placeholder="Введите сообщение..."></textarea>
                                            <input type=hidden value=0 name=n>
                                            <input type=hidden value=1025804759 name=id>
                                            <input type=hidden name=redirect>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <table width="100%">
                                                <tr>
                                                    <td>
                                                        <input type="hidden" name="icon" value="13">
                                                    </td>
                                                    <td align="right">
                                                        <input type="submit" class="btn" value="Добавить" name="add"/>
                                                        <input type="hidden" name="n" value="klans">
                                                        <input type="hidden" id="act" name="act" value="add_branch"/>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </form>
                <?
            }
            }
            } else echo ' <div style="width: 300px; margin: auto; font-weight: bold;">Ничего не найдено!</div>	';
            }
            ?>
            <!-- End of text -->
        </td>
    </tr>
</table>

<?php if ($isModerator == true): ?>
    <form name='repltopic' method='post'>
        <input type='hidden' id='selectt' name='selectt'/>
        <input type='hidden' id='numt' name='numt'/>
    </form>
<? endif; ?>
</body>
</html>