<?php
include_once('../inclfiles/core.php');
if($id != 0){
	if(mysql_num_rows(mysql_query("SELECT * FROM `forum_themes` WHERE `id` = ".$id."".$deleted."")) != 0){
        $theme = mysql_fetch_array(mysql_query("SELECT * FROM `forum_themes` WHERE `id` = ".$id.""));
        $razdel = mysql_fetch_array(mysql_query("SELECT * FROM `forum_razdels` WHERE `id` = ".$theme['razdel'].""));
		$title = $theme['name'];
		include_once('../inclfiles/head.php');

		if($user AND ($user['level'] >= 2 OR $user['id'] == $theme['user'])){
        	if($act == 'close'){
        	    if($theme['zakril'] == 0){
           		 	mysql_query("UPDATE `forum_themes` SET `zakril` = ".$user['id']." WHERE `id` = ".$id."");
	        		m('Тема успешно закрыта');
	        		$theme['zakril'] = $user['id'];
	       		}
	       		else e('Тема уже закрыта');
        	}
		}

   		if($user AND $user['level'] >= 2){
   			if($act == 'delete'){
	        	if(mysql_num_rows(mysql_query("SELECT * FROM `forum_posts` WHERE `id` = ".$id2." AND `theme` = ".$id." AND `deleted` = 0")) > 0){
	        		mysql_query("UPDATE `forum_posts` SET `deleted` = ".$user['id']." WHERE `id` = ".$id2." AND `theme` = ".$id."");
	        		m('Пост успешно удален');
	        	}
	        	else e('Пост не найден. Возможно, он был удален раннее');
	      	}
	      	else if($act == 'vost'){
	      		if(mysql_num_rows(mysql_query("SELECT * FROM `forum_posts` WHERE `id` = ".$id2." AND `theme` = ".$id." AND `deleted` > 0")) > 0){
	        		mysql_query("UPDATE `forum_posts` SET `deleted` = 0 WHERE `id` = ".$id2." AND `theme` = ".$id."");
	        		m('Пост успешно восстановлен');
	        	}
	        	else e('Пост не найден. Возможно, он был восстановлен раннее');
	      	}
	      	else if($act == 'open'){
	      		if(mysql_num_rows(mysql_query("SELECT * FROM `forum_themes` WHERE `id` = ".$id." AND `zakril` > 0")) > 0){
	        		mysql_query("UPDATE `forum_themes` SET `zakril` = 0 WHERE `id` = ".$id."");
	        		m('Тема успешно открыта');
	        		$theme['zakril'] = 0;
	        	}
	        	else e('Тема не найдена. Возможно, она была открыта раннее');
	      	}
		}

 		if($_POST['ok'] != null){
			$text = filter($_POST['text']);
			if(!$user) $err[] ='Вы не авторизованы';
			else if($theme['zakril'] != 0) $err[] ='Данная тема закрыта';
			else if($text == null) $err[] ='Не введен текст поста';
			else if(strlen2($text) > 500 OR strlen2($text) < 1) $err[] ='Текст поста должен быть не менее 1 символа и не более 500 символов';
			else{
				$all_user_coms = mysql_num_rows(mysql_query("SELECT * FROM `forum_posts` WHERE `user` = ".$user['id']." AND `theme` = ".$id.""));
				if($all_user_coms > 0) $user_message = mysql_fetch_array( mysql_query("SELECT * FROM `forum_posts` WHERE `user` = ".$user['id']." AND `theme` = ".$id." ORDER BY `time` DESC LIMIT 1"));
				if($all_user_coms > 0 AND $user_message['text'] == $text) $err[] = 'Вы уже писали такой пост раннее';
                if(!isset($err)){
					mysql_query("INSERT INTO `forum_posts` SET `text` = '".$text."', `theme` = ".$id.", `user` = ".$user['id'].", `time` = ".time()."");
					mysql_query("UPDATE `forum_themes` SET `posts`=(`posts`+1),`posts_all`=(`posts_all`+1),`time_last` = '".time()."' WHERE `id` = '".$theme['id']."'");
					m('Ваш пост успешно добавлен');
				}
			}
		}

		err();

        if($theme['zakril'] != 0) $zakr = zna4ok('zakrito','Тема закрыта');
		else $zakr = '';
        t(time_right($theme['time']).user($theme['user']).$zakr.deleted($theme['deleted']).'<br/>'.nl2br(smiles($theme['text'])));
        if($user AND $theme['zakril'] == 0 AND ($user['level'] >= 2 OR $user['id'] == $theme['user'])) a('index.php?act=close&id='.$id.'&page='.$page.'&','Закрыть тему','zakrito');
        if($user AND $user['level'] >= 2 AND $theme['zakril'] != 0) a('index.php?act=open&id='.$id.'&page='.$page.'&','Открыть тему','open');

        $all = mysql_num_rows(mysql_query("SELECT * FROM `forum_posts` WHERE `theme` = ".$theme['id']."".$deleted.""));
        if($all != 0){
		    t('Посты ('.$all.'):');
			$total=intval(($all-1)/$set['napage'])+1;
			if(empty($page) OR $page < 0) $page = 1;
			if($page > $total) $page = $total;
			$past=intval($all/$set['napage']);
			$start=$page*$set['napage']-$set['napage'];
			$posts = mysql_query("SELECT * FROM `forum_posts` WHERE `theme` = ".$theme['id']."".$deleted." ORDER BY `time` ASC LIMIT ".$start.",".$set['napage']."");
			while($post= mysql_fetch_array($posts)){
				$start++;
				t($start.'. '.time_right($post['time']).user($post['user']).deleted($post['deleted']).'<br/>'.nl2br(smiles($post['text'])));
				if($user AND $user['level'] >= 2){
					if($post['deleted'] == 0) a('index.php?act=delete&id='.$id.'&id2='.$post['id'].'&page='.$page.'&','Удалить пост','delete');
					else a('index.php?act=vost&id='.$id.'&id2='.$post['id'].'&page='.$page.'&','Восстановить пост','delete');
				}
			}
			navigation($all,$set['napage'],$page,'index.php?id='.$post['id'].'&',$total);
		}

		if($theme['zakril'] == 0){
			if($user) c('<form action="index.php?id='.$theme['id'].'&'.$gets.'" method="post"><textarea name="text" type="text" maxlength="500"  /></textarea><br/><input name="ok" type="submit" value="Добавить пост" /></form>');
			else t('Чтобы добавить пост нужно <a href="/reg.php?'.$gets.'">зарегистрироваться</a> либо, если Вы уже зарегистрированы, <a href="/auth.php?'.$gets.'">авторизоваться</a>');
        }
        else{
           	if($theme['zakril'] == $theme['user']) t('Тема закрыта автором');
   			else t('Тема закрыта пользователем '.user($theme['zakril']));
   		}
   		a('razdels.php?id='.$razdel['id'].'&',$razdel['name'],'razdels');

	}
	else{
    	$title = 'Ошибка';
		include_once('../inclfiles/head.php');
		t('Тема не найдена. Возможно, она была удалена');
	}
	a('index.php?','Форум','forum',mysql_num_rows(mysql_query("SELECT * FROM `forum_themes` WHERE `zakril` = 0 ".$deleted."")),mysql_num_rows(mysql_query("SELECT * FROM `forum_themes` ".$wdeleted."")));
}
else{
    $title = 'Форум';
	include_once('../inclfiles/head.php');
	$all = mysql_num_rows(mysql_query("SELECT * FROM `forum_themes` ".$wdeleted.""));
	if($all != 0){
		$total=intval(($all-1)/$set['napage'])+1;
		if(empty($page) OR $page < 0) $page = 1;
		if($page > $total) $page = $total;
		$past=intval($all/$set['napage']);
		$start=$page*$set['napage']-$set['napage'];
		$themes = mysql_query("SELECT * FROM `forum_themes` ".$wdeleted." ORDER BY `time_last` DESC LIMIT ".$start.",".$set['napage']."");
		while($theme = mysql_fetch_array($themes)){
			if($theme['zakril'] != 0) $zakr = 'zakrito';
			else $zakr = 'theme';
			a('index.php?id='.$theme['id'].'&',time_right($theme['time_last']).$theme['name'].deleted($theme['deleted']),$zakr,mysql_num_rows(mysql_query("SELECT * FROM `forum_posts` WHERE `theme` = ".$theme['id']." ".$deleted."")));
		}
		navigation($all,$set['napage'],$page,'index.php?',$total);
	}
	else t('Нет тем');
	a('razdels.php?','Разделы форума','razdels');
}
include_once('../inclfiles/foot.php');
?>