<?php
if (isset($INCLUDED["class.msg"])) return;
else $INCLUDED["class.msg"]=1;

class msg {
        var $log;
        var $table="";
        var $table_n="";
        var $limit=10;

        function add_log($text, $is_date=true, $is_enter=true, $is_print=false) {
                $text=($is_date ? date("d.m.y [H:i:s]> ") : "").$text.($is_enter ? "\n" : "");
                $this->log.=$text;
                if ($is_print) print nl2br($text);
                return $text;
        }

        function msg($table=NULL) {
                global $config;
                $this->log="";
                $this->table_n="newsletters".$config["table_prefix"];
                if (isset($table)) {
                        $this->table=$table;
                        return true;
                }
                else false;
        }

        function add($r, $is_print_log=false) {
                global $db;
                $data=array(
                        "date_created"  => time(),
                        "date_start"    => (isset($r["date_start"]) ? $r["date_start"] : time()),
                        "last_update"   => time(),
                        "subscriber_id" => (isset($r["subscriber_id"]) ? $r["subscriber_id"] : 0),
                        "newsletter_id" => (isset($r["newsletter_id"]) ? $r["newsletter_id"] : 0),
                        "status"        => 0,
                );
                $fields="date_created, date_start, last_update, subscriber_id, newsletter_id, status, log";
                if ($data["subscriber_id"] && $data["newsletter_id"]) {
                        $data["log"]=$this->add_log("Add to list", true, true, $is_print_log);
                        $sql=get_sql_insert($this->table, $fields, $data);
                        $db->execute($sql);
                        return mysql_insert_id();
                } else return false;
        }

        function send_message($data) {
                global $PATH, $_SERVER, $config, $db, $newsletter;
                $subscriber=get_rec("subscribers".$config["table_prefix"], "where id='".$data["subscriber_id"]."'");
                $sql="select * from ".$this->table_n." where id='".$data["newsletter_id"]."'";
                $rs=$db->select($sql);
                $newsletter=$rs[0];
                $smtp=get_account("smtp_accounts", $newsletter["smtp"]);
                $pop3=get_account("pop3_accounts", $newsletter["pop3"]);
                if ($pop3['mail']) $pop3['mail']=preg_replace("/@.*/", '', $pop3['login']).'@'.$pop3['host'];
                $settings=load_settings($newsletter["owner_id"]);
                $message=($subscriber["receive_format"] ? $newsletter["text_content"] : $newsletter["html_header"].$newsletter["html_css"].$newsletter["html_content"]);
                $groups=explode(",", $newsletter["groups"]);
                $f=array(
                        "%subject%",
                        "%name%",
                        "%email%",
                        "%format%",
                        "%encoding%",
                        "%unsubscribe%",
                        "%properties%",
                        "%date%",
                );
                $v=array(
                        $newsletter["subject"],
                        $subscriber["name"],
                        $subscriber["mail"],
                        ($subscriber["receive_format"] ? "Plain text" : "HTML"),
                        $subscriber["encoding"],
                        "http://".$_SERVER['HTTP_HOST'].str_replace("admin/", "", $PATH)."unsubscribe/?id=".$subscriber["id"]."&group_id=".($data["group_id"] ? $data["group_id"] : $groups[0]),
                        "",
                        date($settings["date_format"]),
                );
                $sql="select cf.id, if(cf.enabled=1, scf.value, '') as value from custom_fields".$config["table_prefix"]." cf
                LEFT JOIN scf".$config["table_prefix"]." as scf ON
                        scf.custom_field_id=cf.id and
                        scf.subscriber_id='".$data["subscriber_id"]."'
                where cf.owner_id='".$subscriber["owner_id"]."'";
                $rs=$db->select($sql);
                for ($i=0; $i<count($rs); $i++) {
                        $f[]="%custom_field_".$rs[$i]["id"]."%";
                        $v[]=$rs[$i]["value"];
                }
                $message=change_links2(str_replace($f, $v, $message), $subscriber["receive_format"], 'n-'.$data['newsletter_id'], $subscriber['id']);
		if (!$subscriber["receive_format"]) {
			$message.='<img src="http://'.$_SERVER['HTTP_HOST'].str_replace("admin/", "", $PATH).'opened/?id='.str_to("type=n&msg_id={$data['id']}").'" width="1" height="1" border="0" />';
		}
		$message=ChangeImageURL($message);
                $array=array(
                        "login"         => $smtp["login"],
                        "password"      => $smtp["password"],
                        "host"          => $smtp["host"],
                        "port"          => $smtp["port"],
                        "from_name"     => $newsletter["from_name"],
                        "report"        => ($pop3['mail'] ? $pop3['mail'] : ''),
                        "from"          => ($newsletter["from_mail"] ? $newsletter["from_mail"] : $settings["mail_from"]),
                        "reply_to"      => $newsletter["reply_mail"],
                        "to_name"       => $subscriber["name"],
                        "to"            => $subscriber["mail"],
                        "subject"       => $newsletter["subject"],
                        "message"       => $message,
                        "charset"       => $subscriber["encoding"],
                        "content_type"  => ($subscriber["receive_format"] ? "text/plain" : "text/html"),
                );
                $SMTP=new SMTP($array);
		$newsletter['files']=($newsletter['files'] ? explode('|', $newsletter['files']) : array());
		for ($i=0; $i<count($newsletter['files']); $i++) {
			$SMTP->addAttach((strpos($PATH, 'admin/') ? '../' : '').'files/'.$newsletter['files'][$i]);
		}
		//$SMTP->debug=true;
                //$res=(($settings["mail_mode"] ? $SMTP->send() : $SMTP->send_mail()) ? $SMTP->message_id : "");
                $res=(($smtp["login"] ? $SMTP->send() : $SMTP->send_mail()) ? $SMTP->message_id : "");
                if ($res) {
                        $stat=new stat();

			// Статистика всех писем
                        //$stat->update("NEWSLETTER.SEND.ALL", 0);
                        //$stat->update("NEWSLETTER.SEND");

			// Статистика конкретного письма
                        $stat->update("NEWSLETTER[".$newsletter["id"]."].SEND.ALL", 0);
                        $stat->update("NEWSLETTER[".$newsletter["id"]."].SEND");

			// Статистика конкретного письма, отосланного через "Send All"
                        //$stat->update("NEWSLETTER[".$newsletter["id"]."].NEWSLETTER.SEND.ALL", 0);
                        //$stat->update("NEWSLETTER[".$newsletter["id"]."].NEWSLETTER.SEND");

 			$sql="update {$this->table_n} set last_sent='".time()."' where id='".$newsletter['id']."'";
			$db->execute($sql);
               }
                return $res;
        }

        function status_0($n_id=0) {
                global $db, $config;
                $sql="select * from ".$this->table." where status=0".($n_id ? " and newsletter_id='$n_id'" : '')." order by last_update limit ".$this->limit;
                $rs=$db->select($sql);
                for ($i=0; $i<count($rs); $i++) {
                        $fields="last_update, log, status, message_id";
                        $data=$rs[$i];
                        $res=$this->send_message($data);
                        $data["last_update"]=time();
                        $data["log"].=$this->add_log(($res ? "Message sent" : "Error: message not sent"), true, true);
                        $data["status"]=($res ? 1 : 0);
                        $data["message_id"]=$res;
                        $sql=get_sql_update($this->table, $fields, $data, "where id='".$data["id"]."'");
                        $db->execute($sql);
                }
        }

        function send_msg($id=0) {
                global $db, $config;
                $sql="select * from ".$this->table." where status=0 and date_start<=".time()." and id='$id'";
                $rs=$db->select($sql);
                for ($i=0; $i<count($rs); $i++) {
                        $fields="last_update, log, status, message_id";
                        $data=$rs[$i];
                        $res=$this->send_message($data);
                        $data["last_update"]=time();
                        $data["log"].=$this->add_log(($res ? "Message sent" : "Error: message not sent"), true, true);
                        $data["status"]=($res ? 1 : 0);
                        $data["message_id"]=$res;
                        $sql=get_sql_update($this->table, $fields, $data, "where id='".$data["id"]."'");
                        $db->execute($sql);
                }
        }

        function close($dir="") {
                $filename=$dir."files/stat/stat.log";
                if ($f=fopen($filename, "a")) {
                        fwrite($f, $this->log);
                        fclose($f);
                } else {
                        die("Can't save in file \"$filename\"");
                }
        }
}
?>