<?php

/**
 * Class used to sanitize email
 *
 * @category   Atmail
 * @package    Zend_Filter_EmailPurifier
 * @copyright  Copyright (c) NetBased Software pty ltd
 */

/**
 * @category   Atmail
 * @package    Zend_Filter_EmailPurifier
 * @copyright  Copyright (c) NetBased Software pty ltd
 */

require_once('Mail/RFC822.php');

class Zend_Filter_EmailPurifier implements Zend_Filter_Interface
{
	    
	protected $_htmlPurifier = null;
   
    public function __construct($options = null)
    {        
		$this->_mail_rfc822 =  new Mail_RFC822; //appears to be buggy (trying to decode encoded words, but seems ok with already decoded words), fails to pass all addresses with utf-8 charset    
	}

    public function filter($value)
    {
    	if($value == "")
    	{
    		return "";
	   	}
	   	
	   	$address = array();
    	
		// Generate the users real-name + email address for the UI
		$rcpt = $this->_mail_rfc822->parseAddressList($value, null, false);
		
		if( is_array($rcpt) )
		{
			foreach( $rcpt as $email )
			{
				if( isset($email->personal) )
				{
					$address['name'] = trim($email->personal, ' "' );
					$address['email'] = $email->mailbox . '@' . $email->host;
				}
			}
		}
		else
		{
			$address['name'] = trim( trim( substr($value, 0, (strrpos($value,'<')-1) ) ), ' "');
			$address['email'] = trim( substr($value, (strrpos($value,'<')+1), (strrpos($value,'>')-strrpos($value,'<')-1) ));
		}
		
		if ($address['email'] != "@localhost" )
		{
			return $address['email'];
		}
		else
		{
			return "";
		}
    }

}
