<?
session_start();
if(empty($_GET['page'])){
$_SESSION['fpage']=1;
}else{
$_SESSION['fpage']=intval($_GET['page']);
}
require_once('../classes/body.class.php');
require_once('../classes/db.class.php');
require_once('../classes/system.class.php');
$title= new Body;
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/classes/level.class.ini');
$id = isset($_GET['id']) ? abs((int)$_GET['id']) : false;
$array = DB::$dbs->query("SELECT * FROM forum_topic WHERE id = ? LIMIT 1", [$id]);
if ($array -> rowCount() == 0) {
header('location: /');
die();
}
if (isset($_GET['name'])) {
header ('location: /');
exit;
}
$arr = $array -> fetch();
if ($b == true) {
$InThem = DB::$dbs->query("SELECT `id` FROM `forum_inthem` WHERE `user_id` = ? AND `tid` = ?", [$b['id'],$id]);
if ($InThem -> rowCount()== false){
DB::$dbs->query("INSERT INTO `forum_inthem` SET `user_id` = ?, `tid` = ?, `time` = ?", [$b['id'],$id,time()]);
}
elseif ($InThem -> rowCount() != false){
DB::$dbs->query("UPDATE `forum_inthem` SET `time` = ? WHERE `user_id` = ? AND `tid` = ?", [time(),$b['id'],$id]);
}
}
$raz = DB::$dbs->queryFetch("SELECT * FROM forum_razdel WHERE id = ? LIMIT 1", [$arr['rid']]);
$praz = DB::$dbs->queryFetch("SELECT * FROM forum_prazdel WHERE id = ? LIMIT 1", [$arr['prid']]);
$title->SetTitle('Форум - '.$arr['name'].'');
$title->GetHeader();


echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-widgets"></i><a href="/"style="text-decoration:none; color:white;"> Главная</a> :: Форум - '.$arr['name'].'</div></div></div>';

if (isset($_GET['who_vote'])) {
$v = abs(intval($_GET['v']));
if (empty($arr['quest'])) {
header('location: /forum/thema'.$id);
exit();
}
if ($v < 1 || $v > 4) {
header('location: /forum/thema'.$id);
die();
}
$res = DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_votes WHERE tid = ? AND var = ?", [$id,$v]);
$num = 10;
$k_page = k_page($res, $num);
$page = page($k_page);
$start = $num*$page-$num;
if ($res != 0)
{
$Res = DB::$dbs->query("SELECT * FROM forum_votes WHERE tid = ? AND var = ? ORDER BY id DESC LIMIT $start,$num", [$id,$v]);
while($inRes = $Res->fetch())
{
echo '<div class="list-group-item media">'.Nick($inRes['user_id']).'</div>';

}
} else {
err('За этот вариант никто не голосовал');
}
if ($k_page>1) {
str('/forum/thema'.$id.'?who_vote&v='.$v.'&', $k_page,$page);
}
echo '<div class="list-group-item media"><a href="/forum/thema'.$arr['id'].'"><i class="zmdi zmdi-format-list-bulleted"></i> Вернуться в тему</a></div>';
echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
$title->GetMenu();
$title->GetFooter();
die();
}
if (isset($_GET['like'])) {
$v = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE id = ? LIMIT 1", [abs((int)$_GET['like'])]);
if (empty($v['id'])) {
header('location: /');
die();
}
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
if ($b['post'] < 100) {
header('location: /');
die();
}
$p = isset($_GET['page']) ? abs((int)$_GET['page']) : 1;
$post_row = DB::$dbs->queryFetch("SELECT * FROM forum_like WHERE tid = ? AND user_id = ? ORDER BY time DESC LIMIT 1", [$id,$b['id']]);

$zxzx = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE id = ? LIMIT 1", [$v['id']]);
$xxxz = DB::$dbs->query("SELECT * FROM `forum_like` WHERE `user_id` = ? AND `tid` = ? AND `komu` = ?", [$b['id'],$zxzx['tid'],$zxzx['user_id']]);
if ($xxxz -> rowCount()== true){
err('Вы уже голосовали за этого пользователя!');
}elseif ($post_row['time'] > time()+100) {
err('Вы уже голосовали в этой теме! Следующая попытка будет доступна через 1 час!'); 
} elseif (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_like WHERE user_id = ? AND post_id = ?", [$b['id'],$v['id']]) > 0) {
err('Вы уже голосовали за этот пост!');
} elseif ($v['user_id'] == $b['id']) {
err('Нельзя голосовать за свой пост!');
} else {

DB::$dbs->query("INSERT INTO forum_like SET user_id = ?, post_id = ?, type = ?, tid = ?,komu = ?, time = ?", [$b['id'],$v['id'],1,$id,$zxzx['user_id'],time()]);
$g = '0.25';
DB::$dbs->query("UPDATE `blogger` SET `gears` = `gears` + ? WHERE `id` = ?", [$g,$v['user_id']]);
$message = Nick($b['id']).' [b]положительно[/b] оценил ваш пост [b]'.mb_substr($v['text'],0,60, 'UTF-8').'...[/b] в теме <a href="/forum/thema'.$id.'">'.$arr['name'].'</a>';
jurnal($v['user_id'],$message,4);
}
}
if (isset($_GET['dlike'])) {
$v = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE id = ? LIMIT 1", [abs((int)$_GET['dlike'])]);
if (empty($v['id'])) {
header('location: /');
die();
}
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
if ($b['post'] < 100) {
header('location: /');
die();
}
$p = isset($_GET['page']) ? abs((int)$_GET['page']) : 1;
$post_row = DB::$dbs->queryFetch("SELECT * FROM forum_like WHERE tid = ? AND user_id = ? ORDER BY time DESC LIMIT 1", [$id,$b['id']]);
$zxzx = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE id = ? LIMIT 1", [$v['id']]);
$xxxz = DB::$dbs->query("SELECT * FROM `forum_like` WHERE `user_id` = ? AND `tid` = ? AND `komu` = ?", [$b['id'],$zxzx['tid'],$zxzx['user_id']]);
if ($xxxz -> rowCount()== true){
err('Вы уже голосовали за этого пользователя!');
}elseif ($post_row['time'] > time()+100) {
err('Вы уже голосовали в этой теме! Следующая попытка будет доступна через 1 час!'); 
} elseif (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_like WHERE user_id = ? AND post_id = ?", [$b['id'],$v['id']]) > 0) {
err('Вы уже голосовали за этот пост!');
} elseif ($v['user_id'] == $b['id']) {
err('Нельзя голосовать за свой пост!');
} else {

DB::$dbs->query("INSERT INTO forum_like SET user_id = ?, post_id = ?, type = ?, tid = ?,komu = ?, time = ?", [$b['id'],$v['id'],2,$id,$zxzx['user_id'],time()]);
$g = '0.25';
DB::$dbs->query("UPDATE `blogger` SET `gears` = `gears` - ? WHERE `id` = ?", [$g,$v['user_id']]);
$message = Nick($b['id']).' [b]отрицательно[/b] оценил ваш пост [b]'.mb_substr($v['text'],0,60, 'UTF-8').'...[/b] в теме <a href="/forum/thema'.$id.'">'.$arr['name'].'</a>';
jurnal($v['user_id'],$message,4);
header('location: /forum/thema'.$id.'?page='.$p);
}
}
if (isset($_GET['acc'])) {
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
if ($b['post'] < 100) {
header('location: /');
die();
}
echo '<div class="list-group-item media"> Действительно проголосовать положительно за этот пост?<br/><a href="/forum/thema'.$id.'?like='.abs((int)$_GET['acc']).'&page='.abs((int)$_GET['page']).'">Да</a> | <a href="/forum/thema'.$id.'?page='.abs((int)$_GET['page']).'">Нет</a></div>';
echo '<div class="list-group-item media"><a href="/forum/thema'.$arr['id'].'"><i class="zmdi zmdi-format-list-bulleted"></i> Вернуться в тему</a></div>';
echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
$title->GetMenu();
$title->GetFooter();
die();
}
if (isset($_GET['acce'])) {
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
if ($b['post'] < 100) {
header('location: /');
die();
}
echo '<div class="list-group-item media"> Действительно проголосовать отрицательнo за этот пост?<br/><a href="/forum/thema'.$id.'?dlike='.abs((int)$_GET['acce']).'&page='.abs((int)$_GET['page']).'">Да</a> | <a href="/forum/thema'.$id.'?page='.abs((int)$_GET['page']).'">Нет</a></div>';
echo '<div class="list-group-item media"><a href="/forum/thema'.$arr['id'].'"><i class="zmdi zmdi-format-list-bulleted"></i> Вернуться в тему</a></div>';
echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
$title->GetMenu();
$title->GetFooter();
die();
}
// удаление голосования
if (isset($_GET['delvote'])) {
if ($arr['user_id'] != $b['id'] && $b['level'] < 3) {
header('Location: /forum/thema' .$id);
} else {
DB::$dbs->query("UPDATE `forum_topic` SET
`quest` = ?,
`var1` = ?, 
`var2` = ?,
`var3` = ?,
`var4` = ?
WHERE `id` = ? LIMIT 1", ['','','','','',$id]);
DB::$dbs->query("DELETE FROM `forum_votes` WHERE `tid` = ?", [$id]);
header('Location: /forum/thema'.$id);
}
}
// голосовал ли пользователь?
$ResVote = DB::$dbs-> querySingle("SELECT COUNT(id) FROM `forum_votes` WHERE `tid` = ? AND `user_id` = ?", [$id,$b['id']]);
// голосуем
if (isset($_POST['variant'])) {
$var = abs((int)$_POST['var']);
if ($var < 1 || $var > 4) {
header('Location: /forum/thema'.$id);
} elseif ($arr['type'] == 'closed') {
err('Тема закрыта!');
} elseif ($ResVote != false) {
err('Вы уже голосовали в этой теме!');
} else {
DB::$dbs->query("INSERT INTO `forum_votes` SET `user_id` = ?, `tid` = ?, `var` = ?", [$b['id'],$id,$var]);
header('Location: /forum/thema'.$id);
}
}
if ($arr['type'] != 'closed') {
if (isset($_GET['podp'])) {
if ($b == true) {
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_podpis WHERE tid = ? AND user_id = ?", [$id,$b['id']]) == 0) {
DB::$dbs->query("INSERT INTO forum_podpis (tid,user_id) VALUES (?,?)", [$id,$b['id']]);
} else {
DB::$dbs->query("DELETE FROM forum_podpis WHERE tid = ?", [$id]);
}
header('location: /forum/thema'.$id.'?page='.$_SESSION['fpage']);
}
}
}
echo '<div class="list-group-item media">Действие с темой:  <a href=javascript:document.location.reload()> [Обновить]</a>';
if ($arr['type'] != 'closed') {
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_podpis WHERE tid = ? AND user_id = ?", [$id,$b['id']]) == 0) {
echo '<a href="/forum/thema'.$id.'?podp">[Подписаться]</a>';
} else {
echo '<a href="/forum/thema'.$id.'?podp">[Отписаться]</a>';
}
}
if (empty($arr['quest']) && $arr['user_id'] == $b['id'] && $arr['type'] != 'closed')
{
echo '  <a href="/forum/modcp.php?do=addvote&id='.$id.'">[Доб. опрос]</a>';
}
elseif (!empty($arr['quest']) && $arr['user_id'] == $b['id'] && $arr['type'] != 'closed')
{
echo '  <a href="/forum/modcp.php?do=edit_vote&id='.$id.'">[Изм. опрос]</a> 
<a href="/forum/thema'.$id.'?delvote">[Убр. опрос]</a>';
}
if ($b['level'] >= 1) {
echo ($arr['block'] == 1 ? '<a href="/forum/thema'.$id.'?block">[Блокировать]</a>':'<a href="/forum/thema'.$id.'?unblock">[Разблокировать]</a>').'';
}
if ($b['level']>=2) {
if ($arr['fasten'] != 1){
echo ' <a href="modcp.php?do=fasten&id='.$id.'"> [Закрепить] </a>';
} else {
echo ' <a href="modcp.php?do=unfasten&id='.$id.'"> [Открепить] </a>';
}
}
if ($arr['type'] == 'closed') {
if ($b['level'] >= $ini['open']) {
echo ' <a href="modcp.php?do=open&id='.$id.'"> [Открыть]</a> ';
}
} else {
if ($b['level'] >= $ini['closed'] OR $arr['user_id'] == $b['id']) {
echo ' <a href="modcp.php?do=closed&id='.$id.'"> [Закрыть]</a>';
}
}
if ($b['level'] >= $ini['delt']) {
echo ' <a href="modcp.php?do=delt&id='.$id.'"> [Удалить]</a>';
}
if ($arr['type'] != 'closed') {
if ($b['level'] >= $ini['per']) {
echo ' <a href="modcp.php?do=per&id='.$id.'"> [Перенести]</a>';
}
}
if ($b['level'] >= $ini['rename']) {
echo ' <a href="modcp.php?do=rename&id='.$id.'"> [Переименовать]</a>';
}
$tema = DB::$dbs->queryFetch("SELECT user_id,time FROM forum_mess WHERE tid = ? ORDER BY time DESC LIMIT 1", [$id]);
if ($arr['user_id'] == $b['id'] AND $arr['type'] != 'closed' AND $tema['time'] < (time()-86400)) {
echo ' <a href="/forum/thema'.$id.'?accept"><b>[Поднять тему]</b></a><br/>';
}
echo'</div>';
if ($b == true){ 
if (!isset($_GET['results']) && !empty($arr['quest']) && $ResVote == 0) {
// если еще не голосовал
echo '<div class="list-group-item media"><b><i class="zmdi zmdi-trending-up"></i> ' . $arr['quest'] . '</b></div>';
echo '<div class="list-group-item media">';
echo '<form action="/forum/thema'.$id.'" method="post">';
echo'<div class="checkbox cr-alt">';
echo '<label><input type="radio" name="var" value="1"/><i class="input-helper"></i> '.$arr['var1'].'</label><br/>';
echo '<label><input type="radio" name="var" value="2"/><i class="input-helper"></i> '.$arr['var2'].'</label><br/>';
if (!empty($arr['var3'])) echo '<label><input type="radio" name="var" value="3"/><i class="input-helper"></i> '.$arr['var3'].'</label><br/>';
if (!empty($arr['var4'])) echo '<label><input type="radio" name="var" value="4"/><i class="input-helper"></i> '.$arr['var4'].'</label><br/>';
echo '<input type="submit" name="variant" class="btn btn-primary" value="Голосовать"/></form>';
echo '</div></div>';
echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'?results">  Результаты опроса</a></div>';
} elseif (isset($_GET['results']) || !empty($arr['quest']) && $ResVote != 0) {
// если уже голосовал или нажал на "результаты"
function NumVote($variant, $tema = NULL){
return DB::$dbs->querySingle("SELECT COUNT(id) FROM `forum_votes` WHERE `var` = ? AND `tid` = ?", array($variant,$tema));
}
// вычисление процентов
if (!empty($arr['var3']) && empty($arr['var4'])) {
$common = NumVote(1, $id) + NumVote(2, $id) + NumVote(3, $id);
}
elseif (!empty($arr['var3']) && !empty($arr['var4'])) {
$common = NumVote(1, $id) + NumVote(2, $id) + NumVote(3, $id) + NumVote(4, $id);
}
else
{
$common = NumVote(1, $id) + NumVote(2, $id);
}

$prec_1 = round(NumVote(1, $id) * 100 / $common);
$prec_2 = round(NumVote(2, $id) * 100 / $common);
$prec_3 = round(NumVote(3, $id) * 100 / $common);
$prec_4 = round(NumVote(4, $id) * 100 / $common);
echo '<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-trending-up"></i> ' . $arr['quest'] . '</div></div></div>

      <div class="list-group-item media"><a href="/forum/thema'.$id.'?who_vote&v=1"> 1.' . $arr['var1'] . ': '.$prec_1.' %</a></div>';
echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'?who_vote&v=2"> 2.' . $arr['var2'] . ': '.$prec_2.'%</a></div>';
if (!empty($arr['var3'])) {
echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'?who_vote&v=3"> 3.' . $arr['var3'] . ': '.$prec_3.'%</a></div>';
}
if (!empty($arr['var4'])) {
echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'?who_vote&v=4"> 4.' . $arr['var4'] . ': '.$prec_4.'%</a></div>';
}
echo '<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title">Опрошено: '.DB::$dbs->querySingle("SELECT COUNT(id) FROM `forum_votes` WHERE `tid` = ?", [$id]).'</div></div></div>';
if ($ResVote == 0) echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'" > Голосовать</a></div>';
}
}
if ($b['level'] >= 1) {
if (isset($_POST['block'])) {
if ($arr['block'] == 2) {
header('location: /forum/thema'.$id);
die();
}
$block_text = mb_substr($_POST['block_text'],0,250);
if (empty($block_text)) {
err('Введите причину!');
} else {
$mess = 'Ваша тема <a href="/forum/thema'.$id.'">'.$arr['name'].'</a> заблокированa администратором '.Nick($b['id']).' по причине [b]'.check($block_text).'[/b]!';
jurnal($arr['user_id'],$mess,5);
DB::$dbs->query("UPDATE forum_topic SET block = ?, block_text = ?, block_who = ? WHERE id = ? LIMIT 1", [2,check($block_text),$b['id'],$id]);
header('location: /forum/thema'.$id);
die();
}
}
if (isset($_GET['unblock'])) {
DB::$dbs->query("UPDATE forum_topic SET block = ?, block_text = ?, block_who = ? WHERE id = ? LIMIT 1", [1,NULL,NULL,$id]);
header('location: /forum/thema'.$id);
die();
}
if (isset($_GET['block'])) {
echo '<div class="list-group-item media"><form action="/forum/thema'.$id.'?block" method="POST">Причина блокировки (max.: 250):<br/><br/>';
quickpaste('text');
quickpanel();
echo'<br/><br/><textarea name="block_text" class="form-control" rows="8"></textarea><br/><input type="submit" class="btn btn-primary" name="block" value="Дальше"/></form></div>';
$title->GetMenu();
$title->GetFooter();
die();
}
}
if ($arr['block'] == 2) {
echo '<div class="list-group-item media">'.Nick($arr['block_who']).' заблокировал тему по причине: <strong>'.text($arr['block_text']).'</strong></div>';
echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
$title->GetMenu();
$title->GetFooter();
die();
}
$mess = DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_mess WHERE tid = ?", [$id]);
if ($mess > 10) {
$pg = ceil($mess / 10);
$st = 'page='.$pg;
} else {
$st = '';
}
$tema_row = DB::$dbs->queryFetch("SELECT id,user_id,time FROM forum_mess WHERE tid = ? ORDER BY time DESC LIMIT 1", [$id]);
if (isset($_POST['app']) AND $arr['user_id'] == $b['id'] AND $arr['type'] != 'closed' AND $tema_row['time'] < (time()-86400)) {
$msg = 'Автор поднял тему по истечению 24 часов после последнего поста!';
$m2 = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE tid = ? AND text = ? LIMIT 1", [$id,$msg]);
if ($m2 > 0) {
DB::$dbs->query("DELETE FROM forum_mess WHERE id = ?", [$m2['id']]);
DB::$dbs->query("INSERT INTO forum_mess SET text = ?, user_id = ?, time = ?, tid = ?, rid = ?, prid = ?", [$msg,0,time(),$id,$arr['rid'],$arr['prid']]);
DB::$dbs->query("UPDATE forum_topic SET last = ? WHERE id = ?", [time(),$id]);
} else {
DB::$dbs->query("INSERT INTO forum_mess SET text = ?, user_id = ?, time = ?, tid = ?, rid = ?, prid = ?", [$msg,0,time(),$id,$arr['rid'],$arr['prid']]);
DB::$dbs->query("UPDATE forum_topic SET last = ? WHERE id = ?", [time(),$id]);
header('location: /forum/thema'.$id.'?'.$st);
die();
}
}
if (isset($_GET['accept']) AND $arr['user_id'] == $b['id'] AND $arr['type'] != 'closed' AND $tema_row['time'] < (time()-86400)) {
echo '<div class="list-group-item media"><form action="/forum/thema'.$id.'?accept" method="POST">Действительно поднять тему?<br/><input type="submit" name="app" class="btn btn-primary"value="Подтвердить"> :: <a href="/forum/thema'.$id.'?'.$st.'"class="btn btn-primary">Нет</a></div></form>';
echo '<div class="list-group-item media"><a href="/forum/thema'.$id.'?'.$st.'"><i class="zmdi zmdi-format-list-bulleted"></i> Вернуться в тему</a></div>';
echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
$title->GetMenu();
$title->GetFooter();
die();
}
if (isset($_GET['delfile'])) {
$delf = DB::$dbs->queryFetch("SELECT * FROM forum_files WHERE id = ? LIMIT 1", [abs((int)$_GET['delfile'])]);
if (empty($delf['id'])) {
header('location: /');
}
if ($b['level'] < 3) {
header('location: /');
}
unlink('/files/forum/'.$delf['files']);
DB::$dbs->query("DELETE FROM forum_files WHERE id = ?", [$delf['id']]);
header('location: /forum/thema'.$id.'?'.$st);
die();
}
if (isset($_GET['del'])) {
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
$del = abs((int)$_GET['del']);
if (!$del) header('location: /');
DB::$dbs->query("DELETE FROM forum_mess WHERE id = ?", [$del]);
header('location: /forum/thema'.$id.'?'.$st);
}
if (isset($_GET['down'])) {
$down = abs((int)$_GET['down']);
$files = DB::$dbs->queryFetch("SELECT id,files FROM forum_files WHERE id = ? LIMIT 1", [$down]);
if (!$files == 0) header('Location: /');
DB::$dbs->query("UPDATE `forum_files` SET `count` = `count` + ? WHERE `id` = ?", [1,$down]);
header('Location: /files/forum/'.$files['files']);
die();
}
if (isset($_GET['otv'])) {
if ($arr['type'] == 'closed') {
header('location: /');
die();
}
$post = DB::$dbs->queryFetch("SELECT user_id,id FROM forum_mess WHERE user_id = ? LIMIT 1", [abs((int)$_GET['otv'])]);
$user = DB::$dbs->queryFetch("SELECT nick,id FROM blogger WHERE id = ? LIMIT 1", [$post['user_id']]);
if (empty($post['user_id'])) {
header('location: /forum/thema'.$id);
die();
}
$reply = '[b]'.$user['nick'].'[/b], ';
} else {
$reply = '';
}
$otv = isset($_GET['otv']) ? abs((int)$_GET['otv']) : false;
$k_mess = DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_mess WHERE tid = ? ".($b['level'] < 4 ? 'AND del != 1': NULL)."", [$id]);
$num = 10;
$k_page = k_page($k_mess, $num);
$page = page($k_page);
$start = $num*$page-$num;

$sql = DB::$dbs->query("SELECT * FROM forum_mess WHERE tid = ? ".($b['level'] < 4 ? 'AND del != 1': NULL)." ORDER BY id ASC LIMIT $start,$num", [$id]);
if ($sql -> rowCount() == 0) {
err('Сообщений ещё нет!');
} else {
if ($arr['rid'] == 3) {
echo '<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-trending-up"></i> Информация о владельце:</div></div></div><div class="list-group-item media">';
echo '&#187;   WMID: <a href="https://passport.webmoney.ru/asp/certView.asp?wmid='.user_inf($arr['user_id'], 'wmid').'">'.user_inf($arr['user_id'], 'wmid').'</a><br/>
&#187;  BL <img src="https://bl.wmtransfer.com/img/bl/'.user_inf($arr['user_id'], 'wmid').'?w=35&h=18" /><br/>
&#187;  Претензии/Отзывы: <img src="http://arbitrage.webmoney.ru/xml/AL.aspx?wmid='.user_inf($arr['user_id'], 'wmid').'"/><br/>
&#187;  WMR: <a href="http://search.wmtransfer.com/?w=w&q=R'.user_inf($arr['user_id'], 'wmr').'">'.user_inf($arr['user_id'], 'wmr').'</a></div>';
}
$n = 0;
while($a = $sql->fetch()) {
++$n;
$cols = ($start + $n);
$avtor = (($arr['user_id'] == $a['user_id']) ? ' <b><font color="green"> [автор]</font></b> ':NULL);
$us = DB::$dbs->queryFetch("SELECT last,id FROM blogger WHERE id = ? LIMIT 1", [$a['user_id']]);
//$nar = (($a['user_id'] != $b['id'] && $b['level'] > 0 && $b['level'] >= user_inf($a['user_id'], 'level')) ? '  <a href="posting.php?do=nar&id='.$a['id'].'">[Нар]</a>':NULL);
if ($b['level'] >= 4) {
$vost = ($a['del'] == 1 ? ' <a href="posting.php?do=vost_post&id='.$a['id'].'">[Вос]</a>':NULL);
} else {
$vost = '';
}
//if ($b['id'] == $arr['user_id'] && $arr['otvet_2'] != $a['id'] && $arr['otvet']==0 && $b['id'] != $a['user_id']) $best = ' <a href="posting.php?do=best&id='.$a['id'].'">[Лучш]</a>';
//if ($b['id'] == $arr['user_id'] && $arr['otvet_2'] == 0 && $arr['otvet'] != $a['id'] && $b['id'] != $a['user_id']) $worts = ' <a href="posting.php?do=worst&id='.$a['id'].'">[Худш]</a>';
$compl = (($a['user_id'] != $b['id'] && $b['level'] < 1) ? ' <a href="posting.php?do=complaint&id='.$a['id'].'">[Жал]</a>':NULL);


echo '<div class="t-body"><div class="list-group lg-alt"><a href="/users/'.$a['user_id'].'"class="list-group-item media"><div class="pull-left"><img class="img-circle pull-left" src="/'.(user_inf($a['user_id'], 'ava') != NULL ? user_inf($a['user_id'], 'ava') : 'assets/img/4.jpg').'" alt="" width="40" height="40"></div><div class="media-body"><div class="list-group-item-heading">'. $cols.'.   '.NickN($a['user_id']).' '.$avtor.'  '.$br.' </div><small class="list-group-item-text"> ('.vr($a['time']).')</small>';
if ($arr['otvet'] == $a['id']) echo '<span style="color:#FF0000"><b>Лучший ответ!</b></span>';
if ($arr['otvet_2'] == $a['id']) echo '<span style="color:#FF0000"><b>Худший ответ!</b></span>';
if ($a['del'] == 1) {
echo '<b><font color="red">Пост удалил '.user_inf($a['who_del'], 'nick').'</font></b>';
} elseif ($a['del'] == 2) {
echo '<b><font color="green">Пост восстановил '.user_inf($a['who_del'], 'nick').'</font></b>';
}
echo'</div></a>';
echo '</div></div><div class="list-group-item media"><div class="media-body"><div class="list-group-item-heading">';
echo (user_inf($a['user_id'], 'row')>=0 ? strtr(user_inf($a['user_id'], 'row'), $row).'<br/>':NULL);
echo (!empty($a['cit']) ? '<div class="citat">'.text($a['cit']).'</div>':NULL).text($a['text']).'<br/>';
$file = DB::$dbs->query("SELECT * FROM forum_files WHERE mid = ?", [$a['id']]);
if ($file -> rowCount() > 0) {
echo '------------<br/>';
while($f = $file->fetch()) {
echo ($b['level'] >= 3 ? '[<a href="/forum/thema'.$id.'?delfile='.$f['id'].'">X</a>]':NULL).'  <a href="/forum/thema'.$id.'?down='.$f['id'].'">'.$f['files'].'</a> ('.get_size($f['size']).')<br/>Скачано '.$f['count'].' раз(а)</br>';
}
}
echo '</div></div></div>';
if($b == true) {
if ($arr['type'] != 'closed') {
$count_vote = ' (<font color="green">'.DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_like WHERE post_id = ? AND type = ?", [$a['id'],1]).'</font>/<font color="red">'.DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_like WHERE post_id = ? AND type = ?", [$a['id'],2]).'</font>) ';

$posts_row = DB::$dbs->queryFetch("SELECT * FROM forum_like WHERE tid = ? AND user_id = ? ORDER BY time DESC LIMIT 1", [$id,$b['id']]);
$zxzx = DB::$dbs->queryFetch("SELECT * FROM forum_mess WHERE id = ? LIMIT 1", [$posts_row['post_id']]);
$xxxz = DB::$dbs->query("SELECT * FROM `forum_like` WHERE `user_id` = ? AND `tid` = ? AND `komu` = ?", [$b['id'],$a['tid'],$a['user_id']]);

$like = ((DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_like WHERE post_id = ? AND user_id = ?", [$a['id'],$b['id']]) == 0 && $a['user_id'] != $b['id'] && $b['post'] >= 100 && $posts_row['time'] < time()+100  && $xxxz-> rowCount()==false) ? '[<a href="/forum/thema'.$id.'?acc='.$a['id'].'&page='.$page.'">+1</a> | <a href="/forum/thema'.$id.'?acce='.$a['id'].'&page='.$page.'">-1</a>]':NULL);
echo '<div class="list-group-item media"><div class="media-body"><div class="list-group-item-heading">';
echo (($b['id'] == $a['user_id'] || $b['level'] > 0 && $b['level'] > user_inf($a['user_id'], 'level')) ? '  <a href="posting.php?do=editp&id='.$a['id'].'">[Изм]</a> ':'').(($b['id'] != $a['user_id']) ? '   <a href="posting.php?do=quote&id='.$a['id'].'">[Цит]</a>  <a href="/forum/thema'.$id.'?otv='.$a['user_id'].'&'.$st.'#add">[Отв]</a> ':'').($b['level']>0 ? '  <a href="/forum/posting.php?do=del_post&id='.$a['id'].'">[Удл]</a>':NULL).$vost.$compl.$count_vote.$like.'</div></div></div>';
}
}
if ($a['time_edit']>0) {
echo '<div class="list-group-item media">посл.ред. '.(!empty($a['who_edit']) ? Nick($a['who_edit']) : NULL).' в '.date('d.m.y / H:i', $a['time_edit']).'; всего '.$a['count_edit'].' раз</div>';
}
}
}

if ($arr['type'] == 'closed') {
echo '<div class="alert alert-danger" role="alert">
<img src="/assets/images/warning.png" alt="*" align="middle" /> Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.</div>';
}
if (isset($b)) {
if ($arr['type'] != 'closed') {
if (isset($_POST['add'])) {
$err = [];
$form = ['text' => isset($_POST['text']) ? check($_POST['text']) : null];
if (empty($form['text'])) {
$err[] = 'Введите текст!';
}
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_mess WHERE tid = ? AND text = ? AND user_id = ?", [$id,$form['text'],$b['id']]) > 0) {
$err[] = 'Такое сообщение в этой теме уже есть!';
}
$time = DB::$dbs->query("SELECT * FROM forum_mess WHERE user_id = ? ORDER BY time DESC", [$b['id']]);
while($t = $time -> fetch()) {
if ((time() - $t['time']) < 10) {
err('Пишите не чаще чем раз в 10 секунд!');
$title->GetMenu();
$title->GetFooter();
die();
}
}
if (empty($err)) {
$podpis = DB::$dbs -> query("SELECT * FROM `forum_podpis` WHERE `tid`=? AND `user_id`!=? order by id", [$id,$b['id']]);
if ($podpis -> rowCount() != 0){
$podp = DB::$dbs -> query("SELECT * FROM `forum_podpis` WHERE `tid` = ? order by id", [$id]);
while($pod = $podp -> fetch()) {
$mes = Nick($b['id']).' оставил сообщение в теме <a href="/forum/thema'.$id.'">'.$arr['name'].'</a>';
jurnal($pod['user_id'],$mes,2);
}
}
DB::$dbs->query("INSERT INTO forum_mess SET text = ?, user_id = ?, time = ?, rid = ?, prid = ?, tid = ?", [$form['text'],$b['id'],time(),$raz['id'],$praz['id'],$id]);
$m = DB::$dbs->lastInsertId();
DB::$dbs->query("UPDATE forum_topic SET last = ? WHERE id = ?", [time(),$id]);
DB::$dbs->query("UPDATE `blogger` SET `gears` = `gears` + ? WHERE id = ?", [1,$b['id']]);
DB::$dbs->query("UPDATE `blogger` SET `post` = `post` + ? WHERE id = ?", [1,$b['id']]);
$posts = DB::$dbs->queryFetch("SELECT user_id,id FROM forum_mess WHERE id = ? LIMIT 1", [abs((int)$_GET['otv'])]);
if (!empty($otv)) {
$mess = 'Пользователь [b]'.$b['nick'].'[/b] ответил на ваше сообщение в теме  [url=http://'.$_SERVER['HTTP_HOST'].'/forum/thema'.$id.'?page='.$_SESSION['fpage'].'] [b]'.$arr['name'].'[/b][/url]';
jurnal($otv,$mess,2);
}
if ($_POST['addfile'] == 1) {
header('location: posting.php?do=addfile&id='.$m);
} else {
header('location: /forum/thema'.$id.'?'.$st);
die();
}
} else {
echo '<div class="alert alert-danger" role="alert">';
foreach($err as $error) {
echo '<b>'.$error.'</b><br/>';
}
echo '</div>';
}
}
if ($otv) {
$o = 'otv='.$otv.'&page='.$page;
} else {
$o = NULL;
}


echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-comments"></i> Сообщение:</div></div></div>';
echo '<div class="list-group-item media"><form name="form" method="post" action="/forum/thema'.$id.'?'.$o.'" ><br/>';
quickpaste('text');
quickpanel();
echo'<br/><br/><textarea class="form-control" rows="8"name="text">'.$reply.'</textarea><br/><input type="checkbox" name="addfile" value="1"/> Прикрепить файл<br/><input class="btn btn-primary btn-block" type="submit" name="add" value="Написать"/></form></div>';
}
}
echo '<a name="add"></a>';
$in = DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_inthem WHERE tid = ?", [$id]);
echo'<div class="list-group-item media"><a href="who_visit.php?id='.$id.'"><i class="zmdi zmdi-apps"></i> Кто тему посетил? ['.$in.']</a></div>';

echo'<div class="tile"><div class="t-header th-alt bg-teal"><div class="th-title"><i class="zmdi zmdi-format-list-bulleted"></i>  <a href="/rules"style="text-decoration:none; color:white;">Правила</a> | <a href="/bbcodes"style="text-decoration:none; color:white;"> Справка BBcode</a> | <a href="/smiles"style="text-decoration:none; color:white;">Все смайлы</a> | <a href="search"style="text-decoration:none; color:white;">Поиск</a></div></div></div>'; 
if ($k_page>1) {
str('/forum/thema'.$id.'?', $k_page,$page);
}
$title->GetMenu();
$title->GetFooter();
?>