<?php

use Battles\Nick;
use Battles\Template;
use Battles\User;

require_once 'config.php';
$sleep = db::c()->query('SELECT `id` FROM `effects` WHERE `owner` = ?i AND `time` > ?i AND `type` = 3', User::getInstance()->getId(), time())->fetch_assoc();
$ps = $_GET['page'] ?? 0;
$isModerator = false;
$isAdmin = false;
$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 = [
        // Стандартные 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>",
        // Смайлы
        '/\:susel\:/' => '<img src="i/smile/susel.gif" />',
        '/\:ponder\:/' => '<img src="i/smile/ponder.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']) && User::getInstance()->getId()) {

    $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::getInstance()->getAlign() >= $minmax['min_align'] && User::getInstance()->getAlign() <= $minmax['max_align']) || $isAdmin) {
        $userPost = Nick::id(User::getInstance()->getId())->full();
        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']) && User::getInstance()->getId()) {
    $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::getInstance()->getAlign() >= $minmax['min_align'] && User::getInstance()->getAlign() <= $minmax['max_align']) && $minmax['close'] == "0" || $isAdmin) {
        $userPost = Nick::id(User::getInstance()->getId())->full();

        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) {
    $addText = Nick::id(User::getInstance()->getId())->full() . ": " . $_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::getInstance()->getId())->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();
    }
}
Template::header('Форум');
?>
    <link rel="stylesheet" href="css/wysibb/theme/default/wbbtheme.css"/>
    <script type="text/javascript" language="JavaScript" src='js/forum.js'></script>
    <table width="100%" border="0">
        <tr valign="top">
            <td width="200">
                <br/>
                <?php if (User::getInstance()->getId()) { echo "Игрок : " . Nick::id(User::getInstance()->getId())->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::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $row['max_align']) || $isAdmin) {
                            $min = $row['min_align'] == 0;
                            $max = $row['max_align'] == 0;

                            if (!User::getInstance()->getId() || ((User::getInstance()->getAlign() < $row['min_align']) || (User::getInstance()->getAlign() > $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::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $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="let 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="let 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 (User::getInstance()->getBlock()) {
                                    $error = "Вы заблокированы!";
                                } elseif (User::getInstance()->getLevel() < 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::getInstance()->getAlign() >= $row['min_align'] && User::getInstance()->getAlign() <= $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], "");
                            [$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 (User::getInstance()->getBlock()) {
                    $error = "Вы заблокированы!";
                } elseif (User::getInstance()->getLevel() < 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; ?>