<?php
/* SVN FILE: $Id: rkt_message.php 608 2008-07-16 12:47:51Z bb_yujiro $ */
/**
 * メール送信
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/rktSNS/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 608 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-07-16 21:47:51 +0900 (水, 16 7 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * RKT_Messageクラス
 *
 * @category        hitSuji Core
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/rktSNS/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 608 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-07-16 21:47:51 +0900 (水, 16 7 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class RKT_Message
{
    /**
     * Singleton用インスタンス
     * @var object
     */
    private static $_instance;

    /**
     * メールオブジェクト
     * @var object
     */
    private $_objmail = null;

    /**
     * 言語
     * @var string
     */
    private $_language = '';

    /**
     * テンプレート情報
     * @var array
     */
    private $_msgtpl = array();

    /**
     * 置換変数
     * @var array
     */
    private $_vars = array();

    /**
     * コンストラクタ
     *
     * @access private
     * @return void
     */
    private function __construct($code)
    {
        include LIB_DIR.'PEAR/Mail.php';

        $this->_language = getenv('LANG');
        $this->setTemplate($code);
    }

    /**
     * Singleton メソッド
     *
     * @access public
     * @return object
     */
    public static function getInstance($code)
    {
        if (!isset(self::$_instance)) {
            $classname = __CLASS__;
            self::$_instance = new $classname($code);
            self::$_instance->setMail();
            self::$_instance->setFooter();
        } else {
            self::$_instance->setTemplate($code);
        }
        return self::$_instance;
    }

    /**
     * 雛形メールへ変数を設定
     *
     * @access public
     * @param string $key
     * @param mixed $value
     * @return void
     */
    public function Assign($key, $value)
    {
        $this->_vars[$key] = $value;
    }

    /**
     * メール本文の作成・取得
     *
     * @access private
     * @return string  メール本文
     */
    public function getBody()
    {
        $body = $this->_msgtpl['body'];

        /* 変数の設定  2次元配列まで有効 */
        $body = preg_replace('/{\$(\w+)\.(\w+)\}/', '<?php echo \$this->_vars[\'\\1\'][\'\\2\']; ?>', $body);
        $body = preg_replace('/{\$(\w+)\}/', '<?php echo \$this->_vars[\'\\1\']; ?>', $body);

        /* foreachの設定 変数のキーは「_row」で決めうち */
        $body = preg_replace('/{foreach \$(\w+)}/', '<?php \$_ary = \$this->_vars[\'\\1\'];\r\nforeach (\$_ary as \$this->_vars[\'_row\']): ?>', $body);
        $body = preg_replace('/{\/foreach}/', '<?php endforeach; unset(\$_ary); ?>', $body);

        /* emptyによるif文の設定 */
        $body = preg_replace('/{empty \$(\w+)}/', '<?php if (!empty(\$this->_vars[\'\\1\'])): ?>', $body);
        $body = preg_replace('/{\/empty}/', '<?php endif; ?>', $body);

        ob_start();
        @eval('?>'. $body);
        $result = ob_get_contents();
        ob_end_clean();
        
        return $result;
    }

    /**
     * メールオブジェクトの設定
     *
     * @access public
     */
    public function getSubject()
    {
        return $this->_msgtpl['subject'];
    }

    /**
     * メールオブジェクトの設定
     *
     * @access public
     */
    public function setMail()
    {
        $backend = 'mail';
        $params = array();
        $sendmail_path = ini_get('sendmail_path');

        if (USED_SMTP){
            $backend = 'smtp';
            $params = array(
                'host'=>     SMTP_HOST,
                'port'=>     SMTP_PORT,
                'auth'=>     SMTP_AUTH,
                'username'=> SMTP_ACCOUNT,
                'password'=> SMTP_PASSWORD,
            );
        } elseif(!empty($sendmail_path)) {
            $backend = 'sendmail';
            $params = array(
                'sendmail_path'=> $sendmail_path
            );
        }
        $this->_objmail = Mail::factory($backend, $params);
    }

    /**
     * 雛形情報の設定
     *
     * @access public
     * @param string $code
     * @return void
     */
    public function setTemplate($code)
    {
        $wheres = array(
            'code'=>     $code,
            'language'=> $this->_language,
        );
        $this->_msgtpl = RKT_DB::getRow('sys_msgtpl', $wheres);
    }

    /**
     * メール送信実行
     *
     * @access public
     * @param integer|string $to
     * @param string $subject
     * @return integer  送信結果
     */
    public function send($to, $subject=null)
    {
        if (is_integer($to)){
            $to = $this->_idToEmail($to);
        }
        $subject   = empty($subject)? $this->_msgtpl['subject']:$subject;
        $subject   = '['.SNS_NAME.']'.$subject;
        $from      = $this->_msgtpl['email'];
        $from_name = $this->_msgtpl['name'];

        // 送信元ヘッダー作成
        $from_name = mb_convert_encoding($from_name, 'ISO-2022-JP', ENCODE_TYPE);
        $from_name = mb_encode_mimeheader($from_name,'ISO-2022-JP', 'Q');
        $subject   = mb_encode_mimeheader($subject,'ISO-2022-JP', 'Q');

        $headers = array(
            'From'=>        '"'.$from_name.'" <'.$from.'>',
            'Return-Path'=> '<'.$from.'>',
            'To'=>          $to,
            'Subject'=>     $subject,
        );

        // メール本文の構築
        $body = $this->getBody();

        // メール送信
        $body = mb_convert_encoding($body, 'ISO-2022-JP', ENCODE_TYPE);
        return $this->_objmail->send($to, $headers, $body);
    }

    /**
     * フッター情報の設定
     *
     * @access private
     * @return void
     */
    public function setFooter()
    {
        $condition = array(
            'code'=>     'footer',
            'language'=> $this->_language,
        );
        $mailtpl = RKT_DB::getRow('sys_msgtpl', $condition);
        
        $footer = $mailtpl['body'];
        $footer = str_replace('{$sns_name}',    SNS_NAME,      $footer);
        $footer = str_replace('{$admin_email}', ADMINISTRATOR, $footer);
        $footer = str_replace('{$base_url}',    BASE_URL,      $footer);

        $this->_vars['site_name'] = SNS_NAME;
        $this->_vars['footer']    = $footer;
    }

    /**
     * 会員登録用メール設定の取得
     *
     * @access private
     * @return string
     */
    private function _idToEmail($id)
    {
        $condition = array(
            'id'=>    $id
        );
        $footer = RKT_DB::getRow('act_account', $condition);
        
        return RKT_Crypt::getDecrypted($result['email']);
    }
}
// RKT_Messageの終了
?>
