<?

class send_mail {

    var $notify_type;
    var $channel = 'email';
 
 function send ($email, $title, $body, $mailfrom = '', $attaches=array() ) {
      if (!$email ) return false;
      if (!$mailfrom) $mailfrom = 'zakaz@zootovar-spb.ru';
      if ( !$title ) {
        $title = "Mail from " . _MAIL_FROM_;
      }
      
      $email = str_replace('@.','@', $email); // Часто пишут @.mail.ru
      
      
      // Временно
      //return $this->sendSMTP($email, $title, $body);
     
      $title = '=?utf-8?B?'.base64_encode($title).'?=';
 
 
 
 	  if ( $attaches ) {
	      $boundary     = md5(uniqid(time()));

	      $headers = 
	      "MIME-Version: 1.0;\r\n" .   
	      "Reply-to: ".htmlspecialchars_decode($mailfrom)."\r\n".
	      "From: ".htmlspecialchars_decode($mailfrom)."\r\n".
	      "Content-type:  multipart/related; type=\"text/html\"; charset=utf-8; boundary=\"".$boundary."\"";
	      
	      $parts  = "--$boundary\r\n";   
    	  $parts .= "Content-Type: text/html; charset=utf-8\r\n";   
    	  $parts .= "Content-Transfer-Encoding: base64\r\n";   
    	  $parts .= "\r\n"; // раздел между заголовками и телом html-части 
    	  $parts .= chunk_split(base64_encode($body));
    	  
    	  foreach( $attaches as $arr ) {
    	  	$data = $arr['data'];	  
    	  	$name = $arr['name'];
    	  	$ct =	$arr['ct'];
    	  	$disp = $arr['attach']?'attachment':'inline';

			$parts .=  "\r\n--$boundary\r\n";   
		    $parts .= "Content-Type: ".$ct."; name=\"$name\"\r\n";   
		    $parts .= "Content-Transfer-Encoding: base64\r\n";   
		    $parts .= "Content-ID: <$name>\r\n";   
		    $parts .= "Content-Disposition: inline; filename=\"$name\"\r\n";   
		    $parts .= "\r\n"; // раздел между заголовками и телом прикрепленного файла 
		    $parts .= chunk_split(base64_encode($data));   
    	  }
 		  
 		  //$parts .=  "\r\n--$boundary\r\n";   
	      
 	  } else {
	      $headers = 
	      "Reply-to: ".htmlspecialchars_decode($mailfrom)."\n".
	      "From: ".htmlspecialchars_decode($mailfrom)."\n".
	      "Content-Transfer-Encoding: base64\r\n".
    	  "Content-type: text/html; charset=utf-8";
           $parts = chunk_split(base64_encode($body));
 	  }
      

      return mail($email, $title, $parts, $headers);
 }
 
 function sendSMTP($email, $title, $body) {
    require_once('smtp.class.php');
    $mail = new KM_Mailer("smtp.yandex.ru", "587", "zakaz@zootovar-spb.ru", "xcHkoYJx", "tls");
    if($mail->isLogin)  {
         if(  $mail->send("zakaz@zootovar-spb.ru", $email, $title, $body) ) {
            return true;
         }
         return false;
    }
    return false;
 }
 
 	 
 
 function to_pool($email, $title, $msg, $api_id = 1, $attach_ids = '', $from = '') {
 	 if (!$email) return;

     $email = trim($email);
     /*
     if ( !preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/i",$email ) ) {
            return;
     }
     */

 	 // Не отправляем на локальные адреса
     if ( preg_match("/client\d{1,}@zootovar-spb.ru/", $email) ) {
     	return false;
     }

     // проверяем тип оповещения в стоп-листе клиента
     if($this->notify_type){
         $types_obj = new cobject('shop_notify_types');
         $types_obj->byAttr('notify_type', $this->notify_type);

         $user_obj = new cobject('shop_users');
         $user_obj->byAttr('email', $email);

         $stop_obj = new cobject('shop_notify_stoplist');
         $db = $stop_obj->getDB()->q($stop_obj->getSelect(' AND `client_id`="'.$user_obj->id.'" AND `type_id`="'.$types_obj->id.'" AND `channel`="'.$this->channel.'"'));
         if($db->nr()){
            return false;
         }
     }


     $obj = new cobject('_sys_mail_pool');
     $obj->getDB()->q('INSERT INTO `_sys_mail_pool` (`id`,`email`,`title`,`msg`,`create_time`,`send_time`,`from`,`attach_ids`) VALUES (NULL,"'.db_escape_string($email).'","'.mysql_real_escape_string($title).'","'.mysql_real_escape_string($msg).'",'.time().', 0, "'.mysql_real_escape_string($from).'",  "'.$attach_ids.'" )');
     
     // Вместо пула - сразу шлём письмо
     /*
     $from = _MAIL_FROM_;
     $this->send($email, $title, $msg, $from);
        */
 }

function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
    $tmp = array_chunk(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
    $str = "";
    foreach ($tmp as $t) {
        $str .= join("", $t) . $e;
    }
    return $str;
}


}

?>
