<?
include_once $_SERVER['DOCUMENT_ROOT'].'/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 H.'mail/classes/PHPMailerAutoload.php';

function save_settings($set) {
    unset($set['web']);
    if ($fopen = @fopen(H.'sys/dat/settings_6.2.dat', 'w')) {
        @fputs($fopen, serialize($set));
        @fclose($fopen);
        @chmod(H.'sys/dat/settings_6.2.dat', 0777);
        return true;
    }
    else
    return false;
}

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

/**
* Крон MySQL запросов 1 раз в день
* Очистка почты за указанный период
*/

$c = mysql_query("SELECT * FROM `cron` WHERE `id` = 'mail_delete'");

if (mysql_num_rows($c) == 0) {
    mysql_query("INSERT INTO `cron` (`id`, `time`) VALUES ('mail_delete', '" . time() . "')");
}

$cronTime = mysql_fetch_assoc($c);

if (isset($cronTime['time']) && $cronTime['time'] < (time() - 60 * 60 * 24))
{
  /**
  * Очистка корзин почты
  */
  mysql_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')");
  
  mysql_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 = mysql_query("SELECT * FROM `mail` WHERE `deleted` = '-1' AND `time` < '" . (time() - $set['mail_truncate_time']) . "'");

  while($delete = mysql_fetch_assoc($b)) {
    if ($delete['attachments'] == 1) {
      $f = mysql_query("SELECT * FROM `mail_files` WHERE `email_id` = '$delete[id]'");
      while($fileDelete = mysql_fetch_assoc($f)) {
        if (mysql_result(mysql_query("SELECT 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'"), 0) == 0) {
          if (is_file($config['attachments'] . $fileDelete['md5'] . '.dat')) {
            @unlink($config['attachments'] . $fileDelete['md5'] . '.dat');           
          }
        }
      }
      mysql_query("DELETE FROM `mail_files` WHERE `email_id` = '$delete[id]'");
    }
  }
  mysql_query("DELETE FROM `mail` WHERE `deleted` = '-1' OR (`id_user` = '0' AND `deleted` != '0')");
  mysql_query("UPDATE `cron` SET `time` = '" . time() . "' WHERE `id` = 'mail_delete'");
}

/**
* 
* @var  Проверка 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_settings($temp_set)) {
        mysql_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 = mysql_fetch_assoc(mysql_query("SELECT id, nick FROM user WHERE nick = '" . mysql_real_escape_string(strtolower($matches[1])) . "' LIMIT 1"));
        
        if (isset($nouser['nick'])) {
          $userToDefault = $nouser['id']; 
          $contact_set = mysql_fetch_assoc(mysql_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) {
          if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `id_kont` = '" . mysql_real_escape_string($post->fromAddress) . "' AND `id_user` = '$nouser[id]' AND `deleted` != '$nouser[id]' AND `deleted` != '-1'"), 0) == 0) {
            unset($userToDefault);
          }
        }
        
        if (isset($userToDefault)) {
          if (mysql_result(mysql_query("SELECT COUNT(*) FROM `mail` WHERE `flaggedTo` = 'spam' AND `id_user` = '" . mysql_real_escape_string($post->fromAddress) . "' AND `id_kont` = '" . $userToDefault . "'"), 0) > 0) {
              $flaggedIs = 'spam';
          } else {
              $flaggedIs = 'inbox';
          }

          mysql_query("INSERT INTO `mail`(`id_user`, `id_kont`, `time`, `type`, `msg`, `attachments`, `read`, `flaggedTo`) VALUES ('" . mysql_real_escape_string($post->fromAddress) . "', '" . $userToDefault . "', '" . $time . "', 'email', '" . mysql_real_escape_string($post->message) . "', '" . ($files ? 1 : 0) . "', '0', '$flaggedIs')");
          
          $id_email = mysql_insert_id();
          foreach($files AS $file) {
              mysql_query("INSERT INTO `mail_files`(`name`, `md5`, `id_user`, `id_kont`, `ras`, `type`, `size`, `email_id`) VALUES ('" . mysql_real_escape_string($file->nameSave) . "', '" . $file->fileSave . "', '" . mysql_real_escape_string($post->fromAddress) . "', '" . $userToDefault . "', '" . mysql_real_escape_string($file->ras) . "', '" . mysql_real_escape_string($file->mimetype) . "', '" . $file->size . "', '" . $id_email . "')");
          }              
        }

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