Файл: 3020.ru/file_3020/plugins/user.mail.php
Строк: 267
<?
if (isset($ID)) {
  $ank = $sql -> fetch("SELECT * FROM `users` WHERE `id` = '$ID' LIMIT 1");
  $contact = $sql -> fetch("SELECT * FROM `contacts` WHERE `id_contact` = '$ID' AND `id_user` = '".$user['id']."' LIMIT 1");
}
if ($level == 0 || !isset($ank['id']) || $ank['id'] == $user['id']){
  header('Location: /index.php');
  exit;
}
$sban = $sql -> fetch("SELECT * FROM `ban` WHERE `id_ban` = '".$user['id']."' AND `time` > '$time' ORDER BY `time` DESC LIMIT 1");
if (isset($sban['id'])) {
  if ($sban['view'] == 1 && $sban['id_user'] == $ank['id']) {
    $spost = $sql -> fetch("SELECT * FROM `mail` WHERE `id_user` = '".$user['id']."' OR `id_contact` = '".$user['id']."' ORDER BY `time` DESC LIMIT 1");
    
    if ($spost['id_user'] == $user['id']) {
      $err[] = 'Теперь дождитесь ответа ' . login($ank['id'], 0);
    }
  } else {
    header('Location: /?func=user.ban');
    exit;
  }  
}
$status = $sql -> fetch("SELECT 
      SUM(IF(`id_contact` = '".$user['id']."' AND `id_user` = '$ID' AND `type` = '0', 1, 0)) AS 'ignore',
      SUM(IF(`id_contact` = '$ID' AND `id_user` = '".$user['id']."', 1, 0)) AS 'user',
      SUM(IF(`id_contact` = '".$user['id']."' AND `id_user` = '$ID', 1, 0)) AS 'contact'
      FROM `contacts`");
      
      $status = array('user' => (int) $status['user'], 'contact' => (int) $status['contact'], 'ignore' => (int) $status['ignore']);
      
if ($status['ignore'] == 1 && $level <= $ank['level']) {
  $err[] = login($ID, 0) . ' запретил Вам писать ему';
}
      
if (isset($_GET['type']) && $contact['id_user']) {
  if ($_GET['type'] >= 0 && $_GET['type'] <= 2) {
    $type = (int) $_GET['type'];
    $contact['type'] = $type;
    
    $sql -> update("UPDATE `contacts` SET `type` = '$type' WHERE `id_user` = '".$user['id']."' AND `id_contact` = '$ID'");
    if ($type == 0) {
      $messages[] = 'Контакт успешно добавлен в список игнорируемых';
    } elseif ($type == 1) {
      $messages[] = 'Контакт успешно добавлен в общий список';
    } elseif ($type == 2) {
      $messages[] = 'Контакт успешно добавлен в список избранных';
    }
  }
}
if (isset($_GET['delete'])) {
  $delete = (int) $_GET['delete'];
  $delete = $sql -> fetch("SELECT * FROM `mail` WHERE `id` = '$delete' AND (`id_user` = '".$user['id']."' OR `id_contact` = '".$user['id']."') LIMIT 1");
  
  if ($delete['id']) {
    if ($delete['unlink'] == $ank['id']) {
      $sql -> delete("DELETE FROM `mail` WHERE `id` = '".$delete['id']."' AND (`id_user` = '".$user['id']."' OR `id_contact` = '".$user['id']."') LIMIT 1");
      
      if ($delete['file'] != '0') {
        $file = unserialize($delete['file']);
        @unlink(SRC . 'screen/mail/' . $file['cache'] . '.png');
        unlink(FILES . 'mail/' . $file['cache'] . '.dat');
      }
    } else {
      $sql -> update("UPDATE `mail` SET `unlink` = '".$user['id']."' WHERE `id` = '".$delete['id']."' AND (`id_user` = '".$user['id']."' OR `id_contact` = '".$user['id']."') LIMIT 1");
    }
    $messages[] = 'Сообщение успешно удалено';    
  }
}
if (isset($_GET['truncate']))
{
  $array = $sql -> select("SELECT * FROM `mail` WHERE `unlink` = '$ank[id]' AND (`id_user` = '".$user['id']."' AND `id_contact` = '$ank[id]' OR `id_user` = '$ank[id]' AND `id_contact` = '$user[id]' AND `unlink` = '$ank[id]')");
  
  foreach ($array AS $post) {
    if ($post['file']) {
      $file = unserialize($post['file']);
      @unlink(SRC . 'screen/mail/' . $file['cache'] . '.png');
      unlink(FILES . 'mail/' . $file['cache'] . '.dat');
    } else {
      $file = false;
    }
    $sql -> delete("DELETE FROM `mail` WHERE `id` = '$post[id]' AND (`id_user` = '$user[id]' OR `id_contact` = '$user[id]') LIMIT 1");
  }
  $sql -> update("UPDATE `mail` SET `unlink` = '$user[id]' WHERE (`id_user` = '$user[id]' AND `id_contact` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_contact` = '$user[id]')");
  
  $_SESSION['message'] = 'Переписка успешно очищена';
  header('Location: ?func=' . $func . '&id=' . $ank['id']);
  exit;
}
    
if (isset($_GET['download'])) {
  $id_file = (int) $_GET['download'];
  $_file = $sql -> fetch("SELECT * FROM `mail` WHERE `id` = '$id_file' AND `file` != '0' LIMIT 1");
  if ($_file['id']) {
    $file = unserialize($_file['file']);
    if (is_file(FILES . 'mail/' . $file['cache'] . '.dat')) {
      DownloadFile(FILES . 'mail/' . $file['cache'] . '.dat', $file['name'] . '.' . $file['ras'], $file['type']);
      exit;
    }
  }
}
$sql -> update("UPDATE `mail` SET `read` = '1' WHERE `id_user` = '$ank[id]' AND `id_contact` = '$user[id]' AND `read` = '0'");
if (isset($_POST['msg'])) {
  $msg = $sql->esc($_POST['msg']);
  $files = 0;
  
  if (strlen2($msg) > 3072) {
    $err[] = 'Сообщение слишком длинное';
  } elseif (strlen2($msg) < 2) {
    $err[] = 'Сообщение слишком короткое';
  }
  
  
if($sql -> selectCount("SELECT COUNT(*) FROM `mail` WHERE `id_user` = '".$user['id']."' AND `msg` = '".$msg."' AND `time` > '".($time - 10)."' LIMIT 1") != 0)
{
$err='Сообщение повторяет предедущее !';
}
/// Если нет покупок то проверяем заполнен ли вмид и если нет не даём писать
$pokupka = $sql -> selectCount("SELECT COUNT(*) FROM `shop_pays` WHERE `id_user` = '".$user['id']."' AND `pays` = '1'");
if ($pokupka == 0) {
//if ($user['wmid']==0)$err[] = 'Не заполнены реквизиты в анкете !'; /// by_Mstivoj
}
  if (isset($_FILES['file']) && $_FILES['file']['name'])
  { 
      if (!preg_match("#^([A-z/- ])+$#ui", $_FILES['file']['type'])) {
          $err[] = 'Не допустимое значение типа файла';
      }
    
    $file = esc(stripcslashes(htmlspecialchars($_FILES['file']['name'])));
    $size = (int) $_FILES['file']['size'];
    $type = $sql->esc($_FILES['file']['type']);
    $file = preg_replace('(#|?)', NULL, $file);    
    $name = preg_replace('#.[^.]*$#', NULL, $file);
    $cache = md5($time);
    $ras = strtolower(preg_replace('#^.*.#', NULL, $file));
    
    $files = array('name' => $name, 'ras' => $ras, 'size' => $size, 'type' => $type, 'cache' => $cache);    
    
    if ($files != 0) {
          if (!copy($_FILES['file']['tmp_name'], FILES.'mail/' . $cache . '.dat'))    {          
        $files = 0;    
              $err[] = 'Ошибка при выгрузке файла'; 
          } else {
            if ($ras == 'gif' || $ras == 'png' || $ras == 'jpg' || $ras == 'jpeg') {
                if (isset($_FILES['file']) && $imgc = @imagecreatefromstring(file_get_contents($_FILES['file']['tmp_name'])))    {
                    $img_x = imagesx($imgc);
                    $img_y = imagesy($imgc);
                    
                  if ($img_x == $img_y) {
                      $dstW = 220;
                      $dstH = 220;
                  }    elseif ($img_x > $img_y) {        
                      $prop = $img_x / $img_y;
                      $dstW = 220;
                      $dstH = ceil($dstW / $prop);
                  } else {
                      $prop = $img_y / $img_x;
                      $dstH = 220;
                      $dstW = ceil($dstH / $prop);
                  }
                  $screen = imagecreatetruecolor($dstW, $dstH);
                  imagecopyresampled($screen, $imgc, 0, 0, 0, 0, $dstW, $dstH, $img_x, $img_y);
                  imagedestroy($imgc);
                  imagegif($screen, SRC.'screen/mail/' . $cache . '.png');
                  imagedestroy($screen);
                }
            }
        $files = serialize($files);
        @chmod(FILES.'mail/' . $cache . '.dat', 0666);
      }
    }
  }
        
  
  if (!isset($err)) {
    $sql -> insert("INSERT INTO `mail` (`id_user`, `id_contact`, `time`, `msg`, `file`) VALUES ('" . $user['id'] . "', '" . $ank['id'] . "', '$time', '$msg', '$files')");
    $id_file = $sql->insert_id();
    if ($status['contact'] == 0) {
      $sql -> insert("INSERT INTO `contacts` (`id_user`, `id_contact`, `time`, `time_last`, `type`, `id_last`) VALUES ('" . $ank['id'] . "', '" . $user['id'] . "', '$time', '$time', '1', '$user[id]')");
    }
    
    if ($status['user'] == 0) {
      $sql -> insert("INSERT INTO `contacts` (`id_user`, `id_contact`, `time`, `time_last`, `type`, `id_last`) VALUES ('" . $user['id'] . "', '" . $ank['id'] . "', '$time', '$time', '1', '$user[id]')");
    }
    
/*sms оповещение*/
if ($ank['MyTelefonOk'] == 1 && $ank['tel_mail']== 1 && $ank['date_last'] < time()-600 && $ank['wmr'] > 1)
{
     if ($sql -> select("SELECT * FROM `smsantiflud` WHERE `id_user` = '".$ank['id']."' AND `mod` = 'mail'") == 0)
     {
     include_once FUNC.'smsc_api.php';
     $r = send_sms($ank['MyTelefon'], "У Вас новое личное сообщение на 4i4i.Ru");
          if ($r[1] > 0)
          {
          $sql -> update("UPDATE `users` SET `wmr` = `wmr` - '1' WHERE `id` = '".$ank['id']."' LIMIT 1");
          $sql -> insert("INSERT INTO `smsantiflud`(`time`, `id_user`, `mod`) VALUES('".time()."', '".$ank['id']."', 'mail')");
          $BySMS = "Списание За смс оповещение на мобильный телефон.";
          $sql -> insert("INSERT INTO `billing_log` (`time`, `type`, `id_user`, `coins`, `msg`) VALUES ('".time()."', 'Mysms', '$ank[id]', '-1', '$BySMS')"); 
          }
     }
}
/*sms оповещение*/
    if (function_exists('mail')) {
      if ($ank['em_mail'] == 1) {
        // в этом массиве то, что попадет в наш HTML шаблон письма
    $array = array('hello' => 'Здравствуйте ' . $ank['login'], // {hello} . Приветствие  
    'message' => 'Пользователь <b>'.$user['login'].'</b>, оставил(а) новое сообщение.<br />
Текст Сообщения:<br />
    '. $_POST['msg'] .'
            ', // обязательно текст письма, но само завизит от того что в шаблоне указано. у меня {message}
    'linkbutton' => 'http://' . $_SERVER['HTTP_HOST'] . '/?func=user.auth', // у меня в шаблоне кнопка, это ссылка в ней {linkbutton}
    'textbutton' => 'Авторизация' // а это название моей кнопки {textbutton}
    );
        $Subject = 'У вас новое сообщение';  // обязательно заголовок письма
        $addAdress = $ank['email']; // сверх важно!! кому письмо
        $template = 'default'; // название шаблона и папки в которой он лежит. Если у вас свой шаблон, напишите название воего 
        // пробуем выслать наше письмо
        $OutMailer = Mailer($array, $Subject, $addAdress, $template);
        if ($OutMailer === false)
        {
        
        }
else  echo $OutMailer; // если есть ошибки, их покажет
}
/*
            $subject = 'У вас новое сообщение';
            $mailmsg = "Пользователь <b>$user[login]</b>, оставил(а) новое сообщение.<br />С уважением администрация <a href='http://" . urlencode($_SERVER['SERVER_NAME']) . "'>" . text($_SERVER['SERVER_NAME']) . "</a>!";
        
            $adds = "From: "support@$_SERVER[HTTP_HOST]" <support@$_SERVER[HTTP_HOST]>n";
            $adds .= "Content-Type: text/html; charset=utf-8n";
            mail($ank['email'], '=?utf-8?B?' . base64_encode($subject).'?=', $mailmsg, $adds);              
      }
*/
/*
if ($ank['icq_mail'] == 1) {
if($ank['icq']!=NULL){
require FUNC . 'WebIcqLite.class.php';
define('UIN', 687336743);
define('PASSWORD', 'qazxswedc123');
$icq = new WebIcqLite();
if($icq->connect(UIN, PASSWORD)){
$msg= 'Система оповещений 4i4i.Ru: 
У вас новое личное сообщение от '. $user['login'] .' ';
$msg = iconv('UTF-8', 'CP1251', ' '.$msg.' ');
if(!$icq->send_message(''.$ank['icq'].'',' '.$msg.' '))
{
//echo $icq->error;
}
} 
}
}
*/
    }
    $sql -> update("UPDATE `contacts` SET `time_last` = '$time', `id_last` = '$user[id]' WHERE (`id_user` = '$user[id]' AND `id_contact` = '$ank[id]') OR (`id_user` = '$ank[id]' AND `id_contact` = '$user[id]') LIMIT 2");
    $_SESSION['message'] = 'Сообщение отправлено';
    header('Location: ?func=' . $func . '&id=' . $ank['id']);
    exit;
  } else {
    @unlink(SRC . 'screen/mail/' . $cache . '.png');
    @unlink(FILES . 'mail/' . $cache . '.dat');
  }
}
$system['title'] = 'Почта от ' . login($ID, 0);
require SYS . 'header.php';
?>
<form class="form_t" action="?func=user.mail&id=<?= $ID?>" method="POST" style="margin: 2px;" enctype="multipart/form-data">
  <? if (is_file(THEME . 'php/form.textarea.php')) {
    require THEME . 'php/form.textarea.php';
  } else {
    ?><textarea style="width: 75%;" name="msg" id="msg" placeholder="Cообщение..."></textarea><br /><?
  }
  ?>
        <?= ($user['mail_send_files'] == 1 ? '<input type="file" name="file" style="width:95%;margin-bottom: 10px;" class="btn"/><br />' : '')?>
  <button type="submit" class="btn">Отправить</button>      <a href="/?func=user.mail&id=<?= $ank['id']?>" class="btn">Обновить</a> 
</form>
<?
$k_post = $sql -> selectCount("SELECT COUNT(*) FROM `mail` WHERE (`id_user` = '$user[id]' AND `id_contact` = '$ID' OR `id_user` = '$ID' AND `id_contact` = '$user[id]') AND `unlink` != '$user[id]'");
if ($k_post == 0) {
  ?>
  <div class="alert" style="margin: 2px;">Список сообщений пуст</div>
  <?
} else {
  $k_page = k_page($k_post, $system['page_str']);
  $page = page($k_page);
  $start =  $system['page_str'] * $page -  $system['page_str'];
  $array = $sql -> select("SELECT * FROM `mail` WHERE  (`id_user` = '$user[id]' AND `id_contact` = '$ID' OR `id_user` = '$ID' AND `id_contact` = '$user[id]') AND `unlink` != '$user[id]' ORDER BY `time` DESC LIMIT $start, $system[page_str]");
  foreach ($array AS $post) {
    $num++;
    
    if ($post['file']) {
      $file = unserialize($post['file']);
    } else {
      $file = false;
    }
    
    ?>
    <div class="<?= ($num % 2 ? "nav1" : "nav2")?>">
      <a href="?func=<?= $func?>&id=<?= $ank['id']?>&delete=<?= $post['id']?>&page=<?= $page?>" class="close">×</a> 
      <? if ($post['id_user'] != $user['id']) { ?>
        <a href="?func=complaint&id=<?= $post['id']?>&type=mail&page=<?= $page?>" class="close" title="Жалоба на сообщение">∅</a> 
      <? } ?>
      
      <?= avatar($post['id_user'])?> <?= login($post['id_user'], 1)?> <?= vremja($post['time'])?> <?= ($post['read'] == 0 ? '<span class="off">[не прочитано]</span>' : '')?> <br />
      <?= text_out($post['msg'])?><br />
      <? if (isset($file['name'])) { ?>
      <?= (preg_match('/image/i', $file['type']) ? '<img src="/_images/screen/mail/' . $file['cache'] . '.png" /><br />' : '')?>
<a href="/mail/user/<?= $ank['id']?>/download/<?= $post['id']?>/<?= text(latin($file['name']))?>.<?= text($file['ras'])?>">      
<i class="icon-download-alt"></i> <?= text($file['name'])?>.<?= text($file['ras'])?></a>
      <? } ?>
    </div>
    <?
  }
  if ($k_page > 1) { 
    str('?func=' . $func . '&id=' . $ank['id'] . '&', $k_page, $page);
  }  
}
if ($contact['id_contact']) {
?>
  <div class="foot">
  Переместить: 
  <?= ($contact['type'] != 1 ? '<a href="?func=user.mail&id=' . $ID . '&type=1">Общие</a>' : '<b>Общие</b>')?> |
  <?= ($contact['type'] != 2 ? '<a href="?func=user.mail&id=' . $ID . '&type=2">Избранные</a>' : '<b>Избранные</b>')?> |
  <?= ($contact['type'] != 0 ? '<a href="?func=user.mail&id=' . $ID . '&type=0">Игнор</a>' : '<b>Игнор</b>')?>
  </div> 
<?
}
?>
<div class="foot">
« <a href="?func=user.contacts">Контакты</a> | <a href="?func=<?= $func?>&id=<?= $ank['id']?>&truncate">Очистить переписку</a>
</div>