<?



include 'connect.php';

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

$location = 'forum';



switch($_GET['act'])
{
//Создание записи ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add':
$title = $title.' | Дневники';
include 'head.php';
echo '<div class="title"><img src= "img/diary.gif"> Дневники - Новая запись</div>';
$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);
echo '<div class="subtitle"><a href = "diary.php?act=view">Мой дневник</a> ('.$cdiary.')</div>';
echo '<div class="main_menu">';
   if (isset($_POST['submit']) && $_POST['name'] && $_POST['message']) {
   $name = check(substr($_POST['name'], 0, 100));
   $message = check(substr($_POST['message'], 0, 10000));
   mysql_query("INSERT INTO `diary_messages` SET
   `user` = '".$u['id']."',
   `name` = '$name',
   `message` = '$message',
   `time` = '".time()."',
   `rating` = '0',
   `view` = '0'
   ");
   $id = mysql_insert_id();
   $name = checkout(substr($_POST['name'], 0, 100));
   echo '<div class = "action">Запись <a href = "diary.php?act=message&id='.$id.'"><b>'.$name.'</b></a> успешно добавлена в <a href = "diary.php?act=view">Ваш дневник!</a></div>';
   } else {
   echo '<form action="diary.php?act=add" method="post">
   Название: <br/><input type="text" name="name" maxlength="50"><br/>
   Текст: <br/><textarea cols="20" rows="3" name="message"></textarea><br/>
   <input type="submit" name="submit" class="btn" value="Добавить" class="submit white"></form>';
   }
echo '</div>';
include 'foot.php';
break;

//Дневник пользователя ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'view':
//Если id получен 
$id=num($_GET['id']); if($id == 0) $id=$u['id'];
$req = mysql_query("SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1");
if (mysql_num_rows($req))$user = mysql_fetch_assoc($req); else header ("Location: index.php");

$title = $title.' | Дневники';
include 'head.php';

$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);
if($user['id'] != $u['id'])echo '<div class="subtitle"><a href = "page.php?id='.$user['id'].'"> '.$user['login'].'</a> / <a href = "diary.php?act=view&id='.$user['id'].'">Дневник</a></div><br>';


else echo '<div class="subtitle"> <img src= "img/add.png"> <a href = "diary.php?act=add"> Новая запись</a></div>';

echo '<div class="main_menu">';
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$user['id']."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 10) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 10 - 10;
$result = mysql_query("SELECT * FROM `diary_messages` WHERE `user` = '".$user['id']."' ORDER BY `time` DESC LIMIT $start, 10");
   while($message = mysql_fetch_assoc($result)){
      $name = checkout($message['name']);
	  $msg = checkout($message['message']);
	  if (iconv_strlen($msg, 'UTF-8') > 25) {
      $msg = iconv_substr($msg, 0, 25, 'UTF-8');
      $msg=''.$msg.'...';
      }
	  echo '<img src = "img/diary_messages.png"> <a href = "diary.php?act=message&id='.$message['id'].'">'.$name.'</a>'; 
	  echo '<br/><font color = "#000">'.$msg.'</font><br/>'.vremya($message['time']);
	  echo '<hr>';
echo '<div class = "bloc"></div>';
   }
   navigation($page, $total,'diary.php?act=view&id='.$user['id'].'');
}else{
echo '<div class = "center">Записей пока нет!</div>';
}
echo '</div>';
include 'foot.php';
break;

//Редактирование ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'edit':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `diary_messages` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)){
   $message = mysql_fetch_assoc($req); 
   } else {header ("Location: index.php");
   exit;
   }
} else {
header ("Location: index.php");
exit;
}

if($u['admin'] == 1 || $u['admin'] == 2 || $message['user'] == $u['id'])
{
$title = $title.' | Дневники';
include 'head.php';
echo '<div class="title"><img src= "img/diary.gif"> Дневники - Редактирование записи</div>';
$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);
echo '<div class="subtitle"><a href = "diary.php?act=view">Мой дневник</a> ('.$cdiary.')</div>';
echo '<div class="main_menu">';
      if (isset($_POST['submit']) and $_POST['name'] and $_POST['msg']) {
	  $name = check(substr($_POST['name'], 0, 100));
	  $msg = check(substr($_POST['msg'], 0, 10000));
	  mysql_query("UPDATE `diary_messages` SET
      `name` = '$name',
	  `message` = '$msg'
      WHERE `id` = '$id'
      ");
      echo '<div class = "action">Изменения сохранены!</div>';
      } else {
      $name = checkout($message['name']);
	  $msg = checkout($message['message']);
      echo '<form action="diary.php?act=edit&amp;id='.$id.'" method="post">';
	  echo 'Название:<br/><textarea cols="20" rows="1" name="name">'.$name.'</textarea><br/>';
	  echo 'Текст:<br/><textarea cols="20" rows="3" name="msg">'.$msg.'</textarea><br/>';
      echo '<input type="submit" name="submit" class="btn" value="Сохранить" class="submit white"/>';
      echo '</form>';
	  }
echo '</div>';
include 'foot.php';

} else {
header ("Location: index.php");
}
break;

//Удаление ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'delete':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `diary_messages` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)){
   $message = mysql_fetch_assoc($req); 
   } else {header ("Location: index.php");
   exit;
   }
} else {
header ("Location: index.php");
exit;
}

if($u['admin'] == 1 || $u['admin'] == 2 || $message['user'] == $u['id'])
{
$title = $title.' | Дневники';
include 'head.php';
echo '<div class="title"><img src= "img/diary.gif"> Дневники - Удаление записи</div>';
$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);
echo '<div class="subtitle"><a href = "diary.php?act=view">Мой дневник</a> ('.$cdiary.')</div>';
echo '<div class="main_menu">';
      if (isset($_POST['submit'])) {
	  mysql_query("DELETE FROM `diary_messages` WHERE `id` = '".$id."'");
	  mysql_query("DELETE FROM `diary_like` WHERE `diary` = '".$id."'");
	  mysql_query("DELETE FROM `diary_view` WHERE `diary` = '".$id."'");
	  mysql_query("DELETE FROM `diary_comm` WHERE `diary` = '".$id."'");
      echo '<div class = "action">Запись удалена!</div>';
      } else {
      $name = checkout($message['name']);
	  echo 'Вы уверены, что хотите удалить запись <a href = "diary.php?act=message&id='.$message['id'].'">'.$name.'</a>?';
      echo '<form action="diary.php?act=delete&amp;id='.$id.'" method="post">';
      echo '<input type="submit" name="submit" class="btn" value="Да, удалить" class="submit white"/>';
      echo '</form>';
	  }
echo '</div>';
include 'foot.php';

} else {
header ("Location: index.php");
}
break;

//Просмотр записи ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'message':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `diary_messages` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)){
   $message = mysql_fetch_assoc($req); 
   } else {header ("Location: index.php");
   exit;
   }
} else {
header ("Location: index.php");
exit;
}

$user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$message['user']."' LIMIT 1"));

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

//Записываем в журнал
      if($message['user'] != $u['id']){
      if($u['sex'] == 'm'){
      $action[0] = 'Оставил';
      } else {
      $action[0] = 'Оставила';
      }
      $text = $action[0].' комментарий к Вашей <a href = "diary.php?act=message&id='.$message['id'].'">записи</a> в дневнике.';
      mysql_query("INSERT INTO `jurnal` SET
      `user` = '".$user['id']."',
      `outuser` = '".$u['id']."',
      `text` = '$text',
      `time` = '".time()."',
      `new` = '1'
      ");
      }
header ("Location: diary.php?act=message&id=".$message['id']."");
exit;
}

//Просмотры
if($u['id']){
$req = mysql_query("SELECT * FROM `diary_view` WHERE `user` = '".$u['id']."' AND `diary` = '".$message['id']."' LIMIT 1");
   if (!mysql_num_rows($req)) {
   mysql_query("INSERT INTO `diary_view` SET
   `user` = '".$u['id']."',
   `view` = '1',
   `last_time` = '".time()."',
   `time` = '".time()."',
   `diary` = '".$message['id']."'
   ");
   mysql_query("UPDATE `diary_messages` SET
   `view` = `view`+1
   WHERE `id` = '".$message['id']."'
   ");
   $message['view']++;
   } else {
   $view = mysql_fetch_assoc($req); 
   mysql_query("UPDATE `diary_view` SET
   `view` = `view`+1,
   `last_time` = '".time()."'
   WHERE `id` = '".$view['id']."'
   ");
   }
}

//Рейтинг (Мне нрав)
if($_GET['like'] && $u['id']){
$req = mysql_query("SELECT * FROM `diary_like` WHERE `user` = '".$u['id']."' AND `diary` = '".$message['id']."' LIMIT 1");
   if (!mysql_num_rows($req)) {
   $message['rating']++;
   mysql_query("INSERT INTO `diary_like` SET
   `user` = '".$u['id']."',
   `time` = '".time()."',
   `diary` = '".$message['id']."'
   ");
   mysql_query("UPDATE `diary_messages` SET
   `rating` = '".$message['rating']."'
   WHERE `id` = '".$message['id']."'
   ");
      //Записываем в журнал
      if($message['user'] != $u['id']){
      if($u['sex'] == 'm'){
      $action[0] = 'Отметил';
      $action[1] = 'ему';
      } else {
      $action[0] = 'Отметила';
      $action[1] = 'ей';
      }
      $text = $action[0].' что '.$action[1].' понравилась ваша <a href = "diary.php?act=message&id='.$message['id'].'">запись</a> в дневнике.';
      mysql_query("INSERT INTO `jurnal` SET
      `user` = '".$user['id']."',
      `outuser` = '".$u['id']."',
      `text` = '$text',
      `time` = '".time()."',
      `new` = '1'
      ");
	  }
   }
}

$title = $title.' | Дневники';
include 'head.php';
$name = checkout($message['name']);
$msg = checkout($message['message']);

$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$user['id']."'"), 0);
if($user['id'] == $u['id'])echo '<div class="subtitle"><a href = "page.php?id='.$user['id'].'"> '.$user['login'].'</a> / <a href = "diary.php?act=view&id='.$user['id'].'">Дневник</a></div>';
else echo '<div class="subtitle"><a href = "page.php?id='.$user['id'].'"> '.$user['login'].'</a> / <a href = "diary.php?act=view&id='.$user['id'].'">Дневник</a></div>';
echo '<div class="main_menu">';

echo '<a href = "page.php?id='.$user['id'].'"><b> '.$user['login'].'</b></a> <font color = "green">'.vremya($message['time']).'</font>  : <font color = "#069"><b>'.$name.'</b> <br/><br/>
'.smile($msg).'<br/><br/></font>
';
if (($message['user'] == $u['id']) || ($u['admin'] == 1 || $u['admin'] == 2)) { echo '  <hr><a href = "diary.php?act=edit&id='.$message['id'].'"> Ред запись</a>  | <a href = "diary.php?act=delete&id='.$message['id'].'"> Удалить</a>'; }
echo '<div class="subtitle">';
$req = mysql_query("SELECT * FROM `diary_like` WHERE `user` = '".$u['id']."' AND `diary` = '".$message['id']."' LIMIT 1");
   if (!mysql_num_rows($req)) echo '<img src = "img/like.png">  <a href = "diary.php?act=message&id='.$message['id'].'&like=1">Мне нрав</a> ('.$message['rating'].')'; else echo '<img src = "img/like.png"> Нравится : '.$message['rating'].'';
echo '<br/>

<img src = "img/view.gif"> Просмотров : '.$message['view'].'<br/>
';
echo '</div>';
//Комментарии
   if(isset($_GET['o'])) {
   $o = num($_GET['o']);
   $user = mysql_fetch_assoc(mysql_query("SELECT `login` FROM `users` WHERE `id` = '".$o."'"));
   if($user['login']) $otv = $user['login'].', ';
   }
echo '<div class="title">
<b><img src = "img/comm.png">  Комментарии</b></div><br>  ';

//Удаление
if(isset($_GET['del'])){
$del = num($_GET['del']);
$req = mysql_query("SELECT * FROM `diary_comm` WHERE `id` = '$del' LIMIT 1");
   if (mysql_num_rows($req)){
   $del_comm = mysql_fetch_assoc($req); 
      if(($u['admin'] == 1 || $u['admin'] == 2) || $del_comm['diary'] == $u['id']){
	  
	  mysql_query("DELETE FROM `diary_comm` WHERE `id` = '$del'");
      echo '<div class = "action">Комментарий удален!</div><hr>';
	  }
   }
}

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_comm` WHERE `diary` = '".$message['id']."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 10) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 10 - 10;
$result = mysql_query("SELECT * FROM `diary_comm` WHERE `diary` = '".$message['id']."' ORDER BY `time` DESC LIMIT $start, 10");
   while($comm = mysql_fetch_assoc($result)){
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$comm["user"]."'"));
   $msg = checkout($comm['message']);
   //Вывод
	  echo '<table><tr>';
	     echo '<td VALIGN=top>';
		    ava($user['id'],35);
	     echo '</td>';
		 
		 echo '<td VALIGN=top>';
		    echo ico($user['sex'],$user['admin']).'  <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a> '.onl($user['online'],$system['online_time']); if($user['id'] != $u['id'])  echo ' | <a href = "diary.php?act=message&id='.$message['id'].'&o='.$user['id'].'">Ответить</a>'; 
		    echo '<br/><font color = "#000">'.smile($msg).'</font><br/>
			'.vremya($comm['time']);
			if($u['admin'] == 1 || $u['admin'] == 2 || $comm['diary'] == $u['id']) echo ' | <a href = "diary.php?act=message&id='.$message['id'].'&del='.$comm['id'].'"><img src = "img/delete.gif"></a>';
		 echo '</td>';
	  echo '</tr></table>';
	  echo '</div>';
   }  
   navigation($page, $total,'diary.php?act=message&id='.$message['id'].'&');
}else{
echo '<div class = "center">Комментариев еще нет!</div>';
}
echo ' <form action="diary.php?act=message&id='.$message['id'].'" method="post">';
echo '<textarea cols="20" rows="2" name="message">';
echo $otv;
echo '</textarea><br/>';
echo '<input type="submit" title="Нажмите для отправки" name="submit" class="btn" value="Написать"  class="submit white"/>
</form><hr>';

echo '</div>';
include 'foot.php';
break;


//Новые ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'new':
$title = $title.' | Новые Записи';
include 'head.php';
echo '<div class="title"><a href = "index.php">Visiti.ru</a> / <b>Новые записи</b></div>';
$all_msg = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `diary_messages`"), 0);
$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);

echo '<div class="navigation">
<img src = "img/diary_messages.png"> <a href = "diary.php?">Все записи</a> ('.$all_msg.')<br/>
</div>';

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `time` > '".(time()-(60*60*24))."'"), 0);
if($all > 0){
$total = intval(($all - 1) / 10) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 10 - 10;
$result = mysql_query("SELECT * FROM `diary_messages` WHERE `time` > '".(time()-(60*60*24))."' ORDER BY `time` DESC LIMIT $start, 10");
   while($message = mysql_fetch_assoc($result)){
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$message['user']."' LIMIT 1"));
   $name = checkout($message['name']);
   $ccomm = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_comm` WHERE `diary` = '".$message['id']."'"), 0);
   echo '<table><tr>';
	echo '<td VALIGN=top>';
		    echo ico($user['sex'],$user['admin']).' <a href = "page.php?id='.$user['id'].'"><b> '.$user['login'].'</b></a>'.onl($user['online'],$system['online_time']).'  <font color = "green">'.vremya($message['time']).'</font><br/> '; 
		    echo '
			<img src = "img/diary_messages.png">'.$name.'
	  <br/>
<a href = "diary.php?act=message&id='.$message['id'].'"> Обсудить >>> </a>
			 <img src = "img/comm.png"> '.$ccomm.'
			';
		 
		 echo '</td>';
	  echo '</tr></table>';
	  echo '</div>';
   }
   navigation($page, $total,'diary.php?act=new');
}else{
echo '<div class = "center">Записей пока нет!</div>';
}

include 'foot.php';
break;



//Все записи ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
default:
$title = $title.' | Дневники';
include 'head.php';
echo '<div class="title"><a href = "index.php">Visiti.ru</a> / <b>Дневники</b></div>';
$new = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `diary_messages` WHERE `time` > '".(time()-(60*60*24))."'"), 0);
$cdiary = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages` WHERE `user` = '".$u['id']."'"), 0);

echo '<div class="navigation">
<img src = "img/new.gif"> <a href = "diary.php?act=new">Новые</a> ('.$new.')<br/>
</div>';
echo '<div class="main_menu">';
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_messages`"), 0);
if($all > 0){
$total = intval(($all - 1) / 10) + 1;
$page = num($_GET['page']);
if(empty($page) or $page < 0) $page = 1; 
if($page > $total) $page = $total;
$start = $page * 10 - 10;
$result = mysql_query("SELECT * FROM `diary_messages` ORDER BY `time` DESC LIMIT $start, 10");
   while($message = mysql_fetch_assoc($result)){
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$message['user']."' LIMIT 1"));
   $name = checkout($message['name']);
   $ccomm = mysql_result(mysql_query("SELECT COUNT(*) FROM `diary_comm` WHERE `diary` = '".$message['id']."'"), 0);
   echo '<div class="block_list">';
   echo '<table><tr>';
	     
		 
		 echo '<td VALIGN=top>';
		    echo ico($user['sex'],$user['admin']).' <a href = "page.php?id='.$user['id'].'"><b> '.$user['login'].'</b></a>'.onl($user['online'],$system['online_time']).'  <font color = "green">'.vremya($message['time']).'</font><br/> '; 
		    echo '
			<img src = "img/diary_messages.png">'.$name.'
	  <br/>
<a href = "diary.php?act=message&id='.$message['id'].'"> Обсудить >>> </a>
			 <img src = "img/comm.png"> '.$ccomm.'
			';
		 
		 echo '</td>';
	  echo '</tr></table>';
	  echo '</div>';
   }
   navigation($page, $total,'diary.php?');
}else{
echo '<div class = "center">Записей пока нет!</div>';
}
echo '</div>';
include 'foot.php';
break;
}
?>