<?



include 'connect.php';

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

switch ($_GET['act']) {
//############################################# Отправка сообщения #############################################
case 'ok':
//--------------- Проверяю пользователя ------------------------------
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT `id` FROM `users` WHERE `id` = '$id' LIMIT 1");
     if (mysql_num_rows($req)){
     $user = mysql_fetch_assoc($req);
     }
}
if(empty($user)){header ("Location: ?");exit;}

//--------------- Отправляем ------------------------------
if (isset($_POST['message']) && $_POST['message']){
     //Себе нельзя
	 if($user['id'] == $u['id']){header ("Location: ?");exit;}

//Проверяем на флуд
$flood = mysql_query("SELECT `time` FROM `mail_messages` WHERE `user` = '".$u['id']."' AND `time` > '" . (time() - 3) . "'");
     if (mysql_num_rows($flood)) {header ("Location: ?act=view&id=".$user["id"]."");exit;}

//Создаем контакт, если нет
$req = mysql_query("SELECT * FROM `mail_contacts` WHERE `user` = '".$u['id']."' and `contact` = '".$user['id']."' LIMIT 1");
     if (mysql_num_rows($req) == 0)
     mysql_query("INSERT INTO `mail_contacts` SET
     `user` = '".$u['id']."',
     `contact` = '".$user['id']."',
	 `time` = '".time()."'
     ");

//Создаем контакт, если нет у контакта
$req = mysql_query("SELECT * FROM `mail_contacts` WHERE `user` = '".$user['id']."' and `contact` = '".$u['id']."' LIMIT 1");
     if (mysql_num_rows($req) == 0)
     mysql_query("INSERT INTO `mail_contacts` SET
     `user` = '".$user['id']."',
     `contact` = '".$u['id']."',
	 `time` = '".time()."'
     ");

//Записывем сообщение
$message = check(substr($_POST['message'], 0, 2000));
mysql_query("INSERT INTO `mail_messages` SET
`user` = '".$user['id']."',
`outuser` = '".$u['id']."',
`inuser` = '".$user['id']."',
`message` = '$message',
`time` = '".time()."',
`new` = '1'
");
$id=mysql_insert_id();
mysql_query("INSERT INTO `mail_messages` SET
`user` = '".$u['id']."',
`outuser` = '".$u['id']."',
`inuser` = '".$user['id']."',
`message` = '$message',
`time` = '".time()."',
`new` = '1',
`id2` = '$id'
");

//Обновляем последнее время в контактах
mysql_query("UPDATE `mail_contacts` SET 
`time` = '".time()."' 
WHERE 
(`user` = '".$u['id']."' and `contact` = '".$user['id']."') or 
(`user` = '".$user['id']."' and `contact` = '".$u['id']."')
");

//Добавляем в счетчик новое сообщение
mysql_query("UPDATE `users` SET 
`count_mail` = `count_mail`+1
WHERE 
`id` = '".$user['id']."'
");

//Готово
header ("Location: mail.php?act=view&id=".$user["id"]."&ok");
exit;
}

//Если не готово
header ("Location: mail.php?act=view&id=".$user["id"]."");
break;

//############################################# Диалог с пользователем #############################################
case 'view':



//--------------- Проверяю пользователя ------------------------------
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT `id`,`login`,`sex`,`admin`,`online` FROM `users` WHERE `id` = '$id' LIMIT 1");
     if (mysql_num_rows($req)){
     $user = mysql_fetch_assoc($req);
     }
}
if(empty($user)){header ("Location: ?");exit;}

//--------------- Убираем новизну сообщений ------------------------------

$req = mysql_query("SELECT `id` FROM `mail_messages` WHERE `user` = '".$u['id']."' and `outuser` = '".$user['id']."' and `inuser` = '".$u['id']."' and `new` = '1'");
$count_req = mysql_num_rows($req);

if($count_req){
//Вычитаем из счетчика новых сообщений
$u['count_mail'] = $u['count_mail']-$count_req;
mysql_query("UPDATE `users` SET 
`count_mail` = `count_mail`-'".$count_req."'
WHERE 
`id` = '".$u['id']."'
");

     //Меняем в базе сообщений
     while ($res = mysql_fetch_assoc($req)) {
     mysql_query("UPDATE `mail_messages` SET `new` = 0 WHERE `id` = '".$res['id']."'");
     mysql_query("UPDATE `mail_messages` SET `new` = 0 WHERE `id2` = '".$res['id']."'");
     }
}

//--------------- Вывод ------------------------------
$title = $title.' | Сообщения';
include 'head.php';
echo '<div class="title"><img src= "img/mail.gif"> Сообщения</div>';
$mi = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_contacts` WHERE `user` = '".$u['id']."'"), 0);
echo '<div class="subtitle"><a href = "mail.php">Диалоги ('.$mi.')</a> | <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a></div>';
echo '<div class="main_menu">';

//Если отправлено
if(isset($_GET['ok'])) show_ok('Сообщение отправлено');

//Удаление
if(isset($_GET['del'])){
$del = num($_GET['del']);
$req = mysql_query("SELECT * FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."')) and `id` = '$del' LIMIT 1");
	 if (mysql_num_rows($req)) {
     mysql_query("DELETE FROM `mail_messages` WHERE `id` = '$del'");
	 //Удаляем диалог если сообщений не осталось
	 $req = mysql_query("SELECT * FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."')) LIMIT 1");
	      if (mysql_num_rows($req) == 0) {
	      mysql_query("DELETE FROM `mail_contacts` WHERE `user` = '".$u['id']."' and `contact` = '".$user['id']."'");
	      }
	//Обновляем счетчик новых сообщений
	$mn = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_messages` WHERE `user` = '".$u['id']."' and `inuser` = '".$u['id']."' and `new` = '1'"), 0);
    mysql_query("UPDATE `users` SET `count_mail` = '$mn' WHERE `id` = '".$u['id']."'");
	echo '<div class = "action">Сообщение удалено!</div><hr>';
    }
}

//Спам
if(isset($_GET['spam'])){
$spam = num($_GET['spam']);
$req = mysql_query("SELECT * FROM `mail_messages` WHERE (`user` = '".$u['id']."') and (`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') and `id` = '$spam' LIMIT 1");
	 if (mysql_num_rows($req)) {
	 $msg = mysql_fetch_assoc($req);
	 //Записываем в журнал спама
	 $message = check($msg['message']);
	 mysql_query("INSERT INTO `spam` SET
     `user` = '".$u['id']."',
     `spamer` = '".$user['id']."',
     `message` = '$message',
     `type` = 'mail',
	 `time` = '".time()."'
      ");
	 
     mysql_query("DELETE FROM `mail_messages` WHERE `id` = '$spam'");
	 //Удаляем диалог если сообщений не осталось
	 $req = mysql_query("SELECT * FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."')) LIMIT 1");
	      if (mysql_num_rows($req) == 0) {
	      mysql_query("DELETE FROM `mail_contacts` WHERE `user` = '".$u['id']."' and `contact` = '".$user['id']."'");
	      }
	//Обновляем счетчик новых сообщений
	$mn = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_messages` WHERE `user` = '".$u['id']."' and `inuser` = '".$u['id']."' and `new` = '1'"), 0);
    mysql_query("UPDATE `users` SET `count_mail` = '$mn' WHERE `id` = '".$u['id']."'");
	echo '<div class = "action">Сообщение отправлено администрации!</div><hr>';
    }
}

echo '<form action="?act=ok&id='.$user['id'].'" method="post">';
echo '<textarea cols="25" rows="3" name="message" style="width: 97%"></textarea><br>';
echo '<input type="submit" name="submit" class="btn" value="Отправить" class="submit">
<a href = "?act=view&id='.$user['id'].'&refresh='.rand(1,9999).'"><button type="button" class="btn"> Обновить</button></a>  <a href = "smiles.php"><button type="button" class="btn">Смайлы</button></a>
</form><hr>'; 



//Сообщений на страницу
if($u['setting_mail_list']) $count = $u['setting_mail_list']; else $count = 10;

//Выводим сообщения
$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."'))"), 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 `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."')) ORDER BY `time` DESC LIMIT $start, $count");
     while($mail = mysql_fetch_assoc($result)){
	 //Выбираем контакт
     $contact = mysql_fetch_assoc(mysql_query("SELECT `id`,`login`,`sex`,`admin`,`online` FROM `users` WHERE `id` = '".$mail["outuser"]."'"));
     $message = checkout($mail['message']);
     //Вывод
if($mail['new'] == 1)echo '<div class="new">';
else
     echo '<div class="block_list">';
   
	 echo '<table><tr>';
	 echo '<td VALIGN=top>';
        ava($contact['id'],25);
     echo '</td><td VALIGN=top>';
        echo ''.ico($contact['sex'],$contact['admin']).' <a href = "page.php?id='.$contact['id'].'">'.$contact['login'].' </a>';
if($mail['new'] == 1) echo "<font color='red'> ( Не прочитано )</font>";
echo ' '.online($contact['online']).'';
 echo '| <a href = "?act=view&id='.$user['id'].'&del='.$mail['id'].'">Удалить</a>';
             if($contact['id'] != $u['id']) echo ' | <a href = "?act=view&id='.$user['id'].'&spam='.$mail['id'].'">Спам </a>'; 
        echo '<br/> <font color = "black">'.smile($message).'</font>';
        echo '<br><font color = "#777777"><small>'.vremya($mail['time']).'</small> </div>';
     echo '</td>';
	 echo '</tr></table>';
	 if($mail['new'] == 1) echo '</div>';
     echo '</div>';
     }
navigation($page, $total,'?act=view&id='.$user['id'].'&');
}else{
echo '<div class = "center">История переписки пуста!</div>';
}
echo '</div>';
include 'foot.php';
break;

//############################################# Новое #############################################
case 'write':

if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1");
     if (mysql_num_rows($req) and $id != $u['id']) {
     header ("Location: ?act=view&id=".$id."");
	 exit;
     }
} else {
header ("Location: ?");
exit;
}
break;

//############################################# Удаление диалога #############################################
case 'delete_dialog':

//--------------- Проверяю пользователя ------------------------------
if(isset($_GET['id'])){
$id=num($_GET['id']);
$req = mysql_query("SELECT `id`,`login`,`sex`,`admin`,`online` FROM `users` WHERE `id` = '$id' LIMIT 1");
     if (mysql_num_rows($req)){
     $user = mysql_fetch_assoc($req);
     }
}
if(empty($user)){header ("Location: ?");exit;}

//Проверяем есть ли диалог
$req = mysql_query("SELECT * FROM `mail_contacts` WHERE `user` = '".$u['id']."' and `contact` = '".$user['id']."' LIMIT 1");
     if (mysql_num_rows($req) == 0){header ("Location: ?");exit;}

if (isset($_POST['submit'])) {
mysql_query("DELETE FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."'))");
mysql_query("DELETE FROM `mail_contacts` WHERE `user` = '".$u['id']."' and `contact` = '".$user['id']."'");
//Обновляем счетчик новых сообщений
$mn = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_messages` WHERE `user` = '".$u['id']."' and `inuser` = '".$u['id']."' and `new` = '1'"), 0);
mysql_query("UPDATE `users` SET `count_mail` = '$mn' WHERE `id` = '".$u['id']."'");
header ("Location: ?");
exit;
}

$title = $title.' | Сообщения';
include 'head.php';
echo '<div class="title"><img src= "img/mail.gif"> Сообщения</div>';
$mi = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_contacts` WHERE `user` = '".$u['id']."'"), 0);
echo '<div class="subtitle"><a href = "?">Диалоги ('.$mi.')</a> | <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a></div>';
echo '<div class="main_menu">';
echo 'Вы действительно хотите удалить диалог с пользователем <a href = "page.php?id='.$user['id'].'">'.$user['login'].'</a>?';
echo '<form action="?act=delete_dialog&id='.$user['id'].'" method="post">';
echo '<input type="submit" name="submit" value="Да, удалить" class="submit white"/>';
echo '</form></div>';
echo '</div>';
include 'foot.php';
break;

//############################################# Диалоги #############################################
default:

$title = $title.' | Сообщения';
include 'head.php';
echo '<div class="title"><img src= "img/mail.gif"> Сообщения</div>';

//Заголовок раздела
echo '<div class="subtitle">';
$mi = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_contacts` WHERE `user` = '".$u['id']."'"), 0);
echo '<b>Диалоги ('.$mi.')</b>';
echo '</div>';
echo '<div class="main_menu">';

//Сообщений на страницу
if($u['setting_mail_list']) $count = $u['setting_mail_list']; else $count = 10;

$all = mysql_result(mysql_query("SELECT COUNT(*) FROM `mail_contacts` WHERE `user` = '".$u['id']."'"), 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 `mail_contacts` WHERE `user` = '".$u['id']."' ORDER BY `time` DESC LIMIT $start, $count");
     while($mail = mysql_fetch_assoc($result)){
	 //Выбираем контакт
     $user = mysql_fetch_assoc(mysql_query("SELECT `id`,`login`,`sex`,`admin`,`online` FROM `users` WHERE `id` = '".$mail["contact"]."'"));
     //Выбираем последнее сообщение
	 $last = mysql_fetch_array(mysql_query("SELECT * FROM `mail_messages` WHERE (`user` = '".$u['id']."') and ((`inuser` = '".$u['id']."' and `outuser` = '".$user['id']."') or (`inuser` = '".$user['id']."' and `outuser` = '".$u['id']."')) ORDER BY `time` DESC"));
	      //Вырезаем сообщение если больше 25 символов
          if (iconv_strlen($last['message'], 'UTF-8') > 25) {
          $last['message'] = iconv_substr($last['message'], 0, 25, 'UTF-8');
          $last['message']=''.$last['message'].'...';
          }
     $message = checkout($last['message']);
     //Вывод
          if($last['new'] == 1 and $last['outuser'] != $u['id']) 
	      echo '<div class="new">';
		  else
		  echo '<div class="block_list">';
     echo '<table><tr><td VALIGN=top>';
        ava($user['id'],50);
     echo '</td><td VALIGN=top>';
        echo ''.ico($user['sex'],$user['admin']).'';

echo '<a href = "mail.php?act=view&id='.$user['id'].'">'.$user['login'].'';
/*
if($last['new'] == 1 and $last['outuser'] != $u['id'])mysql_query("UPDATE `users` SET `count_mail` = `count_mail`+1 WHERE `id` = '".$user['id']."'
*/
echo '</a> '.online($user['online']).'</font>';

echo '| <a href = "?act=delete_dialog&id='.$user['id'].'">Удалить</a>';  
        echo '<br/><br/>';
             
             
     
        
		
     echo '</td></tr></table>';
     echo '</div>';
     }
navigation($page, $total,'?');
}else{
echo '<div class = "center">У Вас нет ни одного диалога с пользователями!</div>';
}
echo '</div>';
include 'foot.php';
break;
}

?>