<?php
require_once('classes/body.class.php');
require_once('classes/db.class.php');
require_once('classes/system.class.php');
$title= new Body;

$title->SetTitle(''.homeurl.' - Личные сообщения!');
///Подключаем шапку
$title->GetHeader();

if ($b == false) {
header('location: /');
die();
}
echo '<div class="container-fluid page_header"><div class="container"><div class="row"><div class="col-xs-12 col-sm-8 col-md-9 col-lg-9"><h1>Просмотр почты </h1><ol class="breadcrumb" xmlns:v="http://'.homeurl.'/#"><li typeof="v:Breadcrumb"><a href="/" rel="v:url" property="v:title">'.homeurl.'</a></li><li typeof="v:Breadcrumb"><a href="/office" rel="v:url" property="v:title">Кабинет</a></li><li class="active" typeof="v:Breadcrumb"><span property="v:title">Личные сообщения</span></li></ol></div></div></div></div>';
echo'<div class="container page_body"><div class="row"><div class="col-xs-12 page_content col-lg-9"><div class="navbar page_content_navbar collapse hidden-lg"><div class="container-fluid"><div class="navbar-collapse"></div></div></div><div class="text_box hidden-lg pr_block_small hidden"></div><div class="container-fluid cols_table">';
$do = isset($_GET['do']) ? check($_GET['do']) : false;
switch($do) {
default:
echo '<div class="catSides"><a href="/office"><i class="md-format-list-bulleted"></i> Мой кабинет</a> - Личные сообщения</div>';
$look = DB::$dbs->query("SELECT id FROM `letters` WHERE `idwho` = ? GROUP BY who", [$b['id']]);
$look = $look ->rowCount();

if ($look != FALSE) {
$num = 10;
$k_page = k_page($look, $num);
$page = page($k_page);
$start = $num*$page-$num;
$read = DB::$dbs->query("SELECT who, who AS w, (SELECT COUNT(id) FROM `letters` WHERE `read` = ? AND `idwho` = ? AND `who` = w) AS n,(SELECT COUNT(id) FROM `letters` WHERE `read` = ? AND `idwho` = ? AND `who` = w) AS a FROM `letters` WHERE `idwho` = ?  GROUP BY who ORDER BY MIN(`read`), MAX(data) DESC LIMIT $start,$num", [0,$b['id'],1,$b['id'],$b['id']]);
$cols = 0;
while($a = $read->fetch()){
$ava = (!empty(user_inf($a['who'], 'ava')) ? '<img style = "margin-right: 5px;" src="/'.user_inf($a['who'], 'ava').'" width="35" height="35" alt="not found"/>':'<img style = "margin-right: 5px;" src="/assets/images/noavatar.gif" alt="not found"/>');
// Определяем юзер off или on 
$online = (user_inf($a['who'], 'last')>time()-3600 ? '<img src="/assets/images/on.gif" alt="*"/>':'<img src="/assets/images/off.gif" alt="*"/>');
$cols++;
$n = ($start + $cols);
echo '<div class="row text_box"><form method="post" action="?">';
$adresat = Nick($a['who']);
echo '<strong><a href="?do=view&id='.$a['who'].'">'.$ava.' '.user_inf($a['who'], 'nick').'</a></strong>  '.$online.' (<b>'.$a['n'].'</b>/'.$a['a'].')</div>';
}
} else err('Почта пуста!');
if (isset($_POST['submitForm']))
{
if (empty($_POST['block']))
{
header('Location: ?');
die();
}
if ($_POST['d'] == 1) {
foreach($_POST['block'] as $value) {
DB::$dbs->query("DELETE FROM `letters` WHERE `who` = ? AND `idwho` = ?", [$value,$b['id']]);
header('Location: ?');
}
}
}
if ($k_page>1) {
str('?', $k_page,$page);
}
break;
case 'send':
echo '<div class="catSides"><a href="/messages"><i class="md-format-list-bulleted"></i> Личные сообщения</a> - Написать сообщение </div>';
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM forum_mess WHERE user_id = ?", [$b['id']])>=0) {
$adresat = (isset($_GET['nick'])) ? htmlspecialchars(addslashes(user_inf($_GET['nick'], 'nick'))) : NULL;
echo '<form ENCTYPE="multipart/form-data" method="post" action="?do=send_ok"><div class="row text_box">Кому:<br/><input type="text" class="form-control" name="nick" value="' . $adresat . '"/><br/>Сообщение:<br/><br/>';
quickpaste('text');
quickpanel();
echo'</br></br><textarea class="form-control" rows="3" name="text"></textarea>
<br/>Прикрепить файл: (*max: 3mb)<br/><input name="file" type="file"/><br/><input type="hidden" name="nick" value="'.$adresat.'"/><input type="submit" name="send" class="btn btn-primary" value="Отправить"/></div></form>';
} else err('Наберите 0 постов на форуме!');
break;
case 'send_ok':
if (!ctype_digit($_POST['nick'])) $nick = check($_POST['nick']);
elseif (ctype_digit($_POST['nick'])) $nick = abs((int)$_POST['nick']);
if (ctype_digit($nick)) {
$us = DB::$dbs->queryFetch("SELECT * FROM `blogger` WHERE `id` = ? LIMIT 1", [$nick]);
} elseif (!ctype_digit($nick)) {
$us = DB::$dbs->queryFetch("SELECT * FROM `blogger` WHERE `nick` = ? LIMIT 1", [$nick]);
}
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$us['id'],$b['id']]) == 0) {
$text = check($_POST['text']);
$files = array('.gif', '.jpg', '.jpeg', '.png', '.zip', '.rar', '.gz', '.gzip', '.tar', '.txt');
$ext = strtolower(strrchr($_FILES['file']['name'], '.'));
$fnames = $_FILES['file']['name'];

if ($us == 0) {
$err = 'Получатель не найден!';
}

if (is_numeric($nick) && $us['id'] == $b['id'])
{
$err = 'Получатель не найден!';
}
if (!is_numeric($nick) && $us['nick'] == $b['nick'])
{
$err = 'Получатель не найден!';
}

if (!empty($fnames) && preg_match('/(\.php|\.pl|\.htaccess)/i', $fnames) || !empty($fnames) && !in_array($ext, $files)) {
$err = 'Запрещенный формат файла!';
}

if (!empty($fnames) && $_FILES['file']['size'] > 1024 * 10 * 1024) {
$err = 'Большой размер файла!';
}

if (empty($text)) {
$err = 'Пустое поле сообщения!';
}
if (empty($err)) {
if (!empty($fnames))
{
$path = '/files/mail/GEARNET_RU_' . mt_rand(100000, 999999) . $ext;
copy($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/'.$path);
}
else {
$path = '';
}
$idus = $us['id'];

DB::$dbs->query("INSERT INTO `letters` SET `id` = ?, `who` = ?, `idwho` = ?, `text` = ?, `data` = ?, `read` = ?, `file` = ?", array(0,$b['id'],$idus,$text,time(),0,$path));
header('Location: ?do=view&id=' . $idus);
die();
}
else {
echo err($err);
}
} else err(Nick($us['id']).' добавил Вас в игнор лист!');
break;
case 'view':
$id = isset($_GET['id']) ? abs((int)$_GET['id']) : false;

$array = DB::$dbs->query("SELECT `id` FROM `letters` WHERE `idwho` = ? AND `who` = ? OR `idwho` = ? AND `who` = ?", [$b['id'],$id,$id,$b['id']]);
if ($array->rowCount() == FALSE) {
header('Location: /');
die();
}
$skem = Nick($id);
echo '<div class="catSides"><a href="/messages"><i class="md-format-list-bulleted"></i> Мои диалоги</a> - Переписка с ' . $skem . '</div>';
if (isset($_GET['delign'])) {
$row = DB::$dbs->queryFetch("SELECT * FROM ignor WHERE id_user = ? LIMIT 1", [$id]);
jurnal($id,Nick($row['user_id']).' убрал Вас с игнор-листа.',5);
DB::$dbs->query("DELETE FROM ignor WHERE id_user = ?", [$id]);
header('location: ?do=view&id='.$id);
die();
}
if (isset($_GET['ign'])) {
$row = DB::$dbs->queryFetch("SELECT * FROM blogger WHERE id = ? LIMIT 1", [$id]);
if ($row == 0) {
err('Такого мастера нет!');
} elseif ($row['id'] == $b['id']) {
err('Нельзя себя добавлять.');
} elseif (DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$b['id'],$row['id']]) > 0) {
header('Location: ?do=view&id='.$id);
} else {
DB::$dbs->query("INSERT INTO ignor SET user_id = ?, id_user = ?", [$b['id'],$row['id']]);
$mess = Nick($b['id']).' добавил Вас в игнор-лист.';
jurnal($row['id'],$mess,5);
echo '<div class="row text_box">Успешно добавлено.</div>';
}
}
$all = DB::$dbs->querySingle("SELECT COUNT(id) FROM `letters` WHERE `idwho` = ? AND `who` = ? OR `idwho` = ? AND `who` = ?", [$b['id'],$id,$id,$b['id']]);

$num = 10;
$k_page = k_page($all, $num);
$page = page($k_page);
$start = $num*$page-$num;
$read = DB::$dbs->query("SELECT * FROM `letters` WHERE `idwho` = ? AND `who` = ? OR `idwho` = ? AND `who` = ? ORDER BY `id` DESC LIMIT $start,$num", [$b['id'],$id,$id,$b['id']]);
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$id,$b['id']]) == 0) {
if (isset($_POST['send'])) {
$text = check($_POST['text']);
$files = ['.gif', '.jpg', '.jpeg', '.png', '.zip', '.rar', '.gz', '.gzip', '.tar', '.txt'];
$ext = strtolower(strrchr($_FILES['file']['name'], '.'));
$fnames = $_FILES['file']['name'];
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM letters WHERE idwho = ? AND text = ?", [$id,$text])>0) {
$err = 'Вы уже писали это!';
}
$time = DB::$dbs->query("SELECT * FROM letters WHERE who = ? ORDER BY data DESC", [$b['id']]);
while($t = $time -> fetch()) {
if ((time() - $t['data']) < 10) {
err('Пишите не чаще чем раз в 10 секунд!');
///Подключаем меню
$title->GetMenu();


///Подключаем футер
$title->GetFooter();
die();
}
}
if ($id == 0) {
$err = 'Получатель не найден!';
}

if (!empty($fnames) && preg_match('/(\.php|\.pl|\.htaccess)/i', $fnames) || !empty($fnames) && !in_array($ext, $files)) {
$err = 'Запрещенный формат файла!';
}

if (!empty($fnames) && $_FILES['file']['size'] > 1024 * 10 * 1024) {
$err = 'Большой размер файла!';
}

if (empty($text)) {
$err = 'Пустое поле сообщения!';
}
if (empty($err)) {
if (!empty($fnames))
{
$path = '/files/mail/GEARNET.RU_' . mt_rand(100000, 999999) . $ext;
copy($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/'.$path);
}
else {
$path = '';
}
DB::$dbs->query("INSERT INTO `letters` SET `id` = ?, `who` = ?, `idwho` = ?, `text` = ?, `data` = ?, `read` = ?, `file` = ?", array(0,$b['id'],$id,$text,time(),0,$path));
header('Location: ?do=view&id=' . $id);
die();
}
else {
echo err($err);
}
}
}
$ign = DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$b['id'],$id]);
$ig = DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$id,$b['id']]);
if ($all != false) {
echo ($ign > 0 ? err(Nick($id).' в вашем игнор листе.') : NULL);
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM ignor WHERE user_id = ? AND id_user = ?", [$id,$b['id']]) == 0) {
echo '<form name="form" ENCTYPE="multipart/form-data" method="post" action="?do=view&id='.$id.'"><div class="row text_box"><br/>';
quickpaste('text');
quickpanel();
echo'</br></br><textarea name="text"class="form-control" rows="3">
</textarea>
<br/>Прикрепить файл: (*max: 10 mb.)<br/>
<input name="file" type="file"/><br/><input type="submit" class="btn btn-primary" name="send" value="Отправить"/></div></form>';
} else err(Nick($id).' добавил Вас в игнор лист!');
if ($ign == 0) {
echo '<div class="catSides"><a href="?do=view&id='.$id.'&ign"><i class="md-shuffle"></i> В игнор</a></div>';
} else {
echo '<div class="catSides"><a href="?do=view&id='.$id.'&delign"><i class="md-shuffle"></i> Убрать с игнора</a></div>';
}
while($ot = $read->fetch()) {
$vfile = $_SERVER['DOCUMENT_ROOT'].$ot['file'];
$files = strtolower(strrchr($ot['file'], '.'));
$your = DB::$dbs->queryFetch("SELECT `id`, `read` FROM `letters` WHERE
`idwho` = ? AND
`who` = ? AND
`mod` = ? AND
`id` = ?", [$ot['who'],$b['id'],'i',($ot['id']-1)]);
$nicks = Nick($ot['who']);
if ($ot['read'] == 0) $NoRead = '[<font color="red"><b>Непрочитанное</b></font>]';
else $NoRead = '';
echo '<div class="row text_box">';
echo $nicks . '  ' . $online . ' (' . vr($ot['data'], 0) . ') ' . $NoRead . '<br/>
' . text($ot['text']) . '
<br/>' .($ot['file'] != '' ? '<b>Прикрепленный файл</b><br/><a href="'.$ot['file'].'">'.mb_substr($ot['file'],12,27, 'UTF-8').' ('.get_size(filesize($vfile)).')</a><br/>' : '') . '</div>';
}
} else err('История переписки пуста!');
/////////////////////
DB::$dbs-> query("UPDATE `letters` SET `read` = ? WHERE `idwho` = ? AND `who` = ?", [1,$b['id'],$id]);
/////////////////////
if ($k_page>1) {
str('?do=view&id='.$id.'&', $k_page,$page);
}
break;
}

///Подключаем меню
$title->GetMenu();


///Подключаем футер
$title->GetFooter();
?>