<?php

class kEmailMessage extends kBase {

	var $Compiled;
	var $Headers;
	var $HeadersArray;
	var $BodyText;
	var $BodyHtml;
	var $Body;
	var $Subject;
//	var $From;
//	var $To;
//	var $ReplyTo;
//	var $CC;
//	var $BCC;
	var $Charset;
	var $LineFeed;
	var $TransferEncoding;
	var $From;
	var $To;


	var $IsMultipart;
	var $Parts;
	var $Files;


	var $TextBoundary;
	var $EmailBoundary;

	function kEmailMessage(){
		parent::kBase();
		//$this->TextBoundary = uniqid(adodb_mktime());
		$this->EmailBoundary = uniqid(adodb_mktime());
		$this->LineFeed = "\n";
		$this->Charset='ISO-8859-1';
		$this->TransferEncoding='8bit';
		$this->Body = '';
		$this->setHeader('Subject', 'Automatically generated message');
		$this->HeadersArray=array();

		$this->setHeader('Mime-Version', '1.0');
	}

	function setHeader($header, $value){
		$this->HeadersArray[$header] = $value;
		$this->Compiled = false;
	}

	function fixLineBreaks($data)
	{
		$data = str_replace("\n\n","\r\n\r\n",$data);
		$data = str_replace("\r\n","\n",$data);
		$data = str_replace("\n","\r\n",$data);
		return $data;
	}

	function setHeaders($headers){
		$headers=$this->fixLineBreaks($headers);
		$headers_lines = explode("\r\n", $headers);
		foreach ($headers_lines as $line_num => $line){
			list($header_field, $header_value) = explode(':', $line, 2);
			$header_value = trim($header_value);
			$this->setHeader($header_field, $header_value);
			if ($header_field == 'Subject') $this->Subject = $header_value;
		}

	}

	function appendHeader($header, $value){
		$this->HeadersArray[$header][] = $value;
		$this->Compiled = false;
	}


	function setFrom($from, $name=''){

		$this->From = $from;

		if ($name!=''){
			$from = trim($name).' <'.$from.'>';
		}
		$this->setHeader('From', trim($from));
	}

	function setTo($to, $name=''){

		$this->To = $to;

		if ($name!=''){
			$to = trim($name).' <'.$to.'>';
		}

		$this->setHeader('To', trim($to));
	}

	function setSubject($subj){
		$this->setHeader('Subject', $subj);
	}

	function SetCC($to_cc){
		$this->appendHeader('CC', $to_cc);
	}

	function SetBCC($to_bcc){
		$this->appendHeader('BCC', $to_bcc);
	}

	function setReplyTo($reply_to){
		$this->setHeader('Reply-to', $reply_to);
	}

	function Clear()
	{
		$this->Compiled = false;
		$this->Body = '';
		$this->BodyHtml = '';
		$this->BodyText = '';
		$this->Headers = '';
		$this->Files = '';
		$this->From = '';
		$this->To = '';
	}

	function setTextBody($body_text){

		$this->BodyText = $body_text;
		$this->Compiled = false;
	}

	function setHTMLBody($body_html){

		$this->BodyHtml = $body_html;
		$this->IsMultipart = true;
		$this->Compiled = false;
	}

	function compileBody(){
		$search = array (
							"'(<\/td>.*)[\r\n]+(.*<td)'i",//formating text in tables
							"'(<br[ ]?[\/]?>)|(<\/p>)|(<\/div>)|(<\/tr>)'i",
							"'<head>(.*?)</head>'si",
							"'<style(.*?)</style>'si",
							"'<title>(.*?)</title>'si",
							"'<script(.*?)</script>'si",
//								"'^[\s\n\r\t]+'", //strip all spacers & newlines in the begin of document
//								"'[\s\n\r\t]+$'", //strip all spacers & newlines in the end of document
							"'&(quot|#34);'i",
							"'&(amp|#38);'i",
							"'&(lt|#60);'i",
							"'&(gt|#62);'i",
							"'&(nbsp|#160);'i",
							"'&(iexcl|#161);'i",
							"'&(cent|#162);'i",
							"'&(pound|#163);'i",
							"'&(copy|#169);'i",
							"'&#(\d+);'e"
						);

		$replace = array (
							"\\1\t\\2",
							"\n",
							"",
							"",
							"",
							"",
//								"",
//								"",
							"\"",
							"&",
							"<",
							">",
							" ",
							chr(161),
							chr(162),
							chr(163),
							chr(169),
							"chr(\\1)"
						);
		if($this->BodyHtml){


			$not_html = preg_replace ($search, $replace, $this->BodyHtml);
			$not_html = strip_tags($not_html);
//			$not_html = $this->removeBlankLines($not_html);
			// Fixing problem with add exclamation characters "!" into the body of the email.
			$not_html = wordwrap($not_html, 72);
			$this->BodyHtml = wordwrap($this->BodyHtml, 72);

			$this->Body = '';
			//$this->Body .= 'Content-Type: multipart/alternative;'.$this->LF()." ".'boundary="----='.$this->TextBoundary.'"'.$this->LF();
			//$this->Body .= $this->LF();
			$this->Body .= '------='.$this->EmailBoundary.$this->LF();
			$this->Body .= 'Content-Type: text/plain;'." ".'charset="'.$this->Charset.'"'.$this->LF();
			$this->Body .= $this->LF();
			$this->Body .= $not_html.$this->LF().$this->LF();
			$this->Body .= '------='.$this->EmailBoundary.$this->LF();
			$this->Body .= 'Content-Type: text/html;'." ".'charset="'.$this->Charset.'"'.$this->LF();
			$this->Body .= 'Content-Transfer-Encoding: '.$this->TransferEncoding.$this->LF();
			$this->Body .= 'Content-Description: HTML part'.$this->LF();
			$this->Body .= 'Content-Disposition: inline'.$this->LF();
			$this->Body .= $this->LF();

			$this->BodyHtml = str_replace("\r", "", $this->BodyHtml);
			$this->BodyHtml = str_replace("\n", $this->LF(), $this->BodyHtml);

			$this->Body .= $this->BodyHtml;
			$this->Body .= $this->LF().$this->LF();


			$this->IsMultipart = true;

		}else{
			$not_html = preg_replace ($search, $replace, $this->BodyText);
			$not_html = strip_tags($not_html);
//			$not_html = $this->removeBlankLines($not_html);
			// Fixing problem with add exclamation characters "!" into the body of the email.
			$not_html = wordwrap($not_html, 72);


			if ($this->IsMultipart){
				$this->Body .= '------='.$this->EmailBoundary.$this->LF();
				$this->Body .= 'Content-Type: text/plain;'.$this->LF()." ".'charset="'.$this->Charset.'"'.$this->LF();
				$this->Body .= 'Content-Disposition: inline'.$this->LF();
				$this->Body .= $this->LF();
				$this->Body .= $not_html.$this->LF().$this->LF();
			}else{
				//$this->BodyText = str_replace("\r", "", $this->BodyText);
				//$this->BodyText = str_replace("\n", $this->LF(), $this->BodyText);
				$this->Body = $not_html;
			}

		}

	}

	function setCharset($charset){
		$this->Charset = $charset;
		$this->Compiled = false;
	}

	function setLineFeed($linefeed){
		$this->LineFeed=$linefeed;
	}

	function attachFile($filepath, $mime="application/octet-stream"){

		if(is_file($filepath)){
			$file_info = array('path'=>$filepath, 'mime'=>$mime);
			$this->Files[] = $file_info;
		}else{
			die('File "'.$filepath.'" not exist...'."\n");
		}

		$this->IsMultipart = true;
		$this->Compiled = false;
	}

	function LF($str=''){
		$str = str_replace("\n", "", $str);
		$str = str_replace("\r", "", $str);
		return $str.$this->LineFeed;
	}

	function getContentType(){
		$content_type="";
		if ($this->IsMultipart){
			$content_type .= $this->LF('multipart/alternative; boundary="----='.$this->EmailBoundary.'"');
		}else{
			$content_type .= $this->LF('text/plain;');
  			$content_type .= $this->LF(" ".'charset='.$this->Charset);
		}

		return $content_type;

	}

	// ========================================

	function compileHeaders(){

		$this->Headers="";

//		$this->Headers .= "From: ".$this->LF($this->From);
		//if ($this->ReplyTo){
//			$this->Headers .= "Reply-To: ".$this->ReplyTo.$this->LF();
		//}
		//$this->Headers .= "To: ".$this->LF($this->To);
		//$this->Headers .= "Subject: ".$this->LF($this->Subject);
		/*
		if (sizeof($this->CC)){
			$this->Headers .= "Cc: ";
			foreach ($this->Cc as $key => $addr){
				$this->Headers.=$this->LF($addr.',');
			}
		}

		if (sizeof($this->BCC)){
			$this->Headers .= "Bcc: ";
			foreach ($this->BCC as $key => $addr){
				$this->Headers.=$this->LF($addr.',');
			}
		}
		*/

		foreach ($this->HeadersArray as $key => $val){
			if ($key=="To" || $key=="") continue; // avoid duplicate "To" field in headers
			if (is_array($val)){
				$val = chunk_split(implode(', ', $val),72, $this->LF().' ');


				$this->Headers .= $key.": ".$val.$this->LF();
			}else{
				$this->Headers .= $key.": ".$val.$this->LF();
			}

		}

		if ($this->IsMultipart) {
			$this->Headers .= 'MIME-Version: 1.0'.$this->LF();
		}
		$this->Headers .= "Content-Type: ".$this->getContentType();

		//$this->Headers .= "Content-Transfer-Encoding: ".$this->TransferEncoding.$this->LF();


	}

	function compileFiles(){
			if ($this->Files){
				foreach($this->Files as $key => $file_info)
				{
					$filepath = $file_info['path'];
					$mime = $file_info['mime'];
					$attachment_header  = $this->LF('------='.$this->EmailBoundary);
					$attachment_header .= $this->LF('Content-Type: '.$mime.'; name="'.basename($filepath).'"');
					$attachment_header .= $this->LF('Content-Transfer-Encoding: base64');
					$attachment_header .= $this->LF('Content-Description: '.basename($filepath));
					$attachment_header .= $this->LF('Content-Disposition: attachment; filename="'.basename($filepath).'"');
					$attachment_header .= $this->LF('');

					$attachment_data = fread(fopen($filepath,"rb"),filesize($filepath));
					$attachment_data = base64_encode($attachment_data);
					$attachment_data = chunk_split($attachment_data,72);

					$this->Body .= $attachment_header.$attachment_data.$this->LF('');
					$this->IsMultipart = true;
				}
			}
	}

	function compile(){

		if ($this->Compiled) return;

		$this->compileBody();

		$this->compileFiles();

		$this->compileHeaders();

		// Compile
		if ($this->IsMultipart){
			$this->Body .= '------='.$this->EmailBoundary.'--'.$this->LF();
		}

		$this->Body = $this->fixLineBreaks($this->Body);
		$this->Headers = $this->fixLineBreaks($this->Headers);


		$this->Compiled = true;
	}

	// ========================================

	function getHeaders(){

		$this->Compile();
		return $this->Headers;
	}

	function getBody(){

		$this->Compile();
		return $this->Body;
	}

	function send(){

		return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody());
		//return mail($this->HeadersArray['To'], $this->HeadersArray['Subject'], "", $this->getHeaders().$this->LF().$this->LF().$this->getBody(), '-f'.$this->From);

	}

	function sendSMTP(&$smtp_object, $smtp_host, $user, $pass, $auth_used = 0){

		$params['host'] = $smtp_host;				// The smtp server host/ip
		$params['port'] = 25;						// The smtp server port
		$params['helo'] = $_SERVER['HTTP_HOST'];			// What to use when sending the helo command. Typically, your domain/hostname
		$params['auth'] = TRUE;						// Whether to use basic authentication or not
		$params['user'] = $user;				// Username for authentication


		$params['pass'] = $pass;				// Password for authentication
		$params['debug'] = 1;
		if ($auth_used == 0){
			$params['authmethod'] = 'NOAUTH';	// forse disabling auth
		}


		if (strpos($this->To, ',') !== false) {
			$this->To = str_replace(' ', '', $this->To);
			$send_params['recipients']	= explode(',', $this->To);
		}
		else {
			$send_params['recipients']	= array($this->To);							// The recipients (can be multiple)
		}

		$send_params['headers'] = explode("\r\n", $this->getHeaders());

		array_unshift($send_params['headers'], 'To: '.$this->HeadersArray['To']);
		$send_params['from']		= $this->From;									// This is used as in the MAIL FROM: cmd
		// It should end up as the Return-Path: header
		$send_params['body']=$this->getBody();


		if($smtp_object->connect($params) && $smtp_object->send($send_params)){
			if ( $this->Application->isDebugMode() )
			{
				$this->Application->Debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
				//define('DBG_REDIRECT', 1);
			}
			return true;
		}
		else {
			if ( $this->Application->isDebugMode() )
			{
				$this->Application->Debugger->appendHTML('<pre>'.$smtp_object->debugtext.'</pre>');
				//define('DBG_REDIRECT', 1);
			}
			return false;
		}

	}


}



?>