<?
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: /konts.php?".SID);exit;}
$ank=get_user($_GET['id']);
if (!$ank){header("Location: /konts.php?".SID);exit;}
if ($ank['id']==$user['id']){header("Location: /konts.php?".SID);exit;}


$set['title']='Почта: '.$ank['nick'];
include_once 'sys/inc/thead.php';
title();




if(isset($_GET['set']) && $_GET['set']=='all'){mysql_query("UPDATE `user` SET `mail_set` = '0' WHERE `id` = '$user[id]'");
msg('Сохранено, пишут все');
}
if(isset($_GET['set']) && $_GET['set']=='no'){mysql_query("UPDATE `user` SET `mail_set` = '1' WHERE `id` = '$user[id]'");
msg('Сохранено, почта закрыта');
}
####################

if (isset($_GET['txt']))
{

ob_clean();
ob_implicit_flush();
header('Content-Type: text/plain; charset=utf-8', true);

header('Content-Disposition: attachment; filename="'.retranslit('Переписка '.$ank['nick'].' - '.$user['nick']).'.txt";');

$q=mysql_query("SELECT * FROM `mails` WHERE `user` = '$user[id]' AND ((`id_user` = '$user[id]' AND `id_kont` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_kont` = '$user[id]')) ORDER BY `time` DESC");

//echo "\r\n";
while ($post = mysql_fetch_assoc($q))
{
echo "\r\n";
$ank=get_user($post['id_user']);

echo $ank['nick']."\r\n";
echo trim(br($post['msg'],"\r\n"))."\r\n";


}

exit; }

#######save sms###########
if(isset($_GET['save'])){


$post=mysql_fetch_assoc(mysql_query("SELECT * FROM `mails` WHERE `id` = '".intval($_GET['save'])."' LIMIT 1"));
if($post['id_kont']==$user['id'] || $post['id_user']==$user['id']){
if($post['id_file']!='' && $post['id_file']!='0')$file=$post['id_file']; else $file='';
mysql_query("INSERT INTO `mail_save` (`id_user`,`id_ank`,`id_post`,`id_file`, `msg`, `time`) values('".$user['id']."','".$ank['id']."', '".$post['id']."', '".$file."','$post[msg]', '".time()."')");
msg('Сообщение сохранено');
}
}
###################

if(isset($_GET['spam'])){

$q=mysql_query("SELECT * FROM `user` WHERE `group_access` > '1'");
while ($send = mysql_fetch_array($q))
{
$post=mysql_fetch_assoc(mysql_query("SELECT * FROM `mails` WHERE `id` = '".intval($_GET['spam'])."' LIMIT 1"));
$msg1='Пользователь [url=/info.php?id='.$user['id'].']'.$user['nick'].'[/url]том что завелась крыса которая спамит\rСообщение\r'.$post['msg'].' \r ник [url=/info.php?id='.$ank['id'].']'.$ank['nick'].'[/url]';
mysql_query("INSERT INTO `jurnal` (`id_user`, `id_kont`, `msg`, `time`) values('0','".$send['id']."', '$msg1', '".time()."')");
}
msg('Спасибо, администрация вас не забудет');

}
if (isset($_GET['del'])) {
$post=mysql_fetch_assoc(mysql_query("SELECT * FROM `mails` WHERE `id` = '".intval($_GET['del'])."' LIMIT 1"));
if($post['id_kont']==$user['id'] || $post['id_user']==$user['id']){

//unlink(H."sys/mail/files/$post[id_file].mail");
//mysql_query("DELETE FROM `mail_files` WHERE `id_post` = '".$post['id']."' LIMIT 1");

mysql_query("DELETE FROM `mails` WHERE `id` = '".intval($_GET['del'])."' AND ((`id_user` = '$user[id]' AND `id_kont` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_kont` = '$user[id]')) LIMIT 1");
msg('Сообщение удалено');}
}
########file######






################

// добавляем в контакты
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`, `name`) VALUES ('$user[id]', '$ank[id]', '$time', '$ank[nick]')");
// обновление сведений о контакте
mysql_query("UPDATE `users_konts` SET `new_msg` = '0' WHERE `id_kont` = '$ank[id]' AND `id_user` = '$user[id]' LIMIT 1");
// помечаем сообщения как прочитанные
//mysql_query("UPDATE `mails` SET `read` = '1' WHERE `user` = '$user[id]' AND `id_kont` = '$ank[id]' AND `id_user` = '$user[id]'");

if (isset($_POST['msg']) && $ank['id']!=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 `mails` 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 `mails` (`user`,`id_user`, `id_kont`, `msg`, `time`) values('$user[id]','$user[id]', '$ank[id]', '".my_esc($msg)."', '$time')");
$post_id=mysql_insert_id();

mysql_query("INSERT INTO `mails` (`user`,`id_user`, `id_kont`, `msg`, `time`, `read`) values('$ank[id]','$user[id]', '$ank[id]', '".my_esc($msg)."', '$time','1')");
$post_id2=mysql_insert_id();
#########



if (isset($_FILES['mfile']) && isset($_FILES['mfile']['tmp_name']) && $_FILES['mfile']!=null && filesize($_FILES['mfile']['tmp_name'])>0)
{

mysql_query("INSERT INTO `mail_files` (`id_post`, `name`, `ras`, `size`, `type`) values('$post_id', '".$_FILES['mfile']['name']."', '".$_FILES['mfile']['ras']."', '".$_FILES['mfile']['size']."', '".$_FILES['mfile']['type']."')");
$file_id=mysql_insert_id();
mysql_query("INSERT INTO `mail_files` (`id_post`, `name`, `ras`, `size`, `type`) values('$post_id2', '".$_FILES['mfile']['name']."', '".$_FILES['mfile']['ras']."', '".$_FILES['mfile']['size']."', '".$_FILES['mfile']['type']."')");
mysql_query("UPDATE `mails` SET `id_file` = '$file_id' WHERE `id` = '$post_id2'");
mysql_query("UPDATE `mails` SET `id_file` = '$file_id' WHERE `id` = '$post_id'");
copy($_FILES['mfile']['tmp_name'], H.'sys/mail/files/'.$file_id.'.mail');



}


########
//mysql_query("UPDATE `mails` SET `read` = '1' WHERE `user` = '$user[id]' AND `id_kont` = '$user[id]' AND `id_user` = '$ank[id]'");
// добавляем в контакты
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`, `name`) VALUES ('$user[id]', '$ank[id]', '$time', '$ank[nick]')");
// обновление сведений о контакте
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]'");
msg('Сообщение успешно отправлено');
}
}

aut();
err();
$sort="((`id_user` = '$user[id]' AND `id_kont` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_kont` = '$user[id]'))";
echo "<table class='post'>\n";
if($_GET['sort']=='1')$sort="`id_user` = '$user[id]' AND `id_kont` = '$ank[id]'";
if($_GET['sort']=='2')$sort="`id_user` = '$ank[id]' AND `id_kont` = '$user[id]'";
if($_GET['sort']=='3')$sort="((`id_user` = '$user[id]' AND `id_kont` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_kont` = '$user[id]'))";
echo "<table class='post'>\n";
$k_post=mysql_result(mysql_query("SELECT COUNT(*) FROM `mails` WHERE `user` = '$user[id]' AND $sort"),0);
$k_page=k_page($k_post,$set['p_str']);
$page=page($k_page);
$start=$set['p_str']*$page-$set['p_str'];
echo "<form method='post' action='/mail.php?id=$ank[id]&amp;".rand(100,9999)."'>\n";

echo "<input type='submit' name='save' value='Обновить' />\n";
echo "</form>\n";
if(mysql_result(mysql_query("SELECT COUNT(*) FROM `user` WHERE `id` = '$ank[id]' AND `mail_set` = '1'"),0)==0 || $user['level']>1){
if(mysql_result(mysql_query("SELECT COUNT(*) FROM `users_konts` WHERE `id_user` = '$ank[id]' AND `type` = 'ignor'"),0)==0 || $user['level']>0){
if ($ank['id']!=0){
if ($user['set_files']==1)
echo "<form method='post' name='msg' enctype='multipart/form-data' action='/mail.php?id=$ank[id]&amp;$passgen'>\n";
else
echo "<form method='post' name='msg' action='/mail.php?id=$ank[id]&amp;$passgen'>\n";

echo "<form method='post' name='msg' action='/mail.php?id=$ank[id]&amp;$passgen'>\n";
if ($set['web'] && is_file(H.'style/themes/'.$set['set_them'].'/altername_post_form.php'))
include_once H.'style/themes/'.$set['set_them'].'/altername_post_form.php';
else
echo "Сообщение:<br />\n<textarea name='msg'></textarea><br />\n";
if ($user['set_files']==1){


echo "<input name='mfile' type='file' /><br />\n";
}
if ($user['set_translit']==1)echo "<label><input type='checkbox' name='translit' value='1' /> Транслит</label><br />\n";

echo "<input name='post' value='Отправить' type='submit' /><br />\n";
echo "</form>\n";

}}else{msg('Вы в игноре');}}else{msg('Пользователь закрыл почту от всех');}
if ($k_post==0)
{
echo "   <tr>\n";
echo "  <td class='p_t'>\n";
echo "Нет сообщений\n";
echo "  </td>\n";
echo "   </tr>\n";

}
$q=mysql_query("SELECT * FROM `mails` WHERE `user` = '$user[id]' AND $sort ORDER BY id DESC LIMIT $start, $set[p_str]");
while ($post = mysql_fetch_array($q))
{
$ank2=get_user($post['id_user']);
echo "   <tr>\n";
if ($set['set_show_icon']==2){
echo "  <td class='icon48' rowspan='2'>\n";
avatar($ank2['id']);
echo "  </td>\n";
}
elseif ($set['set_show_icon']==1)
{
echo "  <td class='icon14'>\n";
echo "<img src='/style/themes/$set[set_them]/user/$ank2[pol].png' alt='' />";
echo "  </td>\n";
}
mysql_query("UPDATE `mails` SET `read` = '1' WHERE `user` = '$ank[id]' AND `id_user` = '$ank[id]' AND `id_kont` = '$user[id]' AND `msg` = '$post[msg]' AND `time` = '$post[time]' LIMIT 1");

echo "  <td class='p_t'>\n";
if ($ank2)
echo "<a href=\"/info.php?id=$ank2[id]\">$ank2[nick]</a>".online($ank2['id'])."\n";
else
echo "[DELETED] (+$kont[count])\n";
echo "(".vremja($post['time']).")\n";
echo "  </td>\n";
echo "   </tr>\n";


echo "   <tr>\n";
if ($set['set_show_icon']==1)echo "  <td class='p_m' colspan='2'>\n"; else echo "  <td class='p_m'>\n";
if ($post['read']==0)echo "(не прочитано)<br />\n";
echo output_text($post['msg'])."<br />\n";
######################

$qq=mysql_query("SELECT * FROM `mail_files` WHERE `id_post` = '".$post['id']."'");
while ($files=mysql_fetch_assoc($qq)){

echo "<a href='/files.php?id=$post[id_file]'>$files[name]$ras</a> (".size_file($files['size']).") \n";
echo "Скачано: $files[count] раз(а) ";
echo "<br />\n";
}

##########################
echo "<a href='/mail.php?id=$ank[id]&amp;save=$post[id]'>Save</a> |\n";
echo "<a href='/mail.php?id=$ank[id]&amp;del=$post[id]'>Удалить</a> | \n";
echo "<a href='/mail.php?id=$ank[id]&amp;spam=$post[id]'>Спам</a>\n";
echo "  </td>\n";
echo "   </tr>\n";






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




echo "<div class='foot'>";
echo "Фильтр: ";
echo "<a href='/mail.php?id=$ank[id]&amp;sort=2'>Входящие</a> | \n";
echo "<a href='/mail.php?id=$ank[id]&amp;sort=1'>Исходящие</a> | \n";
echo "<a href='/mail.php?id=$ank[id]&amp;sort=3'>Все</a><br />\n";
echo "Скачать: <a href='/mail.php?id=$ank[id]&amp;txt'>TXT</a><br />";
echo "Пишут мне: <a href='/mail.php?id=$ank[id]&amp;set=all'>Все</a> | <a href='/mail.php?id=$ank[id]&amp;set=no'>Никто</a><br />";
if ($ank['id']!=0)
{
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 href='/konts.php?type=$kont[type]&amp;act=del&amp;id=$ank[id]'>Удалить контакт из списка</a><br />\n";
}
else
{
echo "<a href='/konts.php?type=common&amp;act=add&amp;id=$ank[id]'>Добавить в список контактов</a><br />\n";
}
}

echo "<a href='/konts.php?".(isset($kont)?'type='.$kont['type']:null)."'>Список контактов</a><br />\n";
echo "<a href='/mail_save.php'>Сохр. сообщения</a><br />\n";
echo "</div>\n";
echo "<div class='foot'>\n";
if(isset($_SESSION['refer']) && $_SESSION['refer']!=NULL && otkuda($_SESSION['refer']))
echo "&laquo;<a href='$_SESSION[refer]'>".otkuda($_SESSION['refer'])."</a><br />\n";
echo "&laquo;<a href='umenu.php'>Мое меню</a><br />\n";
echo "</div>\n";
include_once 'sys/inc/tfoot.php';
?>