<?   
include './system/common.php';
include './system/functions.php';
include './system/user.php';
    
if(!$user) {
header('location: /');
exit;}

$id = _string(_num($_GET['id']));

if($id) {

$ho = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = \''.$id.'\''));

  if(!$ho OR $id == $user['id']) {
header('location: /mail/');   
exit;}
if(isset($_GET['gift'])){//Если отправляем подарок
$title = 'Подарок для '.$ho['login'];    
}else{
$title = 'Диалог с '.$ho['login'];    
}
include './system/h.php';


$_s = 1;
$text = _string($_POST['text']);  
  if(isset($_REQUEST['text'])) {
	  $antiflood = mysql_fetch_array(mysql_query('SELECT * FROM `mail` WHERE `from` = \''.$user['id'].'\' ORDER BY `time` DESC LIMIT 1'));
  if(!isset($_GET['gift'])){
  if(empty($text) or mb_strlen($text,'UTF-8') < 1){
header('Location: /mail/'.$ho['id'].'');
$_SESSION['mes'] = mes('Пустое сообщение!');
exit;}
  if(time() - $antiflood['time'] < 0){
header('Location: /mail/'.$ho['r'].'');
$_SESSION['mes'] = mes('Нельзя писать так часто!');
exit;}
  }
      
        $text = eregi_replace( "[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "*", $text);
        
        $arrReplace = array('.ru',
                                 '.net',
                                 '.com',
                                  '.рф',
                                  '.tk',
                                  '.su',
                                  '.us',
 '.keo', 'http', 'www', 'пробелов', 'ебал', 'чмо', 'пидар', 'сука', 
                                '.mobi',
                                  '.ua',
                                 'хочешь себе такую игру', 'админ лох', 'заходи на сайт', 'ссылку без',
                                 '.ru',
                                
                                'http');

$size = count($arrReplace);
  while($size--){
if(substr_count($text, $arrReplace[$size])){
mysql_query("INSERT INTO `mail` SET `from`='2',`to`='1',`text`=' Пользователь ".$user['login']." | ID: ".$user['id']." нарушает правила игры! Сообщение: ".$text."',`time`='".time()."'");
break;
}
}
$text = str_replace($arrReplace, '*', $text);


if(isset($_GET['gift'])){//Если отправляем подарок
$gifts=abs(intval($_GET['gift']));
$privacy = abs(intval($_POST['privacy']));  
$gift = mysql_fetch_array(mysql_query('SELECT * FROM `gifts` WHERE `id` = "'.$gifts.'"'));
$text_msg='<center>[img=60]/images/gifts/'.$gift['img'].'.png[/img]</center> '.$text.' ';
mysql_query('INSERT INTO `mail` (`from`, `to`, `text`,`time`) VALUES ("'.$user['id'].'", "'.$ho['id'].'", "'.$text_msg.'", "'.time().'")');	

  mysql_query('UPDATE `users` SET `g` = `g` - "10" WHERE `id` = "'.$user['id'].'" ');
  mysql_query("INSERT INTO `gifts_user` SET `user` = '".$user['id']."', `komy` = '".$ho['id']."', `time` = '".time()."', `img` = '".$gift['img']."', `text` = '".$text."', `privacy` = '".$privacy."' ");
}else{//Простое сообщение

mysql_query('UPDATE `users` SET `s` = `s` - '.$_s.' WHERE `id` = "'.$user['id'].'" ');
mysql_query('INSERT INTO `mail` (`from`, `to`, `text`,`time`) VALUES ("'.$user['id'].'", "'.$ho['id'].'", "'.$text.'", "'.time().'")');
}
   if(mysql_result(mysql_query('SELECT COUNT(*) FROM `contacts` WHERE `ho` = "'.$user['id'].'" AND `user` = "'.$ho['id'].'"'),0) == 0) {//Проверяем есть ли контакт
 if(mysql_result(mysql_query('SELECT * FROM `contacts` WHERE `ho` = "'.$user['id'].'" AND `user` = "'.$ho['id'].'" '),0) == 0) {
mysql_query('INSERT INTO `contacts` (`ho`, `user`, `time`) VALUES ("'.$user['id'].'", "'.$ho['id'].'", "'.time().'")');
 }
}
  if(mysql_result(mysql_query('SELECT COUNT(*) FROM `contacts` WHERE `user` = \''.$user['id'].'\' AND `ho` = \''.$ho['id'].'\''),0) == 0) {//Проверяем есть ли контакт
  if(mysql_result(mysql_query('SELECT * FROM `contacts` WHERE `ho` = "'.$ho['id'].'" AND `user` = "'.$user['id'].'" '),0) == 0) {
mysql_query('INSERT INTO `contacts` (`user`, `ho`, `time`) VALUES ("'.$user['id'].'", "'.$ho['id'].'", "'.time().'")');
  }
}

                                                 
mysql_query('UPDATE `contacts` SET `time` = \''.time().'\' WHERE `user` = \''.$user['id'].'\' AND `ho` = \''.$ho['id'].'\'');   
mysql_query('UPDATE `contacts` SET `time` = \''.time().'\' WHERE `ho` = \''.$user['id'].'\' AND `user` = \''.$ho['id'].'\'');
     
header('location: /mail/'.$ho['id'].'/'); 
if(isset($_GET['gift'])){
$_SESSION['mes'] = mes('Подарок отправлен!');	
}else{
$_SESSION['mes'] = mes('Сообщение отправленно!');
}
exit;   
  }

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

     echo' '.$_SESSION['mes'].'  ';
    $_SESSION['mes']=NULL; //Удаляем сесию
	
	 if(isset($_GET['gift'])){//Если отправляем подарок
 $gifts=abs(intval($_GET['gift']));
$gift = mysql_fetch_array(mysql_query('SELECT * FROM `gifts` WHERE `id` = "'.$gifts.'"'));
$a= "?text&gifta=".$gift['img'];
echo'<div class="empty_block">
<center>
<img src="/images/gifts/'.$gift['img'].'.png" alt="*"/>
<br/>
 <small><font color="#90b0c0"> цена: </font> <img src="/images/ico/png/gold.png" alt="*"/> <font color="gold"> '.$gift['g'].' </font></small>
 
 <form action="/mail/'.$ho['id'].'?gift='.$gifts.'" method="post">
    (Сообщение, не обязательно)<br/><textarea name="text" style="width: 70%;"></textarea><br/>
    <input class="button" name="send_message" value="Отправить" type="submit">
  
  </center>  
   <input name="privacy" value="1" type="radio" checked> Виден всем <br/>
   <input name="privacy" value="2" type="radio"> Показывать текст и моё имя только получателю 
   </form> 
 </div>
 <div class="line"></div>	';
	
	 }else{//Простое сообщение
if($ho['id']!='2'){
  echo '<div class="empty_block item_center">
  <form action="/mail/'.$ho['id'].'/" method="post">
    Сообщение:<br/><textarea name="text" style="width: 70%;"></textarea><br/>
    <input class="button" name="send_message" value="Отправить" type="submit">
  </form>
  <center><font color="#909090"><small>Стоимость сообщения  <img src="/images/ico/png/silver.png" alt="*"/> '.$_s.'</font></small></font></center>
</div>
<div class="line"></div>
';
}
	 }
$max = 10;
$count = mysql_result(mysql_query('SELECT COUNT(*) FROM `mail` WHERE `from` = "'.$user['id'].'" AND `to` = "'.$ho['id'].'" OR `to` = "'.$user['id'].'" AND `from` = "'.$ho['id'].'"'),0);
$pages = ceil($count/$max);
$page = _string(_num($_GET['page']));

if($page > $pages) $page = $pages;
if($page < 1) $page = 1;
$start = $page * $max - $max;

if($count > 0) {
$col = array('#ffffff', '#f09060', '#90c0c0');
$q = mysql_query('SELECT * FROM `mail` WHERE `from` = \''.$user['id'].'\' AND `to` = \''.$ho['id'].'\' OR `to` = \''.$user['id'].'\' AND `from` = \''.$ho['id'].'\' ORDER BY `time` DESC LIMIT '.$start.', '.$max.'');

while($row = mysql_fetch_array($q)) {
$from = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = \''.$row['from'].'\''));

echo '<div class="empty_block">
<span style="float: right; color: '.(($row['read'] == 0) ? '#90c090':'#909090').';"> <small>'.vremja($row['time']).'</small> </span>
<a href="/user/'.$from['id'].'/"> '.nick($from['id']).' </a><br/>
<font color="'.color($from['id']).'">'.bbcode(smile($row['text'])).'</font></div>
<div class="line"></div>';


if($row['to'] == $user['id'] && $row['read'] == 0) mysql_query('UPDATE `mail` SET `read` = \'1\' WHERE `id` = \''.$row['id'].'\'');
}

echo ''.pages('/mail/'.$id.'/?').'
<div class="line"></div>';
}else{
echo '<div class="line"></div>
<div class="empty_block item_center"> Сообщений нет </div>
<div class="line"></div>';
}
echo '
<div class="block_link"><a href="/choose_gifts/'.$ho['id'].'?tip=0/"><img src="/images/ico/png/gift_s.png" alt="*"/> Отправить подарок </a></div>
<div class="line"></div>
<div class="block_link"><a href="/mail"><img src="/images/ico/png/back.png" alt="*"> Почта</a></div>
<div class="line"></div>';

include './system/f.php';
}else{
  
  
  
  
$title = 'Почта';    
include './system/h.php';
echo '<div class="title">'.$title.'</div>';

$max = 10;
$count = mysql_result(mysql_query('SELECT COUNT(*) FROM `contacts` WHERE `user` = \''.$user['id'].'\''),0);
$pages = ceil($count/$max);
$page = _string(_num($_GET['page']));

if($page > $pages) $page = $pages;
if($page < 1) $page = 1;
$start = $page * $max - $max;

  if($count > 0) {

  

    $q = mysql_query('SELECT * FROM `contacts` WHERE `user` = \''.$user['id'].'\' ORDER BY `time` DESC LIMIT '.$start.', '.$max.'');

    while($row = mysql_fetch_array($q)) {

      $ho = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = \''.$row['ho'].'\''));
      $lost = mysql_fetch_array(mysql_query('SELECT * FROM `mail` WHERE `from` = \''.$user['id'].'\' AND `to` = \''.$row['ho'].'\' OR `to` = \''.$user['id'].'\' AND `from` = \''.$row['ho'].'\' ORDER BY `time` DESC LIMIT 1'));

      echo '<a href="/mail/'.$row['ho'].'/"><div class="empty_block">
	  '.nick($row['ho']).'
      <span style="float: right; color: '.(($lost['read'] == 0 AND $lost['from'] == $row['ho'] AND $lost['to'] = $user['id']) ? '#90c090':'#909090').';"> <small>'.vremja($row['time']).'</small> </span>';
  
      $new = mysql_result(mysql_query('SELECT COUNT(*) FROM `mail` WHERE `from` = "'.$row['ho'].'" AND `to` = "'.$user['id'].'" AND `read` = "0" '),0);
       if($new != 0) echo '<font color="#90c090"> <small> +'.$new.' </small></font>';
       
  
    if($lost){ echo '<br/>  
<font color="'.(($lost['read'] == 0 AND $lost['to'] == $user['id']) ? '#90c090':'#909090').'"> '.(mb_strlen(bbcode(smile($lost['text'])),'UTF-8') >= 255 ? mb_substr(bbcode(smile($lost['text'])),0, 255, 'UTF-8').'...':bbcode(smile($lost['text']))).' </font>';
    }
echo '</font></div></a>
<div class="line"></div>';
	
	
    }


echo ''.pages('/mail/?').'
<div class="line"></div>';

}else{
echo '<div class="line"></div>
<div class="empty_block item_center">Почта пуста</div>
<div class="line"></div>';
}

include './system/f.php';
}

?>