<?php
/**
 * @copyright ONE/DEPO Project
 * @license   PHP License 3.01 <http://www.php.net/license/3_01.txt>
 */

require_once 'Mail.php';

/**
 * メール送信ロジック
 * 
 * ※phpの組み込みメール関数を使用するため、
 * 　設定はphp.iniを変更してください
 *
 * @package     mail
 * @author      FUCO T.Hoshino
 * @access      public
 */
class Onedepo_Logic_Mail {

    var $mailtemplate;
    var $tpl;

    function Onedepo_Logic_Mail() {
    }
    function db_get_template($tpl_name, &$tpl_source, &$smarty)
    {
        // テンプレート取得
        $mailtpl = $this->mailtemplate->selectKey($tpl_name);
        if (!empty($mailtpl)) {
            $tpl = $mailtpl["mailtitle"] ."\n". $mailtpl["mailbody"];
            $tpl_source = $tpl;
            return true;
	} else {
            return false;
        }
    }

    function db_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
    {
        $tpl_timestamp = time();
        return true;
    }
    function db_get_secure($tpl_name, &$smarty){return true;}
    function db_get_trusted($tpl_name, &$smarty){} 

    function val_get_template($tpl_name, &$tpl_source, &$smarty)
    {
        // テンプレート取得
        if (!empty($tpl_name)) {
            $tpl_source = $this->tpl[$tpl_name];
            return true;
	} else {
            return false;
        }
    }

    function val_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty)
    {
        $tpl_timestamp = time();
        return true;
    }
    function val_get_secure($tpl_name, &$smarty){return true;}
    function val_get_trusted($tpl_name, &$smarty){} 

    /**
     * メール送信
     * 
     * @access  public
     */
    function send($to, $from, $title, $text)
    {
        $func_name = "Onedepo_Logic_Mail#send";
        $log =& LogFactory::getLog();
        $log->debug("send mail", $func_name);

        mb_internal_encoding("UTF-8");

        $headers=array(
        "From" => $from,
        "Subject" => mb_encode_mimeheader($title, "ISO-2022-JP"),
        );
        if (defined('MAIL_CC')) {
            $headers["CC"] = MAIL_CC;
        }
         
        $o_mail = Mail::factory("mail");
        $result = $o_mail -> send($to, $headers, mb_convert_encoding($text, "JIS", "auto"));
        
        if (PEAR::isError($result)) {
            $log->error($result->getMessage(), $func_name);
            return false;
        }
        
        return true;

    }

    /**
     * DBよりテンプレートを取得し、メール送信
     * 
     * @access  public
     */
    function sendFromTemplate($templatename, $to, $from, $params)
    {
        $func_name = "Onedepo_Logic_Mail#sendFromTemplate";
        $log =& LogFactory::getLog();
        $log->debug("send mail", $func_name);

        // メール生成
        $renderer =& Smarty4Maple::getInstance();
        $renderer->register_resource("db", array($this,
                                                 "db_get_template",
                                                 "db_get_timestamp",
                                                 "db_get_secure",
                                                 "db_get_trusted"));
        $renderer->assign($params);
        $subject_and_body = $renderer->fetch("db:".$templatename);
        
        $sendmail = explode("\n", $subject_and_body, 2);
        list($subject, $body) = $sendmail;

        // 署名用変数
        $renderer->assign(array("URL" => URL_ROOT));
        $renderer->assign(array("DOMAIN_NAME" => _DOMAIN_NAME . dirname($_SERVER["REQUEST_URI"])));
        //--
        // 署名 - ヘッダ
        $subject_and_body = $renderer->fetch("db:signature_header");
        $sendmail = explode("\n", $subject_and_body, 2);
        list($sig_subject, $sig_head) = $sendmail;
        //--
        // 署名 - フッタ
        $subject_and_body = $renderer->fetch("db:signature_footer");
        $sendmail = explode("\n", $subject_and_body, 2);
        list($sig_subject, $sig_foot) = $sendmail;
        //--
        $h = (!empty($sig_head)) ? $sig_head ."\n\n" : "";
        $f = (!empty($sig_foot)) ? "\n\n". $sig_foot : "";
        $body = $h . $body . $f;

        mb_internal_encoding("UTF-8");
        $headers=array(
        "From" => MAIL_FROM,
        "Subject" => mb_encode_mimeheader($subject, "ISO-2022-JP"),
        );
        
        //BCC
        switch($templatename) {
            case "buy_complete":            // 購入完了
            case "buy_complete_reserve":    // 購入完了 予約
            case "buy_complete_sell":       // 購入完了 出品
            case "send_item":               // 商品発送
            case "buy_cancel":              // キャンセル
            case "buy_return":              // 商品返品
                if (defined('MAIL_BCC_ORDER')) {
                    $headers["BCC"] = MAIL_BCC_ORDER;
                }
                break;

            case "interim_regist":     // 仮会員登録
            case "regist_complete":    // 会員登録完了
            case "consumer_complete":  // 購入者登録完了
            case "seller_complete":    // 出品者登録完了
                if (defined('MAIL_BCC_MEMBER')) {
                    $headers["BCC"] = MAIL_BCC_MEMBER;
                }
                break;

            case "exhibit_complete":    // 出品受付完了
            case "sellout_information": // 売却通知
            case "sell_send_item":      // 出品商品発送
            case "send_consumer":       // 購入者へメール
                if (defined('MAIL_BCC_SELLER')) {
                    $headers["BCC"] = MAIL_BCC_SELLER;
                }
                break;

            default:
                if (defined('MAIL_BCC')) {
                    $headers["BCC"] = MAIL_BCC;
                }
        }

        $o_mail = Mail::factory("mail");
        $result = $o_mail -> send($to, $headers, mb_convert_encoding($body, "JIS", "auto"));
        
        if (PEAR::isError($result)) {
            $log->error($result->getMessage(), $func_name);
            return false;
        }
        
        return true;
    }

    /**
     * DBよりテンプレートを取得し、メール送信
     * 
     * @access  public
     */
    function sendTestFromTemplate($templatename, $subject, $body, $params)
    {
        $this->tpl[$templatename] = "【テスト送信】". $subject ."\n". $body;

        $func_name = "Onedepo_Logic_Mail#sendTestFromTemplate";
        $log =& LogFactory::getLog();
        $log->debug("send mail", $func_name);

        // メール生成
        $renderer =& Smarty4Maple::getInstance();
        $renderer->register_resource("val", array($this,
                                                 "val_get_template",
                                                 "val_get_timestamp",
                                                 "val_get_secure",
                                                 "val_get_trusted"));
        $renderer->assign($params);
        $subject_and_body = $renderer->fetch("val:".$templatename);
        $sendmail = explode("\n", $subject_and_body, 2);
        list($subject, $body) = $sendmail;


        $renderer->register_resource("db", array($this,
                                                 "db_get_template",
                                                 "db_get_timestamp",
                                                 "db_get_secure",
                                                 "db_get_trusted"));

        // 署名用変数
        $renderer->assign(array("URL" => URL_ROOT));
        //--
        // 署名 - ヘッダ
        $subject_and_body = $renderer->fetch("db:signature_header");
        $sendmail = explode("\n", $subject_and_body, 2);
        list($sig_subject, $sig_head) = $sendmail;
        //--
        // 署名 - フッタ
        $subject_and_body = $renderer->fetch("db:signature_footer");
        $sendmail = explode("\n", $subject_and_body, 2);
        list($sig_subject, $sig_foot) = $sendmail;
        //--
        $h = (!empty($sig_head)) ? $sig_head ."\n\n" : "";
        $f = (!empty($sig_foot)) ? "\n\n". $sig_foot : "";
        $body = $h . $body . $f;

        mb_internal_encoding("UTF-8");
        $headers=array(
        "From" => MAIL_FROM,
        "Subject" => mb_encode_mimeheader($subject, "ISO-2022-JP"),
        );
        
        //BCCをToに使用
        switch($templatename) {
            case "buy_complete":            // 購入完了
            case "buy_complete_reserve":    // 購入完了 予約
            case "buy_complete_sell":       // 購入完了 出品
            case "send_item":               // 商品発送
                if (defined('MAIL_BCC_ORDER')) {
                    $to = MAIL_BCC_ORDER;
                }
                break;

            case "interim_regist":     // 仮会員登録
            case "regist_complete":    // 会員登録完了
            case "consumer_complete":  // 購入者登録完了
            case "seller_complete":    // 出品者登録完了
                if (defined('MAIL_BCC_MEMBER')) {
                    $to = MAIL_BCC_MEMBER;
                }
                break;

            case "exhibit_complete":    // 出品受付完了
            case "sellout_information": // 売却通知
            case "sell_send_item":      // 出品商品発送
            case "send_consumer":       // 購入者へメール
                if (defined('MAIL_BCC_SELLER')) {
                    $to = MAIL_BCC_SELLER;
                }
                break;

            default:
                if (defined('MAIL_BCC')) {
                    $to = MAIL_BCC;
                }
        }

        $o_mail = Mail::factory("mail");
        $result = $o_mail->send($to, $headers, mb_convert_encoding($body, "JIS", "auto"));
        
        if (PEAR::isError($result)) {
            $log->error($result->getMessage(), $func_name);
            return false;
        }
        
        return true;
    }
    
    
    /**
     * メールマガジン送信
     * 
     * @access  public
     */
    function sendMailmagazineByPEARMail($userlist, $subject, $body){
        $func_name = "Onedepo_Logic_Mail#sendMailmagazineByPEARMail";
        $log =& LogFactory::getLog();
        $log->debug("send mail", $func_name);
        
        mb_internal_encoding("UTF-8");
        
        $userarray = array_chunk($userlist, MAILMAG_SENDMAX);
        
        foreach($userarray as $key => $val){
            $mailmag_bcc = array_reduce($val, array('Onedepo_Logic_Mail','userListJoiner'));
            
            $headers = array(
                "From" => MAILMAG_FROM,
                "Reply-To" => MAILMAG_REPLYTO,
                "Subject" => mb_encode_mimeheader($subject, "ISO-2022-JP"),
                "BCC" => $mailmag_bcc
            );
            
            $o_mail = Mail::factory("mail");
            $result = $o_mail->send(MAILMAG_TO, $headers, mb_convert_encoding($body, "JIS", "auto"));
            
            if (PEAR::isError($result)) {
                $log->error($result->getMessage(), $func_name);
            }
        }
        
        return true;
    }
    
    /**
     * ２値をカンマ連結（sendMailmagazineByPEARMailで使用）
     * 
     * @access  public
     */
    function userListJoiner($a, $b){
        if (empty($a)) return $b;
        if (!empty($b)) return $a . "," . $b;
        return $a;
    }
}
?>