<?php
function MakeHtmlBodyFromArcmondClient($ip= NULL,$port ="8787",$cmd_seq ="2") 
{
	if ($ip != NULL) 
	{
		sleep(5); // FHS SETTING VALUE (default:30)
		$command = "../inc/arcmond_client $ip $port $cmd_seq";
		exec($command, $raid_res);
		$raid_str = explode(":", $raid_res[0]);

		$body  = "<table border=\"1\" width=\"565\" cellspacing=\"0\" cellpadding=\"0\">";
		$body .= "  <tr>";
		$body .= "      <td colspan=\"2\">";
		$body .= "      <font size=3><b>IP : $ip</b></font> Checked at ".date("Y-m-d H:i:s", $raid_str[1])." <br> ";
		$body .= "      </td>";
		$body .= "  </tr>";

		$to_eli = $raid_str[0].":".$raid_str[1].":";
		$raid_res[0] = str_replace($to_eli,"",$raid_res[0]); // remove header phase
		$tot = count($raid_res);

		for($i=0; $i < $tot; $i++) {
			$raid_res2 = explode("] ", str_replace("[", "", trim($raid_res[$i])));
			echo $raid_res2[0]."<br>";
			if($raid_res2[0] != "" && substr_count($raid_res2[0], "Disabled") == 0) {
				$body .= "  <tr>";
				$body .= "      <td width=\"160\" align=\"center\">".$raid_res2[0];
				$body .= "      </td>";
				$body .= "      <td>&nbsp;".$raid_res2[1];
				$body .= "      </td>";
				$body .= "  </tr>";
			}else if(substr_count($raid_res2[0], "Disabled") > 0) {
				$body .= "  <tr>";
				$body .= "      <td align=\"center\" colspan=\"2\">\n".$raid_res2[0];
				$body .= "      </td>";
				$body .= "  </tr>";	
			}
		}
		$body .= "</table>";
	} else {
		$body = "Fail to detail log!!";
	}
	//echo $body;
	return $body;
}
function htmlBody($ip) 
{
	if($ip != "")
	{
//		sleep(1); // FHS SETTING VALUE (default:30)

		$thisfilename=basename(__FILE__); 
		$temp_filename=realpath(__FILE__); 
		if(!$temp_filename)
			$temp_filename=__FILE__; 
		$osdir=eregi_replace($thisfilename,"",$temp_filename); 

		$command = $osdir . "arcmond_client $ip 8787 2";
		exec($command, $raid_res);
		$raid_str = explode(":", $raid_res[0]);

		$body  = "<table border=\"1\" width=\"565\" cellspacing=\"0\" cellpadding=\"0\">";
		$body .= "  <tr>";
		$body .= "      <td colspan=\"2\">";
		$body .= "      <font size=3><b>IP : $ip</b></font> Checked at ".date("Y-m-d H:i:s", $raid_str[1])." <br> ";
		$body .= "      </td>";
		$body .= "  </tr>";

		$to_eli = $raid_str[0].":".$raid_str[1].":";
		$raid_res[0] = str_replace($to_eli,"",$raid_res[0]);
		$tot = count($raid_res);

		for($i=0; $i < $tot; $i++)
		{
			$raid_res2 = explode("] ", str_replace("[", "", trim($raid_res[$i])));
			if($raid_res2[0] != "" && substr_count($raid_res2[0], "Disabled") == 0) {
				$body .= "  <tr>";
				$body .= "      <td width=\"160\" align=\"center\">".$raid_res2[0];	    
				$body .= "      </td>";
				$body .= "      <td>&nbsp;".$raid_res2[1];	        
				$body .= "      </td>";
				$body .= "  </tr>";
			}else if(substr_count($raid_res2[0], "Disabled") > 0) {
				$body .= "  <tr>";
				$body .= "      <td align=\"center\" colspan=\"2\">\n".$raid_res2[0];
				$body .= "      </td>";
				$body .= "  </tr>";	
			}
		}
		$body .= "</table>";
	} else {
		$body = "Fail to detail log!!";
	}
	//echo $body;
	return $body;
}

class Smtp {

    var $host;
    var $fp;
    var $self;
    var $lastmsg;
    var $parts;
    var $error;
    var $debug;
    var $charset;
    var $ctype;

    function Smtp($host="self") {
        if($host == "self") $this->self = true;
        else $this->host = $host;
        $this->parts = array();
        $this->error = array();
        $$this->debug = 0;
        $this->charset = "euc-kr";
        $this->ctype = "text/html";
    }

    // 디버그 모드 : 1
    function debug($n=1) {
        $this->debug = $n;
    }

    // smtp 통신을 한다.
    function dialogue($code, $cmd) {
        fputs($this->fp, $cmd."\r\n");
        $line = fgets($this->fp, 1024);
        ereg("^([0-9]+).(.*)$", $line, &$data);
        $this->lastmsg = $data[0];

        if($this->debug) {
            echo htmlspecialchars($cmd)."<br>".$this->lastmsg."<br>";
            flush();
        }

        if($data[1] != $code) return false;
        return true;

    }

    //  smptp 서버에 접속을 한다.
    function smtp_connect($host) {    		
        if($this->debug) {
            echo "SMTP($host) Connecting...<br>";
            flush();
        }
        if(!$host) $host = $this->host;
        
        if(!$this->fp = fsockopen($host, 25, $errno, $errstr, 10)) {
            $this->lastmsg = "SMTP($host) 서버접속에 실패했습니다.[$errno:$errstr]";
            return false;
        }
        $line = fgets($this->fp, 1024);
        ereg("^([0-9]+).(.*)$", $line, &$data);
        $this->lastmsg = $data[0];
        if($data[1] != "220") return false;
        if($this->debug) {
            echo $this->lastmsg."<br>";
            flush();
        }
        $this->dialogue(250, "HELO phpmail");
        
        return true;
    }

    // stmp 서버와의 접속을 끊는다.
    function smtp_close() {
        $this->dialogue(221, "QUIT");
        fclose($this->fp);
        return true;
    }

    // 메시지를 보낸다.
    function smtp_send($email, $from, $data) {
				
        if(!$mail_from = $this->get_email($from)) return false;
        if(!$rcpt_to = $this->get_email($email)) return false;
        if(!$this->dialogue(250, "MAIL FROM: $mail_from"))
            $this->error[] = $email.":MAIL FROM 실패($this->lastmsg)";
        if(!$this->dialogue(250, "RCPT TO: $rcpt_to"))
            $this->error[] = $email.":RCPT TO 실패($this->lastmsg)";
        $this->dialogue(354, "DATA");
        $mime = "Message-ID: <".$this->get_message_id().">\r\n";
        $mime .= "From: $from\r\n";
        $mime .= "To: $email\r\n";
        
        
        fputs($this->fp, $mime);
        
        fputs($this->fp, $data);
        
        $this->dialogue(250, ".");
    }

    // Message ID 를 얻는다.
    function get_message_id() {
        $id = date("YmdHis",time());
        mt_srand((float) microtime() * 1000000);
        $randval = mt_rand();
        $id .= $randval."@phpmail";
        return $id;
    }

    // Boundary 값을 얻는다.
    function get_boundary() {
        $uniqchr = uniqid(time());
        $one = strtoupper($uniqchr[0]);
        $two = strtoupper(substr($uniqchr,0,8));
        $three = strtoupper(substr(strrev($uniqchr),0,8));
        return "----=_NextPart_000_000${one}_${two}.${three}";
    }

    // 첨부파일이 있을 경우 이 함수를 이용해 파일을 첨부한다.
    function attach($message, $name="", $ctype="application/octet-stream") {
        $this->parts[] = array ("ctype" => $ctype, "message" => $message, "name" => $name);
    }

    // Multipart 메시지를 생성시킨다.
    function build_message($part) {
        $msg .= "Content-Type: ".$part['ctype'];
        if($part['name']) $msg .= "; name=\"".$part['name']."\"";
        $msg .= "\r\nContent-Transfer-Encoding: base64\r\n";
        $msg .= "Content-Disposition: attachment; filename=\"".$part['name']."\"\r\n\r\n";
        $msg .= chunk_split(base64_encode($part['message']));
        return $msg;
    }

    // SMTP에 보낼 DATA를 생성시킨다.
    function build_data($subject, $body) {
        $boundary = $this->get_boundary();
        $mime .= "Subject: $subject\r\n";
        $mime .= "Date: ".date ("D, j M Y H:i:s T",time())."\r\n";
        $mime .= "MIME-Version: 1.0\r\n";
        $mime .= "Content-Type: multipart/mixed; boundary=\"".$boundary."\"\r\n\r\n".
                 "This is a multi-part message in MIME format.\r\n\r\n";
        $mime .= "--".$boundary."\r\n".
             "Content-Type: ".$this->ctype."; charset=\"".$this->charset."\"\r\n".
             "Content-Transfer-Encoding: base64\r\n\r\n".
             chunk_split(base64_encode($body)).
             "\r\n\r\n--".$boundary;
        $max = count($this->parts);
        for($i=0; $i<$max; $i++) {
            $mime .= "\r\n".$this->build_message($this->parts[$i])."\r\n\r\n--".$boundary;
        }
        $mime .= "--\r\n";
        return $mime;
    }

    // MX 값을 찾는다.
    function get_mx_server($email) {
        if(!ereg("([\._0-9a-zA-Z-]+)@([0-9a-zA-Z-]+\.[a-zA-Z\.]+)", $email, $reg)) return false;
        getmxrr($reg[2], $host);
        if(!$host) $host[0] = $reg[2];
        return $host;
    }

    // 이메일의 형식이 맞는지 체크한다.
    function get_email($email) {
        if(!ereg("([\._0-9a-zA-Z-]+)@([0-9a-zA-Z-]+\.[a-zA-Z\.]+)", $email, $reg)) return false;
        return "<".$reg[0].">";
    }

    // 메일을 전송한다.
    function send($to, $from, $subject, $body) {
        if(!is_array($to)) $to = split("[,;]",$to);
        if($this->self) {
            $data = $this->build_data($subject, $body);
            foreach($to as $email) {
                if($host = $this->get_mx_server($email)) {
                    $flag = false; $i = 0;
                    while($flag == false) {
                        if($host[$i]) {
                            $flag = $this->smtp_connect($host[$i]);
                            $i++;
                            echo "-----------> $i";
                        } else break;
                    }
                    if($flag) {
                        $this->smtp_send($email, $from, $data);
                        $this->smtp_close();
                    } else {
                        $this->error[] = $email.":SMTP 접속실패";
                    }
                } else {
                    $this->error[] = $email.":형식이 잘못됨";
                }
            }
        } else {
            if(!$this->smtp_connect($this->host)) {
                $this->error[] = "$this->host SMTP 접속실패";
                return false;
            }
            $data = $this->build_data($subject, $body);
            foreach($to as $email) $this->smtp_send($email, $from, $data);
            $this->smtp_close();
        }
    }
}

/*-----------------------------------------사용법--------------------------------------------*/
/*
$mail = new Smtp("mail.solutionbox.co.kr");
//$mail->debug();
$mail->send("mirshead@solutionbox.co.kr", "mirshead@solutionbox.co.kr", "이 메일은 정상입니다.", "정상적인 메일이니 삭제하지 마십시오.");
*/
/*-----------------------------------------사용법--------------------------------------------*/

class mime
{
	protected $mime_version            = "1.0";    
	protected $mime_content_type    = "text/plain";
	protected $mime_charset            = "ks_c_5601-1987";
	protected $mime_encoding        = "base64";
	protected $mime_boundary        = null;
	protected $mime_xmailer            = null;

	public function __construct()
	{
	}

	public function set_content_type($content_type = null)
	{
		$this->mime_content_type = $content_type != null ? $content_type : "text/html";
	}

	public function set_charset($charset = null)
	{
		$this->mime_charset = $charset != null ? $charset : "euc_kr";
	}

	public function set_boundary($boundary = null)
	{
		$this->mime_boundary = $boundary ? $boundary : null;
	}

	public function set_encoding($encoding = null)
	{
		$this->mime_encoding = $encoding != null ? $encoding : "base64";
	}

	public function set_xmailer($xmailer = null)
	{
		$this->mime_xmailer = $xmailer != null ? $xmailer : $_SERVER['HTTP_USER_AGENT'];
	}

	public function __destruct()
	{
	}
}

class sendmail extends mime
{
	protected $smtp_server = null;
	protected $smtp_port = 0;
	protected $smtp_timeout = 0;
	protected $smtp_socketopen = 0;
	protected $smtp_status = false;
	protected $smtp_CRLF = "\r\n";
	protected $smtp_attachfile_name    = null;
	protected $smtp_attachfile_size    = 0;
	protected $smtp_attachfile_type    = null;
	protected $smtp_cmd_status    = array();
	protected $mail_from = null;
	protected $mail_to = null;
	protected $mail_subject = null;
	protected $mail_priority = 3;
	protected $mail_notification = 0;
	protected $mail_body = null;

	public function __construct($server = null, $port = 0, $timeout = 0)
	{
		$this->smtp_server = ($server != null) ? $server : "localhost";
		$this->smtp_port = ($port != 0) ? $port : 25;
		$this->smtp_timeout = ($timeout != 0) ? $timeout : 30;
	}

	public function encoding($str)
	{

		return "=?ks_c_5601-1987?B?" . base64_encode($str) . "?=";
	}

	private function _mail_env ($to, $from, $subject, $body, $priority = 3, $notification = 0)
	{
		$this->mail_from = $from;
		$this->mail_to = $to;
		$this->mail_subject = $subject;
		$this->mail_body = $body;
		$this->mail_priority = $priority;
		$this->mail_notification = $notification;
	}

	private function _smtp_base_header()
	{
		$this->_smtp_cmd("From: $this->mail_from");
		$this->_smtp_cmd("To: $this->mail_to");
		$this->_smtp_cmd("Subject: $this->mail_subject");
		$this->_smtp_cmd("MIME-Version: $this->mime_version");
		$this->_smtp_cmd("X-Priority: $this->mail_priority");
		$this->_smtp_cmd("X-Mailer: $this->mime_xmailer");
	}

	private function _smtp_base_content()
	{
		$this->_smtp_cmd("Content-Type: $this->mime_content_type; charset=\"$this->mime_charset\"");
		$this->_smtp_cmd("Content-Transfer-Encoding: $this->mime_encoding");
	}


	private function _smtp_multipart_content($attach = false)
	{
		if($attach)
		{
			$this->_smtp_cmd("Content-Type: multipart/mixed; boundary=\"$this->mime_boundary\"");
		} else {
			$this->_smtp_cmd("Content-Type: multipart/alternative; boundary=\"$this->mime_boundary\"");
		}
		$this->_smtp_cmd("$this->smtp_CRLF");
		$this->_smtp_cmd("This is a multi-part message in MIME format.");
	}

	private function _smtp_attachfile_content()
	{
		$this->_smtp_cmd("Content-Type: $this->smtp_attachfile_type");
		$this->_smtp_cmd("Content-Transfer-Encoding: $this->mime_encoding");
		$this->_smtp_cmd("Content-Disposition: attachment; filename=\"$this->smtp_attachfile_name\"");
	}

	private function _smtp_start_boundary()
	{
		$this->_smtp_cmd("$this->smtp_CRLF");
		$this->_smtp_cmd("--$this->mime_boundary");
	}

	private function _smtp_end_boundary()
	{
		$this->_smtp_cmd("--$this->mime_boundary--");
	}

	public function open()
	{
		$this->smtp_socketopen = @fsockopen($this->smtp_server, $this->smtp_port, $errno, $errstr, $this->smtp_timeout);
		if($this->_smtp_code($this->_receive()) != 220)
		{
			throw new Exception("..... ... . .....");
		}
		else
		{
			$this->smtp_status = true;
		}

		return $this->smtp_status;
	}

	private function _smtp_helo()
	{
		$this->_smtp_cmd("HELO $this->smtp_server");
		if($this->_smtp_code($this->_receive()) == 250)
		{
			return true;
		}
		return false;
	}

	private function _smtp_mailfrom($from)
	{
		$this->_smtp_cmd("MAIL FROM: $this->mail_from");
		if($this->_smtp_code($this->_receive()) == 250)
		{
			return true;
		}
		return false;
	}

	private function _smtp_rcptto($to)
	{
		$this->_smtp_cmd("RCPT TO: $this->mail_to");
		if($this->_smtp_code($this->_receive()) == 250)
		{
			return true;
		}
		return false;
	}

	private function _smtp_data()
	{
		$this->_smtp_cmd("DATA");
		if($this->_smtp_code($this->_receive()) == 354)
		{
			return true;
		}
		return false;
	}

	private function _smtp_end()
	{
		$this->_smtp_cmd(".");
		if($this->_smtp_code($this->_receive()) == 250)
		{
			return true;
		}
		return false;
	}

	private function _smtp_quit()
	{
		$this->_smtp_cmd("QUIT");
		if($this->_smtp_code($this->_receive()) == 221)
		{
			return true;
		}
		return false;
	}

	public function close()
	{
		if(@fclose($this->smtp_socketopen) == false)
		{
			throw new Exception(".. ..... ...... .....");
		}
		return true;
	}

	private function _smtp_send($files = null)
	{
		$this->mime_boundary = "======" . uniqid(rand()) . "/$_SERVER[SERVER_NAME]";

		$mail_body = nl2br(stripslashes($this->mail_body));

		if($this->mime_encoding == "base64")
		{
			$mail_body = chunk_split(base64_encode($mail_body));
		}

		$this->smtp_cmd_status[] = $this->_smtp_helo();
		$this->smtp_cmd_status[] = $this->_smtp_mailfrom($this->mail_from);
		$this->smtp_cmd_status[] = $this->_smtp_rcptto($this->mail_to);
		$this->smtp_cmd_status[] = $this->_smtp_data();

		$this->_smtp_base_header();

		if(is_array($files))
		{
			$this->_smtp_multipart_content(true);
			$this->_smtp_start_boundary();
			$this->_smtp_base_content();
			$this->_smtp_cmd("$this->smtp_CRLF");
			$this->_smtp_cmd($mail_body);
			$this->_smtp_cmd("$this->smtp_CRLF");

			for($i = 0; $i < sizeof($files); $i++)
			{
				if(is_uploaded_file($files[tmp_name][$i]))
				{
					$this->smtp_attachfile_name = $this->_check_empty($files[name][$i]);
					$this->smtp_attachfile_size = $files[size][$i];
					$this->smtp_attachfile_type = $files[type][$i];

					$attachfile_handle = @fopen($files[tmp_name][$i], "r");
					$attachfile_body = @fread($attachfile_handle, $files[size][$i]);

					if($this->mime_encoding == "base64")
					{
						$attachfile_body = chunk_split(base64_encode($attachfile_body));
					}

					$this->_smtp_start_boundary();
					$this->_smtp_attachfile_content();

					$this->_smtp_cmd("$this->smtp_CRLF");
					$this->_smtp_cmd($attachfile_body);
					$this->_smtp_cmd("$this->smtp_CRLF");

					@fclose($attachfile_handle);
				}
			}
		} else {
			$this->_smtp_multipart_content(false);

			$this->mime_content_type    = "text/plain";

			$this->_smtp_start_boundary();
			$this->_smtp_base_content();
			$this->_smtp_cmd("$this->smtp_CRLF");
			$this->_smtp_cmd($mail_body);
			$this->_smtp_cmd("$this->smtp_CRLF");

			$this->mime_content_type    = "text/html";

			$this->_smtp_start_boundary();
			$this->_smtp_base_content();
			$this->_smtp_cmd("$this->smtp_CRLF");
			$this->_smtp_cmd($mail_body);
			$this->_smtp_cmd("$this->smtp_CRLF");
		}

		$this->_smtp_end_boundary();

		$this->smtp_cmd_status[] = $this->_smtp_end();
		$this->smtp_cmd_status[] = $this->_smtp_quit();

		foreach($this->smtp_cmd_status as $key => $value)
		{
			if($value == false)
			{
				return false;
				break;
			}
		}
		return true;
	}

	private function _smtp_cmd($str)
	{
		@fputs($this->smtp_socketopen, $str . $this->smtp_CRLF);
	}

	private function _smtp_code($str)
	{
		return substr($str, 0, 3);
	}

	private function _receive()
	{
		return @fgets($this->smtp_socketopen, 1024);
	}

	private function _check_empty($filename)
	{
		return preg_replace("/ /i", "_", $filename);
	}

	public function send($to, $from, $subject, $text, $priority = 3, $files = null)
	{
		$this->set_xmailer($_SERVER[HTTP_USER_AGENT]);
		$this->set_content_type("text/html");
		$this->set_charset("euc_kr");
		$this->set_encoding("base64");


		$this->_mail_env($to, $from, $this->encoding($subject), $text, $priority);

		if($this->_smtp_send($files) == false)
		{
			throw new Exception("Error");
		}
	}

	public function __destruct()
	{
	}
};

?>
