<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

class Atmail_Mail extends Zend_Mail
{
	public function __construct($config = null)
	{
		//makes connection to single mail store
		//to connect to multiple mail stores call setupMailStore multiple times with required config
		$this->defaultNamespaceName = new Zend_Session_Namespace('defaultNamespaceName');
        parent::__construct($config);
		return $this;
	}
	
   /**
     * fix for buggy ZF implementation
	 */
 
	public function _encodeHeader($value)
	{
	    //TODO: fix this, it wont split the line at 72 chars
		if (Zend_Mime::isPrintable($value)) {
	        return $value;
	    } else {
	        return '=?' . $this->_charset . '?B?' . base64_encode($value) . '?=';
	    }
	}
	
   	/**
	  * Copied from newer version of ZF, can remove once upgraded
	  * Filter of other data
	  *
	  * @param string $data
	  * @return string
	  */
	  protected function _filterOther($data)
	  {
	     $rule = array("\r" => '',
	                   "\n" => '',
	                   "\t" => '',
	     );

	     return strtr($data, $rule);
	  }
	
	/**
     * Copied from newer version of ZF, can remove once upgraded
	 * Sets the Message-ID of the message
     *
     * @param   boolean|string  $id
     * true  :Auto
     * false :No set
     * null  :No set
     * string:Sets string
     * @return  Zend_Mail Provides fluent interface
     * @throws  Zend_Mail_Exception
     */
    public function setMessageId($id = true)
    {
    	if ($id === null || $id === false) {
    		return $this;
    	} elseif ($id === true) {
            $id = $this->createMessageId();
    	}

        if ($this->_messageId === null) {
        	$id = $this->_filterOther($id);
            $this->_messageId = $id;
            $this->_storeHeader('Message-Id', $this->_messageId);
        } else {
            /**
             * @see Zend_Mail_Exception
             */
            require_once 'Zend/Mail/Exception.php';
            throw new Zend_Mail_Exception('Message-ID set twice');
        }

        return $this;
    }

	public function getMessageId() {
		return $this->_messageId;
	}

  /**
    * Copied from newer version of ZF, can remove once upgraded
	* Creates the Message-ID
	*
	* @return string
	*/
	public function createMessageId() {

	   $time = time();

	   if ($this->_from !== null) {
	   	$user = $this->_from;
	   } elseif (isset($_SERVER['REMOTE_ADDR'])) {
	   	$user = $_SERVER['REMOTE_ADDR'];
	   } else {
	   	$user = getmypid();
	   }

	$rand = mt_rand();

	if ($this->_recipients !== array()) {
	       $recipient = array_rand($this->_recipients);
	} else {
		$recipient = 'unknown';
	}

	if (isset($_SERVER["SERVER_NAME"])) {
	       $hostName = $_SERVER["SERVER_NAME"];
	   } else {
	   	$hostName = php_uname('n');
	   }

	   return '<' . sha1($time . $user . $rand . $recipient) . '@' . $hostName . '>';
	}
	
}
