<?
include_once '../sys/inc/start.php';
include_once '../sys/inc/compress.php';
include_once '../sys/inc/sess.php';
include_once '../sys/inc/home.php';
include_once '../sys/inc/settings.php';
include_once '../sys/inc/db_connect.php';
include_once '../sys/inc/ipua.php';
include_once '../sys/inc/fnc.php';
include_once '../sys/inc/user.php';
$ID = intval($_GET['id']);
if (isset($_GET['id']) && $_GET['id']!=NULL && mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news` WHERE `id` = '".intval($_GET['id'])."'"),0)!=0){	
$news = mysql_fetch_array(mysql_query("SELECT * FROM `comm_news` WHERE `id` = '$ID'"));
$comm = get_comm($news['id_comm']);
$author = get_user($news['id_user']);
$set['title']='Новости сообщества '.text($comm['name']).' - '.text($news['title']).''; // заголовок страницы
include_once '../sys/inc/thead.php';
title();
err();
aut();
//======================Начало приватности сообщества===============================//
	if(isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_blacklist` WHERE `id_user` = '$user[id]' AND `id_comm` = '$comm[id]' && (`time_ban` > '$time' OR `navsegda` = '1')"),0)!=0){
	echo'<div class="mess">Вы были забанены ';
	$banned = mysql_fetch_array(mysql_query("SELECT * FROM `comm_blacklist` WHERE `id_user` = '$user[id]' AND `id_comm` = '$comm[id]'"));
	$bancon = mysql_fetch_array(mysql_query("SELECT * FROM `comm_user` WHERE `id_user` = '$banned[id_ban]' AND `id_comm` = '$comm[id]'"));
	if($bancon['level']==1){
		echo 'модератором ';
	}elseif($bancon['level']==2){
		echo 'администратором ';
	}elseif($bancon['level']==3){
		echo 'создателем ';
	}
	echo group($bancon['id_user']);
	echo user::nick($bancon['id_user'],1,1,1);
	if($banned['navsegda']==1){
		echo' навсегда!';
	}else{
		$timefe = $banned['time_ban']-$banned['time'];
		echo ' на ';
		if($timefe>3600){
			$timef = $timefe/3600;
			$timefe = floor($timef);
			
			$timem = $timef-$timefe;
			if($timem==0){
			echo''.$timefe.' часов!';
			}else{
				$timem = round($timem*60);
				echo''.$timefe.' часов '.$timem.' минут!';
			}
		}elseif($timefe<3600){
			$timef = $timefe/60;
			$timefe = round($timef);
			echo''.$timefe.' минут!';
		}
		echo ' <small>';
		echo vremja($banned['time']);
		echo '</small>';
	}
		echo "</div><div class='foot'><img src='/style/icons/str2.gif' alt=''/> <a href='/comm/cat.php?id=$comm[id_category]'>Назад в категорию</a></div>"; 
		include_once '../sys/inc/tfoot.php';
		exit;
	}
	//===========================================//
	if($comm['close']==1 && mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_user` WHERE `id_comm` = '".intval($comm['id'])."' AND `id_user` = '$user[id]'"),0)==0){
		echo'<div class="mess">Сообщество закрыто для чтения!</div>';
		echo "<div class='foot'><img src='/style/icons/str2.gif' alt=''/> <a href='/comm/$comm[id]/'>В сообщество</a></div>";
		include_once '../sys/inc/tfoot.php';
		exit;
	}
	//================Конец приватности сообщества=====================//
$admin = mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_user` WHERE `id_user` = '".intval($user['id'])."' AND `id_comm` = '$comm[id]' AND `level` > '1'"),0);
if (isset($user) && $admin!=0 && isset($_GET['act']) && $_GET['act']=='edit')
{	
	if (isset($_POST['name']) && isset($_POST['save']) && isset($_POST['news']))
	{
		
		$name = my_esc($_POST['name']);
		if (strlen2($name)>25){ $err[] = "Название содержит более 25 символов"; }
		if (strlen2($name)<3){ $err[] = "Название содержит менее 3 символов"; }
		$mat = antimat($name);
		if ($mat)$err[] = "В названии новости обнаружен мат: $mat";
		$news2 = my_esc($_POST['news']);
		if (strlen2($news2)>1024){ $err[] = "Текст новости содержит более 1024 символов"; }
		if (strlen2($news2)<3){ $err[] = "Текст новости содержит менее 3 символов"; }
		$mat = antimat($news2);
		if ($mat)$err[] = "В тексте новости обнаружен мат: $mat";
		err();
		if (!isset($err)){
		mysql_query("UPDATE `comm_news` SET `title` = '$name', `msg` = '$news2' WHERE `id` = '$ID' AND `id_comm` = '$comm[id]'");
		$_SESSION['message'] = 'Новость '.$name.' успешно отредактирована';
		header("Location: ?");
		exit;
	}
		
	}
	echo "<form method=\"post\" name='create_comm' action=\"?act=edit\">";
	echo "Название новости:<br />\n";
echo "<input name=\"name\" type=\"text\" maxlength='32' value='".text($news['title'])."' /><br />\n";
	echo "Текст новости:$tPanel<textarea name=\"news\">".text($news['msg'])."</textarea><br />\n";
	echo "<input name=\"save\" value=\"Сохранить\" type=\"submit\" /><br />\n";
	echo "</form>\n";
	echo "<div class='foot'><img src='/style/icons/str2.gif' alt=''/> <a href='?'>Назад</a></div>";
	include_once '../sys/inc/tfoot.php';
	exit;
}
if (isset($user) && $admin!=0 && isset($_GET['act']) && $_GET['act']=='delete')
{
	if (isset($_POST['delete']))
	{
		mysql_query("DELETE FROM `comm_news` WHERE `id` = '$ID' AND `id_comm` = '$comm[id]'");
		$_SESSION['message'] = 'Новость успешно удалена';
		header("Location: /comm/news/$comm[id]/");
		exit;
	}
	echo "<form method=\"post\" name='cat' action=\"?act=delete\" class=\"mess\">";
	echo "Вы действительно хотите удалить новость ".text($news['title'])."?<br />\n";
	echo "<input name=\"delete\" value=\"Удалить\" type=\"submit\" /><br />\n";
	echo "</form>\n";
	echo "<div class='foot'><img src='/style/icons/str2.gif' alt=''/> <a href='?'>Назад</a></div>";
	include_once '../sys/inc/tfoot.php';
	exit;
}
if (isset($user) && isset($_GET['like']) && ($_GET['like'] == 1 || $_GET['like'] == 0)
    && mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_like_object` WHERE `id_object` = '$news[id]' AND `type` = 'news' AND `id_user` = '$user[id]'"),0) == 0)
{
	mysql_query("INSERT INTO `comm_like_object` (`id_user`, `id_object`, `type`, `like`) VALUES ('$user[id]', '$news[id]', 'news', '" . abs(intval($_GET['like'])) . "')");
	
	// Начисление баллов за активность
	$active_ank = get_user($author['id']);
	include_once H.'sys/add/user.active.php';
	header("Location: /comm/readnews/$ID/");
	exit;
}
echo '<div class="nav1" id="news_title">';
echo '<img src="/style/icons/news.png" alt="*" /> ' . text($news['title']);
echo '</div>';

// Текст новости
echo '<div class="nav2" id="news_content">';
echo output_text($news['msg']);
echo "</div>";

// Мне нравится и автор
echo '<div class="nav2" id="like">';
if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_like_object` WHERE `id_object` = '$news[id]' AND `type` = 'news' AND `id_user` = '$user[id]'"),0)==0)
{
	echo '[<img src="/style/icons/like.gif" alt="*"> <a href="?like=1">Мне нравится</a>] ';
	echo '[<a href="?like=0"><img src="/style/icons/dlike.gif" alt="*"></a>]';
}
else
{
	echo '[<img src="/style/icons/like.gif" alt="*"> ' . mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_like_object` WHERE `id_object` = '$news[id]' AND `type` = 'news' AND `like` = '1'"),0) . '] ';
	echo '[<img src="/style/icons/dlike.gif" alt="*"> ' . mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_like_object` WHERE `id_object` = '$news[id]' AND `type` = 'news' AND `like` = '0'"),0) . '] ';
}

echo '<br />';

// Автор 
echo 'Опубликовал' . ($author['pol'] == 0 ? 'а' : null) . ': ' 
. group($author['id'])
. user::nick($author['id'])
. medal($author['id']) 
. online($author['id']);
	 
echo '</div>';

// Кнопки соц сетей
echo '<div class="nav2" id="news_share">';
echo 'Поделится:<script type="text/javascript" src="//yandex.st/share/share.js" charset="utf-8"></script>
<span class="yashare-auto-init" data-yashareL10n="ru" data-yashareType="none" data-yashareQuickServices="vkontakte,twitter,odnoklassniki,moimir"></span>';
echo '</div>';
if (isset($user) && $admin!=0)
{
	echo '<div class="nav1" id="news_edit">';
	echo '[<img src="/style/icons/edit.gif" alt="*"> <a href="?act=edit">ред</a>] ';
	echo '[<img src="/style/icons/delete.gif" alt="*"> <a href="?act=delete">удл</a>] ';
	echo '</div>';
}

if (isset($user) && isset($_GET['delete']) && (user_access('comm_edit') || $admin != 0 || mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news_komm` WHERE `id` = '".intval($_GET['delete'])."' AND `id_user` = '$user[id]'"),0) != 0)){
	mysql_query("DELETE FROM `comm_news_komm` WHERE `id` = '".intval($_GET['delete'])."' AND `id_user` = '$user[id]'");
	$_SESSION['message'] = 'Коментарий успешно удален';
	header("Location: ?");
	exit;
}
$listr = mysql_fetch_assoc(mysql_query("SELECT * FROM `comm_news` WHERE `id` < '$ID' AND `id_comm` = '$comm[id]'ORDER BY `id` DESC LIMIT 1"));
$list = mysql_fetch_assoc(mysql_query("SELECT * FROM `comm_news` WHERE `id` > '$ID' AND `id_comm` = '$comm[id]'ORDER BY `id`  ASC LIMIT 1"));
echo '<div class="c2" style="text-align: center;">';
echo '<span class="page">' . ($list['id'] ? '<a href="/comm/readnews/' . $list['id'].'/">&laquo; Пред.</a> ':'&laquo; Пред. ') . '</span>';

$k_1 = mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news` WHERE `id` > '$ID' AND `id_comm` = '$comm[id]'"),0)+1;
$k_2 = mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news` WHERE `id_comm` = '$comm[id]'"),0);
echo ' (' . $k_1 . ' из ' . $k_2 . ') ';

echo '<span class="page">' . ($listr['id'] ? '<a href="/comm/readnews/' . $listr['id'] . '/">След. &raquo;</a>' : ' След. &raquo;') . '</span>';
echo '</div>';

echo '<div class="foot" id="news_komm">';
echo 'Комментарии:';
echo '</div>';

// Колличество комментариев
$k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news_komm` WHERE `id_news` = '".intval($ID)."' "),0);

$k_page = k_page($k_post,$set['p_str']);
$page = page($k_page);
$start = $set['p_str'] * $page - $set['p_str'];

// Выборка постов
$q = mysql_query("SELECT * FROM `comm_news_komm` WHERE `id_news` = '" . intval($ID) . "' ORDER BY `id` $sort LIMIT $start, $set[p_str]");

echo '<table class="post">';

if ($k_post == 0)
{
	echo '<div class="mess" id="no_object">';
	echo 'Нет сообщений';
	echo '</div>';
}
else
{
	/*------------сортировка по времени--------------*/
	if (isset($user))
	{
		echo '<div id="comments" class="menus">';
		echo '<div class="webmenu">';
		echo '<a href="?page=' . $page . '&sort=1" class="' . ($user['sort'] == 1 ? 'activ' : null) . '">Внизу</a>';
		echo '</div>'; 
		
		echo '<div class="webmenu">';
		echo '<a href="?page=' . $page . '&sort=0" class="' . ($user['sort'] == 0 ? 'activ' : null) . '">Вверху</a>';
		echo '</div>'; 
		echo '</div>';
	}
	/*---------------alex-borisi---------------------*/
}


while ($post = mysql_fetch_assoc($q))
{
	$ank = mysql_fetch_assoc(mysql_query("SELECT * FROM `user` WHERE `id` = $post[id_user] LIMIT 1"));

	// Лесенка
	echo '<div class="' . ($num % 2 ? "nav1" : "nav2") . '">';
	$num++;

	echo group($ank['id']) . user::nick($ank['id']);

	if (isset($user) && $user['id'] != $ank['id'])
	echo ' <a href="?page=' . $page . '&amp;response=' . $ank['id'] . '">[*]</a> ';

	echo medal($ank['id']) . online($ank['id']) . ' (' . vremja($post['time']) . ')<br />';

	echo output_text($post['msg']) . '<br />';

	if (isset($user)) 
	{
		echo '<div class="right">';

		if (isset($user) && (user_access('comm_edit') || $admin != 0 || $user['id'] == $ank['id']))
		echo '<a href="?delete=' . $post['id'] . '"><img src="/style/icons/delete.gif" alt="*"></a>';

		echo '</div>';
	}

	echo '</div>';
}

echo '</table>';

// Вывод страниц
if ($k_page>1)str('?', $k_page,$page); 

// Форма для комментариев
if (isset($user))
{	
	if(isset($_POST['send']) && isset($_POST['msg']) && isset($_GET['mess']))
	{
	$msg = my_esc($_POST['msg']);
	$mat = antimat($msg);
	if ($mat)$err[] = 'В тексте сообщения обнаружен мат: '.$mat;

	if (strlen2($msg)>1024){$err = 'Сообщение слишком длинное';}
	elseif (strlen2($msg)<2){$err = 'Короткое сообщение';}
	elseif (mysql_result(mysql_query("SELECT COUNT(*) FROM `comm_news_komm` WHERE `id_news` = '" . intval($_GET['id']) . "' AND `id_user` = '$user[id]' AND `msg` = '" . my_esc($msg) . "' LIMIT 1"),0) != 0){$err = 'Ваше сообщение повторяет предыдущее';}
	err();
	if(!isset($err))
	{
		mysql_query("INSERT INTO `comm_news_komm` (`id_user`, `time`, `msg`, `id_news`) values('$user[id]', '$time', '" . my_esc($msg) . "', '" . intval($_GET['id']) . "')");
		// Начисление баллов за активность
		$active_ank = get_user($news['id_user']);
		include_once H.'sys/add/user.active.php';

		
		
		$_SESSION['message'] = 'Ваш комментарий успешно принят';
		header('Location: ?id=' . intval($_GET['id']) . '&page=' . intval($_GET['page']));
		exit;
	}

	}
	echo '<form method="post" name="message" action="?mess=' . intval($_GET['id']) . '&amp;page=' . $page . REPLY . '">';
	if (is_file(H.'style/themes/' . $set['set_them'] . '/altername_post_form.php'))
	include_once H.'style/themes/' . $set['set_them'] . '/altername_post_form.php';
	else
	echo $tPanel . '<textarea name="msg">' . $insert . '</textarea><br />';
	echo '<input name="send" value="Отправить" type="submit" />';
	echo '</form>';
}
echo "<div class='foot'><img src='/style/icons/str2.gif' alt=''/> <a href='/comm/$comm[id]/'>В сообщество</a> | <a href='/comm/news/$comm[id]/'>Новости</a></div>";
}else{
	header("Location: /");
}
include_once '../sys/inc/tfoot.php';
?>