<?php 
require_once '../system/inc/core.php';
$tema = $mysqli->query("SELECT `tema`.*, (SELECT `id` FROM `forum` WHERE `forum`.`id`=`tema`.`id_forum`) AS `id_forum`,
(SELECT `name` FROM `forum` WHERE `forum`.`id`=`tema`.`id_forum`) AS `name_forum`,
(SELECT COUNT(*) FROM `post_file` WHERE post_file.`id_tema` = `tema`.`id`) AS `count_file`,
(SELECT COUNT(*) FROM `tema_send` WHERE tema_send.`id_tema` = `tema`.`id`) AS `count_subscribe`
FROM `tema` WHERE `id`='".$id."'")->fetch_array();
$title = $tema['name'].' | '.$setup['namesite'];
//генерация ключевых слов
$word_counter = new Counter();																					  #
$post = $mysqli->query("SELECT `text` FROM `post` WHERE `id`='".$tema['id']."' ORDER BY `id` ASC LIMIT 1")->fetch_array();#
// подбор слов																	  								  #	
$keywords = $word_counter->get_keywords($post['text']);									    					  
$smarty->assign('keywords',$keywords);											  							      
require_once '../system/inc/head.php';
//если модуль отключен, кидаем на главную
if($setup['forum'] == 0)
header('location: '.$home);

//голосование "за"
if (isset($_GET['plus']))
{
$post = $mysqli->query("SELECT op. * , (SELECT `id` FROM `post_vote` WHERE `post_vote`.`id_post` = op.`id`) AS `votes` FROM `post` op WHERE op.`id` = '".$id."'")->fetch_array();    
$mysqli->query("UPDATE `post` SET `vote`=".intval($post['vote'] + 1)." WHERE `id`='".$post['id']."'");  
if(empty($post['votes']))
$mysqli->query("INSERT INTO `post_vote` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$post['id']."', `id_user`='".$user['id']."', `vote` = 'plus', `time`=".$realtime."");    
$mysqli->query("OPTIMIZE TABLE `post`");
$mysqli->query("OPTIMIZE TABLE `post_vote`");
    exit;
}

//голосование "против"
if (isset($_GET['minus']))
{
$post = $mysqli->query("SELECT op. * , (SELECT `id` FROM `post_vote` WHERE `post_vote`.`id_post` = op.`id`) AS `votes` FROM `post` op WHERE op.`id` = '".$id."'")->fetch_array();   
$mysqli->query("UPDATE `post` SET `vote`=".intval($post['vote'] - 1)." WHERE `id`='".$post['id']."'"); 
if(empty($post['votes']))
$mysqli->query("INSERT INTO `post_vote` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$post['id']."', `id_user`='".$user['id']."', `vote` = 'minus', `time`=".$realtime."");    
$mysqli->query("OPTIMIZE TABLE `post`");
$mysqli->query("OPTIMIZE TABLE `post_vote`");
    exit;
}

if ($user['id']) {
                    // Фиксация факта прочтения темы
                    $req = $mysqli->query("SELECT * FROM `tema_rdm` WHERE `id_tema` = '".$tema['id']."' AND `id_user` = '".$user['id']."' LIMIT 1");
                    if ($req->num_rows > 0) {
                        $res = $req->fetch_array();
                        if ($tema['time'] > $res['time'])
                            $mysqli->query("UPDATE `tema_rdm` SET `time` = '".$realtime."' WHERE `id_tema`='".$tema['id']."' AND `id_user` = '".$user['id']."'");
                    } else {
                        // Ставим метку о прочтении
                        $mysqli->query("INSERT INTO `tema_rdm` SET  `id_tema` = '".$tema['id']."', `id_user` = '".$user['id']."', `time` = '".$realtime."'");
                    }
                }
$counts = $mysqli->query("SELECT * FROM `tema` WHERE `id`='".$id."'")->num_rows;
if($counts==0) 
{
//веб и вап-версия																		
if($setup['style'] == 1)															
{																		
if ($_SESSION['style'] == 'wap')										
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/wap/forum/no_tema.tpl');			
else																				
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/forum/no_tema.tpl');				
}																					
//только веб-версия																	
if($setup['style'] == 2)															
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/forum/no_tema.tpl');				
//только вап-версия																	
if($setup['style'] == 3)															
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/wap/forum/no_tema.tpl');		
require_once '../system/inc/foot.php';
exit;
}

//добавляем кол-во просмотров
if($_SESSION['tema'] != $id) {
$_SESSION['tema'] = $id;
$mysqli->query("UPDATE `tema` SET `count` = '".intval($tema['count'] + 1)."' WHERE `id` = '".$tema['id']."'"); 
}

//ответ на сообщение
if (isset($_GET['reply']))
{
$replys = $mysqli->query("SELECT `post`.*, (SELECT `login` FROM `users` WHERE `users`.`id`=`post`.`id_user`) AS `login` FROM `post` WHERE `id`=".abs(intval($_GET['reply']))."")->fetch_array();
if($_POST['reply'])
{
$text=htmlspecialchars(trim($_POST['text']));

if (mb_strlen($text) < 3 || mb_strlen($text) > 5000)
$error = 'Недопустимая длина текста сообщения!';

if($setup['captcha_forum_add_post'] == 1)
{
if($_POST['captcha']!=$_SESSION['code'])$error='Проверочное число с картинки введено не верно!';
}

//обработка записей типографом
if($setup['forum_tipograf'] == 1 && !empty($text))
{
				$remoteTypograf = new RemoteTypograf();

				$remoteTypograf->htmlEntities();
				$remoteTypograf->br (false);
				$remoteTypograf->p (false);
				$remoteTypograf->nobr (3);
				$remoteTypograf->quotA ('laquo raquo');
				$remoteTypograf->quotB ('bdquo ldquo');

				$text = $remoteTypograf->processText($text);
}
//загрузка файла на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
                                        $file = strtolower($_FILES['file']['name']);//название файла с расширением
					$filetemp = $_FILES["file"]["tmp_name"];//временное название файла
					$fsizefile = $_FILES['file']['size'];//вес файла
					if(!empty($file)){
					$api = file_get_contents('http://gruzimfile.ru/api/?file='.$file.'&filetemp='.$filetemp.'&size='.$fsizefile);
					$api = json_decode($api, true);
					if($api['status']!='ok')
					$error = $api['status'];
									}  
    
}
else {
//загрузка на сервер сайта
                     $do_filefile = false;
                    // Проверка загрузки с обычного браузера
                    if ($_FILES['file']['size'] > 0) {
                        $do_filefile = true;
                        $ifnamefile = strtolower($_FILES['file']['name']);
			$ifnamefile = str_replace(' ', '_', $ifnamefile);
			$typ = pathinfo($ifnamefile, PATHINFO_EXTENSION);
			$fnamefiles = pathinfo($ifnamefile, PATHINFO_FILENAME);
			//Конечное имя файла для сохранения без расширения
			$fnamefile = name_replace($fnamefiles);
			//Конечное имя файла для сохранения с расширением
			$ftp = $fnamefile.'.'.$typ;	
                        $fsizefile = $_FILES['file']['size'];
                    }
				//обработка файла
                    if ($do_filefile) 
					{            
                        // Список допустимых расширений файлов.
                        $al_ext = explode(", ", $setup['forum_upload_type_file']);
                        $ext = explode(".", $ftp);
                        // Проверка на допустимый размер файла
                        if ($fsizefile >=$setup['forum_maxfilesize']*1024*1024)$error = 'Недопустимый вес файла!';
                        // Проверка файла на наличие только одного расширения
                    if (count($ext) != 2)
			$error = 'Файл имеет двойное расширение!';;			
                    // Проверка недопустимых расширений файлов
                    if (!in_array($typ, $al_ext))
			$error = 'Запрещенный тип файла!';
                    if ($typ == null)
			$error = 'Файл не имеет расширения!';
                    }
}
//ограничение на отправку
$flt = $realtime - $setup['antiflood'];
$af = $mysqli->query("select * from `antiflood` where `ip`='".$ip_user."' and time>'".$flt."'");
$af1 = $af->num_rows;
if ($af1 != 0)
$error = 'Вы не можете писать сообщения чаще 1 раза в '.ending_second($setup['antiflood']).'! Пожалуйста, немного подождите...';

if(!isset($error) && empty($_POST['bot']))
{
$mysqli->query("INSERT INTO `antiflood` SET `ip`='".$mysqli->real_escape_string($ip_user)."', `time`='".$realtime."'");
$mysqli->query("INSERT INTO `post` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_user` = '".$user['id']."', `text` = '".$mysqli->real_escape_string(BBcode(smile($text)))."', `time` = '".$realtime."'");
$fid = $mysqli->insert_id;
//если файл загружен на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
 $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$api['file']."', 
     `url` = '".$api['url']."', `id_user`='".$user['id']."', `size` = '".$api['size']."', `time`=".$realtime.""); 
}
//иначе грузим на наш сервер
if($setup['forum_upload_file'] == 1)
{    
if ((move_uploaded_file($_FILES["file"]["tmp_name"], "../files/forum/".$ftp)) == true) {
  $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$ftp."',
                `id_user`='".$user['id']."', `size` = '".size($fsizefile)."', `time`=".$realtime."");   
}    
} 
//поднимаем тему выше
$mysqli->query("UPDATE `tema` SET `time` = '".$realtime."' WHERE `id` = '".$tema['id']."'");
$mysqli->query("OPTIMIZE TABLE `tema`");
$mysqli->query("OPTIMIZE TABLE `post`");
$count = $mysqli->query("SELECT * FROM `post` WHERE `id_tema`=".$tema['id']."")->num_rows;
$starts = max(0, (int)$count - (((int)$count % (int)$message) == 0 ? $message : ((int)$count % (int)$message)));
//производим рассылку по подписавшимся на тему
//кол-во подписчиков
$count_subscribe = $mysqli->query("SELECT * FROM `tema_send` WHERE `id_tema`='".$tema['id']."'")->num_rows;
if($count_subscribe > 0 && !$user['id'])
{
// инициализируем класс
$mailer = new phpmailer();
// Устанавливаем тему письма
$mailer->Subject = 'Уведомление об ответе в подписанной теме';
//задаем e-mail админа
$mailer->From = $setup['emailadmin'];
$mailer->ContentType = 'text/html';
$reqs = $mysqli->query("SELECT `tema_send`.*, (SELECT `login` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `login`,
                        (SELECT `fio` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `fio`,
                        (SELECT `email` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `email` FROM `tema_send`");
while ($rows = $reqs->fetch_array())
{
// Задаем тело письма
$mailer->Body = 'Здравствуйте, '.$rows['login'].' ('.$rows['fio'].')<br/><br/>
    '.$user['login'].' ответил в теме <a href="'.$home.'/forum/tema/'.$tema['id'].'">'.$tema['name'].'</a>, на которую Вы подписаны.<br/><br/><br/>С уважением, администрация сайта <a href="'.$home.'">'.$home.'</a>';    
$mailer->AddAddress($rows['email'], '');
}
$mailer->Send();
}
    //очищаем кеш шаблона
if($setup['cache_smarty'] == 1)
{    
$smarty->clearCache('index.tpl');    
$smarty->clearCache('forum/index.tpl');
$smarty->clearCache('wap/forum/index.tpl');
$smarty->clearCache('forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('wap/forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('forum/tema.tpl', $id);
$smarty->clearCache('wap/forum/tema.tpl', $id);
$smarty->clearCache('forum/files.tpl', $id);
$smarty->clearCache('wap/forum/files.tpl', $id);
}
header('location: '.$home.'/forum/tema/'.$id.',start='.$starts.'#post-'.$fid);	
}
}
}

//цитирование
if (isset($_GET['cit']))
{
$cits = $mysqli->query("SELECT `post`.*, (SELECT `login` FROM `users` WHERE `users`.`id`=`post`.`id_user`) AS `login` FROM `post` WHERE `id`=".abs(intval($_GET['cit']))."")->fetch_array();
if($_POST['citata'])
{
$text=htmlspecialchars(trim($_POST['text']));

if (mb_strlen($text) < 3 || mb_strlen($text) > 5000)
$error = 'Недопустимая длина текста сообщения!';

if($setup['captcha_forum_add_post'] == 1)
{
if($_POST['captcha']!=$_SESSION['code'])$error='Проверочное число с картинки введено не верно!';
}

//обработка записей типографом
if($setup['forum_tipograf'] == 1 && !empty($text))
{
				$remoteTypograf = new RemoteTypograf();

				$remoteTypograf->htmlEntities();
				$remoteTypograf->br (false);
				$remoteTypograf->p (false);
				$remoteTypograf->nobr (3);
				$remoteTypograf->quotA ('laquo raquo');
				$remoteTypograf->quotB ('bdquo ldquo');

				$text = $remoteTypograf->processText($text);
}
//загрузка файла на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
                                        $file = strtolower($_FILES['file']['name']);//название файла с расширением
					$filetemp = $_FILES["file"]["tmp_name"];//временное название файла
					$fsizefile = $_FILES['file']['size'];//вес файла
					if(!empty($file)){
					$api = file_get_contents('http://gruzimfile.ru/api/?file='.$file.'&filetemp='.$filetemp.'&size='.$fsizefile);
					$api = json_decode($api, true);
					if($api['status']!='ok')
					$error = $api['status'];
									}  
    
}
else {
//загрузка на сервер сайта
                     $do_filefile = false;
                    // Проверка загрузки с обычного браузера
                    if ($_FILES['file']['size'] > 0) {
                        $do_filefile = true;
                        $ifnamefile = strtolower($_FILES['file']['name']);
			$ifnamefile = str_replace(' ', '_', $ifnamefile);
			$typ = pathinfo($ifnamefile, PATHINFO_EXTENSION);
			$fnamefiles = pathinfo($ifnamefile, PATHINFO_FILENAME);
			//Конечное имя файла для сохранения без расширения
			$fnamefile = name_replace($fnamefiles);
			//Конечное имя файла для сохранения с расширением
			$ftp = $fnamefile.'.'.$typ;	
                        $fsizefile = $_FILES['file']['size'];
                    }
				//обработка файла
                    if ($do_filefile) 
					{            
                        // Список допустимых расширений файлов.
                        $al_ext = explode(", ", $setup['forum_upload_type_file']);
                        $ext = explode(".", $ftp);
                        // Проверка на допустимый размер файла
                        if ($fsizefile >=$setup['forum_maxfilesize']*1024*1024)$error = 'Недопустимый вес файла!';
                        // Проверка файла на наличие только одного расширения
                    if (count($ext) != 2)
			$error = 'Файл имеет двойное расширение!';;			
                    // Проверка недопустимых расширений файлов
                    if (!in_array($typ, $al_ext))
			$error = 'Запрещенный тип файла!';
                    if ($typ == null)
			$error = 'Файл не имеет расширения!';
                    }
}
//ограничение на отправку
$flt = $realtime - $setup['antiflood'];
$af = $mysqli->query("select * from `antiflood` where `ip`='".$ip_user."' and time>'".$flt."'");
$af1 = $af->num_rows;
if ($af1 != 0)
$error = 'Вы не можете писать сообщения чаще 1 раза в '.ending_second($setup['antiflood']).'! Пожалуйста, немного подождите...';

if(!isset($error) && empty($_POST['bot']))
{
$mysqli->query("INSERT INTO `antiflood` SET `ip`='".$mysqli->real_escape_string($ip_user)."', `time`='".$realtime."'");
$mysqli->query("INSERT INTO `post` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_user` = '".$user['id']."', `text` = '".$mysqli->real_escape_string(BBcode(smile($text)))."', `time` = '".$realtime."'");
$fid = $mysqli->insert_id;
//если файл загружен на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
 $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$api['file']."', 
     `url` = '".$api['url']."', `id_user`='".$user['id']."', `size` = '".$api['size']."', `time`=".$realtime.""); 
}
//иначе грузим на наш сервер
if($setup['forum_upload_file'] == 1)
{    
if ((move_uploaded_file($_FILES["file"]["tmp_name"], "../files/forum/".$ftp)) == true) {
  $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$ftp."',
                `id_user`='".$user['id']."', `size` = '".size($fsizefile)."', `time`=".$realtime."");   
}    
} 
//поднимаем тему выше
$mysqli->query("UPDATE `tema` SET `time` = '".$realtime."' WHERE `id` = '".$tema['id']."'");
$mysqli->query("OPTIMIZE TABLE `tema`");
$mysqli->query("OPTIMIZE TABLE `post`");
$count = $mysqli->query("SELECT * FROM `post` WHERE `id_tema`=".$tema['id']."")->num_rows;
$starts = max(0, (int)$count - (((int)$count % (int)$message) == 0 ? $message : ((int)$count % (int)$message)));
//производим рассылку по подписавшимся на тему
//кол-во подписчиков
$count_subscribe = $mysqli->query("SELECT * FROM `tema_send` WHERE `id_tema`='".$tema['id']."'")->num_rows;
if($count_subscribe > 0 && !$user['id'])
{
// инициализируем класс
$mailer = new phpmailer();
// Устанавливаем тему письма
$mailer->Subject = 'Уведомление об ответе в подписанной теме';
//задаем e-mail админа
$mailer->From = $setup['emailadmin'];
$mailer->ContentType = 'text/html';
$reqs = $mysqli->query("SELECT `tema_send`.*, (SELECT `login` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `login`,
                        (SELECT `fio` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `fio`,
                        (SELECT `email` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `email` FROM `tema_send`");
while ($rows = $reqs->fetch_array())
{
// Задаем тело письма
$mailer->Body = 'Здравствуйте, '.$rows['login'].' ('.$rows['fio'].')<br/><br/>
    '.$user['login'].' ответил в теме <a href="'.$home.'/forum/tema/'.$tema['id'].'">'.$tema['name'].'</a>, на которую Вы подписаны.<br/><br/><br/>С уважением, администрация сайта <a href="'.$home.'">'.$home.'</a>';    
$mailer->AddAddress($rows['email'], '');
}
$mailer->Send();
}
    //очищаем кеш шаблона
if($setup['cache_smarty'] == 1)
{    
$smarty->clearCache('index.tpl');    
$smarty->clearCache('forum/index.tpl');
$smarty->clearCache('wap/forum/index.tpl');
$smarty->clearCache('forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('wap/forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('forum/tema.tpl', $id);
$smarty->clearCache('wap/forum/tema.tpl', $id);
$smarty->clearCache('forum/files.tpl', $id);
$smarty->clearCache('wap/forum/files.tpl', $id);
}
header('location: '.$home.'/forum/tema/'.$id.',start='.$starts.'#post-'.$fid);	
}
}
}

//добавление сообщения
if($user['id'])
{
if($_POST['ok'])
{
$text=htmlspecialchars(trim($_POST['text']));

if (mb_strlen($text) < 3 || mb_strlen($text) > 5000)
$error = 'Недопустимая длина текста сообщения!';

if($setup['captcha_forum_add_post'] == 1)
{
if($_POST['captcha']!=$_SESSION['code'])$error='Проверочное число с картинки введено не верно!';
}

//обработка записей типографом
if($setup['forum_tipograf'] == 1 && !empty($text))
{
				$remoteTypograf = new RemoteTypograf();

				$remoteTypograf->htmlEntities();
				$remoteTypograf->br (false);
				$remoteTypograf->p (false);
				$remoteTypograf->nobr (3);
				$remoteTypograf->quotA ('laquo raquo');
				$remoteTypograf->quotB ('bdquo ldquo');

				$text = $remoteTypograf->processText($text);
} 

//загрузка файла на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
                                        $file = strtolower($_FILES['file']['name']);//название файла с расширением
					$filetemp = $_FILES["file"]["tmp_name"];//временное название файла
					$fsizefile = $_FILES['file']['size'];//вес файла
					if(!empty($file)){
					$api = file_get_contents('http://gruzimfile.ru/api/?file='.$file.'&filetemp='.$filetemp.'&size='.$fsizefile);
					$api = json_decode($api, true);
					if($api['status']!='ok')
					$error = $api['status'];
									}  
    
}
else {
//загрузка на сервер сайта
                     $do_filefile = false;
                    // Проверка загрузки с обычного браузера
                    if ($_FILES['file']['size'] > 0) {
                        $do_filefile = true;
                        $ifnamefile = strtolower($_FILES['file']['name']);
			$ifnamefile = str_replace(' ', '_', $ifnamefile);
			$typ = pathinfo($ifnamefile, PATHINFO_EXTENSION);
			$fnamefiles = pathinfo($ifnamefile, PATHINFO_FILENAME);
			//Конечное имя файла для сохранения без расширения
			$fnamefile = name_replace($fnamefiles);
			//Конечное имя файла для сохранения с расширением
                        $rand = rand(111111111111, 999999999999);//случайное число
			$ftp = $fnamefile.'_'.$rand.'.'.$typ;	
                        $fsizefile = $_FILES['file']['size'];
                    }
				//обработка файла
                    if ($do_filefile) 
					{            
                        // Список допустимых расширений файлов.
                        $al_ext = explode(", ", $setup['forum_upload_type_file']);
                        $ext = explode(".", $ftp);
                        // Проверка на допустимый размер файла
                        if ($fsizefile >=$setup['forum_maxfilesize']*1024*1024)$error = 'Недопустимый вес файла!';
                        // Проверка файла на наличие только одного расширения
                    if (count($ext) != 2)
			$error = 'Файл имеет двойное расширение!';;			
                    // Проверка недопустимых расширений файлов
                    if (!in_array($typ, $al_ext))
			$error = 'Запрещенный тип файла!';
                    if ($typ == null)
			$error = 'Файл не имеет расширения!';
                    }
}

//проверка на одинаковые сообщения
$req = $mysqli->query("SELECT * FROM `post` WHERE `id_user` = '".$user['id']."' AND `id_tema`='".$tema['id']."' ORDER BY `time` DESC")->fetch_array();
if($req['text'] == BBcode(smile($text)))
    $error = 'Ваше сообщение повторяет предыдущее!';
//ограничение на отправку
$flt = $realtime - $setup['antiflood'];
$af = $mysqli->query("select * from `antiflood` where `ip`='".$ip_user."' and time>'".$flt."'");
$af1 = $af->num_rows;
if ($af1 != 0)
$error = 'Вы не можете писать сообщения чаще 1 раза в '.ending_second($setup['antiflood']).'! Пожалуйста, немного подождите...';

if(!isset($error) && empty($_POST['bot']))
{
$mysqli->query("INSERT INTO `antiflood` SET `ip`='".$mysqli->real_escape_string($ip_user)."', `time`='".$realtime."'");
$mysqli->query("INSERT INTO `post` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_user` = '".$user['id']."', `text` = '".$mysqli->real_escape_string(BBcode(smile($text)))."', `time` = '".$realtime."'");
$fid = $mysqli->insert_id;
//если файл загружен на gruzimfile.ru
if($setup['forum_upload_file'] == 0)
{
 $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$api['file']."', 
     `url` = '".$api['url']."', `id_user`='".$user['id']."', `size` = '".$api['size']."', `time`=".$realtime.""); 
}
//иначе грузим на наш сервер
if($setup['forum_upload_file'] == 1)
{    
if ((move_uploaded_file($_FILES["file"]["tmp_name"], "../files/forum/".$ftp)) == true) {
  $mysqli->query("INSERT INTO `post_file` SET `id_forum` = '".$tema['id_forum']."', `id_tema` = '".$tema['id']."', `id_post`='".$fid."', `file` = '".$ftp."',
                `id_user`='".$user['id']."', `size` = '".size($fsizefile)."', `time`=".$realtime."");   
}    
}     
//поднимаем тему выше
$mysqli->query("UPDATE `tema` SET `time` = '".$realtime."' WHERE `id` = '".$tema['id']."'");
$mysqli->query("OPTIMIZE TABLE `tema`");
$mysqli->query("OPTIMIZE TABLE `post`");
$mysqli->query("OPTIMIZE TABLE `post_file`");
$count = $mysqli->query("SELECT * FROM `post` WHERE `id_tema`=".$tema['id']."")->num_rows;
$starts = max(0, (int)$count - (((int)$count % (int)$message) == 0 ? $message : ((int)$count % (int)$message)));
//производим рассылку по подписавшимся на тему
//кол-во подписчиков
$count_subscribe = $mysqli->query("SELECT * FROM `tema_send` WHERE `id_tema`='".$tema['id']."'")->num_rows;
if($count_subscribe > 0 && !$user['id'])
{
// инициализируем класс
$mailer = new phpmailer();
// Устанавливаем тему письма
$mailer->Subject = 'Уведомление об ответе в подписанной теме';
//задаем e-mail админа
$mailer->From = $setup['emailadmin'];
$mailer->ContentType = 'text/html';
$reqs = $mysqli->query("SELECT `tema_send`.*, (SELECT `login` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `login`,
                        (SELECT `fio` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `fio`,
                        (SELECT `email` FROM `users` WHERE `users`.`id`=`tema_send`.`id_user`) AS `email` FROM `tema_send`");
while ($rows = $reqs->fetch_array())
{
// Задаем тело письма
$mailer->Body = 'Здравствуйте, '.$rows['login'].' ('.$rows['fio'].')<br/><br/>
    '.$user['login'].' ответил в теме <a href="'.$home.'/forum/tema/'.$tema['id'].'">'.$tema['name'].'</a>, на которую Вы подписаны.<br/><br/><br/>С уважением, администрация сайта <a href="'.$home.'">'.$home.'</a>';    
$mailer->AddAddress($rows['email'], '');
}
$mailer->Send();
}
//лента
    lenta ('forum', 'ответил в теме <a href="'.$home.'/forum/tema/'.$tema['id'].',start='.$starts.'#post-'.$fid.'">'.$tema['name'].'</a>');
    //очищаем кеш шаблона
if($setup['cache_smarty'] == 1)
{    
$smarty->clearCache('index.tpl');    
$smarty->clearCache('forum/index.tpl');
$smarty->clearCache('wap/forum/index.tpl');
$smarty->clearCache('forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('wap/forum/forum.tpl', $tema['id_forum']);
$smarty->clearCache('forum/tema.tpl', $start.'_'.$id);
$smarty->clearCache('wap/forum/tema.tpl', $start.'_'.$id);
$smarty->clearCache('forum/files.tpl', $start.'_'.$id);
$smarty->clearCache('wap/forum/files.tpl', $start.'_'.$id);
} 
header('location: '.$home.'/forum/tema/'.$id.',start='.$starts.'#post-'.$fid);			
}
}
//предпросмотр
if($_POST['preview'])
{
$textpreview = htmlspecialchars(trim(BBcode(smile($_POST['text']))));    
$smarty->assign('textpreview',$textpreview);    
}
}


$count = $mysqli->query("SELECT * FROM `post` WHERE `id_tema`='".$tema['id']."'")->num_rows;	
$req = $mysqli->query("SELECT op. * , (SELECT `login` FROM `users` WHERE `users`.`id` = op.`id_user` ) AS `login` , 
(SELECT `avatar` FROM `users` WHERE `users`.`id` = op.`id_user`) AS `avatar`, 
(SELECT `login` FROM `users` WHERE `users`.`id` = op.`id_user_edit`) AS `login_edit`,
(SELECT COUNT(*) FROM `post` chp WHERE chp.`id_user` = (SELECT `id` FROM `users` WHERE `users`.`id` = op.`id_user`)) AS `count_post`,
(SELECT COUNT(*) FROM `tema` chp WHERE chp.`id_user` = (SELECT `id` FROM `users` WHERE `users`.`id` = op.`id_user`)) AS `count_tema`,
(SELECT `file` FROM `post_file` WHERE `post_file`.`id_post` = op.`id`) AS `file`,
(SELECT `size` FROM `post_file` WHERE `post_file`.`id_post` = op.`id`) AS `size`,
(SELECT `url` FROM `post_file` WHERE `post_file`.`id_post` = op.`id`) AS `url`,
(SELECT `id` FROM `post_file` WHERE `post_file`.`id_post` = op.`id`) AS `id_file`,
(SELECT `id` FROM `post_vote` WHERE `post_vote`.`id_post` = op.`id`) AS `votes`,
(SELECT `count` FROM `post_file` WHERE `post_file`.`id_post` = op.`id`) AS `count` FROM `post` op
WHERE op.`id_tema` = '".$tema['id']."' ORDER BY op.`id` ASC  LIMIT ".$start.", ".$message);
while ($row = $req->fetch_array())
$arrayrow[] = $row;

//вычисляем номер страницы
$starts = max(0, (int)$count - (((int)$count % (int)$message) == 0 ? $message : ((int)$count % (int)$message)));
//последние темы
$req_tema_pop = $mysqli->query("SELECT * FROM `tema` ORDER BY `time` DESC LIMIT 15");
while ($row_tema_pop = $req_tema_pop->fetch_array())
$arrayrow_tema[] = $row_tema_pop;

//проверка на подписку
$subscribe = $mysqli->query("SELECT * FROM `tema_send` WHERE `id_tema`='".$tema['id']."' AND `id_user`='".$user['id']."'")->fetch_array();

$smarty->assign('subscribe',$subscribe);
$smarty->assign('arrayrow_tema',$arrayrow_tema);
$smarty->assign('count',$count);
$smarty->assign('arrayrow',$arrayrow); 
$smarty->assign('arrayrow_cat',$arrayrow_cat);
$smarty->assign('tema',$tema);
$smarty->assign('error',$error);
$smarty->assign('replys',$replys);
$smarty->assign('cits',$cits);
$smarty->assign('starts',$starts);
$smarty->assign('pagenav',pagenav('/forum/tema/'.$tema['id'].',', $start, $count, $message));

//веб и вап-версия																		
if($setup['style'] == 1)															
{																																			
if ($_SESSION['style'] == 'wap')										
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/wap/forum/tema.tpl', $start.'_'.$id);				
else																				
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/forum/tema.tpl', $start.'_'.$id);					
}																					
//только веб-версия																	
if($setup['style'] == 2)															
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/forum/tema.tpl', $start.'_'.$id);					
//только вап-версия																	
if($setup['style'] == 3)															
$smarty->display(SMARTY_TEMPLATE_LOAD.'/templates/wap/forum/tema.tpl', $start.'_'.$id);			
require_once '../system/inc/foot.php';  
?>