<?php
include_once($CORE_PATH.'\XTemplate.class.inc');

class MailBroker extends XTemplate {

	var $Templates = array();
	var $Properties = array();
	var $frommail;
	var $DB;
	var $LM;
	var $MSprior = array('1' => 'High','3' => 'Normal','5' => 'Low');

	function __construct() {
		global $REGISTRY,$DatabaseBroker;
		$Registry = loadObjectRegistry('MailBroker');
		$this->Templates = $Registry['Templates'];
		$this->Properties = $Registry['Properties'];
		$this->frommail = $REGISTRY['Core']['frommail'];
		$this->DB = $DatabaseBroker;
	}

	function sendMail($task = 'default', $arrayMail = array(), $arrayData = array(), $letter = '', $plain = false, $attachments = array()) {
		GLOBAL $REGISTRY, $Server,$CORE_PATH;
		$boundary = md5(microtime());
		$this->LM = $Server->getLM();
		$selected = $this->DB->SelectArray('system_mail m,system_mail_lang ml','ml.subject,ml.text',array('m.id' => 'ml.ownerid','ml.lang' => 1,'m.sys_name' => $task));
		$template = !empty($letter) ? $letter : $selected[0]['text'];/*implode(' ',file($CORE_PATH.'/Templates/MailBroker/'.$this->Templates['top'])).$selected[0]['text'].'</body></html>'*/
		$parser = new XTemplate($template);
		$parser->Cache = TRUE;
		$parser->Passing = FALSE;
		$parser->useCache = FALSE;
		$els = &$parser->getElements();
		$body = $parser->parseTemplate($arrayData);
		$subj = $selected[0]['subject'];
		$headers = "MIME-Version: 1.0\r\n";
		$headers .= "From: ".$this->frommail."\r\n";
		$headers .= "Return-Path: ".$REGISTRY['Core']['frommail']."\r\n";
		$headers .= "Reply-To: ".$REGISTRY['Core']['frommail']."\r\n";
		$headers .= "X-Sender: ".$REGISTRY['Core']['frommail']."\r\n";
		$headers .= "X-Mailer: ".$REGISTRY['Core']['SiteName']." Mailer v1.07\r\n";
		$headers .= "X-Priority: 3\r\n";
		$headers .= "X-MSMail-Priority: 3\r\n";
		if(empty($attachments)){
			$headers.= $plain ? "Content-type: text/plain; charset=utf-8\r\n" : "Content-type: text/html; charset=utf-8\r\n";
			$headers.= $plain ? "Content-Transfer-Encoding: 8bit\r\n" : "";
		}
		else{
			$headers .= "Content-type: multipart/mixed; boundary=\"".$boundary."\"\r\n";
			$body = "--".$boundary."\r\n".($plain ? "Content-type: text/plain; charset=utf-8\r\n" : "Content-type: text/html; charset=utf-8\r\n").($plain ? "Content-Transfer-Encoding: 8bit\r\n" : "").$body;
			$count = count($attachments);
			for($i = 0; $i < $count; $i++){
				$body .= "\n\n--".$boundary."\n";
				$body .= "Content-type: ".$attachments[$i]['type']."; name=\"".$attachments[$i]['filename']."\"\n";
				$body .= "Content-transfer-encoding: base64\n";
				$body .= "Content-disposition: attachment\n\n";
				$body .= chunk_split(base64_encode($attachments[$i]['content']))."\n";
			}
			$body .= "--".$boundary."--\n\n";//echo $body.'<br>';
		}
		foreach($arrayMail as $key => $email) {
			/*echo $body.'<br>';
			if(mail($email,$subj,$body,$headers)) echo $email.' TRUE<br>';
			else echo $email.' FALSE<br>';
			echo '<hr>';*/
			mail($email, $subj, $body, $headers);
		}
	}
	
}
?>