<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 */

define('_IN_JOHNCMS', 1);

require('../system/bootstrap.php');

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';
$mod = isset($_GET['mod']) ? trim($_GET['mod']) : '';
$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : false;

/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ToolsInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);

/** @var Johncms\Counters $counters */
$counters = App::getContainer()->get('counters');

/** @var Zend\I18n\Translator\Translator $translator */
$translator = $container->get(Zend\I18n\Translator\Translator::class);
$translator->addTranslationFilePattern('gettext', __DIR__ . '/locale', '/%s/default.mo');

if (isset($_SESSION['ref'])) {
    unset($_SESSION['ref']);
}

// Настройки форума
$set_forum = $systemUser->isValid() ? unserialize($systemUser->set_forum) : [
    'farea'    => 0,
    'upfp'     => 0,
    'preview'  => 1,
    'postclip' => 1,
    'postcut'  => 2,
];

// Список расширений файлов, разрешенных к выгрузке

// Файлы архивов
$ext_arch = [
    'zip',
    'rar',
    '7z',
    'tar',
    'gz',
    'apk',
];
// Звуковые файлы
$ext_audio = [
    'mp3',
    'amr',
];
// Файлы документов и тексты
$ext_doc = [
    'txt',
    'pdf',
    'doc',
    'docx',
    'rtf',
    'djvu',
    'xls',
    'xlsx',
];
// Файлы Java
$ext_java = [
    'sis',
    'sisx',
    'apk',
];
// Файлы картинок
$ext_pic = [
    'jpg',
    'jpeg',
    'gif',
    'png',
    'bmp',
];
// Файлы SIS
$ext_sis = [
    'sis',
    'sisx',
];
// Файлы видео
$ext_video = [
    '3gp',
    'avi',
    'flv',
    'mpeg',
    'mp4',
];
// Файлы Windows
$ext_win = [
    'exe',
    'msi',
];
// Другие типы файлов (что не перечислены выше)
$ext_other = ['wmf'];

// Ограничиваем доступ к Форуму
$error = '';

if (!$config->mod_forum && $systemUser->rights < 7) {
    $error = _t('Forum is closed');
} elseif ($config->mod_forum == 1 && !$systemUser->isValid()) {
    $error = _t('For registered users only');
}

if ($error) {
    require('../system/head.php');
    echo '<div class="rmenu"><p>' . $error . '</p></div>';
    require('../system/end.php');
    exit;
}

$headmod = $id ? 'forum,' . $id : 'forum';

// Заголовки страниц форума
if (empty($id)) {
    $textl = _t('Forum');
} else {
    $res = $db->query("SELECT `text` FROM `forum` WHERE `id`= " . $id)->fetch();
    $hdr = preg_replace('#\[c\](.*?)\[/c\]#si', '', $res['text']);
    $hdr = strtr($hdr, [
        '&laquo;' => '',
        '&raquo;' => '',
        '&quot;'  => '',
        '&amp;'   => '',
        '&lt;'    => '',
        '&gt;'    => '',
        '&#039;'  => '',
    ]);
    $hdr = mb_substr($hdr, 0, 30);
    $hdr = $tools->checkout($hdr, 2, 2);
    $textl = empty($hdr) ? _t('Forum') : $hdr;
}

// Переключаем режимы работы
$mods = [
    'addfile',
    'addvote',
    'close',
    'deltema',
    'delvote',
    'editpost',
    'editvote',
    'file',
    'files',
    'filter',
    'loadtem',
    'massdel',
    'new',
    'nospam',
    'nt',
    'per',
    'post',
    'ren',
    'restore',
    'say',
    'tema',
    'users',
    'vip',
    'vote',
    'who',
    'xoafile',
    'curators',
];

if ($act && ($key = array_search($act, $mods)) !== false && file_exists('includes/' . $mods[$key] . '.php')) {
    require('includes/' . $mods[$key] . '.php');
} else {
    require('../system/head.php');

    // Если форум закрыт, то для Админов выводим напоминание
    if (!$config->mod_forum) {
        echo '<div class="alarm">' . _t('Forum is closed') . '</div>';
    } elseif ($config->mod_forum == 3) {
        echo '<div class="rmenu">' . _t('Read only') . '</div>';
    }

    if (!$systemUser->isValid()) {
        if (isset($_GET['newup'])) {
            $_SESSION['uppost'] = 1;
        }

        if (isset($_GET['newdown'])) {
            $_SESSION['uppost'] = 0;
        }
    }

    if ($id) {
        // Определяем тип запроса (каталог, или тема)
        $type = $db->query("SELECT * FROM `forum` WHERE `id`= '$id'");

        if (!$type->rowCount()) {
            // Если темы не существует, показываем ошибку
            echo $tools->displayError(_t('Topic has been deleted or does not exists'), '<a href="index.php">' . _t('Forum') . '</a>');
            require('../system/end.php');
            exit;
        }

        $type1 = $type->fetch();

        // Фиксация факта прочтения Топика
        if ($systemUser->isValid() && $type1['type'] == 't') {
            $req_r = $db->query("SELECT * FROM `cms_forum_rdm` WHERE `topic_id` = '$id' AND `user_id` = '" . $systemUser->id . "' LIMIT 1");

            if ($req_r->rowCount()) {
                $res_r = $req_r->fetch();

                if ($type1['time'] > $res_r['time']) {
                    $db->exec("UPDATE `cms_forum_rdm` SET `time` = '" . time() . "' WHERE `topic_id` = '$id' AND `user_id` = '" . $systemUser->id . "' LIMIT 1");
                }
            } else {
                $db->exec("INSERT INTO `cms_forum_rdm` SET `topic_id` = '$id', `user_id` = '" . $systemUser->id . "', `time` = '" . time() . "'");
            }
        }

        // Получаем структуру форума
        $res = true;
        $allow = 0;
        $parent = $type1['refid'];

        while ($parent != '0' && $res != false) {
            $res = $db->query("SELECT * FROM `forum` WHERE `id` = '$parent' LIMIT 1")->fetch();

            if ($res['type'] == 'f' || $res['type'] == 'r') {
                $tree[] = '<span typeof="v:Breadcrumb"><a href="'.$home.'/forum/' . $tools->rewriteUrl($res['text']) . '_' . $parent . '.html">' . $res['text'] . '</a></span>';

                if ($res['type'] == 'r' && !empty($res['edit'])) {
                    $allow = intval($res['edit']);
                }
            }
            $parent = $res['refid'];
        }

        $tree[] = '<span typeof="v:Breadcrumb"><a href="index.php" rel="v:url" property="v:title">' . _t('Forum') . '</a></span>';
        krsort($tree);

        if ($type1['type'] != 't' && $type1['type'] != 'm') {
            $tree[] = '<span typeof="v:Breadcrumb"><b property="v:title">' . $type1['text'] . '</b></span>';
        }

        // Счетчик файлов и ссылка на них
        $sql = ($systemUser->rights == 9) ? "" : " AND `del` != '1'";

        if ($type1['type'] == 'f') {
            $count = $db->query("SELECT COUNT(*) FROM `cms_forum_files` WHERE `cat` = '$id'" . $sql)->fetchColumn();

            if ($count > 0) {
                $filelink = '<a href="index.php?act=files&amp;c=' . $id . '">' . _t('Category Files') . '</a>';
            }
        } elseif ($type1['type'] == 'r') {
            $count = $db->query("SELECT COUNT(*) FROM `cms_forum_files` WHERE `subcat` = '$id'" . $sql)->fetchColumn();

            if ($count > 0) {
                $filelink = '<a href="index.php?act=files&amp;s=' . $id . '">' . _t('Section Files') . '</a>';
            }
        } elseif ($type1['type'] == 't') {
            $count = $db->query("SELECT COUNT(*) FROM `cms_forum_files` WHERE `topic` = '$id'" . $sql)->fetchColumn();

            if ($count > 0) {
                $filelink = '<a href="index.php?act=files&amp;t=' . $id . '">' . _t('Topic Files') . '</a>';
            }
        }

        $filelink = isset($filelink) ? $filelink . '&#160;<span class="red">(' . $count . ')</span>' : false;

        // Счетчик "Кто в теме?"
        $wholink = false;

        if ($systemUser->isValid() && $type1['type'] == 't') {
            $online_u = $db->query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > " . (time() - 300) . " AND `place` = 'forum,$id'")->fetchColumn();
            $online_g = $db->query("SELECT COUNT(*) FROM `cms_sessions` WHERE `lastdate` > " . (time() - 300) . " AND `place` = 'forum,$id'")->fetchColumn();
            $wholink = '<a href="index.php?act=who&amp;id=' . $id . '">' . _t('Who is here') . '?</a>&#160;<span class="red">(' . $online_u . '&#160;/&#160;' . $online_g . ')</span><br>';
        }

/*
-----------------------------------------------------------------
Hacklord
-----------------------------------------------------------------
*/
					if (!empty($systemUser->ban)) {
					echo '<div class="mainblok"><div class="phdr"><font color="red"><b>You are banned..!!</b></font></div><div class="gmenu">' . $tools->image('prvs.gif') . ' We are sorry..<br>You are not allowed to view this thread..!!<br>' . $lng['ban'] . '&#160;<a href="' . $config->homeurl . '/users/profile.php?act=ban">Reason for ban</a></div></div>';
					require('../system/end.php');
					exit;
				}
					if (!$systemUser->isValid()) {
						$post_gue = 1;
					} else {
					$post_gue = $systemUser->postforum;
				}
						if (empty($systemUser->id) && $type1['min_post']) {
							echo '<div class="orange"><img src="../images/prvlock.gif" class="left"/>&nbsp;We are sorry..<br>Thread you selected are for registered member only..!!<br><a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">Go back</a></div>';
							require_once("../system/end.php");
							exit;
						}
						elseif ($post_gue < $type1['min_post']) {
							echo '<div class="orange"><img src="../images/prvlock.gif" class="left"/>&nbsp;We are sorry..<br>Thread that you entered required atleast '.$type1['min_post'].' post in forum..<br>and your post are <span class="red">' . $systemUser->postforum . '</span><br>you must active in forum to post in another section..<br>' . $tools->image('prvs.gif') . ' but please dont spam or you will get banned..!!<br><a href="' . htmlspecialchars(getenv("HTTP_REFERER")) . '">Go back</a></div>';
						require_once("../system/end.php");
						exit;
					}


        // Выводим верхнюю панель навигации
        echo '<a id="up"></a><p>' . $counters->forumNew(1) . '</p>' .
            '<div class="mainblok"><div class="phdr" xmlns:v="http://rdf.data-vocabulary.org/#">' . implode(' / ', $tree) . '</div>' .
            '<div class="topmenu"><a href="search.php?id=' . $id . '">' . _t('Search') . '</a>' . ($filelink ? ' | ' . $filelink : '') . ($wholink ? ' | ' . $wholink : '') . '</div></div>';

/*
----------------------------------------------------------------- 
Bookmark Forum By MASTERSCLIQ
-----------------------------------------------------------------
*/
if ($type1['type'] == 't' && $systemUser->id) {
if(!$res_r['bookmark'] && isset($_GET['addBookmark'])) {
$db->exec("UPDATE `cms_forum_rdm` SET `bookmark` = '1' WHERE `topic_id` = '$id' AND `user_id` = '$systemUser->id' LIMIT 1");
$res_r['bookmark'] = 1;
} elseif($res_r['bookmark'] && isset($_GET['delBookmark'])) {
$db->exec("UPDATE `cms_forum_rdm` SET `bookmark` = '0' WHERE `topic_id` = '$id' AND `user_id` = '$systemUser->id' LIMIT 1");
$res_r['bookmark'] = 0;
}
echo '<div class="rmenu">';
echo $res_r['bookmark'] ? '<a href="index.php?id=' . $id . '&amp;start=' . $start . '&amp;delBookmark">Delete Bookmark</a>' :
'<a href="index.php?id=' . $id . '&amp;start=' . $start . '&amp;addBookmark">Follow Topic</a>';
echo ' | <a href="bookmark.php">My Followed Topics</a>';
$usersBookmark = $db->query("SELECT COUNT(*) FROM `cms_forum_rdm` WHERE `topic_id` = '$id' AND `bookmark` = '1'")->fetchColumn();
if($usersBookmark && !isset($_GET['usersBookmark']))
echo '<br /><a href="index.php?id=' . $id . '&amp;usersBookmark">' . $usersBookmark . ' Users Are Following This Thread.</a>';
echo '</div>';
}
if(isset($_GET['usersBookmark']) && $usersBookmark) {
echo '<div class="mainblok"><div class="phdr"><a href="index.php?id=' . $id . '">' . $type1['text'] . '</a> | Footage...</div>';
$req = $db->query("SELECT `cms_forum_rdm`.*, `users`.`rights`, `users`.`lastdate`, `users`.`name`, `users`.`balans`, `users`.`sex`, `users`.`status`, `users`.`datereg`, `users`.`id` FROM `cms_forum_rdm` LEFT JOIN `users` ON `cms_forum_rdm`.`user_id` = `users`.`id` WHERE `cms_forum_rdm`.`topic_id`='$id' AND `cms_forum_rdm`.`bookmark` = '1' ORDER BY `id` DESC LIMIT $start,$kmess");
$i = 0;
while ($res = $req->fetch()) {
echo $i % 2 ? '<div class="gmenu">' : '<div class="list1">';
echo $tools->displayUser($res, array ('iphide' => 1));
echo '</div>';
++$i;
}
echo '<div class="phdr">Total: ' . $usersBookmark . '</div>';
if ($usersBookmark > $kmess) {
echo '<div class="topmenu">' . $tools->displayPagination('index.php?id=' . $id . '&amp;usersBookmark&amp;', $start, $usersBookmark, $kmess) . '</div>' . '<p><form action="index.php?id=' . $id . '&amp;usersBookmark" method="post">' . '<input type="text" name="page" size="2"/>' . '<input type="submit" value="' . _t('Go to') . ' &gt;&gt;"/></form></p>';
}
echo '</div>';
echo '<div class="orange"><a href="index.php?id=' . $id . '">Back To Thread</a></div>';
require_once('../system/end.php');
exit;
}


        switch ($type1['type']) {
            case 'f':
                ////////////////////////////////////////////////////////////
                // Список разделов форума                                 //
                ////////////////////////////////////////////////////////////
                $req = $db->query("SELECT `id`, `text`, `soft`, `edit` FROM `forum` WHERE `type`='r' AND `refid`='$id' ORDER BY `realid`");
                $total = $req->rowCount();
						 echo '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Category list</b></div>';

                if ($total) {
                    $i = 0;

                    while ($res = $req->fetch()) {
                        echo $i % 2 ? '<div class="menu">' : '<div class="menu">';
                        $coltem = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type` = 't' AND `refid` = '" . $res['id'] . "'")->fetchColumn();
                        echo '<img src="../images/op.gif" alt="op"/>&nbsp;<a href="'.$config->homeurl.'/forum/' . $tools->rewriteUrl($res['text']) . '_'.$res['id'].'.html">' . $res['text'] . '</a>';

                        if ($coltem) {
                            echo " [$coltem]";
                        }

                        if (!empty($res['soft'])) {
                            echo '<div class="sub"><span class="gray">' . $res['soft'] . '</span></div>';
                        }

                        echo '</div>';
                        ++$i;
                    }
                    unset($_SESSION['fsort_id']);
                    unset($_SESSION['fsort_users']);
                } else {
                    echo '<div class="menu"><p>' . _t('There are no sections in this category') . '</p></div>';
                }

                echo '<div class="phdr">' . _t('Total') . ': ' . $total . '</div></div>';
                break;

            case 'r':
                ////////////////////////////////////////////////////////////
                // Список топиков                                         //
                ////////////////////////////////////////////////////////////
							if ($systemUser->rights == 7 || $systemUser->rights >=9) {
									echo '<div class="mainblok"><div class="phdr"><img src="../images/priv.png" align="left" alt="private"/>&nbsp;<b>New Threads Option</b></div>';
									echo '<div class="menu">';
							if (isset($_GET['msgs'])) {
									echo "<span class='green'>$_GET[msgs]</span><br/>";
								}
							echo 'Query exist <span class="red">'.$type1['min_post_nt'].'</span><br/><span class="red">Post Required:</span><br/><form method="post">
<input type="text" size="5" maxlength="5" value="'.$type1['min_post_nt'].'" name="totalpostnt"/>&#160;<input type="submit" name="minpostnt" value="Apply"/></form>';
								echo '</div></div>';
							}
							$reqo = $db->query("SELECT COUNT(*) FROM `forum` WHERE `id` = '".($type1['id'])."' AND `type` = 'r'");
						if (isset($_POST['minpostnt'])) {
							if ($reqo->fetchColumn()) { 
								$db->exec("UPDATE `forum` SET  `min_post_nt` = '" . ($_POST['totalpostnt']) . "' WHERE `id` = '".($type1['id'])."'");
							header('Location: index.php?id='.$id.'&msgs=Done saved..!!');
						} else {
							echo $tools->displayError(_t('Wrong Data'));
							exit;
							}
					}

							echo '<div class="mainblok">';
							if (!$user_id) {
								$post_gue = 1;
							} else {
							$post_gue = $systemUser->postforum;
						}
							if (empty($systemUser->id) && $type1['min_post_nt']) {
							echo '<div class="gmenu"><img src="../images/prvlock.gif" class="left"/>&nbsp;Only registered member can use this feature..!!</div>';
							}
							elseif ($post_gue < $type1['min_post_nt']) {
							echo '<div class="gmenu"><img src="../images/prvlock.gif" class="left"/>&nbsp;We are sorry..<br>Form to create new thread on this section required atleast ' . $type1['min_post_nt'] . ' post in forum..<br>and your post are <span class="red">' . $systemUser->postforum . '</span><br>you must active in forum to post in another section first..<br><img src="../images/prvs.gif"/> but please dont spam or you will get banned..!!</div>';
							} elseif (($systemUser->isValid() && !isset($systemUser->ban['1']) && !isset($systemUser->ban['11']) && $config->mod_forum != 4) || $systemUser->rights) {
                    // Кнопка создания новой темы
                    echo '<div class="gmenu"><form action="index.php?act=nt&amp;id=' . $id . '" method="post"><input type="submit" value="' . _t('New Topic') . '" /></form></div>';
                }

                $total = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type`='t' AND `refid`='$id'" . ($systemUser->rights >= 7 ? '' : " AND `close`!='1'"))->fetchColumn();

                if ($total) {
                    $req = $db->query("SELECT * FROM `forum` WHERE `type`='t'" . ($systemUser->rights >= 7 ? '' : " AND `close`!='1'") . " AND `refid`='$id' ORDER BY `nospam`,  `vip`, `min_post` DESC, `time` DESC LIMIT $start, $kmess");
                    $i = 0;

                    while ($res = $req->fetch()) {
                        if ($res['close']) {
                            echo '<div class="rmenu">';
                        } else {
                            echo $i % 2 ? '<div class="menu">' : '<div class="menu">';
                        }

                        $nam = $db->query("SELECT `from` FROM `forum` WHERE `type` = 'm' AND `close` != '1' AND `refid` = '" . $res['id'] . "' ORDER BY `time` DESC LIMIT 1")->fetch();
                        $colmes = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type`='m' AND `refid`='" . $res['id'] . "'" . ($systemUser->rights >= 7 ? '' : " AND `close` != '1'"))->fetchColumn();
                        $cpg = ceil($colmes / $kmess);
                        $np = $db->query("SELECT COUNT(*) FROM `cms_forum_rdm` WHERE `time` >= '" . $res['time'] . "' AND `topic_id` = '" . $res['id'] . "' AND `user_id` = " . $systemUser->id)->fetchColumn();
                        // Значки
                        $icons = [
                            ($np ? (!$res['vip'] ? $tools->image('op.gif') : '') : $tools->image('np.gif')),
                            ($res['vip'] ? $tools->image('pt.gif') : ''),
                            ($res['nospam'] ? $tools->image('nospam.png') : ''),
                            ($res['realid'] ? $tools->image('rate.gif') : ''),
                            ($res['edit'] ? $tools->image('tz.gif') : ''),
                        ];
                        echo implode('', array_filter($icons));
                        echo '<a href="'.$config->homeurl.'/forum/' . $tools->rewriteUrl($res['text']) . '_' . $res['id'] . '.html">' . (empty($res['text']) ? '-----' : $res['text']) . '</a> [' . $colmes . ']';

                        if ($cpg > 1) {
                            echo '<a href="'.$config->homeurl.'/forum/' . $tools->rewriteUrl($res['text']) . '_' . $res['id'] . '_p' . $cpg . '.html">&#160;<img src="/images/viewpost.gif" width="12" height="10"/></a>';
                        }

                        echo '<div class="sub">';
                        echo 'Thread Started By:&#160;' . $res['from'];

                        if (!empty($nam['from'])) {
                            echo '<br/>Last Message Post By:&#160;<font color="orange">' . $nam['from'] . '</font>';
                        }

                        echo '<br/>Time:&#160;<span class="gray">(' . $tools->displayDate($res['time']) . ')</span></div></div>';
                        ++$i;
                    }
                    unset($_SESSION['fsort_id']);
                    unset($_SESSION['fsort_users']);
                } else {
                    echo '<div class="menu"><p>' . _t('No topics in this section') . '</p></div>';
                }

                echo '<div class="phdr">' . _('Total') . ' Topics: ' . $total . '</div>';

                if ($total > $kmess) {
                    echo '<div class="topmenu">' . $tools->displayPage(''.$config->homeurl.'/forum/'.$tools->rewriteUrl($type1["text"]).'_' . $id, $start, $total, $kmess) . '</div>' .
                        '<p><form action="index.php?id=' . $id . '" method="post">' .
                        '<input type="text" name="page" size="2"/>' .
                        '<input type="submit" value="' . _t('To Page') . ' &gt;&gt;"/>' .
                        '</form></p>';
                }
									echo '</div>';
							
                break;

            case 't':
                ////////////////////////////////////////////////////////////
                // Показываем тему с постами                              //
                ////////////////////////////////////////////////////////////
                $filter = isset($_SESSION['fsort_id']) && $_SESSION['fsort_id'] == $id ? 1 : 0;
                $sql = '';

                if ($filter && !empty($_SESSION['fsort_users'])) {
                    // Подготавливаем запрос на фильтрацию юзеров
                    $sw = 0;
                    $sql = ' AND (';
                    $fsort_users = unserialize($_SESSION['fsort_users']);

                    foreach ($fsort_users as $val) {
                        if ($sw) {
                            $sql .= ' OR ';
                        }

                        $sortid = intval($val);
                        $sql .= "`forum`.`user_id` = '$sortid'";
                        $sw = 1;
                    }
                    $sql .= ')';
                }

                // Если тема помечена для удаления, разрешаем доступ только администрации
                if ($systemUser->rights < 6 && $type1['close'] == 1) {
                    echo '<div class="rmenu"><p>' . _t('Topic deleted') . '<br><a href="?id=' . $type1['refid'] . '">' . _t('Go to Section') . '</a></p></div>';
                    require('../system/end.php');
                    exit;
                }

// Mod. Thanks
$checkthankdau = $db->query('SELECT COUNT(*) FROM `forum_thank` WHERE `userthank` = "' . $systemUser->id . '" and `topic` = "' . $_GET['thanks'] . '" and `user` = "' . $_GET['user'] . '"');
if ($systemUser->isValid() && $systemUser->id != $_GET['user'] && ($checkthankdau->fetchColumn() < 1)) {
if (isset($_GET['thank']) && isset($_GET['user']) && isset($_GET['thanks'])) {
echo '<div class="rmenu" id="thankyou">Your thanks has been received..!!</div>';
$db->exec("INSERT INTO `forum_thank` SET
`user` = '".trim($_GET['user'])."',
`topic` = '".trim($_GET['thanks'])."' ,
`time` = '$realtime',
`userthank` = '$systemUser->id',
`chude` = '".$_GET['id']."'
");
$congcamon = $db->query('SELECT * FROM `users` WHERE `id` = "' . trim($_GET['user']) . '"')->fetch();
$db-exec("UPDATE `users` SET `thank_duoc`='" . ($congcamon['thank_duoc'] + 1) . "' WHERE `id` = '" . trim($_GET['user']) . "'");
$db-exec("UPDATE `users` SET `thank_duoc`='" . ($congcamon['thank_duoc'] + 1) . "' WHERE `id` = '" . trim($_GET['user']) . "'");
$db-exec("UPDATE `users` SET `thank_di`='" . ($systemUser->thank_di + 1) . "' WHERE `id` = '" . $systemUser->id . "'");
}
}


                // Счетчик постов темы
                $colmes = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type`='m'$sql AND `refid`='$id'" . ($systemUser->rights >= 7 ? '' : " AND `close` != '1'"))->fetchColumn();

                if ($start >= $colmes) {
                    // Исправляем запрос на несуществующую страницу
                    $start = max(0, $colmes - (($colmes % $kmess) == 0 ? $kmess : ($colmes % $kmess)));
                }

                // Выводим название топика
                echo '<div class="phdr"><a href="#down">' . $tools->image('down.png', ['class' => '']) . '</a>&#160;&#160;<b>' . (empty($type1['text']) ? '-----' : $type1['text']) . '</b></div>';

                if ($colmes > $kmess) {
                    echo '<div class="topmenu" align="right">' . $tools->displayPage(''.$config->homeurl.'/forum/'.$tools->rewriteUrl($type1["text"]).'_' . $id, $start, $colmes, $kmess) . '</div>';
                }

                // Метка удаления темы
                if ($type1['close']) {
                    echo '<div class="rmenu">' . _t('Topic deleted by') . ': <b>' . $type1['close_who'] . '</b></div>';
                } elseif (!empty($type1['close_who']) && $systemUser->rights >= 7) {
                    echo '<div class="gmenu"><small>' . _t('Undelete topic') . ': <b>' . $type1['close_who'] . '</b></small></div>';
                }

/*
-----------------------------------------------------------------
Masterscliq Quota post thread
-----------------------------------------------------------------
*/
							if ($systemUser->rights == 7 || $systemUser->rights >=9) {
									echo '<div class="mainblok"><div class="phdr"><img src="../images/priv.png" align="left" alt="private"/>&nbsp;<b>Private Threads Option</b></div>';
							echo '<div class="menu">';
							// Successfully saved
							if (isset($_GET['msg'])) {
							echo "<span class='green'>$_GET[msg]</span><br/>";
						}
							// topic with nospam icon
							if ($type1['nospam'] == 1)
							echo '<a href="index.php?act=nospam&amp;id=' . $id . '">Sign topic without spam icon</a><br/>';
							else
							echo '<a href="index.php?act=nospam&amp;id=' . $id . '&amp;nosped">Sign topic with spam icon</a><br/>';
							// topic private
							echo 'Query exist <span class="red">'.$type1['min_post'].'</span><br/><span class="red">Post Required:</span><br/><form method="post">
<input type="text" size="5" maxlength="5" value="'.$type1['min_post'].'" name="totalpost"/>&#160;<input type="submit" name="minpost" value="Apply"/></form>';
echo '</div></div>';
							}
								$req = $db->query("SELECT COUNT(*) FROM `forum` WHERE `id` = '".($type1['id'])."' AND `type` = 't'");
								if (isset($_POST['minpost'])) {
									if ($req->fetchColumn()) {
$db->exec("UPDATE `forum` SET  `min_post` = '" . ($_POST['totalpost']) . "' WHERE `id` = '".($type1['id'])."'");
									header('Location: index.php?id='.($type1['id']).'&msg=Done saved..!!');
								} else {
							echo $tools->displayError(_t('Wrong Data'));
							exit;
							}
					}


                // Метка закрытия темы
                if ($type1['edit']) {
                    echo '<div class="rmenu">' . _t('Topic closed') . ' . <br/> . ' . $tools->image('closed_t.gif') . '</div>';
                }

                // Блок голосований
                if ($type1['realid']) {
                    $clip_forum = isset($_GET['clip']) ? '&amp;clip' : '';
                    $vote_user = $db->query("SELECT COUNT(*) FROM `cms_forum_vote_users` WHERE `user`='" . $systemUser->id . "' AND `topic`='$id'")->fetchColumn();
                    $topic_vote = $db->query("SELECT `name`, `time`, `count` FROM `cms_forum_vote` WHERE `type`='1' AND `topic`='$id' LIMIT 1")->fetch();
                    echo '<div  class="mainblok"><div  class="gmenu"><b>' . $tools->checkout($topic_vote['name']) . '</b><br />';
                    $vote_result = $db->query("SELECT `id`, `name`, `count` FROM `cms_forum_vote` WHERE `type`='2' AND `topic`='" . $id . "' ORDER BY `id` ASC");

                    if (!$type1['edit'] && !isset($_GET['vote_result']) && $systemUser->isValid() && $vote_user == 0) {
                        // Выводим форму с опросами
                        echo '<form action="index.php?act=vote&amp;id=' . $id . '" method="post">';

                        while ($vote = $vote_result->fetch()) {
                            echo '<input type="radio" value="' . $vote['id'] . '" name="vote"/> ' . $tools->checkout($vote['name'], 0, 1) . '<br />';
                        }

                        echo '<p><input type="submit" name="submit" value="' . _t('Vote') . '"/><br /><a href="index.php?id=' . $id . '&amp;start=' . $start . '&amp;vote_result' . $clip_forum .
                            '">' . _t('Results') . '</a></p></form></div></div>';
                    } else {
                        // Выводим результаты голосования
                        echo '<small>';

                        while ($vote = $vote_result->fetch()) {
                            $count_vote = $topic_vote['count'] ? round(100 / $topic_vote['count'] * $vote['count']) : 0;
                            echo $tools->checkout($vote['name'], 0, 1) . ' [' . $vote['count'] . ']<br />';
                            echo '<img src="vote_img.php?img=' . $count_vote . '" alt="' . _t('Rating') . ': ' . $count_vote . '%" /><br />';
                        }

                        echo '</small></div></div><div class="bmenu">' . _t('Total votes') . ': ';

                        if ($systemUser->rights > 6) {
                            echo '<a href="index.php?act=users&amp;id=' . $id . '">' . $topic_vote['count'] . '</a>';
                        } else {
                            echo $topic_vote['count'];
                        }

                        echo '</div>';

                        if ($systemUser->isValid() && $vote_user == 0) {
                            echo '<div class="mainblok"><div class="gmenu"><a href="index.php?id=' . $id . '&amp;start=' . $start . $clip_forum . '">' . _t('Vote') . '</a></div></div>';
                        }
                    }
                }

                // Получаем данные о кураторах темы
                $curators = !empty($type1['curators']) ? unserialize($type1['curators']) : [];
                $curator = false;

                if ($systemUser->rights < 6 && $systemUser->rights != 3 && $systemUser->isValid()) {
                    if (array_key_exists($systemUser->id, $curators)) {
                        $curator = true;
                    }
                }

                // Фиксация первого поста в теме
                if (($set_forum['postclip'] == 2 && ($set_forum['upfp'] ? $start < (ceil($colmes - $kmess)) : $start > 0)) || isset($_GET['clip'])) {
                    $postres = $db->query("SELECT `forum`.*, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`datereg`, `users`.`balans`, `users`.`negara`, `users`.`podpis`, `users`.`www` , `users`.`ip` , `users`.`browser`
                    FROM `forum` LEFT JOIN `users` ON `forum`.`user_id` = `users`.`id`
                    WHERE `forum`.`type` = 'm' AND `forum`.`refid` = '$id'" . ($systemUser->rights >= 7 ? "" : " AND `forum`.`close` != '1'") . "
                    ORDER BY `forum`.`id` LIMIT 1")->fetch();
                    echo '<div class="topmenu"><p>';
								if ($postres['sex']) {
								echo $tools->image(($postres['sex'] == 'm' ? 'm' : 'w') . ($postres['datereg'] > time() - 86400 ? '_new' : '') . '.png', ['class' => 'icon-inline']);
								} else {
								echo '<img src="../images/del.png" width="10" height="10" alt=""/>&#160;';
								} 
                    if ($systemUser->isValid() && $systemUser->id != $postres['user_id']) {
                        echo '<a href="../profile/?user=' . $postres['user_id'] . '&amp;fid=' . $postres['id'] . '"><b>' . $postres['from'] . '</b></a> ' .
                            '<a href="index.php?act=say&amp;id=' . $postres['id'] . '&amp;start=' . $start . '"> ' . _t('[r]') . '</a> ' .
                            '<a href="index.php?act=say&amp;id=' . $postres['id'] . '&amp;start=' . $start . '&amp;cyt"> ' . _t('Quote') . '</a> ';
                    } else {
                        echo '<b>' . $postres['from'] . '</b> ';
                    }

                    $user_rights = [
                        1 => '(Member)',
                        3 => '(Forum Moderator)',
                        6 => '(Super Moderator)',
                        7 => '(Administrator)',
                        9 => '(Super Admin)',
                    ];
                    echo @$user_rights[$postres['rights']];
                    echo(time() > $postres['lastdate'] + 300 ? '<span class="red">&nbsp;<img src="/images/offline.gif" width="8" height="10" alt="off"/></span>' : '<span class="green">&nbsp;<img src="/images/online.gif" width="8" height="10" alt="on"/></span>');
                    echo ' <span class="gray">(' . $tools->displayDate($postres['time']) . ')</span><br>';

                    if ($postres['close']) {
                        echo '<span class="red">' . _t('Post deleted') . '</span><br>';
                    }

                    echo $tools->checkout(mb_substr($postres['text'], 0, 500), 0, 2);

                    if (mb_strlen($postres['text']) > 500) {
                        echo '...<a href="index.php?act=post&amp;id=' . $postres['id'] . '">' . _t('Read more') . '</a>';
                    }

                    echo '</p></div>';
                }

                // Памятка, что включен фильтр
                if ($filter) {
                    echo '<div class="rmenu">' . _t('Filter by author is activated') . '</div>';
                }

                // Задаем правила сортировки (новые внизу / вверху)
                if ($systemUser->isValid()) {
                    $order = $set_forum['upfp'] ? 'DESC' : 'ASC';
                } else {
                    $order = ((empty($_SESSION['uppost'])) || ($_SESSION['uppost'] == 0)) ? 'ASC' : 'DESC';
                }

                ////////////////////////////////////////////////////////////
                // Основной запрос в базу, получаем список постов темы    //
                ////////////////////////////////////////////////////////////
                $req = $db->query("
                  SELECT `forum`.*, `users`.`sex`, `users`.`rights`, `users`.`lastdate`, `users`.`status`, `users`.`karma_plus`, `users`.`postforum`, `users`.`postguest`, `users`.`komm`, `users`.`balans`, `users`.`karma_minus`, `users`.`datereg`, `users`.`negara`, `users`.`podpis`, `users`.`www` , `users`.`ip` , `users`.`browser`
                  FROM `forum` LEFT JOIN `users` ON `forum`.`user_id` = `users`.`id`
                  WHERE `forum`.`type` = 'm' AND `forum`.`refid` = '$id'"
                    . ($systemUser->rights >= 7 ? "" : " AND `forum`.`close` != '1'") . "$sql
                  ORDER BY `forum`.`id` $order LIMIT $start, $kmess
                ");

                // Верхнее поле "Написать"
                if (($systemUser->isValid() && !$type1['edit'] && $set_forum['upfp'] && $config->mod_forum != 3 && $allow != 4) || ($systemUser->rights >= 7 && $set_forum['upfp'])) {
                    echo '<div class="mainblok"><div class="phdr"><img src="/images/qpost.gif" width="80" height="18" class="left"/>&nbsp;</div><form name="form1" action="index.php?act=say&amp;id=' . $id . '" method="post">';

                    if ($set_forum['farea']) {
                        $token = mt_rand(1000, 100000);
                        $_SESSION['token'] = $token;
                        echo '<p>' .
                            $container->get(Johncms\Api\BbcodeInterface::class)->buttons('form1', 'msg') .
                            '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="msg"></textarea></p>' .
                            '<p><input type="checkbox" name="addfiles" value="1" /> ' . _t('Add File') .
                            '</p><p><input type="submit" name="submit" value="' . _t('Write') . '" style="width: 107px; cursor: pointer;"/> ' .
                            (isset($set_forum['preview']) && $set_forum['preview'] ? '<input type="submit" value="' . _t('Preview') . '" style="width: 107px; cursor: pointer;"/>' : '') .
                            '<input type="hidden" name="token" value="' . $token . '"/>' .
                            '</p></form></div>';
                    } else {
                        echo '<p><input type="submit" name="submit" value="' . _t('Write') . '"/></p></form></div>';
                    }
                }

                // Для администрации включаем форму массового удаления постов
                if ($systemUser->rights == 3 || $systemUser->rights >= 6) {
                    echo '<form action="index.php?act=massdel" method="post">';
                }
                $i = 1;

                ////////////////////////////////////////////////////////////
                // Основной список постов                                 //
                ////////////////////////////////////////////////////////////
                while ($res = $req->fetch()) {
                    // Фон поста
                    if ($res['close']) {
                        echo '<div class="mainblok">';
                    } else {
                        echo $i % 2 ? '<div class="mainblok">' : '<div class="mainblok">';
                    }

                    // Пользовательский аватар
                    $rank = [
                        1 => '<font color="black">',
                        3 => '<font color="green">',
                        6 => '<font color="blue">',
                        7 => '<font color="orange">',
                        9 => '<font color="red">',
                    ];
								$vrp = $res['time'] + ($config->timeshift + ($systemUser->getConfig()->timeshift * 3600));
								$vr = date("d.m.Y - g:i:s a", $vrp);
								echo '<div class="phdr"><table width="100%" cellpadding="0" cellspacing="0"><tr><td width="auto"><img src="/images/file.png" align="top" alt="file"/>&#160;' . $vr . '</td><td width="auto" align="right">&#160;#<a href="'.$config->homeurl.'/forum/' . $tools->rewriteUrl($type1['text']) . '_p' . $res['id'] . '.html">';
								$ts = 'Ts';
								if (($start + $i) - 1){
									echo ($start + $i);
								} else { 
									echo 'Ts';
								} 
							echo '</a></td></tr></table></div>';
							echo '<div class="newsx">';

                    echo '<table width="100%" cellpadding="0" cellspacing="0"><tr><td width="39" align="left" valign="top">';
                    if (file_exists(('../files/users/avatar/' . $res['user_id'] . '.png'))) {
                        echo '<img src="../files/users/avatar/' . $res['user_id'] . '.png" width="32" height="32" alt="' . $res['from'] . '" />&#160;';
                    } else {
                        echo '<img src="../images/empty.png" width="32" height="32" alt="' . $res['from'] . '" />&#160;';
                    }
                    echo '</td><td width="auto" align="left" valign="top">';

                    // Метка пола
                    if ($res['sex']) {
                        echo $tools->image(($res['sex'] == 'm' ? 'm' : 'w') . ($res['datereg'] > time() - 86400 ? '_new' : '') . '.png', ['class' => 'icon-inline']);
                    } else {
                        echo $tools->image('del.png');
                    }

                    // Ник юзера и ссылка на его анкету
                    if ($systemUser->isValid() && $systemUser->id != $res['user_id']) {
                        echo '<a href="../profile/?user=' . $res['user_id'] . '">&#160;' . $rank[$res['rights']] . '<b>' . $res['from'] . '</b></a></font>';
                    } else {
                        echo '&#160;' . $rank[$res['rights']] . '<b>' . $res['from'] . '</b></font>';
                    }

                    // Метка должности
                   $user_rights = [
                        1 => '(Member)',
                        3 => '(Forum Moderator)',
                        6 => '(Super Moderator)',
                        7 => '(Administrator)',
                        9 => '(Super Admin)',
                    ];

                    // Метка онлайн/офлайн
                    echo(time() > $res['lastdate'] + 300 ? '&#160;<span class="red"><img src="/images/offline.gif" width="8" height="10" alt="off"/></span>' : '&#160;<span class="green"><img src="/images/online.gif" width="8" height="10" alt="on"/></span><br/>');
							$user_rights = array(
							0 => '<img src="/images/member.png" width="100" height="24" alt="" align="middle"/>',
							3 => '<img src="/images/moderator.png" width="100" height="24" alt="" align="middle"/>',
							6 => '<img src="/images/moderator.png" width="100" height="24" alt="" align="middle"/>',
							7 => '<img src="/images/admin.png" width="100" height="24" alt="" align="middle"/>',
							9 => '<img src="/images/owner.png" width="100" height="24" alt="" align="middle"/>'
							);
								echo '<div class="status">';
                    echo(isset($user_rights[$res['rights']]) ? $user_rights[$res['rights']] : '');
								echo '</div>';
								include ('rank.php');

                    // Статус пользователя
                    if (!empty($res['status'])) {
                        echo '<div class="status">' . $tools->image('label.png', ['class' => 'icon-inline']) . $res['status'] . '</div>';
                    }

								echo '</td><td width="auto" align="right" valign="top">';
								// Link pm
								if(!$systemUser->isValid()) {
								echo '<a href="../index.php"><img src="/images/pm.png" width="16" height="16" alt="pm"/></a><br />';
							} else {
								echo '<a href="../mail/index.php?act=write&amp;id=' . $res['user_id'] . '"><img src="/images/pm.png" width="16" height="16" alt="pm"/></a><br />';
						}
						$user_z = $res['user_id'];
						$req_z = $db->query("SELECT * FROM `users` WHERE `id` = '$user_z' LIMIT 1");
						$res_z = $req_z->fetch();
						$pnt = $res_z['karma_plus'];
						echo '<img src="/images/thanx.gif" width="14" height="14" alt="thanx"/><span class="red">&#160;' . $pnt . '</span>';
							// Total post
							echo '<br/>Post: ';
							echo '<span class="red">' . $res['postforum'] . '</span>';


                    // Закрываем таблицу с аватаром
                    echo '</td></tr></table></div><div class="textx">';

                    ////////////////////////////////////////////////////////////
                    // Вывод текста поста                                     //
                    ////////////////////////////////////////////////////////////
                    $text = $res['text'];
								$text = $res['text'];
								if ($set_forum['postcut']) {
									// ADEPETER
										switch ($set_forum['postcut']) {
											case 2:
											$cut = 1000;
											break;

											case 3:
											$cut = 3000;
											break;
											default :
											$cut = 500;
										}
									}

								if ($set_forum['postcut'] && mb_strlen($text) > $cut) {
								$text = mb_substr($text, 0, $cut);
								$text = $tools->checkout($text, 1, 1);
								$text = preg_replace('#\[c\](.*?)\[/c\]#si', '<div class="quote">\1</div>', $text);
								$text = $tools->smilies($text, $res['rights'] ? 1 : 0);
								$checkthank = $db->query('SELECT COUNT(*) FROM `forum_thank` WHERE `userthank` = "' . $systemUser->id . '" and `topic` = "' . $res['id'] . '" and `user` = "' . $res['user_id'] . '"');
								$thankcheck = $checkthank->fetchColumn();
								if (($thankcheck < 1) && $systemUser->id != $res['user_id']) {
									$text = preg_replace('#\[thank\](.*?)\[/thank\]#si', '<div class="orange" style="text-align:center"><font color="cc0000"><b>POST LOCKED</b></font><br><font color="blue">Click ' . $tools->image('thanks.gif') . ' To Unlock Content(s)</font></div>', $text);
									} else {
									$text = preg_replace('#\[thank\](.*?)\[/thank\]#si', '\1', $text);
									}
									echo $bbcode->notags($text) . '...<br /><a href="index.php?act=post&amp;id=' . $res['id'] . '">' . _t('Read All') . ' &gt;&gt;</a>';
								} else {

                    $text = $tools->checkout($text, 1, 1);
                    $text = $tools->smilies($text, $res['rights'] ? 1 : 0);
								$checkthank = $db->query('SELECT COUNT(*) FROM `forum_thank` WHERE `userthank` = "' . $systemUser->id . '" and `topic` = "' . $res['id'] . '" and `user` = "' . $res['user_id'] . '"');
								$thankcheck = $checkthank->fetchColumn();
if(($thankcheck < 1) && $systemUser->id != $res['user_id']) {
								$text = preg_replace('#\[thank\](.*?)\[/thank\]#si', '<div class="orange" style="text-align:center"><font color="cc0000"><b>POST LOCKED</b></font><br><font color="blue">Click ' . $tools->image('thanks.gif') . ' To Unlock Content(s)</font></div>', $text);
								} else {
								$text = preg_replace('#\[thank\](.*?)\[/thank\]#si', '\1', $text);
								}
                    echo $text;
								if (($start + $i) == 1) {
									echo '<div style="text-align:left"><a href="' . $config->adslink . '">' . $tools->smilies($bbcode->tags($config->adstext)) . '</a></div>';
									}
								} 

                    // Если пост редактировался, показываем кем и когда
                    if ($res['kedit']) {
                        echo '<br /><div class="block"><small>' . _t('Last Edited By') . ' <b>' . $res['edit'] . '</b> (' . $tools->displayDate($res['tedit']) . ') <b>[' . $res['kedit'] . ']</b></small></div>';
                    }

							// Forum Right Align
							echo '<div class="forumb"><table width="100%" cellspacing="0" cellpadding="0"><tr><td width="auto" align="left">';
							// Mod. Thanks
							$checkthank = $db->query('SELECT COUNT(*) FROM `forum_thank` WHERE `userthank` = "' . $systemUser->id . '" and `topic` = "' . $res['id'] . '" and `user` = "' . $res['user_id'] . '"')->fetchColumn();
							if ($systemUser->isValid() && $systemUser->id != $res['user_id'] && ($checkthank < 1)) {
							echo '<a href="index.php?id=' . $id . '&amp;thanks=' . $res['id'] . '&amp;user=' . $res['user_id'] . '&amp;start=' . $start . '&amp;thank#thankyou"><img src="/images/thanks.gif" width="55" height="16" alt="thanx"/></a>&#160;';
							}
								// Hacklord quote
								echo '</td><td width="auto" align="right">';
								if ($systemUser->isValid() && $systemUser->id != $res['user_id']) {
									echo '<a href="index.php?act=say&amp;id=' . $res['id'] . '&amp;start=' . $start . '&amp;cyt"><img src="/images/quote.gif" width="55" height="16" alt="Quote Button" /></a>';
										}
									echo '</td></tr></table>';
									echo '</div>';
									echo '<div class="list1">';
									// Mod. Signature
									if (!empty($res['podpis'])){
										echo '<div class="signature"><font color="green">&#160;' . $tools->smilies($bbcode->tags($res['podpis'])) . '</font></div>';
							} 

                    // Задаем права на редактирование постов
                    if (
                        (($systemUser->rights == 3 || $systemUser->rights >= 6 || $curator) && $systemUser->rights >= $res['rights'])
                        || ($res['user_id'] == $systemUser->id && !$set_forum['upfp'] && ($start + $i) == $colmes && $res['time'] > time() - 300)
                        || ($res['user_id'] == $systemUser->id && $set_forum['upfp'] && $start == 0 && $i == 1 && $res['time'] > time() - 300)
                        || ($i == 1 && $allow == 2 && $res['user_id'] == $systemUser->id)
                    ) {
                        $allowEdit = true;
                    } else {
                        $allowEdit = false;
                    }

                    // Если есть прикрепленные файлы, выводим их
                    $freq = $db->query("SELECT * FROM `cms_forum_files` WHERE `post` = '" . $res['id'] . "'");

                    if ($freq->rowCount()) {
                        echo '<div class="post-files">';
                        while ($fres = $freq->fetch()) {
                            $fls = round(@filesize('../files/forum/attach/' . $fres['filename']) / 1024, 2);
                            echo '<div class="gray" style="font-size: x-small;background-color: rgba(128, 128, 128, 0.1);padding: 2px 4px;float: left;margin: 4px 4px 0 0;">' . _t('Attachment') . ':';
                            // Предпросмотр изображений
                            $att_ext = strtolower(pathinfo('./files/forum/attach/' . $fres['filename'], PATHINFO_EXTENSION));
                            $pic_ext = [
                                'gif',
                                'jpg',
                                'jpeg',
                                'png',
                            ];
											$reqposts = $db->query("SELECT `postforum`, `id` FROM `users` WHERE `id` = '$systemUser->id'");
											$fetchpost = $reqposts->fetch();
											$calcposts = $config['puf'] - $fetchpost['postforum'];
                            if (in_array($att_ext, $pic_ext)) {
                                echo '<div><a href="index.php?act=file&amp;id=' . $fres['id'] . '">';
                                echo '<img src="thumbinal.php?file=' . (urlencode($fres['filename'])) . '" alt="' . _t('Click to view image') . '" /></a></div>';
                            } else {

											if (empty($systemUser->id) || ($systemUser->ban['1']) || ($systemUser->ban['12']) || ($systemUser->ban['11']) || $systemUser->postforum < $config['puf']) {
											echo '<br/><img src="/images/lock.png" align="left" alt="attach"/>&#160;<span class="red">File Locked..!!</span>';
											echo '<p><span class="red">You need at least ' . abs($calcposts) . ' post, to download this file..</span></p>';
											} else {
											if ($systemUser->isValid() && $systemUser->id != $res['user_id'] && ($thankcheck < 1)) {
											echo '<br/><div class="gmenu"><font color="red"><b>Click ' . $tools->image('thanks.gif') . ' to download</b></font></div>'; 
											} else {

                                echo '<br><img src="/images/attach.png" align="left" alt="attach"/>&#160;<a href="index.php?act=file&amp;id=' . $fres['id'] . '">' . $fres['filename'] . '</a>';
                            }

                            echo ' (' . $fls . ' кб.)<br>';
                            echo _t('Downloads') . ': ' . $fres['dlcount'] . ' ' . _t('Time');

                            if ($systemUser->rights >= 1) {
                            $file_id = $fres['id'];

												echo '<br/><a href="index.php?act=xoafile&amp;id=' . $fres['id'] . '">Delete Attachment</a>';
										} 
											if ($fls == 0) {
											echo '<br/><span class="red">File has been deleted..!!</span>';
										} 
										}                 

                            echo '</div>';
                        }
} 
                        echo '<div style="clear: both;"></div></div>';
                    }

								$thongkethank = $db->query("SELECT COUNT(*) from `forum_thank` where `topic`='" . $res["id"] . "'");
								$thongkethanks = $thongkethank->fetchColumn();
								$thongkea = $db->query("select * from `forum_thank` where `topic` = '" . $res['id'] . "'");
								$thongke = $thongkea->fetch();
								$idthongke = trim($_GET['idthongke']);
									if($thongkethanks && empty($_GET['idthongke'])) {
										echo '<div class="nonex" align="right"><a href="index.php?id=' . $id . '&amp;start=' . $start . '&amp;idthongke='.$thongke['id'].'#'.$thongke['id'].'">'.$thongkethanks.'</a> Thanks</div>';
								}
								if(!empty($idthongke) && $thongke['id'] == $idthongke) {
								echo '<div id="'.$idthongke.'" class="nonex" style="font-size:x-small">Thanks from: ';
$thongkeaa = $db->query("select * from `forum_thank` where `topic` = '" . $res['id'] . "'");
while($thongkea = $thongkeaa->fetch()) {
{
$dentv = $db->query('SELECT * FROM `users` WHERE `id` = "'.$thongkea['userthank'].'"')->fetch();
						echo '<a href="/users/profile.php?users='.$thongkea['userthank'].'">'.$dentv['name'].'</a>, ';
								}
					++$f;
							}
					echo '</div>';
					} 

                    // Ссылки на редактирование / удаление постов
                    if ($allowEdit) {
                        echo '<div class="sub">';

                        // Чекбокс массового удаления постов
                        if ($systemUser->rights == 3 || $systemUser->rights >= 6) {
                            echo '<input type="checkbox" name="delch[]" value="' . $res['id'] . '"/>&#160;';
                        }

                        // Служебное меню поста
                        $menu = [
                            '<a href="index.php?act=editpost&amp;id=' . $res['id'] . '">' . _t('Edit Post') . '</a>',
                            '<a href="index.php?act=addfile&amp;id=' . $res['id'] . '">' . _t('Upload File') . '</a>',
                            '<a href="index.php?act=import&amp;id=' . $res['id'] . '">' . _t('Import File') . '</a>',
                            ($systemUser->rights >= 7 && $res['close'] == 1 ? '<a href="index.php?act=editpost&amp;do=restore&amp;id=' . $res['id'] . '">' . _t('Restore') . '</a>' : ''),
                            ($res['close'] == 1 ? '' : '<a href="index.php?act=editpost&amp;do=del&amp;id=' . $res['id'] . '">' . _t('Delete Post') . '</a>'),
                        ];
                        echo implode(' | ', array_filter($menu));

                        // Показываем, кто удалил пост
                        if ($res['close']) {
                            echo '<div class="red">' . _t('Post deleted') . ': <b>' . $res['close_who'] . '</b></div>';
                        } elseif (!empty($res['close_who'])) {
                            echo '<div class="green">' . _t('Post restored by') . ': <b>' . $res['close_who'] . '</b></div>';
                        }

                        // Показываем IP и Useragent
                        if ($systemUser->rights == 3 || $systemUser->rights >= 6) {
                            if ($res['ip_via_proxy']) {
                                echo '<div class="gray"><b class="red"><a href="' . $config->homeurl . '/admin/index.php?act=search_ip&amp;ip=' . long2ip($res['ip']) . '">' . long2ip($res['ip']) . '</a></b> - ' .
                                    '<a href="' . $config->homeurl . '/admin/index.php?act=search_ip&amp;ip=' . long2ip($res['ip_via_proxy']) . '">' . long2ip($res['ip_via_proxy']) . '</a><br/>' .
                                    ' - ' . $res['soft'] . '</div>';
                            } else {
                                echo '<div class="gray"><a href="' . $config->homeurl . '/admin/index.php?act=search_ip&amp;ip=' . long2ip($res['ip']) . '">' . long2ip($res['ip']) . '</a> - ' . $res['soft'] . '</div>';
                            }
                        }

                         echo '</div>';
                    }

                    echo '</div></div></div>';
                    ++$i;
                }

                // Кнопка массового удаления постов
                if ($systemUser->rights == 3 || $systemUser->rights >= 6) {
                    echo '<div class="mainblok"><div class="gmenu"><input type="submit" value=" ' . _t('Delete marked post') . ' "/></div>';
                    echo '</form></div>';
                }

                // Нижнее поле "Написать"
                if (($systemUser->isValid() && !$type1['edit'] && !$set_forum['upfp'] && $config->mod_forum != 3 && $allow != 4) || ($systemUser->rights >= 7 && !$set_forum['upfp'])) {
                    echo '<div class="mainblok"><div class="phdr"><img src="/images/qpost.gif" width="80" height="18" class="left"/>&nbsp;</div><div class="list1"><form name="form2" action="index.php?act=say&amp;id=' . $id . '" method="post">';

                       echo '<p>';
                        echo $container->get(Johncms\Api\BbcodeInterface::class)->buttons('form2', 'msg');
                        echo '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="msg"></textarea><br></p>' .
                            '<p><input type="checkbox" name="addfiles" value="1" /> ' . _t('Add File');

                        echo '</p><p><input type="submit" name="submit" value="' . _t('Write') . '" style="width: 107px; cursor: pointer;"/> ' .
($set_forum['preview'] ? '<input type="submit" value="' . _t('preview') . '" style="width: 107px; cursor: pointer;"/>' : '') .
                            '</p></form></div>';
                			echo '<div class="phdr"><a id="down"></a><a href="#up">' . $tools->image('up.png', ['class' => '']) . '</a>' .
                    '&#160;&#160;' . _t('Total Posts') . ': ' . $colmes . '</div>';

                    } else {
                        echo '<p><input type="submit" name="submit" value="' . _t('Write') . '"/></p></form>';
                    }

                // Постраничная навигация
                if ($colmes > $kmess) {
                    echo '<div class="topmenu">' . $tools->displayPage(''.$config->homeurl.'/forum/'.$tools->rewriteUrl($type1["text"]).'_' . $id, $start, $colmes, $kmess) . '</div>' .
                        '<form action="index.php?id=' . $id . '" method="post">' .
                        '<input type="text" name="page" size="2"/>' .
                        '<input type="submit" value="' . _t('To Page') . ' &gt;&gt;"/>' .
                        '</form></div>';
                } else {

                }
							echo '</div>';

#HACKLORD
if ($systemUser->isValid()) {
$upload_file_size = 1024;
echo '<div class="mainblok"><div class="phdr"><img src="/images/file.png" align="top" alt="file"/>&#160;<b>BBcode images</b></div>';
echo '<form enctype="multipart/form-data" method="post"><div class="gmenu">' .
'Import an image:<br/><input type="text" name="url" value="http://"/>' .
'<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $upload_file_size) . '"/>' . '<br/>' .
'<input type="submit" name="proceed" value="Import image"/></div></form>';
#Hacklord
if (isset($_POST['proceed'])) {
#folder to save imported files must end with slash..
$url = $_POST['url'];
$destination_folder = '../files/forum/attach/';
$newfname = $destination_folder.basename($url);
$file = fopen($newfname, "rb");
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
$target_file = $newfname;
require_once(ROOT_PATH . 'downloads/classes/class.upload.php');
$handle = new upload($target_file);
if ($handle->uploaded) {
$name_file = time() . '_' . mt_rand(100, 999);
$handle->file_new_name_body = $name_file;
$handle->allowed = array('image/jpeg', 'image/gif', 'image/bmp', 'image/png');
$handle->file_max_size = 1024 * $upload_file_size;
$handle->file_overwrite = true;
$handle->image_convert = 'jpg';
$handle->process('../files/images/');
if ($handle->processed) {
$handle->file_new_name_body = $name_file;
$GetImageSize = GetImageSize('../files/images/' . $name_file . '.jpg');
$handle->file_overwrite = true;
$handle->jpeg_quality = 90;
$handle->image_ratio_fill = true;
$handle->image_ratio_crop = true;
$x_ratio = 100 / $GetImageSize[0];
$y_ratio = 100 / $GetImageSize[1];
if (($GetImageSize[0] <= 100) && ($GetImageSize[1] <= 100)) {
$handle->image_x = $GetImageSize[0];
$handle->image_y = $GetImageSize[1];
}
else if (($x_ratio * $GetImageSize[1]) < 100) {
$handle->image_y = ceil($x_ratio * $GetImageSize[1]);
$handle->image_x = 100;
} else {
$handle->image_x = ceil($y_ratio * $GetImageSize[0]);
$handle->image_y = 100;
}
$handle->image_convert = 'jpg';
$handle->process('../files/images/');
if ($handle->processed) {
echo '<div class="gmenu">Image successfully imported..!! You now can paste it into your post..!!<br/>' .
'BBimg: <input type="text" value="[img=' . $name_file . ']"/></div>';
@unlink($newfname);
} else {
echo '<div class="gmenu">';
echo $tools->displayError($handle->error);
echo '</div>';
@unlink($newfname);
}
} else {
echo '<div class="gmenu">';
echo $tools->displayError($handle->error);
echo '</div>';
@unlink($newfname);
$handle->clean();
}
} else {
echo '<div class="gmenu">';
echo $tools->displayError('No image imported..!!');
echo '</div>';
@unlink($newfname);
}
}
echo '<div class="phdr">Allowed to import files jpg, jpeg, png, gif<br/>' .
'file size should not exceed ' . $upload_file_size . ' kb</div></div>';
} else {
#ONLY FOR MEMBERS
}

						
                // Список кураторов
                if ($curators) {
                    $array = [];

                    foreach ($curators as $key => $value) {
                        $array[] = '<a href="../profile/?user=' . $key . '">' . $value . '</a>';
                    }

                    echo '<div class="mainblok"><div class="phdr"><img src="../images/file.png" align="left" alt="curators"/>&nbsp;<b>' . _t('Curators of the topic') . '</b></div><div class="menu">' . _t('Curators') . ': ' . implode(', ', $array) . '</div></div>';
                }
                // Ссылки на модерские функции управления темой
                if ($systemUser->rights == 3 || $systemUser->rights >= 6) {
								echo '<div class="mainblok"><div class="phdr"><img src="../images/file.png" align="left" alt="tools"/>&nbsp;<b>Admin tools</b></div>';
                    echo '<div class="menu">';

                    if ($systemUser->rights >= 7) {
                        echo '<a href="index.php?act=curators&amp;id=' . $id . '&amp;start=' . $start . '">' . _t('Curators of the Topic') . '</a><br />';
                    }

                    echo isset($topic_vote) && $topic_vote > 0
                        ? '<a href="index.php?act=editvote&amp;id=' . $id . '">' . _t('Edit Poll') . '</a><br><a href="index.php?act=delvote&amp;id=' . $id . '">' . _t('Delete Poll') . '</a><br>'
                        : '<a href="index.php?act=addvote&amp;id=' . $id . '">' . _t('Add Poll') . '</a><br>';
                    echo '<a href="index.php?act=ren&amp;id=' . $id . '">' . _t('Rename Topic') . '</a><br>';

                    // Закрыть - открыть тему
                    if ($type1['edit'] == 1) {
                        echo '<a href="index.php?act=close&amp;id=' . $id . '">' . _t('Open Topic') . '</a><br>';
                    } else {
                        echo '<a href="index.php?act=close&amp;id=' . $id . '&amp;closed">' . _t('Close Topic') . '</a><br>';
                    }

                    // Удалить - восстановить тему
                    if ($type1['close'] == 1) {
                        echo '<a href="index.php?act=restore&amp;id=' . $id . '">' . _t('Restore Topic') . '</a><br>';
                    }

                    echo '<a href="index.php?act=deltema&amp;id=' . $id . '">' . _t('Delete Topic') . '</a><br>';

                    if ($type1['vip'] == 1) {
                        echo '<a href="index.php?act=vip&amp;id=' . $id . '">' . _t('Unfix Topic') . '</a>';
                    } else {
                        echo '<a href="index.php?act=vip&amp;id=' . $id . '&amp;vip">' . _t('Pin Topic') . '</a>';
                    }

                    echo '<br><a href="index.php?act=per&amp;id=' . $id . '">' . _t('Move Topic') . '</a></div></div>';
                }
                // Ссылка на список "Кто в теме"
                if ($wholink) {
                    echo '<div>' . $wholink . '</div>';
                }
							
                // Ссылка на фильтр постов
                if ($filter) {
                    echo '<div><a href="index.php?act=filter&amp;id=' . $id . '&amp;do=unset">' . _t('Cancel Filter') . '</a></div>';
                } else {
                    echo '<div><a href="index.php?act=filter&amp;id=' . $id . '&amp;start=' . $start . '">' . _t('Filter by author') . '</a></div>';
                }

                // Ссылка на скачку темы
                echo '<a href="index.php?act=tema&amp;id=' . $id . '">' . _t('Download Topic') . '</a>';
                break;

            default:
                // Если неверные данные, показываем ошибку
                echo $tools->displayError(_t('Wrong data'));
                break;
        }
    } else {
        ////////////////////////////////////////////////////////////
        // Список Категорий форума                                //
        ////////////////////////////////////////////////////////////
        $count = $db->query("SELECT COUNT(*) FROM `cms_forum_files`" . ($systemUser->rights >= 7 ? '' : " WHERE `del` != '1'"))->fetchColumn();
        echo '<p>' . $counters->forumNew(1) . '</p>' .
            '<div class="mainblok"><div class="phdr"><img src="/images/subfldr.png" width="16" height="16" class="left"/>&nbsp;<b>Forum structure</b></div>' .
            '<div class="topmenu"><a href="search.php">' . _t('Search') . '</a> | <a href="index.php?act=files">' . _t('Files') . '</a> <span class="red">(' . $count . ')</span></div>';
        $req = $db->query("SELECT `id`, `text`, `soft` FROM `forum` WHERE `type`='f' ORDER BY `realid`");
        $i = 0;
        while ($res = $req->fetch()) {
            echo $i % 2 ? '<div class="menu">' : '<div class="list1">';
            $count = $db->query("SELECT COUNT(*) FROM `forum` WHERE `type`='r' AND `refid`='" . $res['id'] . "'")->fetchColumn();
            echo '<img src="../images/catlist.png" width="16" height="16" class="left"/>&nbsp;<a href="'.$config->homeurl.'/forum/' . $tools->rewriteUrl($res['text']) . '_' . $res['id'] . '.html">' . $res['text'] . '</a> [' . $count . ']';

            if (!empty($res['soft'])) {
                echo '<div class="sub"><span class="gray">' . $res['soft'] . '</span></div>';
            }

            echo '</div>';
            ++$i;
        }
					echo '</div>';
        $online_u = $db->query("SELECT COUNT(*) FROM `users` WHERE `lastdate` > " . (time() - 300) . " AND `place` LIKE 'forum%'")->fetchColumn();
        $online_g = $db->query("SELECT COUNT(*) FROM `cms_sessions` WHERE `lastdate` > " . (time() - 300) . " AND `place` LIKE 'forum%'")->fetchColumn();
        echo '<div class="phdr">' . ($systemUser->isValid() ? '<a href="index.php?act=who">' . _t('Who in Forum') . '</a>' : _t('Who in Forum')) . '&#160;(' . $online_u . '&#160;/&#160;' . $online_g . ')</div>';
        unset($_SESSION['fsort_id']);
        unset($_SESSION['fsort_users']);
    }

    // Навигация внизу страницы
    echo '<p>' . ($id ? '<a href="index.php">' . _t('Forum') . '</a><br />' : '');

    if (!$id) {
        echo '<a href="../help/?act=forum">' . _t('Forum rules') . '</a>';
    }

    echo '</p>';

    if (!$systemUser->isValid()) {
        if ((empty($_SESSION['uppost'])) || ($_SESSION['uppost'] == 0)) {
            echo '<a href="index.php?id=' . $id . '&amp;page=' . $page . '&amp;newup">' . _t('New at the top') . '</a>';
        } else {
            echo '<a href="index.php?id=' . $id . '&amp;page=' . $page . '&amp;newdown">' . _t('New at the bottom') . '</a>';
        }
    }
}

// Hacklord share
echo'<div class="mainblok"><div class="phdr"><b>Share This Topic On:</b></div><center>';
include_once('../social_bookmarking.php');
echo digg();
echo facebook();
echo twitter();
echo delicious();
echo '</center></div>';

//Bbcodes to forum

echo '<div class="mainblok"><div class="phdr"><b>BB Codes:</b></div>';
echo '<div class="gmenu"><b>Topic Url:</b><br/>';

//Forum link

echo '<input type="text" size="18" value="[url='.$config->homeurl.'/forum/'.$tools->rewriteUrl($type1["text"]).'_'.$id.'.html]'.$type1["text"].'[/url]"/><br/><b>Link:<br/></b><input type="text" size="18" value="'.$config->homeurl.'/forum/'.$tools->rewriteUrl($type1["text"]).'_'.$id.'.html"/><br/>';

//Forum tag bbcode 

echo '<b>Forum Tag:</b><br/><input type="text" size="18" value="[forum='.$id.']'.$type1["text"].'[/forum]"/>';
echo '</div></div>';


require_once('../system/end.php');
