<?php
/* DCMS Special
 * Дата последнего редактирования 12.10.2016
 * Модифицировал densnet
 */

foreach (array('start', 'compress', 'sess', 'settings', 'db_connect', 'ipua', 'fnc', 'user') as $inc) {
    require_once "../../sys/inc/$inc.php";
}

$config = array(
    'domain' => $set['mail_panel_domain'],
    'aliase' => explode("\n", $set['mail_panel_aliase']),
    'sender' => $set['mail_sender'],
);

only_reg();

$EmailUser = new EmailUser($user['id']);
$user = $EmailUser->getUser();

$user_set = $db->get_row($db->query("SELECT * FROM `user_set` AS u WHERE `id_user` = '" . $user['id'] . "' LIMIT 1"));

$addres = null;
if (isset($_GET['contact']) || isset($_POST['to'])) {
    $addres = (isset($_POST['to']) ? $_POST['to'] : urldecode($_GET['contact']));
}

$EmailUser = new EmailUser(strtolower($addres));
$contact = $EmailUser->getUser();

if ($contact['id'] === $user['id']) {
    header('Location: ?');
    exit;
}

if (!isset($_SESSION['mail']) || $_SESSION['mail']['to'] != $contact['id']) {
    $_SESSION['mail'] = array(
        'msg' => '',
        'to' => $contact['id'],
        'attachments' => array(),
    );
}

/**
 * @var Отправка сообщений
 */
if (isset($_POST['msg']) && isset($_POST['sid'])) {

    if ($_SESSION['sid'] != $_POST['sid']) {
        $err[] = lang('Повторите отправку сообщения');
    }

    if (isset($_POST['files']) && !isset($err)) {
        $_SESSION['mail']['msg'] = $_POST['msg'];
        header('Location: attachments.php');
        exit;
    }

    if (utf8_strlen($_POST['msg']) > 10240) {
        $err[] = lang('Сообщение слишком длинное');
    } elseif (utf8_strlen($_POST['msg']) < 2) {
        $err[] = lang('Сообщение слишком короткое');
    }

    if ($contact['id'] == $user['id']) {
        $err[] = lang('Запрещено писать самому себе');
    }

    if (!preg_match('/([A-z0-9\-\_]+)/i', $contact['id'])) {
        $err[] = lang('Контакт не найден');
    }

    if (is_numeric($contact['id']) && $user['group_access'] <= 1) {
        $contact_set = $db->get_row($db->query("SELECT * FROM `user_set` AS u WHERE `id_user` = '" . $contact['id'] . "' LIMIT 1"));

        if ($contact_set['privat_mail'] != 1) {
            $m = $db->super_query("SELECT COUNT(*) as count FROM `mail` WHERE `id_kont` = '$user[id]' AND `id_user` = '$contact[id]' AND `deleted` != '$contact[id]' AND `deleted` != '-1'");
            if ($m['count'] == 0) {
                $err['p'] = lang('Вы не можете отправлять сообщения пользователю');

                $f = $db->super_query("SELECT COUNT(*) as count FROM `friends` WHERE (`user` = '$user[id]' AND `friends` = '$contact[id]') OR (`user` = '$contact[id]' AND `friends` = '$user[id]') LIMIT 1");
                #Запрещаем писать всем, кроме знакомых
                if ($contact_set['privat_mail'] == 2 && $f['count'] != 2) {
                    $err['p'] = lang('Вы не можете отправлять сообщения пользователю');
                }
            }
        }
    }

    if (!isset($err)) {
        if (preg_match("#^[A-z0-9-\._-]+@[A-z0-9\._-]{2,}\.[A-z]{2,4}$#ui", $contact['id'])) {
            $to = $contact['id'];
            $from = strtolower($user['nick'] . '@' . $config['domain']);

            if ($config['sender'] == 'phpmailer') {
                $mail = new PHPMailer();
                $mail->CharSet = 'UTF-8';
                $mail->IsSendmail();
                $mail->AddReplyTo($from, $user['nick']);
                $mail->SetFrom($from, $user['nick']);
                $mail->AddReplyTo($from, $user['nick']);
                $mail->AddAddress($to, $to);
                $mail->Subject = lang('Сообщение от') . ' ' . $user['nick'];
                $mail->AltBody = lang('Вам новое сообщение от') . ' ' . $to . ' (' . $user['nick'] . ')';
                $mail->msgHTML($_POST['msg']);

                if (isset($_SESSION['mail']['attachments'])) {
                    foreach ($_SESSION['mail']['attachments'] AS $type => $files) {
                        foreach ($files AS $id => $file) {
                            $mail->AddAttachment($file['filePatch'], $file['fileName'] . '.' . $file['fileRas']);
                        }
                    }
                }
                $result = true;

                if (!$mail->Send()) {
                    $result['error'] = $mail->ErrorInfo;
                }
            } else {
                $sendMessage = new EmailSender($config);
                $boundary = '--' . md5(uniqid(time()));

                $headers = $sendMessage->getHeaders(array('subject' => $user['nick'], 'to' => $to, 'from' => $from), $boundary);
                $msg = $sendMessage->getBody($_POST['msg'], $boundary);
                $result = $sendMessage->mail($cont['to'], lang('Сообщение от') . ' ' . $user['nick'], $msg, $headers, $from);
            }
        }

        if (is_array($result)) {
            $err = $result['error'];
        } else {
            $r = $db->super_query("SELECT COUNT(*) as count FROM `mail` WHERE `flaggedTo` = 'spam' AND `id_user` = '$user[id]' AND `id_kont` = '" . $db->safesql($contact['id']) . "'");

            if ($r['count'] > 0) {
                $flaggedIs = 'spam';
            } else {
                $flaggedIs = 'inbox';
            }

            $db->query("INSERT INTO `mail`(`id_user`, `id_kont`, `time`, `type`, `msg`, `read`, `flaggedTo`) VALUES ('" . $user['id'] . "', '" . $db->safesql($contact['id']) . "', '" . $time . "', '" . (isset($result) ? 'email' : 'personal') . "', '" . $db->safesql($_POST['msg']) . "', '" . (isset($result) ? '1' : '0') . "', '$flaggedIs')");
            $id_email = $db->insert_id();

            $is_attachment = false;

            if (isset($_SESSION['mail']['attachments'])) {
                foreach ($_SESSION['mail']['attachments'] AS $type => $files) {
                    foreach ($files AS $id => $file) {
                        $db->query("INSERT INTO `mail_files`(`name`, `md5`, `id_user`, `id_kont`, `ras`, `type`, `size`, `email_id`) VALUES ('" . $db->safesql($file['fileName']) . "', '" . $id . "', '" . $db->safesql($user['id']) . "', '" . $db->safesql($contact['id']) . "', '" . $file['fileRas'] . "', '" . $type . "', '" . $file['fileSize'] . "', '" . $id_email . "')");
                        $is_attachment = true;
                    }
                }
            }

            if ($is_attachment) {
                $db->query("UPDATE `mail` SET `attachments` = '1' WHERE `id` = '$id_email' LIMIT 1");
            }

            $_SESSION['mail'] = array(
                'msg' => '',
                'to' => $contact['id'],
                'attachments' => array(),
            );
            $_SESSION['message'] = lang('Сообщение успешно отправлено');
        }
    }

    if (!isset($err)) {
        header('Location: ?contact=' . urlencode($contact['id']));
        exit;
    }
}

$listFlagged = array(
    'inbox' => lang('Контакты'),
    'favorite' => lang('Избранное'),
    'archive' => lang('Архив'),
    'spam' => lang('Спам'),
    'deleted' => lang('Корзина'),
);

if (isset($_GET['s']) && $_GET['s'] != 'inbox' && array_key_exists($_GET['s'], $listFlagged)) {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = '" . $db->safesql($_GET['s']) . "' ";
    $flagged = $_GET['s'];
} else {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = 'inbox' ";
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = 'favorite' ";
    $flagged = 'inbox';
}

if (isset($_GET['fav']) && isset($_GET['message_id'])) {
    $message_id = (int) $_GET['message_id'];
    $post = $db->get_row($db->query("SELECT * FROM `mail` WHERE `id` = '$message_id' AND (`id_user` = '$user[id]' OR `id_kont` = '$user[id]') LIMIT 1"));
    $flags = ($_GET['fav'] == 1 ? 'favorite' : $flagged);
    $setFlags = ($post['id_kont'] == $user['id'] ? 'flaggedTo' : 'flaggedFrom');
    $db->query("UPDATE `mail` SET `$setFlags` = '$flags' WHERE `id` = '$post[id]' LIMIT 1");
}

if ($contact['id'] !== '') {
    $db->query("UPDATE `mail` SET `read` = '1' WHERE `id_kont` = '$user[id]' AND `id_user` = '" . $db->safesql($contact['id']) . "'");
}

$_SESSION['sid'] = mt_rand(11111, 99999);

require_once H . 'sys/inc/thead.php';

aut();
err();

echo "<link rel='stylesheet' href='/style/css/email.css' type='text/css' />";

#Навигация
echo "<div class='list-group-item-null list-group-item-grey'><small>";
echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
echo "<a href='/id$user[id]'>$user[nick]</a> <i class='fa fa-angle-right fa-fw'></i> ";
echo "<a href='/user/mail/'>" . lang('Почта') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";

if ($flagged == 'inbox') {
    echo "$contact[nick]";
} else {
    echo "<a href='/user/mail/?s=$flagged'>$listFlagged[$flagged]</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "$contact[nick]";
}

echo "</small></div><br />";

if ($contact['id']) {
    echo "<div class='card-header' style='color: grey;'>";

    echo "<span style='float: right;' id='hides'>";
    if (IS_WEB) {
        echo "<a data-toggle='modal' data-target='#im' href='/?users_set'><span style='padding: 10px;' data-toggle='tooltip' data-placement='left' title='" . lang('Выберите действие') . "'><i class='fa fa-ellipsis-v fa-fw'></i></span></a>";
    } else {
        echo "<a data-toggle='modal' data-target='#im' href='/?users_set'><span style='padding: 10px;' title='" . lang('Выберите действие') . "'><i class='fa fa-ellipsis-v fa-fw'></i></span></a>";
    }
    echo "</span>";

    echo lang('Диалог с') . " $contact[nick]";
    echo "</div>";


    if ($flagged == 'deleted') {
        $d = 'pencil';
    } else {
        $d = 'trash';
    }
    ?>

    <div class="modal fade" id='im' tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form class="list-group-item-null" action="index.php?s=<?= $flagged ?>" method="POST">
                    <input type="hidden" name="cnt1" value="<?= stripcslashes(htmlspecialchars($contact['id'])) ?>">
                    <button type="submit" name="action" value="<?= ($flagged != 'archive' ? 'archive' : 'inbox') ?>" class="btn btn-block"><i class='fa fa-archive fa-fw'></i> <?= ($flagged != 'archive' ? '' . lang('В архив') . '' : '' . lang('Из архива') . '') ?></button><br />
                    <button type="submit" name="action" value="<?= ($flagged != 'spam' ? 'spam' : 'inbox') ?>" class="btn btn-block"><i class='fa fa-ban fa-fw'></i> <?= ($flagged != 'spam' ? '' . lang('Это спам') . '' : '' . lang('Это не спам') . '') ?></button><br />
                    <button type="submit" name="action" value="<?= ($flagged != 'deleted' ? 'deleted' : 'inbox') ?>" class="btn btn-block"><i class='fa fa-<?= $d ?> fa-fw'></i> <?= ($flagged != 'deleted' ? '' . lang('Удалить') . '' : '' . lang('Восстановить') . '') ?></button>
                </form>
            </div>
        </div>
    </div>
    <?php
}

if ($contact['id'] !== 0 && ($flagged == 'inbox' || $flagged == 'archive')) {

    echo "<form class='list-group-item-null' method='post' name='message' action='?contact=" . urlencode($contact['id']) . "'>";
    echo "<input type='hidden' name='sid' value='" . $_SESSION['sid'] . "'>";
    if (!$contact['id']) {
        echo lang('Кому') . ":<br />";
        $doc->Input('to', 'Логин', 100);
    }

    $insert = stripcslashes(htmlspecialchars($_SESSION['mail']['msg']));
    $msg2 = stripcslashes(htmlspecialchars($_SESSION['mail']['msg']));
    echo auto_bb("message", "msg");
    $doc->Textarea('msg', null, 10024, "$insert");

    echo "<br />";
    $doc->Button('btn btn-success btn-sm', null, 'pencil', 'Отправить');
    echo "<span style='float: right;'>";
    $doc->Link('btn btn-secondary btn-sm', '/modules/smiles/', 'smile-o');
    $doc->Button('btn btn-secondary btn-sm', 'files', 'camera');
    echo "</span>";
    echo "</form>";
}

$attachments = new Attachments();
echo $attachments->get_list();


if ($contact['id'] !== '') {
    $arrContacts = $db->query("SELECT e.`id_user` FROM `mail` AS e WHERE (`id_kont` = '$user[id]' AND `id_user` = '" . $db->safesql($contact['id']) . "' OR `id_kont` = '" . $db->safesql($contact['id']) . "' AND `id_user` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") ");
    $k_post = $db->num_rows($arrContacts);

    if ($k_post == 0) {
        $doc->NoResult();
    } else {

        $k_page = k_page($k_post, $set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];

        $q = $db->query("SELECT * FROM `mail` AS e WHERE (`id_kont` = '$user[id]' AND `id_user` = '" . $db->safesql($contact['id']) . "' OR `id_kont` = '" . $db->safesql($contact['id']) . "' AND `id_user` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") ORDER BY `id` DESC LIMIT $start, $set[p_str]");

        while ($post = $db->get_row($q)) {

            $ank = ($post['id_user'] != $user['id'] ? $contact : $user);
            $flags = ($post['id_kont'] == $user['id'] ? 'flaggedTo' : 'flaggedFrom');
            if ($post['id_kont'] == $user['id']) {
                $z1 = "mail";
                $z2 = "mails";
            } else {
                $z1 = "mail";
                $z2 = "mails";
            }

            if ($post['id_kont'] == $user['id']) {
                echo "<table class='list-group-item-null list-group-item-grey dop' " . ($post['read'] == 0 && $post['id_kont'] != $user['id'] ? 'style="background-color: #edf1f5;"' : '') . "><tr><td class='icon14' style='vertical-align: top;'>";
                echo avatar($ank['id'], '40', 'border-radius: 2px;');
                echo "</td><td class='null'>";
                echo " <span class='hint--left' data-hint='" . date::time($post['time']) . "' style='color:grey;float:right;'><small>" . date::timek($post['time']) . "</small></span> ";

                echo "<b><font color='#4C6B8F'>$ank[nick]</font></b><br />";

                echo toOutput($post['msg']);
                if ($post['attachments'] == 1) {
                    $f = $db->query("SELECT * FROM `mail_files` AS e WHERE `email_id` = '$post[id]' ORDER BY `id` DESC");

                    while ($file = $db->get_row($f)) {
                        echo "<br /><small><a href='$post[time]/$file[md5]/" . retranslit($file['name']) . ".$file[ras]'><i class='fa fa-paperclip fa-fw'></i> " . stripcslashes(htmlspecialchars($file['name'])) . ".$file[ras]</a> (" . size_file($file['size']) . ")</small>";
                    }
                }

                if ($post[$flags] == 'favorite') {
                    $s = '<i class="fa fa-star"></i>';
                } else {
                    $s = '<i class="fa fa-star-o"></i>';
                }
                echo "<a style='float: right;' href='?s$flagged&amp;page=$page&amp;contact=" . urlencode($contact['id']) . "&amp;message_id=$post[id]&amp;fav=" . ($post[$flags] == 'favorite' ? '0' : '1') . "'>$s</a>";

                echo "</td></tr></table>";
            } else {
                #Я пишу...
                echo "<table class='list-group-item-null list-group-item-grey dop' " . ($post['read'] == 0 && $post['id_kont'] != $user['id'] ? 'style="background-color: #edf1f5;"' : '') . "><tr><td class='icon14' style='vertical-align: top;'>";
                echo avatar($ank['id'], '40', 'border-radius: 2px;');
                echo "</td><td class='null'>";
                echo " <span class='hint--left' data-hint='" . date::time($post['time']) . "' style='color:grey;float:right;'><small>" . date::timek($post['time']) . "</small></span> ";

                echo "<b><font color='#4C6B8F'>$ank[nick]</font></b><br />";

                echo toOutput($post['msg']);
                if ($post['attachments'] == 1) {
                    $f = $db->query("SELECT * FROM `mail_files` AS e WHERE `email_id` = '$post[id]' ORDER BY `id` DESC");

                    while ($file = $db->get_row($f)) {
                        echo "<br /><small><a href='$post[time]/$file[md5]/" . retranslit($file['name']) . ".$file[ras]'><i class='fa fa-paperclip fa-fw'></i> " . stripcslashes(htmlspecialchars($file['name'])) . ".$file[ras]</a> (" . size_file($file['size']) . ")</small>";
                    }
                }

                if ($post[$flags] == 'favorite') {
                    $s = '<i class="fa fa-star"></i>';
                } else {
                    $s = '<i class="fa fa-star-o"></i>';
                }
                echo "<a style='float: right;' href='?s$flagged&amp;page=$page&amp;contact=" . urlencode($contact['id']) . "&amp;message_id=$post[id]&amp;fav=" . ($post[$flags] == 'favorite' ? '0' : '1') . "'>$s</a>";
                echo "</td></tr></table>";
            }
        }


        if ($k_page > 1) {
            str('?s=' . $flagged . '&amp;contact=' . urlencode($contact['id']) . '&amp;', $k_page, $page);
        }
    }
}

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