<?



include 'connect.php';

if(!$u['id']){
header ("Location: aut.php");
exit;
}

$location = 'forum';

switch($_GET['act'])
{
//Создание категории ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add_cat':
if ($u['admin'] == 1){
if (isset($_POST['submit']) and $_POST['name']) {
$name = check(substr($_POST['name'], 0, 100));
mysql_query("INSERT INTO `forum_categories` SET
`name` = '$name',
`time` = '".time()."',
`ord` = '0'
");
header("location: forum.php");
} else {
$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Добавить категорию</b>';
echo '</div>';

echo '<div class="block_action">';
//Блоки ввода
echo '<form action=forum.php?act=add_cat method=post>
Название: <br/><textarea cols="20" rows="1" name="name" style="width: 97%"></textarea><br/>
<input type=submit name="submit" class="btn" value=Добавить class=submit white/ ></form>';
echo '</div>';
include 'foot.php';
}
}

break;

//Создание форума ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add_forum':
if ($u['admin'] == 1){
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $category = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($category){
if (isset($_POST['submit']) and $_POST['name']) {
$name = check(substr($_POST['name'], 0, 100));
mysql_query("INSERT INTO `forum_forums` SET
`name` = '$name',
`time` = '".time()."',
`cat` = '".$category['id']."',
`ord` = '0'
");
header("location: forum.php?act=cat&id=".$category['id']."");
} else {
$title = $title.' | Форум';
include 'head.php';
$name_cat = checkout($category['name']);
echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=cat&id='.$category['id'].'">'.$name_cat.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Добавить форум</b>';
echo '</div>';

echo '<div class="block_action">';
//Блоки ввода
echo '<form action=forum.php?act=add_forum&id='.$id.' method=post>
Название: <br/><textarea cols="20" rows="1" name="name" style="width: 97%"></textarea><br/>
<input type=submit name="submit" class="btn" value=Добавить class=submit white/ ></form>';
echo '</div>';
include 'foot.php';
}
}
}
break;

//Создание темы ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add_theme':

//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $forum = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($forum){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$forum['cat']."' LIMIT 1"));
if (isset($_POST['submit']) and $_POST['name'] and $_POST['message']) {
$name = check(substr($_POST['name'], 0, 100));
$message = check(substr($_POST['message'], 0, 10000));
   //Проверяем на флуд
   $flood = mysql_query("SELECT `time` FROM `forum_themes` WHERE `user` = '".$u['id']."' AND `time` > '" . (time() - 3) . "'");
   if (mysql_num_rows($flood)) {
   header ("Location: forum.php?act=forum&id=$id");
   exit;
   }
// Вставляем сообщение в базу
mysql_query("INSERT INTO `forum_themes` SET
`user` = '".$u['id']."',
`name` = '$name',
`time` = '".time()."',
`forum` = '".$forum['id']."',
`cat` = '".$cat['id']."',
`ord` = '".time()."'
");
$id = mysql_insert_id();

mysql_query("UPDATE `users` SET
      `stat_forum_themes` = `stat_forum_themes`+1
      WHERE `id` = '".$u['id']."'
      ");

mysql_query("INSERT INTO `forum_messages` SET
`user` = '".$u['id']."',
`message` = '$message',
`time` = '".time()."',
`main` = '1',
`theme` = '$id',
`forum` = '".$forum['id']."',
`cat` = '".$cat['id']."'
");

mysql_query("UPDATE `users` SET
      `stat_forum_messages` = `stat_forum_messages`+1
      WHERE `id` = '".$u['id']."'
      ");

header ("Location: forum.php?act=theme&id=$id");

} else {
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=forum&id='.$forum['id'].'">'.$name_forum.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Создать тему</b>';
echo '</div>';

echo '<div class="block_action">';

//Блоки ввода
echo '<form action=forum.php?act=add_theme&id='.$id.' method=post>
Тема: <br/><textarea cols="20" rows="1" name="name" style="width: 97%"></textarea><br/>
Сообщение: <br/><textarea cols="20" rows="2" name="message" style="width: 97%"></textarea><br/>
<input type=submit name="submit" class="btn" value=Создать class=submit white/ ></form>';
}
echo '</div>';
include 'foot.php';
}

break;

//Редактирование категории ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'edit_cat':
if ($u['admin'] == 1){
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $cat = mysql_fetch_assoc($req);
   }
}
if($cat){
      if (isset($_POST['submit']) and $_POST['name']) {
      $name = check(substr($_POST['name'], 0, 100));
      mysql_query("UPDATE `forum_categories` SET
      `name` = '$name'
      WHERE `id` = '$id'
      ");
      header ("Location: forum.php");
      } else {
$title = $title.' |Форум';

include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Изменить категорию</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($cat['name']);
      echo '<form action="forum.php?act=edit_cat&amp;id='.$id.'" method="post">';
	  echo 'Название:<br/><textarea cols="20" rows="1" name="name" style="width: 97%">'.$name.'</textarea><br/>';
      echo '<input type="submit" name="submit" class="btn" value="Сохранить" class="submit white"/>';
      echo '</form>';
      }
echo '</div>';
include 'foot.php';
}
}
break;

//Удаление категории ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'delete_cat':
if ($u['admin'] == 1){
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $cat = mysql_fetch_assoc($req);
   }
}
if($cat){

      if (isset($_POST['submit'])) {
	  mysql_query("DELETE FROM `forum_categories` WHERE `id` = '".$cat['id']."'");
	  mysql_query("DELETE FROM `forum_forums` WHERE `cat` = '".$cat['id']."'");
	  mysql_query("DELETE FROM `forum_themes` WHERE `cat` = '".$cat['id']."'");
	  mysql_query("DELETE FROM `forum_messages` WHERE `cat` = '".$cat['id']."'");
      header ("Location: forum.php");
      } else {
$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Удалить категорию</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($cat['name']);
	  echo 'Вы уверены, что хотите удалить категорию <a href = "forum.php?act=cat&id='.$id.'"><b>'.$name.'</b></a> и все находящиеся в ней темы?<br/>';
      echo '<form action="forum.php?act=delete_cat&amp;id='.$id.'" method="post">';
      echo '<input type="submit" name="submit" class="btn" value="Да, удалить" class="submit white"/>';
      echo '</form></div>';
      }
echo '</div>';
include 'foot.php';
}
}
break;

//Редактирование форума ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'edit_forum':
if ($u['admin'] == 1){
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $forum = mysql_fetch_assoc($req);
   }
}
if($forum){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$forum['cat']."' LIMIT 1"));
$name_cat = checkout($cat['name']);
      if (isset($_POST['submit']) and $_POST['name']) {
      $name = check(substr($_POST['name'], 0, 100));
      mysql_query("UPDATE `forum_forums` SET
      `name` = '$name'
      WHERE `id` = '$id'
      ");
      header ("Location: forum.php?act=cat&id=".$cat['id']."");
      } else {

$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=cat&id='.$cat['id'].'">'.$name_cat.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Изменить форум</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($forum['name']);
      echo '<form action="forum.php?act=edit_forum&amp;id='.$id.'" method="post">';
	  echo 'Название:<br/><textarea cols="20" rows="1" name="name" style="width: 97%">'.$name.'</textarea><br/>';
      echo '<input type="submit" name="submit" class="btn" value="Сохранить" class="submit white"/>';
      echo '</form>';
      }
echo '</div>';
include 'foot.php';
}
}
break;

//Удаление форума ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'delete_forum':
if ($u['admin'] == 1){
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $forum = mysql_fetch_assoc($req);
   }
}
if($forum){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$forum['cat']."' LIMIT 1"));
$name_cat = checkout($cat['name']);

      if (isset($_POST['submit'])) {
	  mysql_query("DELETE FROM `forum_forums` WHERE `id` = '".$forum['id']."'");
	  mysql_query("DELETE FROM `forum_themes` WHERE `forum` = '".$forum['id']."'");
	  mysql_query("DELETE FROM `forum_messages` WHERE `forum` = '".$forum['id']."'");
header ("Location: forum.php?act=cat&id=".$cat['id']."");
      } else {
$title = $title.' | Форум';

include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=cat&id='.$cat['id'].'">'.$name_cat.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Удалить форум</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($forum['name']);
	  echo 'Вы уверены, что хотите удалить форум <a href = "forum.php?act=forum&id='.$id.'"><b>'.$name.'</b></a> и все находящиеся в ней темы?<br/>';
      echo '<form action="forum.php?act=delete_forum&amp;id='.$id.'" method="post">';
      echo '<input type="submit" name="submit" class="btn" value="Да, удалить" class="submit white"/>';
      echo '</form></div>';
      }
echo '</div>';
include 'foot.php';
}
}
break;

//Удаление темы ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'delete_theme':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_themes` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $tema = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($tema){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$tema['cat']."' LIMIT 1"));
$forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '".$tema['forum']."' LIMIT 1"));

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_messages` WHERE `theme` = '".$tema['id']."'"), 0);
   if($tema['user'] == $u['id'] || $u['admin'] == 1 || $u['admin'] == 2){
      if($u['admin'] == 1 || !$all > 1){
      if (isset($_POST['submit'])) {
	  mysql_query("DELETE FROM `forum_themes` WHERE `id` = '".$id."'");
	  mysql_query("DELETE FROM `forum_messages` WHERE `theme` = '".$id."'");
header ("Location: forum.php?act=forum&id=".$forum['id']."");
      } else {
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$name_theme = checkout($tema['name']);
$title = $title.' | Форум';

include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=theme&id='.$tema['id'].'">'.$name_theme.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Удалить тему</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($cat['name']);
	  echo 'Удалить тему <a href = "forum.php?act=theme&id='.$id.'"><b>'.$name_theme.'</b></a>?<br/>';
      echo '<form action="forum.php?act=delete_theme&amp;id='.$id.'" method="post">';
      echo '<input type="submit" name="submit" class="btn" value="Да, удалить" class="submit white"/>';
echo '</form></div>';
      }
	  } else { 
$name_theme = checkout($tema['name']);
$title = $title.' | Форум';
$main_title = '<a href = "forum.php">Удалить тему</a>';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=theme&id='.$tema['id'].'">'.$name_theme.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Удалить тему</b>';
echo '</div>';

	  echo '<div class="block_action2">Нельзя удалить тему на которую уже ответили!</div>'; }
   }
include 'foot.php';
} else {
header ("Location: forum.php");
}

break;

//Изменение темы ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'edit_theme':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_themes` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $tema = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($tema){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$tema['cat']."' LIMIT 1"));
$forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '".$tema['forum']."' LIMIT 1"));
$messages = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_messages` WHERE `theme` = '".$tema['id']."' and `main` = '1' LIMIT 1"));
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$name_theme = checkout($tema['name']);

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_messages` WHERE `theme` = '".$tema['id']."'"), 0);
   if($tema['user'] == $u['id'] || $u['admin'] == 1){
      if (isset($_POST['submit']) and $_POST['name'] and $_POST['message']) {
	  $name = check(substr($_POST['name'], 0, 100));
	  $message = check(substr($_POST['message'], 0, 10000));
	  mysql_query("UPDATE `forum_themes` SET
      `name` = '$name'
      WHERE `id` = '$id'
      ");
      mysql_query("UPDATE `forum_messages` SET
      `message` = '$message'
      WHERE `id` = '".$messages['id']."'
      ");
		 mysql_query("UPDATE `forum_messages` SET
         `cedit` = `cedit`+1
         WHERE `id` = '".$messages['id']."'
         ");
		 mysql_query("UPDATE `forum_messages` SET
         `etime` = '".time()."'
         WHERE `id` = '".$messages['id']."'
         ");
      header ("Location: forum.php?act=theme&id=".$tema['id']."");
      } else {
$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=theme&id='.$tema['id'].'">'.$name_theme.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Изменить тему</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($tema['name']);
	  $message = checkout($messages['message']);
      echo '<form action="forum.php?act=edit_theme&amp;id='.$id.'" method="post">';
	  echo 'Тема:<br/><textarea cols="20" rows="1" name="name" style="width: 97%">'.$name.'</textarea><br/>';
	  echo 'Сообщение:<br/><textarea cols="20" rows="3" name="message" style="width: 97%">'.$message.'</textarea><br/>';
      echo '<input type="submit" name="submit" class="btn" value="Сохранить" class="submit white"/>';
      echo '</form>';
	  }
   }
echo '</div>';
include 'foot.php';
} else {
header ("Location: forum.php");
}

break;

//Изменение сообщения ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'edit_message':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_messages` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $msg = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($msg){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$msg['cat']."' LIMIT 1"));
$forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '".$msg['forum']."' LIMIT 1"));
$tema = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_themes` WHERE `id` = '".$msg['theme']."' LIMIT 1"));
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$name_theme = checkout($tema['name']);

   if($msg['user'] == $u['id'] || $u['admin'] == 1){
      if (isset($_POST['submit']) and $_POST['message']) {
	  $message = check(substr($_POST['message'], 0, 10000));
      mysql_query("UPDATE `forum_messages` SET
      `message` = '$message'
      WHERE `id` = '".$msg['id']."'
      ");
		 mysql_query("UPDATE `forum_messages` SET
         `cedit` = `cedit`+1
         WHERE `id` = '".$msg['id']."'
         ");
		 mysql_query("UPDATE `forum_messages` SET
         `etime` = '".time()."'
         WHERE `id` = '".$msg['id']."'
         ");
      header ("Location: forum.php?act=theme&id=".$tema['id']."");
      } else {
$title = $title.' | Форум';

include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=theme&id='.$tema['id'].'">'.$name_theme.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Изменить сообщение</b>';
echo '</div>';

echo '<div class="block_action">';
	  $message = checkout($msg['message']);
      echo '<form action="forum.php?act=edit_message&amp;id='.$id.'" method="post">';
	  echo 'Сообщение:<br/><textarea cols="20" rows="3" name="message" style="width: 97%">'.$message.'</textarea><br/>';
      echo '<input type="submit" name="submit" class="btn" value="Сохранить" class="submit white"/>';
      echo '</form>';
	  }
   }
echo '</div>';
include 'foot.php';
} else {
header ("Location: forum.php");
}

break;

//Просмотр темы ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'theme':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_themes` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $tema = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($tema){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$tema['cat']."' LIMIT 1"));
$forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '".$tema['forum']."' LIMIT 1"));
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$name_theme = checkout($tema['name']);

if($tema['close'] == 0){
//Запись сообщения, если сообщение получено
if($_POST['message']){
$message = check(substr($_POST['message'], 0, 10000));
   //Проверяем на флуд
   $flood = mysql_query("SELECT `time` FROM `forum_messages` WHERE `user` = '".$u['id']."' AND `time` > '" . (time() - 3) . "'");
   if (mysql_num_rows($flood)) {
   header ("Location: forum.php?act=theme&id=$id");
   exit;
   }
   // Проверка на одинаковые сообщения
   $req = mysql_query("SELECT * FROM `forum_messages` WHERE `user` = '".$u['id']."' and `theme` = '$id' ORDER BY `time` DESC");
   $res = mysql_fetch_array($req);
   if ($res['message'] == $message) {
   header("location: forum.php?act=theme&id=$id");
   exit;
   }

// Вставляем сообщение в базу
mysql_query("INSERT INTO `forum_messages` SET
`user` = '".$u['id']."',
`message` = '$message',
`time` = '".time()."',
`theme` = '$id',
`forum` = '".$forum['id']."',
`cat` = '".$cat['id']."'
");

mysql_query("UPDATE `forum_themes` SET
`ord` = '".time()."'
WHERE `id` = '$id'
");

mysql_query("UPDATE `users` SET
      `stat_forum_messages` = `stat_forum_messages`+1
      WHERE `id` = '".$u['id']."'
      ");

$count = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `theme` = '".$tema['id']."'"), 0);
$all_page = intval(($count - 1) / 10) + 1;
	  
header ("Location: forum.php?act=theme&id=$id&page=$all_page");
}
}

$title = $title.' | Форум';
$main_title = '<a href = "forum.php">Просмотр темы</a>';
include 'head.php';
echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=forum&id='.$forum['id'].'">'.$name_forum.'</a>';
echo '</div>';

echo '<div class="title2">';
echo '<b>'.$name_theme.'</b> ';


$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_messages` WHERE `theme` = '".$tema['id']."'"), 0);
if($tema['user'] == $u['id'] || $u['admin'] == 1 || $u['admin'] == 2){
   $close = num($_GET['close']);
   if($close == 1){
      if($tema['close'] == 0) {
	  mysql_query("UPDATE `forum_themes` SET
      `close` = '".$u['id']."'
      WHERE `id` = '$id'
      ");
	  $tema['close'] = $u['id'];

	  }
   }
   if($close == 2){
      if($tema['close'] == 1) {
	  mysql_query("UPDATE `forum_themes` SET
      `close` = '0'
      WHERE `id` = '$id'
      ");
	  $tema['close'] = 0;

	  }
   }
   
if($tema['close'] == 0) echo '<a href = "forum.php?act=theme&id='.$id.'&close=1">Закрыть</a>';
else echo '<a href = "forum.php?act=theme&id='.$id.'&close=2">Открыть</a>';
   echo '|<a href = "forum.php?act=edit_theme&id='.$id.'">Изменить</a>';
   if($u['admin'] == 1 || $all == 1){
   echo '|<a href = "forum.php?act=delete_theme&id='.$id.'">Удалить</a>';
   }

}
echo '</div>';


//Удаление
if($u['admin'] == 1 || $u['admin'] == 2){
   if($_GET['del']){
	   $del = intval($_GET['del']);
	   $message = mysql_num_rows(mysql_query("SELECT * FROM `forum_messages` WHERE `id` = '$del' and `main` = '0'"));
	   if($message){
		   mysql_query("DELETE FROM `forum_messages` WHERE `id` = '$del' LIMIT 1");
	   }
   }
}
if($all > 0){
   $total = intval(($all - 1) / 10) + 1;
   $page = intval($_GET['page']);
   if(empty($page) or $page < 0) $page = 1; 
   if($page > $total) $page = $total;
   $start = $page * 10 - 10;
   $result = mysql_query("SELECT * FROM `forum_messages` WHERE `theme` = '".$tema['id']."' ORDER BY `time` ASC LIMIT $start, 10");
      $end = mysql_query("SELECT * FROM `forum_messages` WHERE `theme` = '$id' ORDER BY `time` DESC");
      $end_msg = mysql_fetch_array($end);
	  while($msg = mysql_fetch_assoc($result)){
	  $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$msg["user"]."'"));
      $message = checkout($msg['message']);	
	  //Вывод
	  echo '<div class="block_list">';
	  echo '<table>
  <tr>
    <td>';
	ava($user['id'],35);
	echo '</td>
	<td VALIGN=top>';
	echo ''.ico($user['sex'],$user['admin']).' <a href = "page.php?id='.$user['id'].'"><b>'.$user['login'].'</b></a> '.online($user['online']).' <font color = "#777777">('.vremya($msg['time']).')</font> ';
	if($msg['user'] != $u['id']) echo '<a href = "forum.php?act=theme&id='.$id.'&o='.$user['id'].'">[<font color = "red">Отв</font>]</a>'; 
	if($msg['main'] == 0 && $msg['user'] == $u['id']) echo '  <a href = "forum.php?act=edit_message&id='.$msg['id'].'"><img src = "img/edit.gif"></a> ';
	if(($msg['main'] == 0 && $end_msg['id'] == $msg['id'] && $msg['user'] == $u['id']) || ($msg['main'] == 0 && ($u['admin'] == 1 || $u['admin'] == 2))){
	echo '  <a href = "forum.php?act=theme&id='.$id.'&del='.$msg['id'].'"><img src = "img/delete.gif"></a>'; }
	echo '<br/><font color = "#000">';
	  smiles($message);
	  if($msg['cedit'] > 0) echo '<font color = "#999999"><br/>_________<br/>Изм. '.vremya($msg['etime']).' ('.$msg['cedit'].' раз.)</font>';	  
	  echo '</font><br/>';
	
	echo '</td>
  </tr>
</table>';

	  echo '</div>';
	  }
	  
   navigation($page, $total,'forum.php?act=theme&id='.$id.'&');
}else{
	echo '<div class = "center">Сообщений еще нет. Будь первым!</div>';
}



if($tema['close'] == 0){
echo '<div class="block_action">';
$o = abs(intval($_GET['o']));
$user = mysql_fetch_assoc(mysql_query("SELECT `login` FROM `users` WHERE `id` = '".$o."'"));
if($user['login']) $otv = $user['login'].', ';
echo '<form action="forum.php?act=theme&id='.$id.'&del='.$msg['id'].'" method="post">';
echo '<textarea cols="20" rows="3" name="message" style="width: 97%">';
echo $otv;
echo '</textarea><br/>';
echo "<input type='submit' title='Нажмите для отправки' name='submit' class='btn' value='Написать'  class='submit white'/> <a href = 'smiles.php'>[Смайлы]</a>
</form>";
echo '</div>';
} else {
echo '<div class = "action">Тема закрыта и Вы не можете добавлять сообщения в эту тему!<br/>
Закрыл: <a href = "page.php?id='.$tema['close'].'"><b>'.login($tema['close']).'</b></a>
</div>';
}

include 'foot.php';
} else {
header ("Location: forum.php");
}
break;

//Просмотр форума ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'forum':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_forums` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $forum = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($forum){
$cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$forum['cat']."' LIMIT 1"));
$name_cat = checkout($cat['name']);
$name_forum = checkout($forum['name']);
$title = $title.' | Форум';
include 'head.php';


echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '<a href = "forum.php?act=cat&id='.$cat['id'].'">'.$name_cat.'</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>'.$name_forum.'</b>';
echo '</div>';

echo '<div class="block_add"><a href = "forum.php?act=add_theme&id='.$forum['id'].'"><b>Создать тему</b></a></div>';

echo '<div class="main_menu">';
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_themes` WHERE `forum` = '".$forum['id']."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 15) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 15 - 15;
$result = mysql_query("SELECT * FROM `forum_themes` WHERE `forum` = '".$forum['id']."' ORDER BY `ord` DESC LIMIT $start, 15");
   while($theme = mysql_fetch_assoc($result)){
	  //Вывод
	  echo '<div class="block_list">';
	  $count = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `theme` = '".$theme['id']."'"), 0);
      $all_page = intval(($count - 1) / 10) + 1;
	  $name = checkout($theme['name']);
      if($theme['close'] == 1) echo '<font color = ""><b>#</b></font> '; 
	  echo '<a href = "forum.php?act=theme&id='.$theme['id'].'"><b>'.$name.'</b></a> <font color = "#777777">('.$count.')</font> <a href = "forum.php?act=theme&id='.$theme['id'].'&page='.$all_page.'">>>></a>'; 
	  if ($u['admin'] == 1) { echo '<br><a href = "forum.php?act=edit_theme&id='.$theme['id'].'">Изменить</a> - <a href = "forum.php?act=delete_theme&id='.$theme['id'].'">Удалить</a><br/>'; }

      echo '</div>';
   }
   navigation($page, $total,'forum.php?act=forum&id='.$forum['id'].'&');
}else{
echo '<div class="center">Тем пока нет!</div>';
}
echo '</div>';
include 'foot.php';
} else {
header ("Location: forum.php");
}
break;

//Просмотр категории ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'cat':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $category = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($category){
$name = checkout($category['name']);
$title = $title.' | Форум | '.$name.'';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>'.$name.'</b>';
echo '</div>';

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_forums` WHERE `cat` = '".$category['id']."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 15) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 15 - 15;
$result = mysql_query("SELECT * FROM `forum_forums` WHERE `cat` = '".$category['id']."' ORDER BY `ord` DESC LIMIT $start, 15");
   while($forum = mysql_fetch_assoc($result)){
	  //Вывод
	  echo '<div class="block_list">';
	  $count = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_themes` WHERE `forum` = '".$forum['id']."'"), 0);
	  $count2 = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `forum` = '".$forum['id']."'"), 0);
      $name = checkout($forum['name']);
      echo '<a href = "forum.php?act=forum&id='.$forum['id'].'"><b>'.$name.'</b></a> ('.$count.' | '.$count2.') '; 
	  if ($u['admin'] == 1) { echo '<br><a href = "forum.php?act=edit_forum&id='.$forum['id'].'">Изменить</a> - <a href = "forum.php?act=delete_forum&id='.$forum['id'].'">Удалить</a><br/>'; }
      echo '</div>';
   }
   navigation($page, $total,'forum.php?act=cat&id='.$category['id'].'&');
}else{

if($u['admin'] == 1) echo '<div class="block_add"><a href = "forum.php?act=add_forum&id='.$category['id'].'&">Добавить Форум</a></div>';
echo '<div class="center">Форумов не найдено!</div>';
}

include 'foot.php';
} else {
header ("Location: forum.php");
}
break;

//Новые ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'new':

$title = $title.' | Форум';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Новые</b>';
echo '</div>';

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_themes` WHERE `ord` > '".(time()-(60*60*24))."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 15) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 15 - 15;
$result = mysql_query("SELECT * FROM `forum_themes` WHERE `ord` > '".(time()-(60*60*24))."' ORDER BY `ord` DESC LIMIT $start, 15");
   while($theme = mysql_fetch_assoc($result)){
   $cat = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum_categories` WHERE `id` = '".$theme['cat']."' LIMIT 1"));
   $name_cat = checkout($cat['name']);
	  //Вывод
	  echo '<div class="block_list">';
	  $count = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `theme` = '".$theme['id']."'"), 0);
      $all_page = intval(($count - 1) / 10) + 1;
	  $name = checkout($theme['name']);
	  $end = mysql_query("SELECT `user`,`time` FROM `forum_messages` WHERE `theme` = '".$theme['id']."' ORDER BY `time` DESC");
      $end_msg = mysql_fetch_array($end);
	  if($theme['close'] == 1) echo '<font color = ""><b>#</b></font> '; 
	  echo '<a href = "forum.php?act=cat&id='.$cat['id'].'">'.$name_cat.'</a> > <a href = "forum.php?act=theme&id='.$theme['id'].'">'.$name.'</a> (<a href = "page.php?id='.$end['user'].'">'.login($end_msg['user']).'</a>,'.vremya($end_msg['time']).') <a href = "forum.php?act=theme&id='.$theme['id'].'&page='.$all_page.'">>>></a>'; 

      echo '</div>';

   }
   navigation($page, $total,'forum.php?act=new&');
}else{
echo 'Новых сообщений пока нет!';
}

include 'foot.php';
break;

//Ретинг ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'rating':
$title = $title.' | Форум';
include 'head.php';
echo '<div class="block_back">';
echo '<a href = "forum.php">Форум</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>ТОП форума</b>';
echo '</div>';
//Пользователей на страницу
if($u['setting_users_list']) $count = $u['setting_users_list']; else $count = 10;
echo '<div class="main_menu">';
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `stat_forum_messages` > 0"), 0);
if($all > 0){
   $total = intval(($all - 1) / $count) + 1;
   $page = num($_GET['page']);
   if(empty($page) or $page < 0) $page = 1; 
   if($page > $total) $page = $total;
   $start = $page * $count - $count;
   $result = mysql_query("SELECT * FROM `users` WHERE `stat_forum_messages` > 0 ORDER BY `stat_forum_messages` DESC LIMIT $start, $count");
      while($user = mysql_fetch_assoc($result)){
	  //Вывод
	  echo '<div class="block_list">';
	  echo '<table>
      <tr>
      <td>';
	  ava($user['id'],50);
	  echo '</td>
	  <td VALIGN=top>';
	  echo ''.ico($user['sex'],$user['admin']).' <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> '.online($user['online']).'';
	  echo '<br/>';
	  if($user['id'] != $u['id']){
	  echo '<img src = "img/mail.gif"> <a href = "mail.php?act=write&id='.$user['id'].'">Сообщение</a><br/>';
	  //Проверяем не друг ли
      $req = mysql_query("SELECT * FROM `friends` WHERE `user` = '".$u['id']."' and friend = '".$user['id']."' LIMIT 1");
      if(mysql_num_rows($req))
      echo '<img src = "img/friends.gif"> <a href = "friends.php?act=delete&id='.$user['id'].'">Убрать из друзей</a><br/>';
      else 
	  echo '<img src = "img/friends.gif"> <a href = "friends.php?act=adding&id='.$user['id'].'">Добавить в друзья</a><br/>';
	  }
	  echo '<img src = "img/messages.gif"> '.$user['stat_forum_messages'].'';
	  echo '<br/>';
	  echo '</td>
      </tr>
      </table>';

      echo '</div>';

	  }
	  navigation($page, $total,'forum.php?act=rating&');
}else{
echo 'Пользователей не найдено!';
}
echo '</div>';
include 'foot.php';
break;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 case 'add_forums':
    $query = mysql_query("select * from `forum_categories` order by `id`");
    if(mysql_num_rows($query) == 0)
    {
       echo '<div class="forum1">Форумы еще не созданы!</div>';
    }
    else
    {
	   if(isset($_POST['name']) && !empty($_POST['name']))
	   {
		  mysql_query ("INSERT INTO `forum_forums` (id,name) VALUES (".int($_POST['id']).",'".protect($_POST['name'])."')");
		  echo '<div class="where">Подфорум успешно создан!</div>';
	   }
	   echo '<div class="on"><form method="post" action="?act=add_forums">
	   <div>
	   Название:<br />
	   <input type="text" name="title" maxlength="32" value="" /><br />
       Форум:<br />
       <select size="1" name="id">';
       while($row = mysql_fetch_assoc($query))
       {
            echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
       }
        echo '</select><br/>
	   <input type="submit" class="btn" value="Добавить" />
	   </div></form></div><div class="where"><a href="index.php">Админ-панель</a></div>';
    }
    break;
//Список категорий ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
default:
$title = $title.' | Форум';

include 'head.php';

echo '<div class="title">';
echo '<b>Форум</b>';
echo '</div>';

if($u['admin'] == 1) echo '<div class="block_add"><a href = "forum.php?act=add_cat">Добавить категорию</a></div>';
$new = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `time` > '".(time()-(60*60*24))."'"), 0);
$rating = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `stat_forum_messages` > 0"), 0);

echo '<div class="nav">
<a href = "forum.php?act=new">Новые ('.$new.')</a> | <a href = "forum.php?act=rating">ТОП форума ('.$rating.')</a> 
</div>';

echo '<div class="main_menu">';
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_categories`"), 0);
if($all > 0){
$result = mysql_query("SELECT * FROM `forum_categories` ORDER BY `ord` DESC");
   while($cat = mysql_fetch_assoc($result)){
	  //Вывод
	  echo '<div class="block_list">';
      $name = checkout($cat['name']);
	  $count = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_themes` WHERE `cat` = '".$cat['id']."'"), 0);
	  $count2 = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `forum_messages` WHERE `cat` = '".$cat['id']."'"), 0);
      echo '<a href = "forum.php?act=cat&id='.$cat['id'].'"><b>'.$name.'</b></a> <font color = "#777777">('.$count.' | '.$count2.')</font>'; 
	  if ($u['admin'] == 1) { echo '<br><a href = "forum.php?act=edit_cat&id='.$cat['id'].'">Изменить</a> - <a href = "forum.php?act=delete_cat&id='.$cat['id'].'">Удалить</a><br/>'; }
      echo '</div>';
   }  
}else{
echo '<div class = "center">Категорий пока нет!</div>';
}
echo '</div>';
include 'foot.php';
break;
}
?>