<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Author: Chuck Hagenbuch <chuck@horde.org>                            |
// +----------------------------------------------------------------------+

/**
 * Sendmail implementation of the PEAR Mail:: interface.
 * @access public
 * @package Mail
 * @version $Revision: 1.11 $
 */
class Mail_sendmail extends Mail {

	/**
     * The location of the sendmail or sendmail wrapper binary on the
     * filesystem.
     * @var string
     */
    var $sendmail_path = '/usr/sbin/sendmail';

	/**
     * Any extra command-line parameters to pass to the sendmail or
     * sendmail wrapper binary.
     * @var string
     */
    var $sendmail_args = '';

	/**
     * Constructor.
     *
     * Instantiates a new Mail_sendmail:: object based on the parameters
     * passed in. It looks for the following parameters:
     *     sendmail_path    The location of the sendmail binary on the
     *                      filesystem. Defaults to '/usr/sbin/sendmail'.
     *
     *     sendmail_args    Any extra parameters to pass to the sendmail
     *                      or sendmail wrapper binary.
     *
     * If a parameter is present in the $params array, it replaces the
     * default.
     *
     * @param array $params Hash containing any parameters different from the
     *              defaults.
     * @access public
     */
    function Mail_sendmail($params)
    {
        if (isset($params['sendmail_path'])) $this->sendmail_path = $params['sendmail_path'];
        if (isset($params['sendmail_args'])) $this->sendmail_args = $params['sendmail_args'];

        /*
         * Because we need to pass message headers to the sendmail program on
         * the commandline, we can't guarantee the use of the standard "\r\n"
         * separator.  Instead, we use the system's native line separator.
         */
		// [2009-03-11] 메일헤더의 줄구분이 본문과 다른 오류 수정
        //$this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
        $this->sep = "\r\n";
    }

	/**
     * Implements Mail::send() function using the sendmail
     * command-line binary.
     *
     * @param mixed $recipients Either a comma-seperated list of recipients
     *              (RFC822 compliant), or an array of recipients,
     *              each RFC822 valid. This may contain recipients not
     *              specified in the headers, for Bcc:, resending
     *              messages, etc.
     *
     * @param array $headers The array of headers to send with the mail, in an
     *              associative array, where the array key is the
     *              header name (ie, 'Subject'), and the array value
     *              is the header value (ie, 'test'). The header
     *              produced from those values would be 'Subject:
     *              test'.
     *
     * @param string $body The full text of the message body, including any
     *               Mime parts, etc.
     *
     * @return mixed Returns true on success, or a PEAR_Error
     *               containing a descriptive error message on
     *               failure.
     * @access public
     */
    function send($recipients, $headers, $body)
    {
		global $DEBUG, $G_SYS, $G, $mail_smtp_i;

		$DEBUG['mail_smtp_send_hdr']['start'] = getmicrotime();
		$recipients = $this->parseRecipients($recipients);
        if (PEAR::isError($recipients)) {
            return $recipients;
        }
        $recipients = escapeShellCmd(implode(' ', $recipients));

        $headerElements = $this->prepareHeaders($headers);
        if (PEAR::isError($headerElements)) {
            return $headerElements;
        }
        list($from, $text_headers) = $headerElements;

        if (!isset($from)) {
            return PEAR::raiseError('No from address given.');
        } elseif (strpos($from, ' ') !== false ||
                  strpos($from, ';') !== false ||
                  strpos($from, '&') !== false ||
                  strpos($from, '`') !== false) {
            return PEAR::raiseError('From address specified with dangerous characters.');
        }

		// [2010-10-22] 대량메일발송시 리턴메일만 실제주소에서 받기 원할 경우 true
        if (!empty($headers['Return-Path'])) {
            $from = $headers['Return-Path'];
        }

		$DEBUG['mail_smtp_send_hdr']['exec'] += getmicrotime() - $DEBUG['mail_smtp_send_hdr']['start'];

        $result = 0;

		if ($G_SYS['NM_SEND_QUEUE'])
		{
			// direct queue
			$DEBUG['mail_smtp_send_queue']['start'] = getmicrotime();

			// [2009-03-10]발송큐 도입
			if ($G_SYS['NM_MAILER_SPOOL'])
			{
				$_ex = explode('@', trim($recipients));
				$rcpt_domain = ($_ex[1] != '') ? $_ex[1] : '';

				if ($G['mailer_domain_alias'][$rcpt_domain] != '')
					$rcpt_domain = $G['mailer_domain_alias'][$rcpt_domain];

				if ($G['mailer_domain_thread'][$rcpt_domain] == NULL)
					$rcpt_domain = substr($rcpt_domain, 0, 2);

				if (!is_dir($G_SYS['NM_MAILER_SPOOL'].DIRECTORY_SEPARATOR.$G_SYS['NM_MAILER_MS_KEY_NOW'].DIRECTORY_SEPARATOR.$rcpt_domain))
				{
					mkdir($G_SYS['NM_MAILER_SPOOL'].DIRECTORY_SEPARATOR.$G_SYS['NM_MAILER_MS_KEY_NOW'].DIRECTORY_SEPARATOR.$rcpt_domain, 0777);
					chmod($G_SYS['NM_MAILER_SPOOL'].DIRECTORY_SEPARATOR.$G_SYS['NM_MAILER_MS_KEY_NOW'].DIRECTORY_SEPARATOR.$rcpt_domain, 0777);					
				}	// if()

				$file = $G_SYS['NM_MAILER_SPOOL'].DIRECTORY_SEPARATOR.$G_SYS['NM_MAILER_MS_KEY_NOW'].DIRECTORY_SEPARATOR.$rcpt_domain.DIRECTORY_SEPARATOR.getmicrotime().'.'.mt_rand(0,9999).'.'.$mail_smtp_i.'.'.$G_SYS['NM_MAILER_MS_KEY_NOW'];
				#vd($file); return false;
			} else 
			{
				$file = dirname($G_SYS[MAIL_ROOT]).DIRECTORY_SEPARATOR.'spool'.DIRECTORY_SEPARATOR.'local'.DIRECTORY_SEPARATOR.getmicrotime().'.'.mt_rand(0,9999).'.'.$mail_smtp_i.'.'.$G_SYS['NM_MAILER_MS_KEY_NOW'];
			}	// if()

			$fp = fopen($file, "w");

			$crlf = "\r\n";
			$mail_proc = "mail from:<".$from.">".$crlf;
			$mail_proc .= "rcpt to:<".$recipients.">".$crlf.$crlf;
			// [2008-05-30] gmail 로 보낸 메일만 헤더에 줄바꿈 문제가 발견됨.
			//fwrite($fp, $mail_proc.str_replace("\n", "\r\n", $text_headers).$crlf);
			fwrite($fp, $mail_proc.$text_headers.$crlf);
			fwrite($fp, $body);
			$result = fclose($fp);
			chmod($file, 0777);
			$DEBUG['mail_smtp_send_queue']['exec'] += getmicrotime() - $DEBUG['mail_smtp_send_queue']['start'];
		} else if ($G_SYS['NM_SEND_QUEUE_RESERVE'] != '')
		{
			// [2012-09-27] 예약발송
			// 여러명에게 보낼 수 있으므로 mail_write_ok.php 에서만 사용여부만 받아오고, 실제 파일은 $mail_smtp_i 가 들어가야 하므로 여기에서 선언 필요.  또한 
			// mrc_no 를 가져와야 함. $G_SYS['NM_SEND_MRC_NO'] 

			// direct queue
			$DEBUG['mail_smtp_send_queue_reserve']['start'] = getmicrotime();

			//$file = $G_SYS['NM_SEND_QUEUE_RESERVE'].DIRECTORY_SEPARATOR.getmicrotime().'.'.mt_rand(0,9999).'.'.$mail_smtp_i.'.Reserve.eml';
			$file = $G_SYS['NM_SEND_QUEUE_RESERVE'].DIRECTORY_SEPARATOR.'Reserve.'.$G_SYS['NM_SEND_MRC_NO'].'.eml';

			$fp = fopen($file, "w");

			$crlf = "\r\n";
			$mail_proc = "mail from:<".$from.">".$crlf;
			$mail_proc .= "rcpt to:<".$recipients.">".$crlf.$crlf;
			fwrite($fp, $mail_proc.$text_headers.$crlf);
			fwrite($fp, $body);
			$result = fclose($fp);
			chmod($file, 0777);
			$DEBUG['mail_smtp_send_queue_reserve']['exec'] += getmicrotime() - $DEBUG['mail_smtp_send_queue_reserve']['start'];
		} else 
		{
			$DEBUG['mail_smtp_send_popen']['start'] = getmicrotime();
			if (@is_file($this->sendmail_path)) {
				$from = escapeShellCmd($from);
				$mail = popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
				fputs($mail, $text_headers);
				fputs($mail, $this->sep);  // newline to end the headers section
				fputs($mail, $body);
				$result = pclose($mail);
				if (version_compare(phpversion(), '4.2.3') == -1) {
					// With older php versions, we need to shift the
					// pclose result to get the exit code.
					$result = $result >> 8 & 0xFF;
				}
			} else {
				return PEAR::raiseError('sendmail [' . $this->sendmail_path . '] is not a valid file');
			}

			if ($result != 0) {
				return PEAR::raiseError('sendmail returned error code ' . $result,
										$result);
			}

			$DEBUG['mail_smtp_send_popen']['exec'] += getmicrotime() - $DEBUG['mail_smtp_send_popen']['start'];
		}	// if()


        return true;
    }

}
