<?php
/*
 * member/DaoMemberMailTemplate.class.php
 * 
 * CopyRight(C) 2010 Shopformer Development Team. All Right Reserved
 * URL: http://sourceforge.jp/projects/shopformer/
 * 
 * 
 * Mail: m_nakashima@users.sourceforge.jp
 * Auther: Masanori Nakashima
 * Last Update: 2010-06-18
 */
require_once( dirname( __FILE__ )
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'database2'
.DIRECTORY_SEPARATOR.'AbstractData.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'system'
.DIRECTORY_SEPARATOR.'DataFileWriter.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'util'
.DIRECTORY_SEPARATOR.'Mail.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'util'
.DIRECTORY_SEPARATOR.'CharUtility.class.php');
require_once( dirname(dirname( __FILE__ ))
.DIRECTORY_SEPARATOR.'util'
.DIRECTORY_SEPARATOR.'mobile'
.DIRECTORY_SEPARATOR.'PictCharConverter.class.php');
/**
 * メンバーメールテンプレートテーブルレコード対応 DAOクラス
 * 
 * @package member メンバー管理パッケージ
 * @version 1.0.0
 * @author  <m_nakashima@users.sourceforge.jp>
 * @since PHP 4.0
 */
class member_DaoMemberMailTemplate extends database2_AbstractData {
	var $template_number;
	var $template_id;
	var $template_name;
	var $template_type 	= 0;
	var $bgcolor		= '';
	var $list_id;
	var $subject;
	var $subject_mobile;
	var $mail_from_name;
	var $mail_from_address;
	var $mail_reply_address;
	var $mail_return_path;
	var $text_body_default;
	var $text_body_mobile;
	var $html_body_default;
	var $html_body_mobile;
	var $description;
	var $status_flag = 0;
	var $open_flag = 0;
	var $updated_date;
	var $registered_date;
	var $owner_id;
	var $modifier_id;
	// 実送信記録用一時メンバ
	/** 送信本文	*/
	var $body;
	/** 送信対象： p=パソコン, m=携帯	*/
	var $target_type	= 'p';
	/** メールタイプ: h=HTML, p=plain	*/
	var $mail_type		= 'p';
	/**
	 * コンストラクタ
	 */
	function member_DaoMemberMailTemplate(){
	}
	/**
	 * 関連情報を読み込み
	 */
	function loadRelateion( $dbo ) {
		$this->body	= $this->text_body_default;
	}
	/**
	 * 本メールテンプレートの内容をそのままでメール送信を実行します
	 * @param & $request spider_HttpRequestオブジェクト参照
	 * @param $mailToAddress 宛先メールアドレス
	 * @param $replaceWordHash 置換ワードハッシュ
	 * @param $mailType p=plain, h=html
	 * @return 配信結果ステータス: 1=正常配信
	 * 				201=Fail to send mail!
	 * 				204=Fail to create mail_sender!
	 * 				254=Fail to load member package configuration!
	 */
	function sendMail( & $request, $mailToAddress, $replaceWordHash=array(), $mailType=null ) {
		// 送信メールタイプがHTMLかプレーンテキストか設定
		if( !is_null( $mailType ) ) {
			$this->mail_type	= $mailType;
		} else if( $this->mail_type != 'h' ) {
			$this->mail_type = 'p';
		}
		// ベースURLはデフォルトで変換
		if( !isset($replaceWordHash['url_base']) ) {
			$replaceWordHash['url_base']	= SPIDER_URL_BASE;
		}
		if( !isset($replaceWordHash['base_url']) ) {
			$replaceWordHash['base_url']	= SPIDER_URL_BASE;
		}
		// 送信設定の取り出し
		$mailSendClassName	= '';
		$mailSendParams		= array();
		if( defined('MEMBER_MAIL_SEND_METHOD') && strlen(MEMBER_MAIL_SEND_METHOD) > 0 ) {
			// 会員パッケージの設定
			if( is_array($GLOBALS['SYSTEM_SEND_METHOD'][MEMBER_MAIL_SEND_METHOD]) ) {
				$mailSendClassName	= $GLOBALS['SYSTEM_SEND_METHOD'][MEMBER_MAIL_SEND_METHOD]['class_name'];
				if( is_array($GLOBALS['MEMBER_MAIL_SEND_METHOD_OPTIONS']) ) {
					$mailSendParams		= $GLOBALS['MEMBER_MAIL_SEND_METHOD_OPTIONS'];
				}
			}
		}
		if( strlen($mailSendClassName) == 0 ) {
			// 会員パッケージの設定がないならシステム設定の取得を試みる
			if( file_exists(DIR_PATH_DATA.DIRECTORY_SEPARATOR.'system.define.inc.php') ) {
				require_once(DIR_PATH_DATA.DIRECTORY_SEPARATOR.'system.define.inc.php');
				if( defined('SYSTEM_MAIL_SEND_METHOD') && strlen(SYSTEM_MAIL_SEND_METHOD) > 0 ) {
					if( is_array($GLOBALS['SYSTEM_SEND_METHOD'][SYSTEM_MAIL_SEND_METHOD]) ) {
						$mailSendClassName	= $GLOBALS['SYSTEM_SEND_METHOD'][SYSTEM_MAIL_SEND_METHOD]['class_name'];
						if( is_array($GLOBALS['SYSTEM_MAIL_SEND_METHOD_OPTIONS']) ) {
							$mailSendParams		= $GLOBALS['SYSTEM_MAIL_SEND_METHOD_OPTIONS'];
						}
					}
				}
			}
		}
		if( strlen($mailSendClassName) == 0 ) {
			// 設定が取得できなければエラー
			$request->addLocaledError('system.error.common.noinstalled',SPIDER_LOG_LEVEL_FATAL,array(''));
			return 204;
		}
		// 送信者がテンプレートにセットされていなければシステム設定を入力
		if( strlen($this->mail_from_name) == 0 ) {
			$this->mail_from_name	= SYSTEM_MAIL_FROM_NAME;
		}
		if( strlen($this->mail_from_address) == 0 ) {
			$this->mail_from_address	= SYSTEM_MAIL_FROM_ADDRESS;
		}
		if( strlen($this->mail_reply_address) == 0 ) {
			$this->mail_reply_address	= SYSTEM_MAIL_REPLY_ADDRESS;
		}
		if( strlen($this->mail_return_path) == 0 ) {
			$this->mail_return_path	= SYSTEM_MAIL_RETURN_ADDRESS;
		}
		// 対象アドレスが携帯か確認
		$this->target_type	= 'p';
		$isMobile	= false;
		foreach( $GLOBALS['MOBILE_MAIL_DOMAIN_ARRAY'] as $fqdn ) {
			$fqdn_regx	= str_replace('.','\\.',$fqdn );
			if( preg_match('/\\@'.$fqdn_regx.'$/',$mailToAddress) > 0 ) {
				$isMobile	= true;
				$this->target_type	= 'm';
				break;
			}
		}
		// 送信オブジェクト作成
		spider_Controller::loadClassDefinition('util_Mail');
		$mailSender	= util_Mail::get_instance( $mailSendClassName, $mailSendParams );
		if( $mailSender === false ) {
			return 204;
		} else {
			// 送信件名とタイトルの取得
			$mailSubject	= $this->subject;
			if( $isMobile && strlen(trim($this->subject_mobile)) > 0 ) {
				$mailSubject	= $this->subject_mobile;
			}
			$textBody		= $this->text_body_default;
			if( $isMobile && strlen(trim($this->text_body_mobile)) > 0 ) {
				$textBody	= $this->text_body_mobile;
			}
			$htmlBody		= $this->html_body_default;
			if( $isMobile && strlen(trim($this->html_body_mobile)) > 0 ) {
				$htmlBody		= $this->html_body_mobile;
			} else if( strlen(trim($htmlBody)) == 0 ) {
				$htmlBody		= $this->text_body_default;
			}
			// 携帯電話向けの場合
			$encodeAuto		= true;
			if( $isMobile ) {
				$mailSender->setBodyCharset( 'Shift_JIS' );
				$mailSender->setHeaderCharset( 'Shift_JIS' );
				$mailSubject	= mb_convert_kana($mailSubject,'ka');
				$mailSubject	= mb_convert_kana($this->mail_from_name,'ka');
				$textBody	= mb_convert_kana($textBody,'ka');
				$htmlBody	= mb_convert_kana($htmlBody,'ka');
				$mailSubject	= mb_convert_encoding($mailSubject,'SJIS-win');
				$textBody	= mb_convert_encoding($textBody,'SJIS-win');
				$htmlBody	= mb_convert_encoding($htmlBody,'SJIS-win');
				// 置換ワードのカナ変換
				foreach( $replaceWordHash as $key => $object ) {
					if( is_object($object) ) {
						if( is_a($object,'system_AbstractData') ) {
							$replaceWordHash[$key]->convertKanaFields( 'ka' );
						}
					} else if( is_array($object) ){
						foreach( $object as $k => $v ) {
							$replaceWordHash[$key][$k]	= mb_convert_kana($v,'ka');
						}
					} else {
						$replaceWordHash[$key]	= mb_convert_kana($object,'ka');
					}
				}
				$encodeAuto	= false;
			}
			// メールタイプ HTML/PLAINごとに件名と本文を設定
			if( 'h' == $this->mail_type ) {
				// HTMLメールの場合
				spider_Controller::loadClassDefinition('util_mobile_PictCharConverter');
				if( preg_match('/\\@docomo\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'docomosbin', false, 'SJIS-win' );
					$this->mail_from_name	= util_mobile_PictCharConverter::convert( $this->mail_from_name, 'docomou', 'docomosbin', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'docomosbin', false, 'SJIS-win' );
					$htmlBody	= util_mobile_PictCharConverter::convert( $htmlBody, 'docomou', 'docomosbin', false, 'SJIS-win' );
				} else if( preg_match('/\\@ezweb\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'auesjis', false, 'SJIS-win' );
					$this->mail_from_name	= util_mobile_PictCharConverter::convert( $this->mail_from_name, 'docomou', 'auesjis', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'auesjis', false, 'SJIS-win' );
					$htmlBody	= util_mobile_PictCharConverter::convert( $htmlBody, 'docomou', 'auesjis', false, 'SJIS-win' );
				} else if( preg_match('/\\@vodafone\\.ne\\.jp$/',$mailToAddress) > 0
					|| preg_match('/\\@softbank\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'softbankesjis', false, 'SJIS-win' );
					$this->mail_from_name	= util_mobile_PictCharConverter::convert( $this->mail_from_name, 'docomou', 'softbankesjis', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'softbankesjis', false, 'SJIS-win' );
					$htmlBody	= util_mobile_PictCharConverter::convert( $htmlBody, 'docomou', 'softbank', false, 'SJIS-win' );
				} else if( !$isMobile ) {
					$mailSender->setBodyCharset( 'Shift_JIS' );
					$mailSender->setHeaderCharset( 'Shift_JIS' );
					$mailSubject	= mb_convert_encoding($mailSubject,'SJIS-win');
					$textBody	= mb_convert_encoding($textBody,'SJIS-win');
					$htmlBody	= mb_convert_encoding($htmlBody,'SJIS-win');
					$encodeAuto	= false;
				}
				if( preg_match('/\\<[hH][tT][mM][lL](|[^\\>]+)\\>/',$htmlBody) == 0 ) {
					$bgcolor	= '';
					if( strlen(trim($this->bgcolor)) > 0 ) {
						$bgcolor	= ' bgcolor="'.$this->bgcolor.'"';
					}
					$htmlBody	= '<HTML>'
						.'<HEAD><META http-equiv="Content-Type" content="text/html; charset=Shift_JIS"></HEAD>'
						.'<BODY'.$bgcolor.'>'
						.$htmlBody.'</BODY></HTML>';
				}
				// body内のIMGタグを探してインライン添付
				$imageContentIdHash	= array();
				$dateStr			= date('YmdHis');
				preg_match_all( '/\\<[iI][mM][gG][^\\>]*[sS][rR][cC]\\=[\'"]([^\'"]+)[\'"][^\\>]*(|\\/)\\>/', $htmlBody, $imgTagHash, PREG_PATTERN_ORDER );
				foreach( $imgTagHash[1] as $imgUri ) {
					if( preg_match('/^\\//',$imgUri) > 0 && !in_array( $imgUri,$imageContentIdHash) ) {
						$contentId	= 'IC'.$dateStr.'.'.(count($imageContentIdHash)+1)
							.substr($memberMailObject->mail_from_address,strpos($memberMailObject->mail_from_address,'@'));
						$imageContentIdHash[$contentId]	= $imgUri;
					}
				}
				foreach( $imageContentIdHash as $contentId => $imgUri ) {
					// ファイルをインライン添付
					$inAppUri	= $imgUri;
					if( '/' != SPIDER_URI_BASE ) {
						$inAppUri	= str_replace(SPIDER_URI_BASE,'',$imgUri);
					}
					if( preg_match('/^\\//',$inAppUri) == 0 ) {
						$inAppUri	= '/'.$inAppUri;
					}
					if( system_DataFileWriter::isExists( $request, $inAppUri, 'public' ) ){
						// 対象URIのファイルがあるなら添付
						$realPath	= system_DataFileWriter::getRealAbsolutePath( $request, $inAppUri, 'public' );
						if( file_exists($realPath) ) {
							$fileName		= basename($realPath);
							$contentType	= 'image/jpeg';
							if( preg_match('/\\.[gG][iI][fF]$/',$fileName) > 0 ) {
								$contentType	= 'image/gif';
							} else if( preg_match('/\\.[pP][nN][gG]$/',$fileName) > 0 ) {
								$contentType	= 'image/png';
							}
							$mailSender->addInlineImage( $contentId, $realPath, $fileName, $contentType );
							// body内の文字を書き換え
							$preRegx	= '/[sS][rR][cC]\\=[\'"]'.util_CharUtility::escapeRegxStr($imgUri).'[\'"]/';
							$conStr		= 'src="cid:'.$contentId.'"';
							$htmlBody	= preg_replace($preRegx,$conStr,$htmlBody);
						}
					}
					
				}
				$mailSender->setSubject($mailSubject);
				$textBody	= trim(strip_tags($textBody));
				$mailSender->setTextBody($textBody);
				$mailSender->setHtmlBody($htmlBody);
			} else {
				// テキストメールの場合
				spider_Controller::loadClassDefinition('util_mobile_PictCharConverter');
				if( preg_match('/\\@docomo\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'docomosbin', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'docomosbin', false, 'SJIS-win' );
				} else if( preg_match('/\\@ezweb\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'auesjis', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'auesjis', false, 'SJIS-win' );
				} else if( preg_match('/\\@vodafone\\.ne\\.jp$/',$mailToAddress) > 0
					|| preg_match('/\\@softbank\\.ne\\.jp$/',$mailToAddress) > 0 ) {
					$mailSubject	= util_mobile_PictCharConverter::convert( $mailSubject, 'docomou', 'softbankesjis', false, 'SJIS-win' );
					$textBody	= util_mobile_PictCharConverter::convert( $textBody, 'docomou', 'softbankesjis', false, 'SJIS-win' );
				} else {
					
				}
				$mailSender->setSubject($mailSubject);
				$mailSender->setTextBody($textBody);
			}
			// 置換ワード設定
			foreach( $replaceWordHash as $key => $object ) {
				if( is_object($object) ) {
					$mailSender->addReplaceWordByObject( $key, $object );
				} else if( is_array($object) ){
					$mailSender->addReplaceWordByHash( $key, $object );
				} else {
					$mailSender->addReplaceWord( $key, $object );
				}
			}
			// 送信処理
			//$mailSender->addInlineImage( 'AD2009021983.01@users.sourceforge.jp', dirname(__FILE__).DIRECTORY_SEPARATOR.'t01.jpg', 't01.jpg', 'image/jpeg' );
			//$mailSender->addCc('m_nakashima@users.sourceforge.jp');
			$force_convert	= true;
			if( $isMobile ) { $force_convert = false; }
			$from	= '';
			if( strlen($this->mail_from_name) > 0 ) {
				$from	.= $this->mail_from_name.' <';
			}
			$from	.= $this->mail_from_address;
			if( strlen($this->mail_from_name) > 0 ) {
				$from	.= '>';
			}
			$result	= $mailSender->send( $mailToAddress, null, null,
				$from, $this->mail_reply_address, $this->mail_return_path, null, null, false, $encodeAuto );
			if( $result ) {
				// 送信成功したら実際に送信した本文を取得
				$this->body		= $mailSender->_get_header_part_strings(true,true,false,false,$encodeAuto)
					."\r\n\r\n".$mailSender->_get_body_part_strings($encodeAuto);
				return 1;
			} else {
				return 201;
			}
		}
	}
	//
	// メールテンプレートインストール関連
	/**
	 * 指定フォルダ以下のメールテンプレートフォルダを全てインストールする静的メソッド
	 */
	public static function insertTemplateByRootFolder( & $request, $rootFolderPath ) {
		if( is_dir($rootFolderPath) ) {
			$tplRtDh	= @opendir( $rootFolderPath );
			if( $tplRtDh ) {
				while (($fileName = readdir($tplRtDh)) !== false) {
					if( preg_match('/^\\./',$fileName) == 0 ) {
						$targetPath	= $rootFolderPath.DIRECTORY_SEPARATOR.$fileName;
						if( is_dir($targetPath) ){
							$rst	= member_DaoMemberMailTemplate::insertTemplateByFolderPath( $request, $targetPath );
							if( $rst === false){
								@closedir($tplRtDh);
								return false;
							}
						}
					}
				}
				@closedir($tplRtDh);
			}
			return true;
		}
		return false;
	}
	/**
	 * 指定のフォルダをテンプレートとしてインサートする静的メソッド
	 */
	public static function insertTemplateByFolderPath( & $request, $folderPath ){
		$dbo	= $request->getAttribute('dbo');
		spider_Controller::loadClassDefinition('util_Mail');
		if( is_null($dbo) ){
			return false;
		}
		// メールテンプレートの存在確認
		$isUpdate						= false;
		$mailTemplateObject	= new member_DaoMemberMailTemplate();
		if( $dbo->loadById($mailTemplateObject,trim(basename($folderPath))) ){
			$isUpdate					= true;
		}
		$mailTemplateObject->template_id	= basename($folderPath);
		$mailTemplateObject->mail_from_name		= SYSTEM_MAIL_FROM_NAME;
		$mailTemplateObject->mail_from_address	= SYSTEM_MAIL_FROM_ADDRESS;
		$mailTemplateObject->mail_reply_address	= SYSTEM_MAIL_REPLY_ADDRESS;
		$mailTemplateObject->mail_return_path	= SYSTEM_MAIL_RETURN_ADDRESS;
		$mailTemplateObject->updated_date		= date('Y-m-d H:i:s');
		$mailTemplateObject->registered_date	= date('Y-m-d H:i:s');
		$mailTemplateObject->owner_id			= 'SYSADMIN';
		$mailTemplateObject->modifier_id		= 'SYSADMIN';
		// メールテンプレートインストール時は$GLOBALSのスカラーのみ置換
		$replaceHash = array();
		foreach( $GLOBALS as $key => $value ){
			if( is_scalar($value) ){
				$replaceHash[$key] = $value;
			}
		}
		if( file_exists($folderPath.DIRECTORY_SEPARATOR.'info.txt') ){
			$lines	= file($folderPath.DIRECTORY_SEPARATOR.'info.txt');
			foreach( $lines as $line ) {
				$line	= trim($line);
				if( strlen($line)>0 && strpos($line,'=') !== false ){
					$array	= explode('=',$line);
					$key		= array_shift($array);
					$val		= implode('=',$array);
					$mailTemplateObject->$key	= trim(util_Mail::replaceFormatStrings( $val, $replaceHash, 'UTF-8', false));
				}
			}
			if( file_exists($folderPath.DIRECTORY_SEPARATOR.'default.txt') ){
				$lines	= file($folderPath.DIRECTORY_SEPARATOR.'default.txt');
				if( count($lines) > 0 ){
					if( $mailTemplateObject->template_type == '0' ){
						$mailTemplateObject->subject	= trim(array_shift($lines));
					} else {
						$mailTemplateObject->subject	= '';
					}
					$mailTemplateObject->text_body_default	= implode('',$lines);
					$mailTemplateObject->text_body_default	= str_replace("\r\n","\n",$mailTemplateObject->text_body_default);
					$mailTemplateObject->text_body_default	= str_replace("\r","\n",$mailTemplateObject->text_body_default);
					$mailTemplateObject->subject	= util_Mail::replaceFormatStrings( $mailTemplateObject->subject, $replaceHash, 'UTF-8', false);
					$mailTemplateObject->text_body_default	= util_Mail::replaceFormatStrings( $mailTemplateObject->text_body_default, $replaceHash, 'UTF-8', false);
				}
			}
			if( file_exists($folderPath.DIRECTORY_SEPARATOR.'mobile.txt') ){
				$lines	= file($folderPath.DIRECTORY_SEPARATOR.'mobile.txt');
				if( count($lines) > 0 ){
					if( $mailTemplateObject->template_type == '0' ){
						$mailTemplateObject->subject_mobile	= trim(array_shift($lines));
					} else {
						$mailTemplateObject->subject_mobile	= '';
					}
					$mailTemplateObject->subject_mobile			= trim(array_shift($lines));
					$mailTemplateObject->text_body_mobile	= implode('',$lines);
					$mailTemplateObject->text_body_mobile	= str_replace("\r\n","\n",$mailTemplateObject->text_body_mobile);
					$mailTemplateObject->text_body_mobile	= str_replace("\r","\n",$mailTemplateObject->text_body_mobile);
					$mailTemplateObject->subject	= util_Mail::replaceFormatStrings( $mailTemplateObject->subject, $replaceHash, 'UTF-8', false);
					$mailTemplateObject->text_body_default	= util_Mail::replaceFormatStrings( $mailTemplateObject->text_body_default, $replaceHash, 'UTF-8', false);
				}
			}
			if( $isUpdate ){
				if( $dbo->update( $mailTemplateObject ) ){
					return true;
				} else {
					return false;
				}
			} else {
				if( $dbo->insert( $mailTemplateObject ) ){
					return true;
				} else {
					return false;
				}
			}
		} else {
			return false;
		}
	}
}
?>