<?
$ID = (int) $_GET['id'];
$room = mysql_fetch_assoc(mysql_query("SELECT * FROM `chat_rooms` WHERE `id` = '" . $ID . "' LIMIT 1"));
$_SESSION['sid'] = mt_rand(000, 999);

if (!isset($room['id'])) {
	$_SESSION['message'] = __('Такой комнаты не существует');
	header('Location: ?sid=' . $_SESSION['sid']);
	exit;
}

// Обновление информации
if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_who` WHERE `id_user` = '$user[id]'"),0) == 0) {
	mysql_query("INSERT INTO `chat_who` (`id_user`, `time`,  `room`) values('$user[id]', '$time', '$room[id]')");
} elseif (isset($user)) {
	mysql_query("UPDATE `chat_who` SET `room` = '$room[id]', `time` = '$time' WHERE `id_user` = '$user[id]' LIMIT 1");
}

if ($set['time_chat'] != 0 && !isset($ank_reply['id'])) {
	header('Refresh: ' . $set['time_chat'] . '; url=?func=room&id=' . $ID . '&sid=' . $_SESSION['sid']);
}

if (isset($_POST['msg']) && isset($user)) {
	$msg = $_POST['msg'];
	$mat = antimat($msg);
	
	if ($mat) {
		$err[] = __('В тексте сообщения обнаружен мат: ') . $mat;
	}

	if (strlen2($msg) > 512){$err[] = __('Сообщение слишком длинное');}
	elseif (strlen2($msg) < 2){$err[] = __('Короткое сообщение');}
	elseif (mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_post` WHERE `id_user` = '$user[id]' AND `msg` = '" . mysql_escape_string($msg) . "' AND `time` > '" . ($time-300) . "' LIMIT 1"),0) != 0){ $err = __('Ваше сообщение повторяет предыдущее'); }
	elseif(!isset($err))
	{
		$priv = (isset($_POST['privat']) ? (int) $_POST['privat'] : 0);

		mysql_query("INSERT INTO `chat_post` (`id_user`, `time`, `msg`, `room`, `privat`) values('$user[id]', '$time', '" . my_esc($msg) . "', '$room[id]', '$priv')");
		
		// Начисление баллов за активность
		include_once H.'sys/add/user.active.php';
		
		$_SESSION['message'] = __('Сообщение успешно добавлено');
		header('Location: ?func=room&id=' . $ID . '&sid=' . $_SESSION['sid']);
		exit;
	}
}

// Загрузка остальных плагинов чата из папки "plugins/"
$opdirbase = opendir('plugins');

while ($filebase = readdir($opdirbase)) {
	if (preg_match('#\.php$#i', $filebase)) {
		require ('plugins/' . $filebase);
	}
}

$set['title'] = text($room['name']) . ' - ' . mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_who` WHERE `room` = '$room[id]' AND `time` > '" . (time() - 120) . "'"),0) . ' чел.';
include_once H.'sys/inc/thead.php';
title();
aut(); 
err();

if (isset($user)) {
?>
	<form class="mess" method="post" name="message" action="?func=room&id=<?= $ID?>&sid=<?= $_SESSION['sid']?>">
	<?
	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 />';
	}
	
	// Ответ пользователю
	if (isset($ank_reply['id'])){
		echo 'Ответ для ' . $ank_reply['nick'] . '<br /><label><input type="checkbox" name="privat" value="' . $ank_reply['id'] . '" /> Приватно</label><br />';
	}
	?>
	<input value="<?= __('Отправить')?>" type="submit" /> <a href="?func=room&id=<?= $ID?>"><?= __('Обновить')?></a><br />
	</form>
<?
}

$k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `chat_post` WHERE `room` = '$room[id]' AND (`privat` = '0'" . (isset($user) ? " OR `privat` = '$user[id]'" : null) . (isset($user) ? " OR `id_user` = '$user[id]'" : null) . ")"), 0);
$k_page = k_page($k_post,$set['p_str']);
$page = page($k_page);
$start = ($set['p_str'] * $page) - $set['p_str'];

?><table class="post"><?

if ($k_post == 0)
{
	?>
	<div class="mess">
	<?= __('Здесь еще никто ничего не писал =(')?>
	</div>
	<?
}

$q = mysql_query("SELECT * FROM `chat_post` WHERE `room` = '$room[id]' AND (`privat` = '0'" . (isset($user) ? " OR `privat` = '$user[id]'" : null) . (isset($user) ? " OR `id_user` = '$user[id]'" : null) . ") ORDER BY id DESC LIMIT $start, $set[p_str]");

while ($post = mysql_fetch_assoc($q)) {
	$num++;
	
	?><div class="<?= ($num % 2 ? 'nav2' : 'nav1')?>"><?
	
	if ($post['umnik_st'] == 0 && $post['shutnik'] == 0) {
		echo user::avatar($post['id_user'], 2) . user::nick($post['id_user'], 1, 1, 0) . 
		(isset($user) && $user['id'] != $post['id_user'] ? ' <a href="?func=room&amp;id=' . $ID . '&amp;response=' . $post['id_user'] . '">[отв]</a>' : '');
	} elseif ($post['umnik_st'] != 0) {
		?><img src="/style/themes/<?= $set['set_them']?>/chat/14/shut.png" alt="" /> <span style="color: #1c6a9f;"><?= $set['chat_umnik']?></span> <?
	} elseif ($post['shutnik'] == 1) {
		?><img src="/style/themes/<?= $set['set_them']?>/chat/14/umnik.png" alt="" /> <span style="color: #1c6a9f;"><?= $set['chat_shutnik']?></span> <?
	}
	
	echo (isset($user) && $post['privat'] != 0 ? ' <span class="off">' . __('[прив]') . '</span> ' : ''); 
	echo '<br />' . output_text($post['msg']) . ' <span class="time">' . vremja($post['time']) . '</span><br />';
	
	?></div><?
}
?>
</table>

<?
if ($k_page > 1) {
	str('?func=room&amp;id=' . $ID . '&amp;sid=' . $_SESSION['sid'] . '&amp;', $k_page, $page);
}
?>

<div class="foot">
 <img src="/style/icons/str2.gif" alt="*" /> <a href="?"><?= __('Прихожая')?></a><br />
</div>