<?


include 'connect.php';

switch($_GET['act'])
{
//Создание новости ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'add_news':
if ($u['admin'] == 1){

if (isset($_POST['submit']) and isset($_POST['name']) and isset($_POST['message'])) {
$name = check(substr($_POST['name'], 0, 100));
$message = check(substr($_POST['message'], 0, 10000));
mysql_query("INSERT INTO `news` SET
`user` = '".$u['id']."',
`time` = '".time()."',
`name` = '$name',
`message` = '$message'
");
$id = mysql_insert_id();

//Записываем в журнал
$users_r = mysql_query("SELECT `id` FROM `users` WHERE `id` <> '".$u['id']."'");
while ($users = mysql_fetch_assoc($users_r)) {
      if($u['sex'] == 'm'){
      $action[0] = 'Опубликовал';
      } else {
      $action[0] = 'Опубликовала';
      }
      $text = $action[0].' <a href = "news.php?act=view&id='.$id.'">свежие новости</a>.';
      mysql_query("INSERT INTO `lenta` SET
      `user` = '".$users['id']."',
      `outuser` = '".$u['id']."',
      `text` = '$text',
      `time` = '".time()."',
      `new` = '1'
      ");
}
header ("Location: news.php");

} else {

$title = $title.' | Новости';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "news.php">Новости</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Добавить новость</b>';
echo '</div>';

echo '<div class="block_action">';
//Блоки ввода
echo '<form action=news.php?act=add_news method=post>
Название: <br/><textarea cols="20" rows="1" name="name" style="width: 97%"></textarea><br/>
Сообщение: <br/><textarea cols="100%" rows="3" 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_news':
if ($u['admin'] == 1){
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `news` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $news = mysql_fetch_assoc($req);
   }
}
if($news){

      if (isset($_POST['submit']) and isset($_POST['name']) and isset($_POST['message'])) {
      $name = check(substr($_POST['name'], 0, 100));
	  $message = check(substr($_POST['message'], 0, 10000));
      mysql_query("UPDATE `news` SET
      `name` = '$name',
	  `message` = '$message'
      WHERE `id` = '$id'
      ");
      header ("Location: news.php");
      } else {
$title = $title.' | Новости';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "news.php">Новости</a>';
echo '</div>';

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

echo '<div class="block_action">';
      $name = checkout($news['name']);
	  $message = checkout($news['message']);
      echo '<form action="news.php?act=edit_news&amp;id='.$id.'" method="post">';
      echo '<textarea cols="20" rows="1" name="name" style="width: 97%">'.$name.'</textarea><br/>';
	  echo '<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';
}
}
break;

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

      if (isset($_POST['submit'])) {
	  mysql_query("DELETE FROM `news` WHERE `id` = '".$news['id']."'");
	  mysql_query("DELETE FROM `news_comm` WHERE `id` = '".$news['id']."'");
      header ("Location: news.php");
      } else {
$title = $title.' | Новости';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "news.php">Новости</a>';
echo '</div>';

echo '<div class="title">';
echo '<b>Удалить новость</b>';
echo '</div>';

echo '<div class="block_action">';
      $name = checkout($news['name']);
	  echo 'Вы уверены, что хотите удалить новость <a href = "news.php?act=view&id='.$id.'">'.$name.'</a>?<br/>';
      echo '<form action="news.php?act=delete_news&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 'view':
//Если id получен 
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `news` WHERE `id` = '$id' LIMIT 1");
   if (mysql_num_rows($req)) {
   $news = mysql_fetch_assoc($req);
   }
}
//Если существует
if ($news){
//Запись сообщения, если сообщение получено
if($u['id'] and $_POST['message']){
$message = check(substr($_POST['message'], 0, 500));
   //Проверяем на флуд
   $flood = mysql_query("SELECT `time` FROM `news_comm` WHERE `user` = '".$u['id']."' AND `time` > '" . (time() - 3) . "'");
   if (mysql_num_rows($flood)) {
   header ("Location: news.php?act=view&id=".$news['id']."");
   exit;
   }
   // Проверка на одинаковые сообщения
   $req = mysql_query("SELECT * FROM `news_comm` WHERE `user` = '".$u['id']."' ORDER BY `time` DESC");
   $res = mysql_fetch_array($req);
   if ($res['message'] == $message) {
   header ("Location: news.php?act=view&id=".$news['id']."");
   exit;
   }
// Вставляем сообщение в базу
mysql_query("INSERT INTO `news_comm` SET
`user` = '".$u['id']."',
`time` = '".time()."',
`message` = '$message',
`news` = '".$news['id']."'
");

header ("Location: news.php?act=view&id=".$news['id']."");
}

$name_news = checkout($news['name']);
$title = $title.' | Новости | '.$name_news.'';
include 'head.php';

echo '<div class="block_back">';
echo '<a href = "news.php">Новости</a>/ '.$name_news.' ';
echo '</div>';

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

echo '<font color = "#565656"><img src="img/rss_big.png"/> <b> '.$name_news.' </b></font><font color="green">  ('.vremya($news['time']).')</font></div>';
echo '<div class="block_action">';

$message_news = checkout($news['message']);
echo '<font color = "#000000">'.smiles($message_news).'</font><br>

<br><font color = "#777777">Добавил:</font> <a href = "page.php?id='.$news['user'].'"><b>'.login($news['user']).'</b></a></br>';
if ($u['admin'] == 1) echo '<br><a href = "news.php?act=edit_news&id='.$news['id'].'">Изменить</a> | <a href = "news.php?act=delete_news&id='.$news['id'].'">Удалить</a>'; 


echo '</div></div>';

echo '<div class="title"><img src="img/text.png"/> <b> Комментарии :</b></div>';


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

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `news_comm` WHERE `news` = '".$news['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 `news_comm` WHERE `news` = '".$news['id']."' ORDER BY `time` DESC LIMIT $start, 15");
   while($comm = mysql_fetch_assoc($result)){
   $user = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '".$comm["user"]."'"));
   $message = checkout($comm['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'].'">'.$user['login'].'</a> '.online($user['online']).' ('.vremya($comm['time']).')'; if($u['admin'] == 1 || $u['admin'] == 2){ echo '  <a href = "news.php?act=view&id='.$news['id'].'&del='.$comm['id'].'"><img src = "img/delete.gif"></a>'; }
	echo '<br/><font color = "#000">';
	  smiles($message);
	  echo '</font><br/>';
	echo '</td>
  </tr>
</table>';
echo '</div>';
   }  
   navigation($page, $total,'news.php?act=view&id='.$news['id'].'&');
}else{
echo 'Комментариев еще нет!';
}
echo '<div class="block_action2">';
//Блок ввода сообщения
if ($u['id']) {
$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="news.php?act=view&id='.$news['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'/>
</form><hr>";
} else {
echo '<div class="act">Для возможности комментировать новость пройдите <a href = "index.php"><b>авторизацию</b></a> или 
<a href = "reg.php"><b>зарегистрируйтесь</b></a>!:)</div>';
}
echo '</div>';
include 'foot.php';
} else {
header ("Location: news.php");
}
break;

//Список новостей ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
default:
$title = $title.' | Новости';
include 'head.php';

echo '<div class="title">';
echo '<b>Новости</b>';
echo '</div>';

if($u['admin'] == 1) echo '<div class="block"><img src="img/add.png"/><a href = "?act=add_news"><b>Добавить новость</b></a></div>';

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `news`"), 0);
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 `news` ORDER BY `time` DESC LIMIT $start, 10");
   while($news = mysql_fetch_assoc($result)){
	  //Вывод
	  echo '<div class="title">';
      $name = checkout($news['name']);
      //Вырезаем сообщение если больше 25 символов
      if (iconv_strlen($news['message'], 'UTF-8') > 50) {
      $news['message'] = iconv_substr($news['message'], 0, 25, 'UTF-8');
      $news['message']=''.$news['message'].'...';
      }
	  $message = checkout($news['message']);
	  
	  echo '<img src="img/rss.png"/><a href = "news.php?act=view&id='.$news['id'].'"><b>'.$name.'</b></a><font color="green"> ('.vremya($news['time']).')</font></div>';
	  
	  echo '<div class="block_list">'.$message.'</div>';
echo '<div class="bloc">';

echo '</div>';
     
   }  
   navigation($page, $total,'news.php?');
}else{
echo 'Новостей не найдено!';
}

include 'foot.php';
break;
}
?>