<?

include_once '../../sys/inc/start.php';
include_once '../../sys/inc/compress.php';
include_once '../../sys/inc/sess.php';
include_once '../../sys/inc/home.php';
include_once '../../sys/inc/settings.php';
include_once '../../sys/inc/db_connect.php';
include_once '../../sys/inc/ipua.php';
include_once '../../sys/inc/fnc.php';
include_once '../../sys/inc/user.php';

only_reg();
if ((!isset($_SESSION['refer']) || $_SESSION['refer']==NULL)
&& isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']!=NULL &&
!preg_match('#mail\.php#',$_SERVER['HTTP_REFERER']))
$_SESSION['refer']=str_replace('&','&amp;',preg_replace('#^http://[^/]*/#','/', $_SERVER['HTTP_REFERER']));
if (!isset($_GET['id'])){
header("Location: /index.php?".SID);
exit;
}
$ank=get_user($_GET['id']);
if (!$ank){
header("Location: /index.php?".SID);
exit;
}

//Помечаем сообщения как прочитанные
mysql_query("UPDATE `mail` SET `read` = '1' WHERE `id_kont` = '$user[id]' AND `id_user` = '$ank[id]'");
$ank2 = get_user($ank['id']);
if ($ank2['id']==0){
$set['title']=''.$ank2[ank_name].' '.$ank2[ank_fam].'';
}else{
$set['title']=''.user::nick($ank['id'],0).'';
}
include_once '../../sys/inc/thead.php';
title();



//Бан пользователя
if ($user['group_access'] < 1 && mysql_result(mysql_query("SELECT COUNT(*) FROM `ban` WHERE `razdel` = 'all' AND `id_user` = '$ank[id]' AND (`time` > '$time' OR `view` = '0')"), 0)!=0){
$ank=get_user($ank['id']);
$set['title']=$ank['nick'].' - страничка ';
include_once '../../sys/inc/thead.php';
title();
aut();

echo "<div class='nav2'>";
echo "<b><font color=red>Этот пользователь заблокирован!</font></b><br /> \n";
echo "</div>\n";

include_once '../../sys/inc/tfoot.php';
exit;
}	

if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `black_list` WHERE `id_user` = '".$ank['id']."' AND `id_black_user` = '$user[id]' "), 0)!=0){
$set['title']=$ank['nick'].' ';
include_once '../../sys/inc/thead.php';
title();
aut();

echo "<table style='width:100%
' cellspacing='0' cellpadding='0'><tr>";
echo '<div class="menu">';
echo status($ank['id']);
if ((user_access('user_ban_set') || user_access('user_ban_set_h') || user_access('user_ban_unset')) && $ank['id'] != $user['id'])
echo "<span style='float:right;'><a href='/adm_panel/ban.php?id=$ank[id]'><font color=red>[Бан]</font></a></span>";
if ($ank['ank_name']!=NULL)echo " <b>$ank[ank_name]</b>\n"; 
else
echo "<b>$ank[nick]</b>";
if ($ank['ank_fam']!=NULL)echo " <b>$ank[ank_fam]</b>\n"; 
echo online($ank['id']) . " ";
echo '</div>';

echo "<div class='mess'>";
echo "<b><font color=red>Этот пользователь занес вас в черный список!</font></b><br /> \n";
echo "</div>\n";

include_once '../../sys/inc/tfoot.php';
exit;

}

//Добавляем в контакты
if ($user['add_konts']==2 && mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"),0)==0)
mysql_query("INSERT INTO `users_konts` (`id_user`, `id_kont`, `time`) VALUES ('$user[id]', '$ank[id]', '$time')");
//Обновление сведений о контакте
mysql_query("UPDATE `users_konts` SET `new_msg` = '0' WHERE `id_kont` = '$ank[id]' AND `id_user` = '$user[id]' LIMIT 1");

if (isset($_POST['refresh'])){
header("Location: mail.php?id=$ank[id]".SID);
exit;
}

if (isset($_POST['msg']) && $ank['id']!=0 && !isset($_GET['spam'])){
if ($user['level']==0 && mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_kont` = '$user[id]' AND `id_user` = '$ank[id]'"), 0)==0){
}

$msg=$_POST['msg'];
if (isset($_POST['translit']) && $_POST['translit']==1)$msg=translit($msg);
if (strlen2($msg)>1024)$err[]='Сообщение превышает 1024 символа';
if (strlen2($msg)<2)$err[]='Слишком короткое сообщение';
$mat=antimat($msg);
if ($mat)$err[]='В тексте сообщения обнаружен мат: '.$mat;

if (!isset($err) && mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' AND `time` > '".($time-360)."' AND `msg` = '".my_esc($msg)."'"),0)==0){
//Отправка сообщения
mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('$user[id]', '$ank[id]', '".my_esc($msg)."', '$time')");
if ($ank['id'] != 1 && $user['id'] != 1) {
$one = get_user(1);
$msg1 = 'Возможно информация будет вам интересна, пользователь [url=/info.php?id='.$user['id'].'] '.$user['nick'].'[/url] написал сообщение пользователю [url=/info.php?id='.$ank['id'].']'.$ank['nick'].'[/url] [b]сообщение:[/b] '.$msg.' ';
if (preg_match("/.ru|.com|создатель|хозяин|админ|admin|сайт|twipas|".substr($one['nick'], 0, -3)."|".substr($one['ank_name'], 0, -3)."|сайт|http|.net|.su|.mobi/i", $msg) && mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' AND `time` > '".($time-360)."' AND `msg` = '".my_esc($msg1)."'"),0)==0) {
mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '1', '".$msg1."', '$time')");
}
}

//Добавляем в контакты
if ($user['add_konts']==1 && mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"),0)==0)
mysql_query("INSERT INTO `users_konts` (`id_user`, `id_kont`, `time`) VALUES ('$user[id]', '$ank[id]', '$time')");
//Обновление сведений о контакте
mysql_query("UPDATE `users_konts` SET `time` = '$time' WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_kont` = '$user[id]'");
//$_SESSION['message'] = 'Сообщение успешно отправлено';
header("Location: ?id=$ank[id]");
exit;
}
}


if (isset($_GET['delete'])  && $_GET['delete']!='add'){
$mess = mysql_fetch_assoc(mysql_query("SELECT * FROM `mail` WHERE `id` = '".intval($_GET['delete'])."' limit 1"));
if ($mess['id_user']==$user['id'] || $mess['id_kont']==$user['id']){
if ($mess['unlink']!=$user['id'] && $mess['unlink']!=0)
mysql_query("DELETE FROM `mail` WHERE `id` = '".$mess['id']."'");
else
mysql_query("UPDATE `mail` SET `unlink` = '$user[id]' WHERE `id` = '$mess[id]' LIMIT 1");
//$_SESSION['message'] = 'Сообщение удалено';
header("Location: ?id=$ank[id]");
exit;
}
}

if (isset($_GET['delete']) && $_GET['delete']=='add'){
mysql_query("DELETE FROM `mail` WHERE `unlink` = '$ank[id]'  AND `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_kont` = '$user[id]' AND `unlink` = '$ank[id]'  ");
mysql_query("UPDATE `mail` SET `unlink` = '$user[id]' WHERE  `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_kont` = '$user[id]'");
$_SESSION['message'] = 'Сообщения удалены';
header("Location: ?id=$ank[id]");
exit;
}

aut();
err();

//Приватность почты пользователя

$block = true;
$uSet = mysql_fetch_array(mysql_query("SELECT * FROM `user_set` WHERE `id_user` = '$ank[id]'  LIMIT 1"));
$frend=mysql_result(mysql_query("SELECT COUNT(*) FROM `frends` WHERE (`user` = '$user[id]' AND `frend` = '$ank[id]') OR (`user` = '$ank[id]' AND `frend` = '$user[id]') LIMIT 1"),0);
$frend_new=mysql_result(mysql_query("SELECT COUNT(*) FROM `frends_new` WHERE (`user` = '$user[id]' AND `to` = '$ank[id]') OR (`user` = '$ank[id]' AND `to` = '$user[id]') LIMIT 1"),0);

if ($user['group_access'] == 0){
//Если только для друзей
if ($uSet['privat_mail'] == 2 && $frend != 2){
echo '<div class="mess">';
echo 'Писать сообщения пользователю, могут только его друзья!';
echo '</div>';
$block = false;
}
//Если закрыта
if ($uSet['privat_mail'] == 0){
echo '<div class="err"><center>Пользователь запретил писать ему сообщения</center></div>';
$block = false;		
}
}

echo '<div class="block">';
if ($ank2['id']==0){
echo '<span class="nick">'.$ank2[ank_name].' '.$ank2[ank_fam].'</span>';
}
echo ''.user::nick($ank['id']).' ';
echo '<span style="font-size: 14px; color: #8c8c8c; margin-left: 5px;">';
if ($ank['date_last'] > $time-600){
echo 'Online';
}else{
echo '' .vremja($ank['date_last']).'';
}
?><span style="float:right;cursor: pointer;" onclick="$('.block_mail_menu').toggle();return false;"><img src="/img/tmenu.png"></span><?
echo '</div>';

echo '<div class="block_mail_menu">';
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"), 0)==1){
$kont=mysql_fetch_array(mysql_query("SELECT * FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"));
echo '<a class="link3" href="index.php?type='.$kont[type].'&amp;act=del&amp;id='.$ank[id].'">Удалить</a>';
}
echo '<a class="link3" href="mail.php?id='.$ank[id].'&amp;page='.$page.'&amp;delete=add">Очистить</a>';
echo '</div>';

if ($ank['id']!=0 && $block == true){
if (mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"), 0)==1){
$kont=mysql_fetch_array(mysql_query("SELECT * FROM `users_konts` WHERE `id_user` = '$user[id]' AND `id_kont` = '$ank[id]'"));
}
}

$k_post=mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `unlink` != '$user[id]' AND `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_kont` = '$user[id]' AND  `unlink` != '$user[id]'"),0);

if ($k_post==0){
echo '<div class="block2"><center>Нет сообщений</center></div>';
}

$num=0;
$q=mysql_query("SELECT * FROM `mail` WHERE `unlink` != '$user[id]' AND `id_user` = '$user[id]' AND `id_kont` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_kont` = '$user[id]' AND `unlink` != '$user[id]' ORDER BY id ASC LIMIT 1, 100");

echo '<div id="chatbox-history"><div id="messages">';
  
# Вывод сообщений
while ($post = mysql_fetch_array($q)){
$ank2=get_user($post['id_user']);

echo '<table class="block3">';
echo '<td class="block_avatar">';
echo ''.avatar($ank2['id']).' <span class="avatar_icon">'.online($ank2['id']).'</span>';
echo '</td>';
echo '<td class="block_info">';
//Вывод дополнительного меню
if (isset($user) && ($user['level']>=3 || $user['id'] == $post['id_user'])){
echo '<a class="toggle-menu-act" onclick="UI.toggleMenu(this);"><span></span></a>';
echo '<div class="toggle-menu">';
echo '<div class="toggle-menu-arrow"><span></span></div>';
echo '<ul class="toggle-menu-block">';
echo '<a href="mail.php?id='.$ank[id].'&amp;page='.$page.'&amp;delete='.$post[id].'">Удалить</a>';
echo '</ul>';
echo '</div>';
}
echo '<span class="nick">';
//Система
if ($ank2['id']==0){
echo '<span class="nick">'.$ank2[ank_name].' '.$ank2[ank_fam].'</span>';
}
echo ''.user::nick($ank2['id']).'';
echo '</span>';
echo '<span class="time">' . vremja($post['time']) . '</span>';
echo '<div class="block_msg">';
echo ''. output_text($post['msg']) . '';
if ($post['read']==0){
echo '<span style="float:right;"><i style="font-size: 18px; color: #ec2b2b; margin: 0 4px;" class="material-icons">done</i></span>';
}
echo '</div>';
echo '</td>';
echo '</table>';

}

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

?>
<script>
$('#messages').scrollTop($('#messages')[0].scrollHeight);
</script>
<?

# Отправка сообщений
echo '<table class="block_mail">';
echo '<form method="post" name="message" action="mail.php?id='.$ank[id].'">';
echo '<td>';
echo '<textarea class="input_mail" placeholder="Напишите сообщение..." name="msg"></textarea>';
echo '</td>';
echo '<td style="width:50px;">';
echo '<button class="button_mail" type="submit"><img src="/img/send.png"></button>';
echo '</td>';
echo '</form>';
echo '</table>';

//Вывод страниц
if ($k_page>1)str("mail.php?id=$ank[id]&amp;",$k_page,$page); 

include_once '../../sys/inc/tfoot.php';

?>