<?php 

include_once '../sys/inc/home.php';
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/compress.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';

/**
* Классы для работы с почтой
*/
require 'classes/PHPMailerAutoload.php';

include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.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 = mysql_fetch_assoc(mysql_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[] = 'Повторите отправку сообщения';
    }
    
    if (isset($_POST['files']) && !isset($err)) {
        $_SESSION['mail']['msg'] = $_POST['msg'];
        header('Location: attachments.php');
        exit;
    }
    
    if (strlen2($_POST['msg']) > 10240) {
        $err[] = 'Сообщение слишком длинное';
    } elseif (strlen2($_POST['msg']) < 2) {
        $err[] = 'Сообщение слишком короткое';
    }
    
    if ($contact['id'] == $user['id']) {
        $err[] = 'Запрещено писать самому себе';
    }
    
    if (!preg_match('/([A-z0-9\-\_]+)/i', $contact['id'])) {
        $err[] = 'Контакт не найден';
    }
    
    if (is_numeric($contact['id']) && $user['group_access'] <= 1) {
        $contact_set = mysql_fetch_assoc(mysql_query("SELECT * FROM `user_set` AS u
                                                      WHERE `id_user` = '" . $contact['id'] . "'
                                                      LIMIT 1"));
        
        if ($contact_set['privat_mail'] != 1) {
            if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_kont` = '$user[id]' AND `id_user` = '$contact[id]' AND `deleted` != '$contact[id]' AND `deleted` != '-1'"), 0) == 0) {
                $err['p'] = 'Вы не можете отправлять сообщения обитателю, так как он закрыл свою Почту от всех, кроме известных ему контактов.';
                
                if ($contact_set['privat_mail'] == 2 && mysql_result(mysql_query("SELECT COUNT(*) FROM `frends` WHERE (`user` = '$user[id]' AND `frend` = '$contact[id]') OR (`user` = '$contact[id]' AND `frend` = '$user[id]') LIMIT 1"), 0) != 2) {
                    $err['p'] = 'Вы не можете отправлять сообщения обитателю, так как он закрыл свою Почту от всех, кроме своих друзей и известных ему контактов.';
                }
            }
        }
    }
    
    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 = 'Сообщение от ' . $user['nick'];
                $mail->AltBody = 'Вам новое сообщение от ' . $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'], 'Сообщение от ' . $user['nick'], $msg, $headers, $from);
            }
        }
        
        if (is_array($result)) {
            $err = $result['error'];
        } else {
            if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `flaggedTo` = 'spam' AND `id_user` = '$user[id]' AND `id_kont` = '" . my_esc($contact['id']) . "'"), 0) > 0) {
                $flaggedIs = 'spam';
            } else {
                $flaggedIs = 'inbox';
            }
            
            mysql_query("INSERT INTO `mail`(`id_user`, `id_kont`, `time`, `type`, `msg`, `read`, `flaggedTo`) VALUES ('" . $user['id'] . "', '" . my_esc($contact['id']) . "', '" . $time . "', '" . (isset($result) ? 'email' : 'personal') . "', '" . my_esc($_POST['msg']) . "', '" . (isset($result) ? '1' : '0') . "', '$flaggedIs')");
            $id_email = mysql_insert_id();
            
            $is_attachment = false;
            
            if (isset($_SESSION['mail']['attachments'])) {
                foreach($_SESSION['mail']['attachments'] AS $type => $files) {
                    foreach($files AS $id => $file) {
                        mysql_query("INSERT INTO `mail_files`(`name`, `md5`, `id_user`, `id_kont`, `ras`, `type`, `size`, `email_id`) VALUES ('" . my_esc($file['fileName']) . "', '" . $id . "', '" . my_esc($user['id']) . "', '" . my_esc($contact['id']) . "', '" . $file['fileRas'] . "', '" . $type . "', '" . $file['fileSize'] . "', '" . $id_email . "')");
                        $is_attachment = true;
                    }
                }
            }
            
            if ($is_attachment) {
                mysql_query("UPDATE `mail` SET `attachments` = '1' WHERE `id` = '$id_email' LIMIT 1");
            }
            
            $_SESSION['mail'] = array(
                'msg' => '',
                'to'  => $contact['id'],
                'attachments' => array(),
            );  
            $_SESSION['message'] = 'Сообщение успешно отправлено';
        }
    }

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

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

if (isset($_GET['s']) && $_GET['s'] != 'inbox' && array_key_exists($_GET['s'], $listFlagged)) {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = '" . my_esc($_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 = mysql_fetch_assoc(mysql_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');
    mysql_query("UPDATE `mail` SET `$setFlags` = '$flags' WHERE `id` = '$post[id]' LIMIT 1");
}

if ($contact['id'] !== '') {
    mysql_query("UPDATE `mail` SET `read` = '1' WHERE `id_kont` = '$user[id]' AND `id_user` = '" . my_esc($contact['id']) . "'");
}

$_SESSION['sid'] = mt_rand(11111, 99999);
$set['title'] =  'Почта/' . text($contact['nick']);
include_once H.'sys/inc/thead.php';
title();
aut();
err();
?>
<link rel="stylesheet" href="style/css/email.css" type="text/css" />

<ol class="breadcrumb">
  <li><a href="/"><img src="/mail/style/icons/home.png" /></a></li>
  <li><a href="/id<?= $user['id']?>"><?= $user['nick']?></a></li>
  <li><a href="/mail/">Почта</a></li>
  <? if ($flagged == 'inbox') { ?>
    <li class="active"><?= text($contact['nick'])?></li>
  <? } else { ?>
    <li><a href="/mail/?s=<?= $flagged?>"><?= $listFlagged[$flagged]?></a></li>
    <li class="active"><?= text($contact['nick'])?></li>
  <? } ?>
</ol>

<? if ($contact['id']) { ?>
  <div class="email email-panel">
    <span class="email-login">
      <?= $contact['link']?>
    </span> 
    
    <form class="buttonLink pull-right" action="index.php?s=<?= $flagged?>" method="POST">
      <input type="hidden" name="cnt1" value="<?= text($contact['id'])?>">
      <button type="submit" name="action" value="<?= ($flagged != 'archive' ? 'archive' : 'inbox')?>" class="buttonLink"><img src="/mail/style/icons/archive.png" /> <?= ($flagged != 'archive' ? 'В архив' : 'Из архива')?></button>
      <button type="submit" name="action" value="<?= ($flagged != 'spam' ? 'spam' : 'inbox')?>" class="buttonLink"><img src="/mail/style/icons/<?= ($flagged == 'spam' ? 'arrow-curve' : 'spam')?>.png" /> <?= ($flagged != 'spam' ? 'Это спам' : 'Это не спам')?></button>
    </form>
  </div>
<? } ?>

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

  <form class="newMessage" method="post" name="message" action="?contact=<?= urlencode($contact['id'])?>">
    <input type="hidden" name="sid" value="<?= $_SESSION['sid']?>">
    <? if (!$contact['id']) { ?>
      <span class="email-from">Кому:</span> 
      <input type="text" name="to" placeholder="Ник или Email..">
    <? 
    }
    
    $insert = text($_SESSION['mail']['msg']);
    $msg2 = text($_SESSION['mail']['msg']);
    
    if (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 {
        ?>
        <textarea name="msg" placeholder="Написать сообщение.."><?= $insert?></textarea><br />
        <?
    }
    ?>
    <input value="Отправить" type="submit" /> <button class="email-btn-files" type="submit" name="files"><img src="style/icons/paper-clip.png" /></button>
  </form>
  
  <?
  $attachments = new Attachments();
  echo $attachments->get_list();
}

if ($contact['id'] !== '') {
    $arrContacts = mysql_query("SELECT e.`id_user` 
                                FROM `mail` AS e
                                WHERE (`id_kont` = '$user[id]' AND `id_user` = '" . my_esc($contact['id']) . "' OR `id_kont` = '" . my_esc($contact['id']) . "' AND `id_user` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") ");

    $k_post = mysql_num_rows($arrContacts);

    if ($k_post == 0) {
        ?>
        <div class="mess">Список сообщений пуст</div>
        <?
    } else {
        
        $k_page = k_page($k_post,$set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];

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

        while ($post = mysql_fetch_assoc($q))
        {
            $ank = ($post['id_user'] != $user['id'] ? $contact : $user);
            $flags = ($post['id_kont'] == $user['id'] ? 'flaggedTo' : 'flaggedFrom');
            ?>
            <div class="email">
              <div class="email-messages">
                <span class="email-avatar pull-left"><?= $ank['avatar']?></span> 
                <span class="email-flagged pull-right">
                  <a href="?s=<?= $flagged?>&amp;page=<?= $page?>&amp;contact=<?= urlencode($contact['id'])?>&amp;message_id=<?= $post['id']?>&amp;fav=<?= ($post[$flags] == 'favorite' ? '0' : '1')?>">
                    <img src="style/icons/<?= ($post[$flags] == 'favorite' ? 'favorite' : 'nofav')?>.png">
                  </a>
                </span>
                <span class="email-time pull-right"><?= vremja($post['time'])?></span>  
                <span class="email-login">
                  <?= ($ank['icon'] ? $ank['icon'] : '')?> 
                  <span class="<?= ($ank['ban'] == true ? 'user-ban' : '')?>"><?= text($ank['nick'])?></span> <?= ($post['read'] == 0 ? '<span class="email-noread">(не прочитано)</span>' : '')?>
                </span> 
                <div class="email-textList">
                  <div class="<?= ($post['read'] == 0 ? 'email-text-noread' : '')?>">
                    <?= output_text($post['msg'])?><br />
                  </div>
                  <? 
                  if ($post['attachments'] == 1) { 
                    $f = mysql_query("SELECT * FROM `mail_files` AS e
                                      WHERE `email_id` = '$post[id]'
                                      ORDER BY `id` DESC");
                    ?>
                    <div class="attachments">
                    <?
                    while ($file = mysql_fetch_assoc($f))
                    {
                        ?>
                        <div class="attachments-message">
                          <a href="<?= $post['time']?>/<?= $file['md5']?>/<?= retranslit($file['name'])?>.<?= $file['ras']?>">
                            <img src="style/icons/ras/<?= (is_file('style/icons/ras/' . $file['ras'] . '.png') ? $file['ras'] : 'file')?>.png" /> <?= text($file['name'])?>.<?= $file['ras']?>
                          </a> (<?= size_file($file['size'])?>)
                        </div>
                        <?
                    }
                    ?>
                    </div>
                    <? 
                  } 
                  ?>
                </div>
              </div>
            </div>
            <?
        }

        if ($k_page > 1) {
            str('?s=' . $flagged . '&amp;contact=' . urlencode($contact['id']) . '&amp;', $k_page, $page);
        }        
    }
    
    if ($contact['id']) { 
    ?>
    <div class="email email-panel">
      <form class="buttonLink pull-right" action="index.php?s=<?= $flagged?>" method="POST">
        <input type="hidden" name="cnt1" value="<?= text($contact['id'])?>">
        <button type="submit" name="action" value="<?= ($flagged != 'deleted' ? 'deleted' : 'inbox')?>" class="buttonLink"><img src="/mail/style/icons/<?= ($flagged == 'deleted' ? 'arrow-curve' : 'deleted')?>.png" /> <?= ($flagged != 'deleted' ? 'Удалить' : 'Восстановить')?></button>
      </form>
    </div>
    <? 
    } 
}

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