<?php

#Этот файл рекомендуется переименовать и настроить 
require_once '../../sys/inc/start.php';
require_once H . 'sys/inc/compress.php';
require_once H . 'sys/inc/sess.php';
require_once H . 'sys/inc/settings.php';
require_once H . 'sys/inc/db_connect.php';

function save($set) {
    if ($fopen = @fopen(H . 'sys/ini/settings.ini', 'w')) {
        $ini_file = array('[SYSTEM]');

        foreach ($set as $key => $value) {
            $ini_file[] = $key . '="' . htmlentities((string) $value, ENT_QUOTES, 'UTF-8') . '";';
        }

        @fputs($fopen, implode("\r\n", $ini_file));
        @fclose($fopen);
        return true;
    } else {
        return false;
    }
}

$config = array(
    'attachments' => H . 'sys/mail/',
);

/**
 * Крон MySQL запросов 1 раз в день
 * Очистка почты за указанный период
 */
$c = $db->query("SELECT * FROM `cron` WHERE `id` = 'mail_delete'");

if ($db->num_rows($c) == 0) {
    $db->query("INSERT INTO `cron` (`id`, `time`) VALUES ('mail_delete', '" . time() . "')");
}

$cronTime = $db->get_row($c);

if (isset($cronTime['time']) && $cronTime['time'] < (time() - 60 * 60 * 24)) {
    #Очистка корзин почты
    $db->query("UPDATE `mail` SET `deleted` = IF(`flaggedTo` = 'deleted', `id_kont`, `id_user`) WHERE (`flaggedTo` = 'deleted' OR `flaggedFrom` = 'deleted') AND `time` < '" . (time() - $set['mail_clear_time']) . "' AND (`deleted` != '-1' OR `type` = 'email')");
    $db->query("UPDATE `mail` SET `deleted` = '-1' WHERE `flaggedTo` = 'deleted' AND (`flaggedFrom` = 'deleted' OR `id_user` = '0') AND `time` < '" . (time() - $set['mail_clear_time']) . "' AND `deleted` != '-1' AND `deleted` != '0'");

    #Физическое удаление почты и файлов
    $b = $db->query("SELECT * FROM `mail` WHERE `deleted` = '-1' AND `time` < '" . (time() - $set['mail_truncate_time']) . "'");

    while ($delete = $db->get_row($b)) {
        if ($delete['attachments'] == 1) {
            $f = $db->query("SELECT * FROM `mail_files` WHERE `email_id` = '$delete[id]'");
            while ($fileDelete = $db->get_row($f)) {
                $k = $db->super_query("SELECT COUNT(*) as count FROM `mail_files` AS f LEFT JOIN `mail` AS e ON f.email_id = e.id WHERE f.size = '$fileDelete[size]' AND e.deleted != '-1'");

                if ($k['count'] == 0) {
                    if (is_file($config['attachments'] . $fileDelete['md5'] . '.dat')) {
                        @unlink($config['attachments'] . $fileDelete['md5'] . '.dat');
                    }
                }
            }
            $db->query("DELETE FROM `mail_files` WHERE `email_id` = '$delete[id]'");
        }
    }
    $db->query("DELETE FROM `mail` WHERE `deleted` = '-1' OR (`id_user` = '0' AND `deleted` != '0')");
    $db->query("UPDATE `cron` SET `time` = '" . time() . "' WHERE `id` = 'mail_delete'");
}

#Проверка Email почты
if (isset($set['mail_active']) && $set['mail_active'] == 1 && $set['mail_panel_login'] && $set['mail_panel_pass']) {
    $email = new Email('{' . $set['mail_panel_imap'] . ':993/imap/ssl/novalidate-cert}INBOX', $set['mail_panel_login'], $set['mail_panel_pass'], $config['attachments'], 'utf-8');

    if (!$email->getImapStream()) {
        $temp_set = $set;
        $temp_set['mail_active'] = 0;

        if (save($temp_set)) {
            $db->query("INSERT INTO `mail`(`id_user`, `id_kont`, `time`, `type`, `msg`, `attachments`, `read`) VALUES ('0', '1', '$time', 'personal', 'Внимание, при сборе Email почты, система не смогла подключиться к почтовому ящику " . $set['mail_panel_login'] . ", мы отключили проверку Email почты, вам необходимо проверить настройки данных в Админке, а так же проверить настройки Почтового сервера на наличие IMAP, и почтового ящика администратора.', '0', '0')");
        }
    } else {
        $messages = $email->getListMessages();

        if (count($messages) > 0) {
            foreach ($messages AS $key => $post) {
                #Прикрепленные файлы если есть
                $files = $post->getAttachments();

                #Пользователь по умолчанию
                if ($set['mail_user_null'] == 1) {
                    $userToDefault = 1;
                }

                $contact_set = array(
                    'email_on' => '1',
                );

                $userTo = key($post->to);

                preg_match('/(.*)@/i', $userTo, $matches);

                #Поиск адресата
                $nouser = $db->get_row($db->query("SELECT id, nick FROM user WHERE nick = '" . $db->safesql(strtolower($matches[1])) . "' LIMIT 1"));

                if (isset($nouser['nick'])) {
                    $userToDefault = $nouser['id'];
                    $contact_set = $db->get_row($db->query("SELECT * FROM `user_set` AS u WHERE `id_user` = '" . $nouser['id'] . "' LIMIT 1"));
                } else {
                    $post->message .= "\r\n[red]Недоставленное сообщение для [b]" . $userTo . "[/b][/red]";
                }

                #Если настройка стоит не принимать email от неизвестных контактов
                if ($contact_set['email_on'] == 0) {
                    $k_post = $db->super_query("SELECT COUNT(*) as count FROM `mail` WHERE `id_kont` = '" . $db->safesql($post->fromAddress) . "' AND `id_user` = '$nouser[id]' AND `deleted` != '$nouser[id]' AND `deleted` != '-1'");
                    if ($k_post['count'] == 0) {
                        unset($userToDefault);
                    }
                }

                if (isset($userToDefault)) {
                    $t = $db->super_query("SELECT COUNT(*) as count FROM `mail` WHERE `flaggedTo` = 'spam' AND `id_user` = '" . $db->safesql($post->fromAddress) . "' AND `id_kont` = '" . $userToDefault . "'");

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

                    $db->query("INSERT INTO `mail`(`id_user`, `id_kont`, `time`, `type`, `msg`, `attachments`, `read`, `flaggedTo`) VALUES ('" . $db->safesql($post->fromAddress) . "', '" . $userToDefault . "', '" . $time . "', 'email', '" . $db->safesql($post->message) . "', '" . ($files ? 1 : 0) . "', '0', '$flaggedIs')");

                    $id_email = $db->insert_id();
                    foreach ($files AS $file) {
                        $db->query("INSERT INTO `mail_files`(`name`, `md5`, `id_user`, `id_kont`, `ras`, `type`, `size`, `email_id`) VALUES ('" . $db->safesql($file->nameSave) . "', '" . $file->fileSave . "', '" . $db->safesql($post->fromAddress) . "', '" . $userToDefault . "', '" . $db->safesql($file->ras) . "', '" . $db->safesql($file->mimetype) . "', '" . $file->size . "', '" . $id_email . "')");
                    }
                }

                $email->deleteMail($post->id);
            }
            unset($key, $post, $messages, $email, $files, $file);
        }
    }
}