<?php
include_once(searchinc('base.inc'));
include_once(searchinc('mimeclass.inc'));

define('SMTP_DEFAULT_USER', null);

// secure user input for use in SMTP headers
function smtp_header_quote($input, $maxsize=false)
{
	// remove carrage return, new lines and formfeeds
	// and trim whitespace
	$str = trim(strtr($input, array("\n" => "", "\r" => "", "\xB" => "", "\xC" => "")));
	// ensure smaller than maxsize
	if ($maxsize)
		$str = substr($str, 0, $maxsize);
		
	return $str;
}
	
class smtp_mailer extends base
{
//	var $_debug = DEBUG_DETAIL_TRACE;
	
	var $_server;			// override in derived classes
	var $_port = 25;		// override in derived classes
	var $_user;				// override in derived classes
	
	var $_password;
   
	var $_ct;				// connection token
	var $_is_authenticated = false;
	var $_is_announced = false;
	var $_exts = array();	// server supported extensions
   
	function __construct($user, $password, $server=null, $port=null, $mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$server.','.$user.') entering', DEBUG_PROC_TRACE);
		
		parent::__construct($mode);
		if ($this->is_ok())
		{
			if (isset($user)) $this->_user = $user;
			$this->_password = $password;
			if (isset($server)) $this->_server = $server;
			if (!isset($this->_server)) $this->_server = $GLOBALS['default_smtp_host'];
			if (isset($port)) $this->_port = $port;
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
   
	function get_response(&$resp)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$resp = fgets($this->_ct, 256);
		$code = intval(substr($resp, 0, 3));
		if (substr($resp, 3, 1)=='-')
		{
			$tresp = array();
			while(substr($resp, 3, 1)=='-')
			{
				$this->dbgecho($proc.' partial resp - '.$resp, DEBUG_DETAIL_TRACE);
				$tresp[] = $resp;
				$resp = fgets($this->_ct, 256);
			}
			$code = intval(substr($resp, 0, 3));
			$resp = $tresp;
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?look_r($code):'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($code);
	}
   
	function do_cmd($cmd, &$res_str)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$cmd.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->put($cmd."\r\n");
		$res = $this->get_response($res_str);
		$this->dbgecho($proc.'cmd resp: '.look_r($res_str), DEBUG_DETAIL_TRACE);
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?$res:'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok($res);
	}
   
	function _connect()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->_ct = fsockopen($this->_server, $this->_port, &$errno, &$errstr, 1))
		{
			$this->set_error('TCP/IP error - '.$errno.' - '.$errstr, __FILE__, __LINE__);
		}
		elseif (($code=$this->get_response($msg)) != 220)
		{
			$this->quit();
			$this->set_error('SMTP connect error - '.$code.' - '.$msg, __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function connected()
	{
		return (isset($this->_ct));
	}
	
	function announced()
	{
		return $this->_is_announced;
	}
	
	function authenticated()
	{
		return $this->_is_authenticated;
	}
	
	function put($str)
	{
   		fputs($this->_ct, $str);
	}
	
	function do_EHLO()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->connected()) $this->_connect();
		
		if ($this->is_ok())
		{
			// send EHLO message
			$rcode = $this->do_cmd('EHLO '.$this->_server, $tmp);
			if (($rcode < 200) && ($rcode >= 300))
			{
				$this->set_error('Failed to Introduce', __FILE__, __LINE__);
			}
			else
			{
				// save response as server supported extensions
				if (is_array($tmp))
				{
					foreach($tmp as $line)
					{
						// strip the partial completion code portion of the line
						// separate the extension keyword from any parameters
						// and store it away
						list($key, $params) = split(' ', trim(substr($line, 4)));
						$this->_exts[strtoupper($key)] = $params;
					}
				}
			}
			$this->_is_announced = true;
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function do_AUTH()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (!$this->authenticated)
		{
			if (!$this->announced()) $this->do_EHLO();
			
			if ($this->is_ok())
			{
				// find any AUTH extension information
				if (!isset($this->_exts['AUTH']))
				{
					// no authentication required
					$this->_is_authenticated = true;
				}
				else
				{
					$params = strtoupper($this->_exts['AUTH']);
					
					// Try login method
					if (!$this->_is_authenticated && (strpos($params, 'LOGIN') !== false))
					{
						// send auth login command
						$rcode = $this->do_cmd('AUTH LOGIN', $nul);
						if (($rcode >= 300) && ($rcode < 400))
						{
							// send username
							$rcode = $this->do_cmd(base64_encode($this->_user), $nul);
							if (($rcode >= 300) && ($rcode < 400))
							{
								// send password
								$rcode = $this->do_cmd(base64_encode($this->_password), $nul);
								$this->_is_authenticated = ($rcode >= 200) && ($rcode < 300);
							}
							$this->set_error('Failed to Introduce', __FILE__, __LINE__);
						}
						$last_tried ='LOGIN';
					}
					// Try plain method
					if (!$this->_is_authenticated && (strpos($params, 'PLAIN') !== false))
					{
						// send auth plain with encoded username and password
						$param = base64_encode($this->_user."\0".$this->_user."\0".$this->_password);
						$rcode = $this->do_cmd('AUTH PLAIN '.$param, $nul);
						$this->_is_authenticated = ($rcode >= 200) && ($rcode < 300);
						$last_tried ='PLAIN';
					}
					if (!$this->_is_authenticated)
					{
						if(isset($last_tried))
						{
							// unable to authenticate
							$this->set_error('Failed to authenticate as '.$this->_user, __FILE__, __LINE__);
						}
						else
						{
							// no supported autentication mechanisms
							$this->set_error('No supported authentication mechanisms on server', __FILE__, __LINE__);
						}
					}
				}
			}
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function initialize()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$this->do_AUTH();
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function quit()
	{
		if ($this->connected())
		{
			// send quit command
			$this->do_cmd('QUIT', $nul);
			// close connection
			fclose($this->_ct);
			// clear token
			$this->_ct = null;
		}
	}
	
	// modified by Joseph C Miller (josephcmiller2@gmail.com) to provide authenticated logins
	// orignally copied from work by Antony Male (?)
	function mail($to, $subject, $message, $headers)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$to.','.$subject.')entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		$this->dbgecho($proc.'$headers: '.look_r($headers), DEBUG_DETAIL_TRACE);
		
		if (!$this->authenticated())
		{
			$this->initialize();
			$self_initialized = true;
		}
		
		if ($this->is_ok())
		{
			// get From address
			if ( preg_match("/From:.*?[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+.*/", $headers, $froms) )
			{
				preg_match("/[A-Za-z0-9\._%-]+\@[A-Za-z0-9\._%-]+/", $froms[0], $fromarr);
				$from = $fromarr[0];
			}
			
			// Mail from...
			if ($this->do_cmd('MAIL FROM: <'.$from.'>', $nul) != 250)
			{
				$this->set_error('MAIL FROM failed', __FILE__, __LINE__);
			}
			else
			{
				// Rcpt to...
				if ($this->do_cmd('RCPT TO: <'.$to.'>', $nul) != 250)
				{
					$this->set_error('RCPT TO failed', __FILE__, __LINE__);
				}
				else
				{
					// extract and process contents of cc: and bcc: headers
					$hd_array = mk_header_array($headers, $err);
					if (isset($hd_array['to']) || isset($hd_array['cc']) || isset($hd_array['bcc']))
					{
						$recp_str = $hd_array['to'];
						if (isset($hd_array['cc']))
						{
							if (strlen($recp_str)>0) $recp_str .= ',';
							$recp_str .= $hd_array['cc'];
						}
						if (isset($hd_array['bcc']))
						{
							if (strlen($recp_str)>0) $recp_str .= ',';
							$recp_str .= $hd_array['bcc'];
						}
						
						$recips = explode(',', $recp_str);
						foreach($recips as $recp)
						{
							if (trim($recp) != trim($to))
							{
								if ($this->do_cmd('RCPT TO: <'.trim($recp).'>', $nul) != 250)
								{
									$this->set_error('copy RCPT TO failed', __FILE__, __LINE__);
									break;
								}
							}
						}
					}
					
					if ($this->is_ok())
					{
						// Data...
						if ($this->do_cmd('DATA', $nul) != 354)
						{
							$this->set_error('DATA failed', __FILE__, __LINE__);
						}
						else
						{
							// Message Body...
							$txt = 'To: '.$to."\r\n".
								   (strlen($subject)>0?('Subject: '.$subject."\r\n"):'').
								   str_replace("\n","\r\n",$headers)."\r\n\r\n".
								   str_replace("\n","\r\n",str_replace("\n.\n", "\n..\n", str_replace("\r\n","\n",$message)))."\r\n.";
							if ($this->do_cmd($txt, $nul) != 250)
							{
								$this->set_error('Message Body failed', __FILE__, __LINE__);
							}
						}
					}
				}
			}
			
			if ($self_initialized) $this->quit();
		}
		
		$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
}
 ?>
