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

class Atmail_Mail_Transport_Smtp extends Zend_Mail_Transport_Smtp
{
    
	//ZF appears to have implimented the only processing of Zend_Message actually inside the transport, so quickest to extract rawMessage from here
	
	public function getRawMessage(Zend_Mail $mail)
    {
        
   		$this->_isMultipart = false;
        $this->_mail        = $mail;
        $this->_parts       = $mail->getParts();
        $mime               = $mail->getMime();

        // Build body content
        $this->_buildBody();

        // Determine number of parts and boundary
        $count    = count($this->_parts);
        $boundary = null;
        if ($count < 1)
            throw new Zend_Mail_Transport_Exception('Empty mail cannot be sent');
        
		if ($count > 1) {
            // Multipart message; create new MIME object and boundary
            $mime     = new Zend_Mime($this->_mail->getMimeBoundary());
            $boundary = $mime->boundary();
        } elseif ($this->_isMultipart) {
            $boundary = $this->_parts[0]->boundary;
        }

        //$this->recipients = implode(',', $mail->getRecipients());
        $this->_prepareHeaders($this->_getHeaders($boundary));

        $message = new Zend_Mime_Message();
        $message->setParts($this->_parts);
        $message->setMime($mime);
        $this->body = $message->generateMessage($this->EOL);

        return $this->header . Zend_Mime::LINEEND . $this->body . Zend_Mime::LINEEND;
    }
  
	public function saveToMailDir($maildir, Zend_Mail $mail) {
		
		$id = $this->generateMaildirId("$maildir/new/");
		file_put_contents("$maildir/new/$id", $this->getRawMessage($mail));
		chown("$maildir/new/$id", "atmail");

		return;
	}

	public function generateMaildirId($folder)
	{
		$id;
	    $h = "H";
	    $pid = "P" . getmypid();

	    // Generate key
		for(;;)
		{
			$secs = time();

		    for ($i=0; $i<6; $i++)
		        $h .= intval(rand(0,9));

			$id = "$secs.$h$pid.localhost";

		    // Generate another key if it already exists
		    if (!file_exists("$folder/$id"))
				return $id;
		}
	}
	
	public function sendRawMessage( $fromAdd, array $toaddr, $body, $headers, array $ccaddr = array(), array $bccaddr = array() )
	{
		
		// If sending multiple messages per session use existing adapter
        if (!($this->_connection instanceof Zend_Mail_Protocol_Smtp)) {
            // Check if authentication is required and determine required class
            $connectionClass = 'Zend_Mail_Protocol_Smtp';
            if ($this->_auth) {
                $connectionClass .= '_Auth_' . ucwords($this->_auth);
            }
            if (!class_exists($connectionClass)) {
                require_once 'Zend/Loader.php';
                Zend_Loader::loadClass($connectionClass);
            }
            $this->setConnection(new $connectionClass($this->_host, $this->_port, $this->_config));
            $this->_connection->connect();
            $this->_connection->helo($this->_name);
        } else {
            // Reset connection to ensure reliable transaction
            $this->_connection->rset();
        }

        // Set sender email address
        $this->_connection->mail($fromAdd);

        // Set recipient forward paths
        foreach( array($toaddr, $ccaddr, $bccaddr) as $recipientsArray) 
		{
            
			if( !is_array($recipientsArray) )
				$recipientsArray = array($recipientsArray);
				
			foreach( $recipientsArray as $recipient )
				if( $recipient != '')
					$this->_connection->rcpt($recipient);
		
		}

        // Issue DATA command to client
        $this->_connection->data($headers . Zend_Mime::LINEEND . $body);
		return true;
		
	}

}
