<?php
/*
 * framework-spider
 * util/mail/Mime.class.php
 * 
 * CopyRight(C)Framework-Spider Developer Team. 2010. All Right Reserved. 
 * URL         : http://sourceforge.jp/projects/frameworkspider/
 * Mail        : frameworkspider-dev@lists.sourceforge.jp
 * Auther      : Masanori Nakashima
 * Modifier    : Masanori Nakashima
 * Last Updated: 2010.06.23
 * 
 */
/**
 * メールの文字列をヘッダとボディに分割して保持するオブジェクトクラス
 */
class util_mail_Mime {
	/** メールヘッダーハッシュ	*/
	var $headers	= array();
	/** ボディ要素配列	*/
	var $bodys		= array();
	/** From	*/
	var $from;
	/** From Name	*/
	var $fromName;
	/** To		*/
	var $to;
	/** To Name	*/
	var $toName;
	/**
	 * コンストラクタ
	 */
	function util_mail_Mime( $mailData = null ) {
		if( strlen($mailData) > 0 ) {
			$this->decode( $mailData );
		}
	}
	/**
	 * メールデータ文字列を受け取ってデコードします
	 */
	function decode( $mailData ) {
		$elements		= explode("\r\n\r\n",$mailData);
		// メールヘッダの取り出し
		$headerStrings		= array_shift($elements);
		$headerStrings		= str_replace("\r\n","\n",$headerStrings);
		$headerStrings		= str_replace("\r","\n",$headerStrings);
		$headerLines		= explode("\n",$headerStrings);
		$this->headers		= array();
		$before_name		= null;
		foreach( $headerLines as $line ) {
			$line		= trim($line);
			$cols		= explode(':',$line);
			$name		= '';
			if( count($cols) > 1 ) {
				$name	= trim(array_shift($cols));
				$val	= trim(implode(':',$cols));
				$this->headers[$name]	= $val;
			} else if( count($cols) == 1 && strlen(trim($before_name)) > 0 ){
				$val	= trim(array_shift($cols));
				$this->headers[$before_name]	.= "\n".$val;
			}
			if( strlen($name) > 0 ) {
				$before_name	= $name;
			}
		}
		// 残りはボディパーツ
		$this->bodys	= $elements;
		// 主要ヘッダのみ切り分け
		// 受取アドレスを取得
		$this->to		= null;
		if( isset($this->headers['To']) ) {
			$this->to		= $this->headers['To'];
		}
		if( strlen($this->to) == 0 ) {
			if( isset($this->headers['to']) ) {
				$this->to		= $this->headers['to'];
			}
			if( strlen($this->to) == 0 ) {
				if( isset($this->headers['TO']) ) {
					$this->to		= $this->headers['TO'];
				}
			}
		}
		if( strlen($this->to) > 0 && false !== strpos($this->to,'<') ) {
			$this->to	= trim($this->to);
			list( $this->toName, $this->to )	= explode('<',$this->to);
			$this->to	= preg_replace('/>$/','',$this->to);
			$this->toName	= trim($this->toName);
		}
		
		// 送信元アドレス取得
		$this->from		= null;
		if( isset($this->headers['From'] ) ) {
			$this->from		= $this->headers['From'];
		}
		if( strlen($this->from) == 0 ) {
			if( isset($this->headers['from']) ){
				$this->from		= $this->headers['from'];
			}
			if( strlen($this->from) == 0 ) {
				if( isset($this->headers['FROM']) ){
					$this->from		= $this->headers['FROM'];
				}
			}
		}
		if( strlen($this->from) > 0 && false !== strpos($this->from,'<') ) {
			$this->from	= trim($this->from);
			list( $this->fromName, $this->from )	= explode('<',$this->from);
			$this->from	= preg_replace('/>$/','',$this->from);
			$this->fromName	= trim($this->fromName);
		}
	}
}
?>