<?php
if (!defined('R_P')) exit("access Die");
include_once(R_P . "/include/class.phpmailer.php");
@set_time_limit(180);
@ignore_user_abort();
class cron_sendmail{
	var $mail;
	var $queue_num = 10;
	function cron_sendmail(){
		global $_SET;
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->SMTPAuth   = true;                  // enable SMTP authentication
		$mail->SMTPSecure = "";                 // sets the prefix to the servier
		$mail->Host = $_SET['smtpserver'];      // sets GMAIL as the SMTP server
		$mail->Port = $_SET['smtpserverport'];                   // set the SMTP port for the GMAIL server
		$mail->Username   = $_SET['smtpuser'];  // GMAIL username
		$mail->Password   = $_SET['smtppass'];            // GMAIL password
		$mail->From       = $_SET['smtpuser'];
		$mail->FromName   = "webmater";
		$mail->IsHTML(true);
		$mail->CharSet = $_SET['def_charset'];
		$mail->SMTPDebug = false;
		$mail->WordWrap   = 50;
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer! ";
	}
	
	function run(){
		$data = qdb::fetchAll("select * from ".TABLEPRE."mail_queue order by id asc limit {$this->queue_num}");
		foreach($data as $val){
			if($val['status'] == 0){
				qdb::query("update ".TABLEPRE."mail_queue set status = 1, dateline = ".time()." where id = '{$val['id']}' ");
				$r = $this->mailQueueUpdate($val['mailto'],$val['username'],$val['subject'],$val['body']);
				if(!$r) continue;
				else $this->deleteMailQueue($val['id']);
			}elseif($val['status'] == 1){
				if(time() - $val['dateline'] < 180) continue;
				$this->mailQueueUpdate($val['mailto'],$val['username'],$val['subject'],$val['body']);
				$this->deleteMailQueue($val['id']);
			}else{
				$this->deleteMailQueue($val['id']);
			}
		}
	}
	
	function deleteMailQueue($id){
		qdb::query("delete from ".TABLEPRE."mail_queue where id = '{$id}' ");
	}

	function mailQueueUpdate($mailto, $username, $subject, $body){
		global $_SET;
		if(strtolower($_SET['def_charset']) == 'utf-8') $subject = "=?UTF-8?B?".base64_encode($subject)."?=";
		$body = eregi_replace("[\]",'',$body);
		$this->mail->Subject = $subject;
		$this->mail->MsgHTML($body);
		$this->mail->AddAddress($mailto, $username);
		return $this->mail->Send();
	}	
}
?>