Просмотр файла topic.php

Размер файла: 43.18Kb
<?php

	require_once 'sys/inc/core.php';

if(!empty($_GET['viewpost']))
	{
	$viewpost = int($_GET['viewpost']);
	if($viewpost > 0 && $db -> one("SELECT COUNT(*) FROM `posts` WHERE `id` = '$viewpost'"))
		{
		$post_info = $db -> fetch("SELECT `date`, `tid` FROM `posts` WHERE `id` = '$viewpost'");
		$count_before_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `date` < '{$post_info['date']}' AND `tid` = '{$post_info['tid']}'");
		$page = ceil($count_before_posts / ONPAGE_POSTS);
		if(empty($page))$page = 1;

        #d($_SESSION,0);
		if(isset($backup['session_msgs']))$_SESSION['msg'] = $backup['session_msgs'];
		if(isset($backup['session_errors']))$_SESSION['err'] = $backup['session_errors'];
		#d($_SESSION);

		// если это ответ мне, удаляем запись
		if(USER_AUTH && $db -> one("SELECT COUNT(*) FROM `posts_answers` WHERE `user_id` = '".USER_ID."' AND `answer_pid` = '$viewpost'") > 0)
			{
			$db -> sql("DELETE FROM `posts_answers` WHERE `user_id` = '".USER_ID."' AND `answer_pid` = '$viewpost'");
			}
		#d($page);
		locate(PATH.'topic'.$post_info['tid'].'/page'.$page.'/selectpost'.$viewpost.'/#post-'.$viewpost);
		exit;
		}
	}
	
if(ID > 0 && $db -> one("SELECT COUNT(*) FROM `topics` WHERE `id` = '".ID."' AND `level` <= '".USER_LEVEL."'") == 0)locate(PATH.'index.php');

$topic_info = $db -> fetch("SELECT * FROM `topics` WHERE `id` = '".ID."'");

if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` = '{$topic_info['fid']}' AND `level` <= '".USER_LEVEL."'") == 0)locate(PATH.'index.php');

$forum_info = $db -> fetch("SELECT * FROM `forums` WHERE `id` = '{$topic_info['fid']}'");

$template -> forum_id = $forum_info['id'];
$template -> forum_name = $forum_info['name'];

$template -> topic_id = ID;
$template -> topic_name = $topic_info['name'];

$template -> topic_open = (bool)$topic_info['open'];

$last_date = (!empty($topic_info['last_date']) ? $topic_info['last_date'] : $topic_info['date']);

$answers_to_my_posts = array();
		while($answer = $db -> fetch("SELECT `pid`, `answer_pid` FROM `posts_answers` WHERE `tid` = '".ID."' AND `user_id` = '".USER_ID."'"))
	{
	$answers_to_my_posts[$answer['answer_pid']] = $answer['pid'];
	}

show_title($topic_info['name'], $topic_info['name'].' - '.$forum_info['name']);

		switch(MODE)
	{
	default:
	// просмотр постов
	{

	$db -> sql("UPDATE `topics` SET `count_all_views` = `count_all_views` + 1 WHERE `id` = '".ID."'");

	if(USER_AUTH)
		{
		// логи просмотров
		$db -> sql("REPLACE INTO `topics_views` SET `tid` = '".ID."', `user_id` = '".USER_ID."', `date` = '$last_date'");
		$db -> sql("UPDATE `topics` SET `count_views` = `count_views` + 1 WHERE `id` = '".ID."'");

		// есть ли тема в закладках
		$topic_bookmark = ($db -> one("SELECT COUNT(*) FROM `topics_bookmarks` WHERE `tid` = '".ID."' AND `user_id` = '".USER_ID."'")) > 0 ? true : false;
		$template -> topic_bookmark = $topic_bookmark;

		if($topic_bookmark)$db -> sql("REPLACE INTO `topics_bookmarks` SET `tid` = '".ID."', `user_id` = '".USER_ID."', `date` = '$last_date'");
		}



	$selectpost = 0;
	if(isset($_GET['selectpost']))
		{
		$selectpost = int($_GET['selectpost']);
		}

	// если первый пост должен быть
	if(!empty($topic_info['first_post']))
		{
		// если есть пост в бд
		if($db -> one("SELECT COUNT(*) FROM `posts` AS `p`, `posts_text` AS `p_t` WHERE `p`.`id` = '{$topic_info['first_post']}' AND `p`.`id` = `p_t`.`pid`") > 0)
			{
			// если нужно показывать пост
			if(PAGE == 1 || $topic_info['first_post_on_pages'])
				{
				// ояебу запрос
				$first_post = $db -> fetch("SELECT `p`.*, `p_t`.`text`, `u`.`level` AS `user_level`, `u`.`nick` AS `user_nick`, `u`.`date_last_visit` AS `user_visit`, `u`.`punish_to_date` AS `user_punish_to_date`, `u`.`punish_pid` AS `user_punish_pid`, `u`.`punish_ban` AS `user_punish_ban`, `u`.`active` AS `user_active`, (SELECT COUNT(*) FROM `users_punishes` WHERE `user_id` = `p`.`user_id` AND `to_date` > '".TIME."' AND `ban` = '1' ) AS `user_ban`
FROM `posts` AS `p`, `users` AS `u`, `posts_text` AS `p_t`
WHERE `p`.`id` = '{$topic_info['first_post']}' AND `u`.`id` = `p`.`user_id` AND `p_t`.`pid` = `p`.`id`");

#d($first_post);


				$user_nick = show_user($first_post);

				$template_first_post = array('id' => $first_post['id'], 'user' => $user_nick, 'user_id' => $first_post['user_id'], 'date' => xdate($first_post['date']), 'ip' => long2ip($first_post['ip']), 'ua' => $first_post['ua'], 'text' => post($first_post['text']), 'divclass' => ($first_post['id'] == $selectpost ? 'first_select_unit' : 'first_unit'));

				if((USER_LEVEL >= USER_MODERATOR && $first_post['user_level'] < USER_LEVEL) || USER_ID == 1)
					{
					$template_first_post['manage'] = null;
					#if($first_post['user_id'] != USER_ID && ($first_post['user_punish_to_date'] < TIME || ($first_post['user_punish_pid'] != $first_post['id'] && $first_post['user_ban'] != 1)))$template_first_post['manage'] .= '<a href="'.PATH.'post'.$first_post['id'].'/punish/">[бан]</a>';
					if($first_post['user_id'] != USER_ID && ($first_post['user_punish_to_date'] < TIME || ($first_post['user_punish_pid'] != $first_post['id'] && $first_post['user_ban'] != 1)))$template_first_post['manage_punish'] = true;
					#$template_first_post['manage'] .= (USER_ID != $first_post['user_id'] ? '<br />' : null).'<span class="manage">'.long2ip($first_post['ip']).' - '.$first_post['ua'].'</span>';
					$template_first_post['manage_info'] = true;
					$template_first_post['ip'] = long2ip($first_post['ip']);
					$template_first_post['ua'] = $first_post['ua'];
					}

				if(USER_ID != $first_post['user_id'])
					{
					#$template_first_post['answer'] = '<a href="'.PATH.'post'.$first_post['id'].'/answer/">[ответ]</a>';
					$template_first_post['answer'] = true;
					}

				$template -> assign('first_post', $template_first_post);
				}
			}
		else
			{
			// если первый пост не найден
			$db -> sql("DELETE FROM `posts` WHERE `id` = '{$topic_info['first_post']}'");
			$db -> sql("DELETE FROM `posts_text` WHERE `id` = '{$topic_info['first_post']}'");
			$db -> sql("UPDATE `topics` SET `first_post` = 0, first_post_on_pages = '0' WHERE `id` = '".ID."'");
			#$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - 1 WHERE `id` = '{$forum_info['id']}'");
			}
		}

	$count_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `tid` = '".ID."' AND `id` != '{$topic_info['first_post']}'");
	
	// авто координация
	if($topic_info['count_posts'] != $count_posts)
		{
		$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - '{$topic_info['count_posts']}' WHERE `id` = '{$forum_info['id']}'");
		$db -> sql("UPDATE `topics` SET `count_posts` = '$count_posts' WHERE `id` = '".ID."'");
		$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '{$forum_info['id']}'");
		}
	
	if($count_posts > 0)
		{

		check_page($count_posts, PATH.'topic'.ID.'/page{$page}/');

		$template_posts = array();

		$i = START_POSTS;

				// ояебу запрос
				while($post = $db -> fetch("SELECT `p`.*, `p_t`.`text`, `u`.`level` AS `user_level`, `u`.`nick` AS `user_nick`, `u`.`date_last_visit` AS `user_visit`, `u`.`punish_to_date` AS `user_punish_to_date`, `u`.`punish_pid` AS `user_punish_pid`, `u`.`punish_ban` AS `user_punish_ban`, `u`.`active` AS `user_active`,(SELECT COUNT(*) FROM `posts` WHERE `id` = `p`.`answer_to`) AS `is_answer`, (SELECT COUNT(*) FROM `users_punishes` WHERE `user_id` = `p`.`user_id` AND `to_date` > '".TIME."' AND `ban` = '1' ) AS `user_ban`
FROM `posts` AS `p`, `users` AS `u`, `posts_text` AS `p_t`
WHERE `p`.`tid` = '".ID."' AND `p`.`id` != '{$topic_info['first_post']}' AND `p`.`user_id` = `u`.`id` AND `p_t`.`pid` = `p`.`id`
GROUP BY `p`.`id`
ORDER BY `p`.`date` ASC, `p`.`id` ASC
LIMIT ".START_POSTS.",".ONPAGE_POSTS))
			{
			$i ++;

			$user_nick = show_user($post);

			// данные
			$template_post = array('id' => $post['id'], 'user' => $user_nick, 'user_id' => $post['user_id'], 'date' => xdate($post['date']), 'text' => post($post['text']), 'i' => $i, 'divclass' => ($selectpost == $post['id'] ? 'select_unit' : 'unit'));

			$user_level = $post['user_level'];


			// ссылки на управление постом
			if((USER_LEVEL >= USER_MODERATOR) || (USER_ID == $post['user_id'] && (TIME - $post['date']) < $cfg['time_edit_post']))
				{
				#$template_post['manage'] = '<a href="'.PATH.'post'.$post['id'].'/edit/">[изм'.((USER_LEVEL >= USER_MODERATOR) ? null : ' '.($cfg['time_edit_post'] - (TIME - $post['date'])).' сек').']</a>';
				$template_post['manage_edit'] = true;
				if(USER_LEVEL >= USER_MODERATOR)
					{
					#$template_post['info'] = '<span class="manage">'.long2ip($post['ip']).' - '.$post['ua'].'</span>';
					$template_post['manage_info'] = true;
					$template_post['ip'] = long2ip($post['ip']);
					$template_post['ua'] = $post['ua'];

					if(($user_level < USER_LEVEL || USER_ID == 1) && $post['user_id'] != USER_ID && ($post['user_punish_to_date'] < TIME || ($post['user_punish_pid'] != $post['id'] && $post['user_ban'] != 1)))
						{
						#$template_post['manage'] .= '<a href="'.PATH.'post'.$post['id'].'/punish/">[бан]</a>';
						$template_post['manage_punish'] = true;
						}

						if(USER_LEVEL == USER_MODERATOR)
							{
							#$template_post['manage'] .= ' <a href="'.PATH.'post'.$post['id'].'/del/">[удал]</a> <a href="'.PATH.'post'.$post['id'].'/trans/">[перем.]</a>';
							$template_post['manage_del'] = true;
							}

					}
				#$template_post['manage'] .= '</span>';
				}

			// уведомление об изменениях
			if(USER_AUTH && $post['edit_count'] > 0)
				{
				#$template_post['edited'] = '<span class="sml">Измен. '.$post['edit_count'].' '.postfix($post['edit_count'], 'раз', 'раз', 'раза').'; '.get_user($post['edit_user_id']).' : '.xdate($post['edit_date']).'</span><br />';
				$template_post['edited'] = true;
				$template_post['edited_count'] = $post['edit_count'].' '.postfix($post['edit_count'], 'раз', 'раз', 'раза');
				$template_post['edited_user'] = get_user($post['edit_user_id']);
				$template_post['edited_date'] = xdate($post['edit_date']);
				}


			// ссылка на ответ
			if(USER_ID != $post['user_id'])
				{
				#$template_post['answer'] = ' <a href="'.PATH.'post'.$post['id'].'/answer/">ответ</a>';
				$template_post['answer'] = true;
				}

			// система "Reply To"
			if($cfg['mod_reply_to'] == 1 && !empty($post['answer_to']))
				{
				if($post['is_answer'])
					{

					// если мы просматриваем ответ на свое сообщение, удаляем его из логов
					if(isset($answers_to_my_posts[$post['id']]))
						{
						$db -> sql("DELETE FROM `posts_answers` WHERE `pid` = '{$post['answer_to']}' AND `answer_pid` = '{$post['id']}'");
						}

					$answer_post_number = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `tid` = '".ID."' AND `date` < (SELECT `date` FROM `posts` WHERE `id` = '{$post['answer_to']}')");

					#$template_post['answer_to'] = '<span class="sml"> / Reply To : <a href="'.PATH.'post'.$post['answer_to'].'/">#'.$answer_post_number.'</a></span>';
					$template_post['answer_to'] = $post['answer_to'];
					$template_post['answer_to_post'] = $answer_post_number;
					}
				else
					{
					$db -> sql("UPDATE `posts` SET `answer_to` = 0 WHERE `id` = '{$post['id']}'");
					}
				}

			// данные в шаблон
			$template_posts[] = $template_post;
			}

		$template -> assign('posts', $template_posts);

		pagebar($str, PAGE, PATH.'topic'.ID.'/page{$page}/');

		}

	$template -> count_posts = $count_posts;

    
	// ссылки
	if(USER_AUTH)
		{
		#$manage_topic = '&raquo; <a href="'.PATH.'topic'.ID.'/info/">Инфомация</a><br />';
		$topic = array();
		$manage_topic['info'] = true;
		if(USER_LEVEL >= USER_MODERATOR || ($topic_info['user_id'] == USER_ID && $topic_info['not_edit_author'] == 0))
			{
			#$manage_topic .= '&raquo; <a href="'.PATH.'topic'.ID.'/edit/">Изменить тему</a><br />';
			$manage_topic['edit'] = true;
			if(USER_LEVEL >= USER_MODERATOR)
				{
				#$manage_topic .= '&raquo; <a href="'.PATH.'topic'.ID.'/trans/">Перенести тему</a><br />';
				$manage_topic['trans'] = true;

				$count_topic_logs = $db -> one("SELECT COUNT(*) FROM `topics_logs` WHERE `tid` = '".ID."'");
				if($count_topic_logs > 0)
					{
					#$manage_topic .= '&raquo; <a href="'.PATH.'topic'.ID.'/logs/">Логи темы</a>('.$count_topic_logs.')<br />';
					$manage_topic['logs'] = true;
					$manage_topic['count_logs'] = $count_topic_logs;
					}

				#$manage_topic .= '&raquo; <a href="'.PATH.'topic'.ID.'/del/">Удалить тему</a><br />';
				$manage_topic['del'] = true;
				}
			$template -> manage_topic = $manage_topic;
			}
		}
	

	// если забанен
	if($db -> one("SELECT COUNT(*) FROM `users_punishes` WHERE `user_id` = '".USER_ID."' AND `to_date` > '".TIME."' AND `ban` = '1'") > 0)
		{
		$template -> ban = true;
		}


    $template -> fast_post = (bool)$userdata['set_fast_post'];
	$template -> topic_level = $topic_info['level'];

	if(!USER_AUTH || $topic_info['level_posts'] > USER_LEVEL || ((TIME - $userdata['date_reg']) < $cfg['time_silence']))
		{
		$template ->cannot_post = true;
        $template -> fast_post = false;
		}


	$template -> topic_level_posts = $topic_info['level_posts'];

	$template -> block = 'index';

	}
	break;
	############################################################################
	case 'newpost':
	// написание сообщения
	{

	only_reg();

	// тема закрыта
	if(!$topic_info['open'] && USER_LEVEL < USER_MODERATOR)err('Тема закрыта', PATH.'topic'.ID.'/');

	// уроверь доступа мал
	if($topic_info['level_posts'] > USER_LEVEL)err('Вы не можете писать сообщения', PATH.'topic'.ID.'/');

	// еще не прошло время молчалки
	if((TIME - $userdata['date_reg']) < $cfg['time_silence'])err('Вы пока не можете общаться на форуме.', PATH.'topic'.ID.'/');

	// если забанен
	if($db -> one("SELECT COUNT(*) FROM `users_punishes` WHERE `user_id` = '".USER_ID."' AND `to_date` > '".TIME."' AND `ban` = '1'") > 0)err('Вы забанены', PATH.'topic'.ID.'/');

	if($cfg['time_antispam_posts'] > 0 && USER_LEVEL < USER_ADMIN)
		{
		if(($last_post = $db -> one("SELECT MAX(`date`) FROM `posts` WHERE `user_id` = '".USER_ID."'")) > 0)
			{
			if((TIME - $last_post) < $cfg['time_antispam_posts'])
				{
				err('Нельзя так часто писать сообщения', PATH.'topic'.ID.'/');
				}
			}
		}

	if(isset($_POST['create']))
		{
		check_fields(PATH.'topic'.ID.'/newpost/', array(array('post', 'not null', 'minlen' => 2, 'maxlen' => $cfg['maxlen_post'])));

		$post = str($_POST['post']);

		check_repeat_post(PATH.'topic'.ID.'/newpost/', $post);

		if($db -> sql("INSERT INTO `posts` SET `tid` = '".ID."', `fid` = '{$forum_info['id']}', `user_id` = '".USER_ID."', `date` = '".TIME."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."'"))
			{
			$post_id = $db -> last_id();
			if($db -> sql("INSERT INTO `posts_text` SET `pid` = '$post_id', `text` = '$post'"))
				{
				$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` + '1' WHERE `id` = '{$forum_info['id']}'");
				$db -> sql("UPDATE `topics` SET `count_posts` = `count_posts` + '1', `last_date` = '".TIME."', `last_user_id` = '".USER_ID."' WHERE `id` = '".ID."'");

				// перенос темы
				if(USER_LEVEL >= USER_MODERATOR && $db -> one("SELECT COUNT(*) FROM `forums` WHERE `name` = 'Корзина' OR `description` = 'recycled bin'") > 0 && postval('recycled', 1))
					{

					$count_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `id` = '".ID."'");
					if(!empty($topic_info['first_post']))$count_posts --;

					if(!$db -> sql("UPDATE `topics` SET `open` = '0' WHERE `id` = '".ID."'"))
						{
						err('Ошибка при закрытии темы', PATH.'topic'.ID.'/');
						}

					$into_forum = $db -> fetch("SELECT `id`, `name` FROM `forums` WHERE `name` = 'Корзина' OR `description` = 'recycled bin'");

					// переносим посты
					if(!$db -> sql("UPDATE `posts` SET `fid` = '{$into_forum['id']}' WHERE `tid` = '".ID."'"))
						{
						err('Ошибка при перемещении сообщений', PATH.'topic'.ID.'/');
						}

					// переносим тему
					if(!$db -> sql("UPDATE `topics` SET `fid` = '{$into_forum['id']}' WHERE `id` = '".ID."'"))
						{
						err('Ошибка при перемещении темы', PATH.'topic'.ID.'/');
						}

					$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` - 1, `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");
					$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` + 1, `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '{$into_forum['id']}'");

					$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = 'Закрытие темы и перенос в форум {$into_forum['name']}'");

					}

				#msg('Сообщение добавлено', PATH.'topic'.ID.'/');
				msg('Сообщение добавлено', PATH.'post'.$post_id.'/');
				}
			else
				{
				$db -> sql("DELETE FROM `posts` WHERE `id` = '$post_id'");
				err('Ошибка', PATH.'topic'.ID.'/newpost/');
				}
			}
		else
			{
			err('Ошибка', PATH.'topic'.ID.'/newpost/');
			}

		}

	// можно ли отправить в корзину
	if(USER_LEVEL >= USER_MODERATOR && $db -> one("SELECT COUNT(*) FROM `forums` WHERE `name` = 'Корзина' OR `description` = 'recycled bin'") > 0 && $topic_info['open'])
		{
		$template -> recycled = true;
		}

	$template -> page_zag = 'Добавление сообщения';

	$template -> block = 'newpost';

	}
	break;
	############################################################################
	case 'list':
	// массовое управление постами
	{

	only_reg(USER_ADMIN);

	if(!postval('list', 1) || !isset($_POST['posts']))locate(PATH.'topic'.ID.'/');

	$action = (isset($_POST['delete']) ? 'delete' : (isset($_POST['trans']) ? 'trans' : false));

	if(!$action)err('Укажите действие', PATH.'topic'.ID.'/');

	$posts = $_POST['posts'];

	if(empty($posts))err('Выберите сообщения', PATH.'topic'.ID.'/');

	$theme_posts = array();
			while($post = $db -> fetch("SELECT `id` FROM `posts` WHERE `tid` = '".ID."'"))
		{
		$theme_posts[] = $post['id'];
		}

	// удаляем неверно выбраные записи
	$count_posts = count($posts);
	$template_posts = array();
			for($i = 0;$i < $count_posts;$i ++)
		{
		if(!in_array($posts[$i], $theme_posts))unset($posts[$i]);
		$template_posts[] = array('id' => $posts[$i]);
		}

	if(empty($posts))err('Выберите сообщения', PATH.'topic'.ID.'/');
	$count_posts = count($posts);

	$template -> page_zag = 'Массовое управление сообщениями';

			switch($action)
		{
		default:

		break;
		########################################################################
		case 'delete':
		$template -> block = 'list_delete';


		if(postval('yes', 1))
			{
			// удаляем тексты постов
			if($db -> sql("DELETE FROM `posts_text` WHERE `pid` IN (".implode(',', $posts).")"))
				{
				// удаляем посты
				if($db -> sql("DELETE FROM `posts` WHERE `id` IN (".implode(',', $posts).")"))
					{
					$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");
					$db -> sql("UPDATE `topics` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '".ID."'");
					msg('Успешно удалено '.$count_posts.' '.postfix($count_posts, 'сообщений', 'сообщение', 'сообщения'), PATH.'topic'.ID.'/');
					}
				else
					{
					err('Ошибка при удалении постов', PATH.'topic'.ID.'/');
					}
				}
			else
				{
				err('Ошибка при удалении текстов постов', PATH.'topic'.ID.'/');
				}

			}
		// добавляем данные
		$template -> assign('posts', $template_posts);
		$template -> count_posts = $count_posts;
		$template -> postfix = postfix($count_posts, 'сообщений', 'сообщение', 'сообщения');

		break;
		########################################################################
		case 'trans':

		if(postval('yes', 1))
			{
			check_fields(PATH.'topic'.ID.'/', array(array('create', 'values' => array('0', '1'))));

			$create = (bool)$_POST['create'];

			// суммарная информация о постах
			$info_posts = $db -> fetch("SELECT MIN(`date`) AS date, MAX(`date`) AS last_date, (SELECT `user_id` FROM `posts` WHERE `id` IN (".implode(',', $posts).") ORDER BY `date` DESC LIMIT 0,1) AS last_user_id  FROM `posts` WHERE `id` IN (".implode(',', $posts).")");

			// создаем новую тему
			if($create)
				{

				check_fields(PATH.'topic'.ID.'/', array(array('into_forum', 'not null'), array('topic_name', 'not null', 'minlen' => 2, 'maxlen' => $cfg['maxlen_post'])));

				$into_forum = int($_POST['into_forum']);

				$topic_name = str($_POST['topic_name']);

				if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` = '$into_forum'") == 0)err('Форум не выбран', PATH.'topic'.ID.'/del/');


				if(!$db -> sql("INSERT INTO `topics` SET `fid` = '$into_forum', `name` = '$topic_name', `user_id` = '".USER_ID."', `date` = '{$info_posts['date']}', `last_user_id` = '{$info_posts['last_user_id']}', `last_date` = '{$info_posts['last_date']}', `count_posts` = '$count_posts', `level` = '0', `level_posts` = '1'"))
					{
					err('Ошибка при создании темы', PATH.'topic'.ID.'/');
					}

				$topic_id = $db -> last_id();
				if(!$db -> sql("UPDATE `posts` SET `tid` = '$topic_id', `fid` = '$into_forum' WHERE `id` IN (".implode(',', $posts).")"))
					{
					err('Ошибка при перемещении сообщений (ID '.$topic_id.')', PATH.'topic'.ID.'/');
					}

				$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` + 1, `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '$into_forum'");
				$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");
				$db -> sql("UPDATE `topics` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '".ID."'");

				msg('Сообщения перемещены<br /><a href="'.PATH.'topic'.$topic_id.'/">Перейти в тему</a>', PATH.'topic'.ID.'/');

				}
			else
				{

				check_fields(PATH.'topic'.ID.'/', array(array('into_topic', 'not null')));

				$into_topic = int($_POST['into_topic']);

				if(ID == $into_topic)msg('Данные не изменены', PATH.'topic'.ID.'/');

				if($db -> one("SELECT COUNT(*) FROM `topics` WHERE `id` = '$into_topic'") == 0)err('Тема не существует', PATH.'topic'.ID.'/');

				$into_topic_info = $db -> fetch("SELECT `name`, `fid`, `last_date`, `last_user_id` FROM `topics` WHERE `id` = '$into_topic'");

				if(!$db -> sql("UPDATE `posts` SET `tid` = '$into_topic', `fid` = '{$into_topic_info['fid']}' WHERE `id` IN (".implode(',', $posts).")"))
					{
					err('Ошибка при перемещении сообщений (ID '.$into_topic.')', PATH.'topic'.ID.'/');
					}

				// информация темы
				$last_date = max($into_topic_info['last_date'], $info_posts['last_date']);
				$last_user_id = ($into_topic_info['last_date'] > $info_posts['last_date']) ? $into_topic_info['last_user_id'] : $info_posts['last_user_id'];
				if(!$db -> sql("UPDATE `topics` SET `last_date` = '$last_date', `last_user_id` = '$last_user_id', `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '$into_topic'"))
					{
					err('Ошибка при изменени темы (ID '.$into_topic.')', PATH.'topic'.ID.'/');
					}


				$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '{$into_topic_info['fid']}'");
				$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");
				$db -> sql("UPDATE `topics` SET `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '".ID."'");
				msg('Сообщения перемещены<br /><a href="'.PATH.'topic'.$into_topic.'/">Перейти в тему</a>', PATH.'topic'.ID.'/');

				}

			}

		// выбираем форумы для переноса данных
		if($db -> one("SELECT COUNT(*) FROM `forums`") > 0)
			{
			$template_forums = array();

					while($forum = $db -> fetch("SELECT `id`, `name` FROM `forums`ORDER BY `position` ASC"))
				{
				$template_forum = array('id' => $forum['id'], 'name' => $forum['name']);

				$template_forums[] = $template_forum;

				}

			$template -> assign('forums', $template_forums);

			}

		$template -> block = 'list_trans';

		$template -> assign('posts', $template_posts);
		$template -> count_posts = $count_posts;
		$template -> postfix = postfix($count_posts, 'сообщений', 'сообщение', 'сообщения');

		break;
		}


	}
	break;
	############################################################################
	case 'edit':
	// изменение топика
	{

	only_reg();

	if($topic_info['not_edit_author'])only_reg(USER_MODERATOR);
	elseif(USER_LEVEL < USER_MODERATOR && USER_ID != $topic_info['user_id'])locate(PATH.'topic'.ID.'/');

	// тема закрыта
	if(!$topic_info['open'] && USER_LEVEL < USER_MODERATOR)err('Тема закрыта', PATH.'topic'.ID.'/');

	// уроверь доступа мал
	if($topic_info['level_posts'] > USER_LEVEL)err('Вы не можете редактировать сообщения', PATH.'topic'.ID.'/');

	// если забанен
	if($db -> one("SELECT COUNT(*) FROM `users_punishes` WHERE `user_id` = '".USER_ID."' AND `to_date` > '".TIME."' AND `ban` = '1'") > 0)err('Вы забанены', PATH.'topic'.ID.'/');

	$template -> first_post = false;

	if(postval('edit', 1))
		{
		check_fields(PATH.'topic'.ID.'/edit/', array(array('topic_name', 'not null', 'minlen' => 5, 'maxlen' => 100), array('topic_post', 'not null', 'minlen' => 2, 'maxlen' => $cfg['maxlen_post'])));

		$topic_name = str($_POST['topic_name']);
		$topic_post = str($_POST['topic_post']);

		$first_post_on_pages = postval('first_post_on_pages', 1, false);

		$level = $topic_info['level'];
		$level_posts = $topic_info['level_posts'];
		$open = $topic_info['open'];
		$top = $topic_info['top'];

		$not_edit_author = $topic_info['not_edit_author'];

		if(USER_LEVEL >= USER_MODERATOR)
			{
			$topic_log = null;

			if($topic_info['user_id'] != USER_ID)
				{
				$not_edit_author = postval('not_edit_author', 1);
				if($not_edit_author != $topic_info['not_edit_author'])$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = '".($not_edit_author ? 'Запрет' : 'Разрешение')." автору редактировать тему'");
				}

			$level = int($_POST['level']);
			if($level != $topic_info['level'])$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = 'Изменения уровня доступа темы на {$levels[$level][1]}'");

			$level_posts = int($_POST['level_posts']);
			if($level_posts != $topic_info['level_posts'])$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = 'Изменения уровня доступа темы для написания сообщений на {$levels[$level_posts][1]}'");

			$open = postval('open', 1, false);
			if($open != $topic_info['open'])$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = '".($open ? 'Открытие' : 'Закрытие')." темы'");

			$top = postval('top', 1, false);
			if($top != $topic_info['top'])$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = '".($top ? 'Закрепление' : 'Открепление')." темы'");

			}

		// обновляем тему
		if(!$db -> sql("UPDATE `topics` SET `name` = '$topic_name', `first_post_on_pages` = '$first_post_on_pages', `not_edit_author` = '$not_edit_author', `level` = '$level', `level_posts` = '$level_posts', `open` = '$open', `top` = '$top' WHERE `id` = '".ID."'"))
			{
			err('Ошибка при изменении темы', PATH.'topic'.ID.'/edit/');
			}

		// обновляем первый пост
		if(!empty($topic_info['first_post']))
			{
			if(!$db -> sql("UPDATE `posts_text` SET `text` = '$topic_post' WHERE `pid` = '{$topic_info['first_post']}'"))
				{
				err('Ошибка при изменении первого сообщения', PATH.'topic'.ID.'/edit/');
				}
			}
		// создаем первый пост
		else
			{
			if(!$db -> sql("INSERT INTO `posts` SET `tid` = '".ID."', `fid` = '{$forum_info['id']}', `user_id` = '".USER_ID."', `date` = '".TIME."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."'"))
				{
				err('Ошибка при создании первого сообщения', PATH.'topic'.ID.'/edit/');
				}

			$post_id = $db -> last_id();
			if(!$db -> sql("INSERT INTO `posts_text` SET `pid` = '$post_id', `text` = '$topic_post'"))
				{
				err('Ошибка при написании первого сообщения (ID '.$post_id.')', PATH.'topic'.ID.'/edit/');
				}

			if(!$db -> sql("UPDATE `topics` SET `first_post` = '$post_id' WHERE `id` = '".ID."'"))
				{
				err('Ошибка при присвоении первого сообщения (ID '.$post_id.')', PATH.'topic'.ID.'/edit/');
				}

			// добавляем +1 к счетчику
			$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` + 1 WHERE `id` = '{$forum_info['id']}'");

			}

		msg('Тема &quot;'.$topic_info['name'].'&quot; изменена', PATH.'topic'.ID.'/');

		}

	// если первый пост должен быть
	if(!empty($topic_info['first_post']))
		{
		// если есть пост в бд
		if($db -> one("SELECT COUNT(*) FROM `posts` AS `p`, `posts_text` AS `p_t` WHERE `p`.`id` = '{$topic_info['first_post']}' AND `p`.`id` = `p_t`.`pid`") > 0)
			{
			if(PAGE == 1 || $topic_info['first_post_on_pages'])
				{
				$first_post = $db -> one("SELECT `text` FROM `posts_text` WHERE `pid` = '{$topic_info['first_post']}'");

				if($topic_info['first_post_on_pages'])$template -> first_post_on_pages = true;

				$template -> first_post = $first_post;
				}
			}
		else
			{
			// если первый пост не найден
			$db -> sql("DELETE FROM `posts` WHERE `id` = '{$topic_info['first_post']}'");
			$db -> sql("DELETE FROM `posts_text` WHERE `id` = '{$topic_info['first_post']}'");
			$db -> sql("UPDATE `topics` SET `first_post` = 0, first_post_on_pages = '0' WHERE `id` = '".ID."'");
			$db -> sql("UPDATE `forums` SET `count_posts` = `count_posts` - 1 WHERE `id` = '{$forum_info['id']}'");
			}
		}


	if(USER_LEVEL >= USER_MODERATOR)
		{
		#$manage = '<label><input type="checkbox" name="not_edit_author" value="1"'.($topic_info['not_edit_author'] ? ' checked="checked"' : null).'/>Запретить автору редактировать топик</label><br />';
		#$manage .= '<label><input type="checkbox" name="open" value="1"'.($topic_info['open'] ? ' checked="checked"' : null).'/>Топик открыт</label><br />';
		$template -> first_post_on_pages = (bool)$topic_info['first_post_on_pages'];
		$template -> not_edit_author = (bool)$topic_info['not_edit_author'];
		$template -> open = (bool)$topic_info['open'];
		$template -> top = (bool)$topic_info['top'];
		$template -> level = $topic_info['level'];
		$template -> level_posts = $topic_info['level_posts'];
		$template -> manage = true;
		$template -> author_id = $topic_info['user_id'];
		}

	$template -> block = 'edit';

	$template -> page_zag = 'Изменение топика';

	}
	break;
	############################################################################
	case 'del':
	// удаление топика
	{

	only_reg(USER_MODERATOR);

	$count_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `tid` = '".ID."'");

	if(postval('del', 1))
		{

		// удаляем тексты постов
		if(!$db -> sql("DELETE FROM `posts_text` WHERE (SELECT `tid` FROM `posts` WHERE `id` = `posts_text`.`pid`) = '".ID."'"))
			{
			err('Ошибка при удалении сообщений', PATH.'topic'.ID.'/del/');
			}

		// удаляем посты
		if(!$db -> sql("DELETE FROM `posts` WHERE `tid` = '".ID."'"))
			{
			err('Ошибка при удалении сообщений', PATH.'topic'.ID.'/del/');
			}

		// удаляем логи
		if(!$db -> sql("DELETE FROM `topics_logs` WHERE `tid` = '".ID."'"))
			{
			err('Ошибка при удалении логов темы', PATH.'topic'.ID.'/del/');
			}

		// удаляем логи просмотров
		if(!$db -> sql("DELETE FROM `topics_views` WHERE `tid` = '".ID."'"))
			{
			err('Ошибка при удалении логов просмотров темы', PATH.'topic'.ID.'/del/');
			}

		// удаляем логи
		if(!$db -> sql("DELETE FROM `topics_bookmarks` WHERE `tid` = '".ID."'"))
			{
			err('Ошибка при удалении закладок темы', PATH.'topic'.ID.'/del/');
			}

		// удаляем тему
		if(!$db -> sql("DELETE FROM `topics` WHERE `id` = '".ID."'"))
			{
			err('Ошибка при удалении темы', PATH.'topic'.ID.'/del/');
			}

		$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` - 1, `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");

		msg('Тема &quot;'.$topic_info['name'].'&quot; удалена', PATH.'forum'.$forum_info['id'].'/');

		}

	$template -> block = 'del';

	$template -> page_zag = 'Удаление топика';

	}
	break;
	############################################################################
	case 'trans':
	// перенос топика
	{

	only_reg(USER_MODERATOR);

	if(postval('yes', 1))
		{
		$into_forum = int($_POST['into_forum']);

		if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` = '$into_forum'") == 0)err('Форум не выбран', PATH.'topic'.ID.'/trans/');

		$count_posts = $db -> one("SELECT COUNT(*) FROM `posts` WHERE `tid` = '".ID."'");
		if(!empty($topic_info['first_post']))$count_posts --;

		// переносим посты
		if(!$db -> sql("UPDATE `posts` SET `fid` = '$into_forum' WHERE `tid` = '".ID."'"))
			{
			err('Ошибка при перемещении сообщений', PATH.'topic'.ID.'/trans/');
			}

		// переносим тему
		if(!$db -> sql("UPDATE `topics` SET `fid` = '$into_forum' WHERE `id` = '".ID."'"))
			{
			err('Ошибка при перемещении темы', PATH.'topic'.ID.'/trans/');
			}

		$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` - 1, `count_posts` = `count_posts` - '$count_posts' WHERE `id` = '{$forum_info['id']}'");
		$db -> sql("UPDATE `forums` SET `count_topics` = `count_topics` + 1, `count_posts` = `count_posts` + '$count_posts' WHERE `id` = '$into_forum'");

		$db -> sql("INSERT INTO `topics_logs` SET `tid` = '".ID."', `date` = '".TIME."', `user_id` = '".USER_ID."', `ip` = '".MY_INT_IP."', `ua` = '".MY_UA."', `text` = 'Перенос темы в форум ".($db -> one("SELECT `name` FROM `forums` WHERE `id` = '{$into_forum}'"))."'");

		msg('Тема &quot;'.$topic_info['name'].'&quot; перемещена', PATH.'topic'.ID.'/');


		}

	// выбираем форумы для переноса данных
	if($db -> one("SELECT COUNT(*) FROM `forums` WHERE `id` != '{$forum_info['id']}'") > 0)
		{
		$template_forums = array();

				while($forum = $db -> fetch("SELECT `id`, `name` FROM `forums` WHERE `id` != '{$forum_info['id']}' ORDER BY `position` ASC"))
			{
			$template_forum = array('id' => $forum['id'], 'name' => $forum['name']);

			$template_forums[] = $template_forum;

			}

		$template -> assign('forums', $template_forums);

		}
	else
		{
		err('Перемещать некуда', PATH.'topic'.ID.'/');
		}

	$template -> block = 'trans';

	$template -> page_zag = 'Перемещение темы';

	}
	break;
	############################################################################
	case 'logs':
	// логи управления топиком
	{

	only_reg(USER_MODERATOR);

	$count_logs = $db -> one("SELECT COUNT(*) FROM `topics_logs` WHERE `tid` = '".ID."'");
	if($count_logs > 0)
		{
		check_page($count_logs, PATH.'topic'.ID.'/logs/page{$page}/');

		$template_logs = array();

		$i = START_POSTS;
				while($log = $db -> fetch("SELECT * FROM `topics_logs` WHERE `tid` = '".ID."' ORDER BY `date` DESC LIMIT ".START_POSTS.",".ONPAGE_POSTS))
			{
			$i ++;

			$template_log = array('i' => $i, 'date' => xdate($log['date']), 'user_id' => $log['user_id'],'user' => get_user($log['user_id'], 'nick'), 'text' => $log['text'], 'ip' => long2ip($log['ip']), 'ua' => $log['ua']);

			$template_logs[] = $template_log;
			}

		#d($template_logs,0);

		$template -> assign('logs', $template_logs);

		pagebar($str, PAGE, PATH.'topic'.ID.'/logs/page{$page}/');

		}

	$template -> block = 'logs';

	}
	break;
	############################################################################
	case 'bookmark':
	// добавление / удаление из закладок
	{

	only_reg();

	// удаляем
	if($db -> one("SELECT COUNT(*) FROM `topics_bookmarks` WHERE `tid` = '".ID."' AND `user_id` = '".USER_ID."'") > 0)
		{
		if($db -> sql("DELETE FROM `topics_bookmarks` WHERE `tid` = '".ID."' AND `user_id` = '".USER_ID."'"))
			{
			msg('Тема удалена из закладок', PATH.'topic'.ID.'/');
			}
		else
			{
			err('Ошибка', PATH.'topic'.ID.'/');
			}
		}
	// добавляем
	else
		{

		if($db -> sql("INSERT INTO `topics_bookmarks` SET `tid` = '".ID."', `user_id` = '".USER_ID."', `date` = '$last_date'"))
			{
			msg('Тема добавлена в закладки', PATH.'topic'.ID.'/');
			}
		else
			{
			err('Ошибка', PATH.'topic'.ID.'/');
			}
		}

	}
	break;
	############################################################################
	case 'info':
	// информация о теме
	{

	only_reg();

	$template -> count_all_views = $topic_info['count_all_views'].' '.postfix($topic_info['count_all_views'], 'раз', 'раз', 'раза');
	$template -> count_views = $topic_info['count_views'].' '.postfix($topic_info['count_views'], 'раз', 'раз', 'раза');
	$template -> count_views_percent = floor(($topic_info['count_views'] / $topic_info['count_all_views']) * 100);

	$info = $db -> fetch("SELECT (SELECT COUNT(*) FROM `topics_views` WHERE `tid` = `topics`.`id`) AS `count_all_views`, (SELECT COUNT(*) FROM `topics_views` WHERE `tid` = `topics`.`id` AND `date` = `topics`.`last_date`) AS `count_views`, (SELECT COUNT(*) FROM `topics_bookmarks` WHERE `tid` = `topics`.`id`) AS `count_bookmarks`
FROM `topics` WHERE `id` = '".ID."'");


	$template -> count_uniq_views = $info['count_all_views'].' '.postfix($info['count_all_views'], 'форумчан', 'форумчанна', 'форумчан');
	$template -> count_uniq_all_views = $info['count_views'].' '.postfix($info['count_views'], 'форумчан', 'форумчанина', 'форумчан');

	$template -> count_uniq_percent = floor(($info['count_views'] / $info['count_all_views']) * 100);

	if($info['count_bookmarks'] > 0)
		{
		$template -> count_bookmarks = $info['count_bookmarks'].' '.postfix($info['count_bookmarks'], 'форумчан', 'форумчанина', 'форумчан');
		}

	$template -> block = 'info';

	}
	break;
	############################################################################
	case 'rss':
	// RSS лента
	{
	
	only_reg();

	endclean();

	$data = array();

	$first_post = (!empty($topic_info['first_post'])) ? $db -> one("SELECT `text` FROM `posts_text` WHERE `pid` = '{$topic_info['first_post']}'") : null;

	$data['head'] = array
		(
		'title' => 'Тема : '.$topic_info['name'],
		'link' => 'http://'.DOMAIN.PATH.'topic'.ID.'/',
		'description' => $first_post,
		'build_date' => date('r')
#		'copyright' =>,

		);

			while($post = $db -> fetch("SELECT `p_t`.`text` AS `text`, `u`.`nick` AS `user`, `p`.`id`, `p`.`date`
FROM `posts` AS `p`, `posts_text` AS `p_t`, `users` AS `u`
WHERE `p`.`id` != '{$topic_info['first_post']}' AND `p`.`tid` = '".ID."' AND `p_t`.`pid` = `p`.`id` AND `u`.`id` = `p`.`user_id`
ORDER BY `p`.`date` DESC"))
		{

		$data['values'][] = array('title' => 'Сообщение '.$post['user'].' от '.xdate($post['date'], 'G:i d.m.Y'), 'description' => htmlspecialchars(post($post['text'])), 'guid' => $post['id'], 'link' => 'http://'.DOMAIN.PATH.'post'.$post['id'].'/', 'pub_date' => xdate($post['date'], 'r'));
		$max_date = $post['date'];
		}

	$data['head']['pub_date'] = xdate($max_date, 'r');

	$result = create_rss_file($data);

	#d($result);

	header('Content-type:application/rss+xml; charset=utf-8');

	echo $result;

	exit;

	}
	break;
	############################################################################
	case 'txt':
	// скачать в TXT
	{
	
	only_reg();

	endclean();

	$data = array();

	header('Content-type: text/plain; charset=utf-8');

	$rn = "\r\n";

	$result = null;

	$result .= 'Тема : '.destr($topic_info['name']).' ( http://'.DOMAIN.PATH.'topic'.ID.'/ )'.$rn;

	if(!empty($topic_info['first_post']))
		{
		$result .= '----------------'.$rn;
		$result .= '#0. '.destr(post_del($db -> one("SELECT `text` FROM `posts_text` WHERE `pid` = '{$topic_info['first_post']}'"))).$rn;
		}


	$i = 0;
			while($post = $db -> fetch("SELECT `p_t`.`text` AS `text`, `u`.`nick` AS `user`, `p`.`id`, `p`.`date`
FROM `posts` AS `p`, `posts_text` AS `p_t`, `users` AS `u`
WHERE `p`.`id` != '{$topic_info['first_post']}' AND `p`.`tid` = '".ID."' AND `p_t`.`pid` = `p`.`id` AND `u`.`id` = `p`.`user_id`
ORDER BY `p`.`date` ASC"))
		{
		$i ++;

		$result .= '----------------'.$rn;

		$result .= '#'.$i.'. '.$post['user'].' / '.xdate($post['date']).''.$rn;
		$result .= destr(post_del($post['text'])).$rn;

		}

	loadfile(null, $result, DOMAIN.'_topic_'.ID.'.txt', 'text/plain');

	exit;

	}
	break;
	}

$template -> display('topic.page');

show_foot();

?>