Blame Identity/Webenv/phpBB/3.0.4/includes/functions_messenger.php

ef5584
ef5584
/**
ef5584
*
ef5584
* @package phpBB3
ef5584
* @version $Id: functions_messenger.php 9078 2008-11-22 19:55:00Z acydburn $
ef5584
* @copyright (c) 2005 phpBB Group
ef5584
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
ef5584
*
ef5584
*/
ef5584
ef5584
/**
ef5584
* @ignore
ef5584
*/
ef5584
if (!defined('IN_PHPBB'))
ef5584
{
ef5584
	exit;
ef5584
}
ef5584
ef5584
/**
ef5584
* Messenger
ef5584
* @package phpBB3
ef5584
*/
ef5584
class messenger
ef5584
{
ef5584
	var $vars, $msg, $extra_headers, $replyto, $from, $subject;
ef5584
	var $addresses = array();
ef5584
ef5584
	var $mail_priority = MAIL_NORMAL_PRIORITY;
ef5584
	var $use_queue = true;
ef5584
	var $tpl_msg = array();
ef5584
ef5584
	/**
ef5584
	* Constructor
ef5584
	*/
ef5584
	function messenger($use_queue = true)
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		$this->use_queue = (!$config['email_package_size']) ? false : $use_queue;
ef5584
		$this->subject = '';
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Resets all the data (address, template file, etc etc) to default
ef5584
	*/
ef5584
	function reset()
ef5584
	{
ef5584
		$this->addresses = $this->extra_headers = array();
ef5584
		$this->vars = $this->msg = $this->replyto = $this->from = '';
ef5584
		$this->mail_priority = MAIL_NORMAL_PRIORITY;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Sets an email address to send to
ef5584
	*/
ef5584
	function to($address, $realname = '')
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		$pos = isset($this->addresses['to']) ? sizeof($this->addresses['to']) : 0;
ef5584
ef5584
		$this->addresses['to'][$pos]['email'] = trim($address);
ef5584
ef5584
		// If empty sendmail_path on windows, PHP changes the to line
ef5584
		if (!$config['smtp_delivery'] && DIRECTORY_SEPARATOR == '\\')
ef5584
		{
ef5584
			$this->addresses['to'][$pos]['name'] = '';
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->addresses['to'][$pos]['name'] = trim($realname);
ef5584
		}
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Sets an cc address to send to
ef5584
	*/
ef5584
	function cc($address, $realname = '')
ef5584
	{
ef5584
		$pos = isset($this->addresses['cc']) ? sizeof($this->addresses['cc']) : 0;
ef5584
		$this->addresses['cc'][$pos]['email'] = trim($address);
ef5584
		$this->addresses['cc'][$pos]['name'] = trim($realname);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Sets an bcc address to send to
ef5584
	*/
ef5584
	function bcc($address, $realname = '')
ef5584
	{
ef5584
		$pos = isset($this->addresses['bcc']) ? sizeof($this->addresses['bcc']) : 0;
ef5584
		$this->addresses['bcc'][$pos]['email'] = trim($address);
ef5584
		$this->addresses['bcc'][$pos]['name'] = trim($realname);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Sets a im contact to send to
ef5584
	*/
ef5584
	function im($address, $realname = '')
ef5584
	{
ef5584
		// IM-Addresses could be empty
ef5584
		if (!$address)
ef5584
		{
ef5584
			return;
ef5584
		}
ef5584
ef5584
		$pos = isset($this->addresses['im']) ? sizeof($this->addresses['im']) : 0;
ef5584
		$this->addresses['im'][$pos]['uid'] = trim($address);
ef5584
		$this->addresses['im'][$pos]['name'] = trim($realname);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Set the reply to address
ef5584
	*/
ef5584
	function replyto($address)
ef5584
	{
ef5584
		$this->replyto = trim($address);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Set the from address
ef5584
	*/
ef5584
	function from($address)
ef5584
	{
ef5584
		$this->from = trim($address);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* set up subject for mail
ef5584
	*/
ef5584
	function subject($subject = '')
ef5584
	{
ef5584
		$this->subject = trim($subject);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* set up extra mail headers
ef5584
	*/
ef5584
	function headers($headers)
ef5584
	{
ef5584
		$this->extra_headers[] = trim($headers);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Set the email priority
ef5584
	*/
ef5584
	function set_mail_priority($priority = MAIL_NORMAL_PRIORITY)
ef5584
	{
ef5584
		$this->mail_priority = $priority;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Set email template to use
ef5584
	*/
ef5584
	function template($template_file, $template_lang = '')
ef5584
	{
ef5584
		global $config, $phpbb_root_path;
ef5584
ef5584
		if (!trim($template_file))
ef5584
		{
ef5584
			trigger_error('No template file set', E_USER_ERROR);
ef5584
		}
ef5584
ef5584
		if (!trim($template_lang))
ef5584
		{
ef5584
			$template_lang = basename($config['default_lang']);
ef5584
		}
ef5584
ef5584
		if (empty($this->tpl_msg[$template_lang . $template_file]))
ef5584
		{
ef5584
			$tpl_file = "{$phpbb_root_path}language/$template_lang/email/$template_file.txt";
ef5584
ef5584
			if (!file_exists($tpl_file))
ef5584
			{
ef5584
				trigger_error("Could not find email template file [ $tpl_file ]", E_USER_ERROR);
ef5584
			}
ef5584
ef5584
			if (($data = @file_get_contents($tpl_file)) === false)
ef5584
			{
ef5584
				trigger_error("Failed opening template file [ $tpl_file ]", E_USER_ERROR);
ef5584
			}
ef5584
ef5584
			$this->tpl_msg[$template_lang . $template_file] = $data;
ef5584
		}
ef5584
ef5584
		$this->msg = $this->tpl_msg[$template_lang . $template_file];
ef5584
ef5584
		return true;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* assign variables to email template
ef5584
	*/
ef5584
	function assign_vars($vars)
ef5584
	{
ef5584
		$this->vars = (empty($this->vars)) ? $vars : $this->vars + $vars;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Send the mail out to the recipients set previously in var $this->addresses
ef5584
	*/
ef5584
	function send($method = NOTIFY_EMAIL, $break = false)
ef5584
	{
ef5584
		global $config, $user;
ef5584
ef5584
		// We add some standard variables we always use, no need to specify them always
ef5584
		$this->vars['U_BOARD'] = (!isset($this->vars['U_BOARD'])) ? generate_board_url() : $this->vars['U_BOARD'];
ef5584
		$this->vars['EMAIL_SIG'] = (!isset($this->vars['EMAIL_SIG'])) ? str_replace('
', "\n", "-- \n" . htmlspecialchars_decode($config['board_email_sig'])) : $this->vars['EMAIL_SIG'];
ef5584
		$this->vars['SITENAME'] = (!isset($this->vars['SITENAME'])) ? htmlspecialchars_decode($config['sitename']) : $this->vars['SITENAME'];
ef5584
ef5584
		// Escape all quotes, else the eval will fail.
ef5584
		$this->msg = str_replace ("'", "\'", $this->msg);
ef5584
		$this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . ((isset(\$this->vars['\\1'])) ? \$this->vars['\\1'] : '') . '", $this->msg);
ef5584
ef5584
		eval("\$this->msg = '$this->msg';");
ef5584
ef5584
		// We now try and pull a subject from the email body ... if it exists,
ef5584
		// do this here because the subject may contain a variable
ef5584
		$drop_header = '';
ef5584
		$match = array();
ef5584
		if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match))
ef5584
		{
ef5584
			$this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
ef5584
			$drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->subject = (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
ef5584
		}
ef5584
ef5584
		if ($drop_header)
ef5584
		{
ef5584
			$this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg));
ef5584
		}
ef5584
ef5584
		if ($break)
ef5584
		{
ef5584
			return true;
ef5584
		}
ef5584
ef5584
		switch ($method)
ef5584
		{
ef5584
			case NOTIFY_EMAIL:
ef5584
				$result = $this->msg_email();
ef5584
			break;
ef5584
ef5584
			case NOTIFY_IM:
ef5584
				$result = $this->msg_jabber();
ef5584
			break;
ef5584
ef5584
			case NOTIFY_BOTH:
ef5584
				$result = $this->msg_email();
ef5584
				$this->msg_jabber();
ef5584
			break;
ef5584
		}
ef5584
ef5584
		$this->reset();
ef5584
		return $result;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Add error message to log
ef5584
	*/
ef5584
	function error($type, $msg)
ef5584
	{
ef5584
		global $user, $phpEx, $phpbb_root_path, $config;
ef5584
ef5584
		// Session doesn't exist, create it
ef5584
		if (!isset($user->session_id) || $user->session_id === '')
ef5584
		{
ef5584
			$user->session_begin();
ef5584
		}
ef5584
ef5584
		$calling_page = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
ef5584
ef5584
		$message = '';
ef5584
		switch ($type)
ef5584
		{
ef5584
			case 'EMAIL':
ef5584
				$message = 'EMAIL/' . (($config['smtp_delivery']) ? 'SMTP' : 'PHP/' . $config['email_function_name'] . '()') . '';
ef5584
			break;
ef5584
ef5584
			default:
ef5584
				$message = "$type";
ef5584
			break;
ef5584
		}
ef5584
ef5584
		$message .= '
' . htmlspecialchars($calling_page) . '

' . $msg . '
';
ef5584
		add_log('critical', 'LOG_ERROR_' . $type, $message);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Save to queue
ef5584
	*/
ef5584
	function save_queue()
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		if ($config['email_package_size'] && $this->use_queue && !empty($this->queue))
ef5584
		{
ef5584
			$this->queue->save();
ef5584
			return;
ef5584
		}
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Return email header
ef5584
	*/
ef5584
	function build_header($to, $cc, $bcc)
ef5584
	{
ef5584
		global $config;
ef5584
ef5584
		$headers = array();
ef5584
ef5584
		$headers[] = 'From: ' . $this->from;
ef5584
ef5584
		if ($cc)
ef5584
		{
ef5584
			$headers[] = 'Cc: ' . $cc;
ef5584
		}
ef5584
ef5584
		if ($bcc)
ef5584
		{
ef5584
			$headers[] = 'Bcc: ' . $bcc;
ef5584
		}
ef5584
ef5584
		$headers[] = 'Reply-To: ' . $this->replyto;
ef5584
		$headers[] = 'Return-Path: <' . $config['board_email'] . '>';
ef5584
		$headers[] = 'Sender: <' . $config['board_email'] . '>';
ef5584
		$headers[] = 'MIME-Version: 1.0';
ef5584
		$headers[] = 'Message-ID: <' . md5(unique_id(time())) . '@' . $config['server_name'] . '>';
ef5584
		$headers[] = 'Date: ' . date('r', time());
ef5584
		$headers[] = 'Content-Type: text/plain; charset=UTF-8'; // format=flowed
ef5584
		$headers[] = 'Content-Transfer-Encoding: 8bit'; // 7bit
ef5584
ef5584
		$headers[] = 'X-Priority: ' . $this->mail_priority;
ef5584
		$headers[] = 'X-MSMail-Priority: ' . (($this->mail_priority == MAIL_LOW_PRIORITY) ? 'Low' : (($this->mail_priority == MAIL_NORMAL_PRIORITY) ? 'Normal' : 'High'));
ef5584
		$headers[] = 'X-Mailer: PhpBB3';
ef5584
		$headers[] = 'X-MimeOLE: phpBB3';
ef5584
		$headers[] = 'X-phpBB-Origin: phpbb://' . str_replace(array('http://', 'https://'), array('', ''), generate_board_url());
ef5584
ef5584
		// We use \n here instead of \r\n because our smtp mailer is adjusting it to \r\n automatically, whereby the php mail function only works
ef5584
		// if using \n.
ef5584
ef5584
		if (sizeof($this->extra_headers))
ef5584
		{
ef5584
			$headers[] = implode("\n", $this->extra_headers);
ef5584
		}
ef5584
ef5584
		return implode("\n", $headers);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Send out emails
ef5584
	*/
ef5584
	function msg_email()
ef5584
	{
ef5584
		global $config, $user;
ef5584
ef5584
		if (empty($config['email_enable']))
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		$use_queue = false;
ef5584
		if ($config['email_package_size'] && $this->use_queue)
ef5584
		{
ef5584
			if (empty($this->queue))
ef5584
			{
ef5584
				$this->queue = new queue();
ef5584
				$this->queue->init('email', $config['email_package_size']);
ef5584
			}
ef5584
			$use_queue = true;
ef5584
		}
ef5584
ef5584
		if (empty($this->replyto))
ef5584
		{
ef5584
			$this->replyto = '<' . $config['board_contact'] . '>';
ef5584
		}
ef5584
ef5584
		if (empty($this->from))
ef5584
		{
ef5584
			$this->from = '<' . $config['board_contact'] . '>';
ef5584
		}
ef5584
ef5584
		// Build to, cc and bcc strings
ef5584
		$to = $cc = $bcc = '';
ef5584
		foreach ($this->addresses as $type => $address_ary)
ef5584
		{
ef5584
			if ($type == 'im')
ef5584
			{
ef5584
				continue;
ef5584
			}
ef5584
ef5584
			foreach ($address_ary as $which_ary)
ef5584
			{
ef5584
				$$type .= (($$type != '') ? ', ' : '') . (($which_ary['name'] != '') ? '"' . mail_encode($which_ary['name']) . '" <' . $which_ary['email'] . '>' : $which_ary['email']);
ef5584
			}
ef5584
		}
ef5584
ef5584
		// Build header
ef5584
		$headers = $this->build_header($to, $cc, $bcc);
ef5584
ef5584
		// Send message ...
ef5584
		if (!$use_queue)
ef5584
		{
ef5584
			$mail_to = ($to == '') ? 'undisclosed-recipients:;' : $to;
ef5584
			$err_msg = '';
ef5584
ef5584
			if ($config['smtp_delivery'])
ef5584
			{
ef5584
				$result = smtpmail($this->addresses, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $err_msg, $headers);
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				ob_start();
ef5584
				$result = $config['email_function_name']($mail_to, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $headers);
ef5584
				$err_msg = ob_get_clean();
ef5584
			}
ef5584
ef5584
			if (!$result)
ef5584
			{
ef5584
				$this->error('EMAIL', $err_msg);
ef5584
				return false;
ef5584
			}
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->queue->put('email', array(
ef5584
				'to'			=> $to,
ef5584
				'addresses'		=> $this->addresses,
ef5584
				'subject'		=> $this->subject,
ef5584
				'msg'			=> $this->msg,
ef5584
				'headers'		=> $headers)
ef5584
			);
ef5584
		}
ef5584
ef5584
		return true;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Send jabber message out
ef5584
	*/
ef5584
	function msg_jabber()
ef5584
	{
ef5584
		global $config, $db, $user, $phpbb_root_path, $phpEx;
ef5584
ef5584
		if (empty($config['jab_enable']) || empty($config['jab_host']) || empty($config['jab_username']) || empty($config['jab_password']))
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		if (empty($this->addresses['im']))
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		$use_queue = false;
ef5584
		if ($config['jab_package_size'] && $this->use_queue)
ef5584
		{
ef5584
			if (empty($this->queue))
ef5584
			{
ef5584
				$this->queue = new queue();
ef5584
				$this->queue->init('jabber', $config['jab_package_size']);
ef5584
			}
ef5584
			$use_queue = true;
ef5584
		}
ef5584
ef5584
		$addresses = array();
ef5584
		foreach ($this->addresses['im'] as $type => $uid_ary)
ef5584
		{
ef5584
			$addresses[] = $uid_ary['uid'];
ef5584
		}
ef5584
		$addresses = array_unique($addresses);
ef5584
ef5584
		if (!$use_queue)
ef5584
		{
ef5584
			include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
ef5584
			$this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], $config['jab_password'], $config['jab_use_ssl']);
ef5584
ef5584
			if (!$this->jabber->connect())
ef5584
			{
ef5584
				$this->error('JABBER', $user->lang['ERR_JAB_CONNECT'] . '
' . $this->jabber->get_log());
ef5584
				return false;
ef5584
			}
ef5584
ef5584
			if (!$this->jabber->login())
ef5584
			{
ef5584
				$this->error('JABBER', $user->lang['ERR_JAB_AUTH'] . '
' . $this->jabber->get_log());
ef5584
				return false;
ef5584
			}
ef5584
ef5584
			foreach ($addresses as $address)
ef5584
			{
ef5584
				$this->jabber->send_message($address, $this->msg, $this->subject);
ef5584
			}
ef5584
ef5584
			$this->jabber->disconnect();
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			$this->queue->put('jabber', array(
ef5584
				'addresses'		=> $addresses,
ef5584
				'subject'		=> $this->subject,
ef5584
				'msg'			=> $this->msg)
ef5584
			);
ef5584
		}
ef5584
		unset($addresses);
ef5584
		return true;
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* handling email and jabber queue
ef5584
* @package phpBB3
ef5584
*/
ef5584
class queue
ef5584
{
ef5584
	var $data = array();
ef5584
	var $queue_data = array();
ef5584
	var $package_size = 0;
ef5584
	var $cache_file = '';
ef5584
ef5584
	/**
ef5584
	* constructor
ef5584
	*/
ef5584
	function queue()
ef5584
	{
ef5584
		global $phpEx, $phpbb_root_path;
ef5584
ef5584
		$this->data = array();
ef5584
		$this->cache_file = "{$phpbb_root_path}cache/queue.$phpEx";
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Init a queue object
ef5584
	*/
ef5584
	function init($object, $package_size)
ef5584
	{
ef5584
		$this->data[$object] = array();
ef5584
		$this->data[$object]['package_size'] = $package_size;
ef5584
		$this->data[$object]['data'] = array();
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Put object in queue
ef5584
	*/
ef5584
	function put($object, $scope)
ef5584
	{
ef5584
		$this->data[$object]['data'][] = $scope;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Process queue
ef5584
	* Using lock file
ef5584
	*/
ef5584
	function process()
ef5584
	{
ef5584
		global $db, $config, $phpEx, $phpbb_root_path, $user;
ef5584
ef5584
		set_config('last_queue_run', time(), true);
ef5584
ef5584
		// Delete stale lock file
ef5584
		if (file_exists($this->cache_file . '.lock') && !file_exists($this->cache_file))
ef5584
		{
ef5584
			@unlink($this->cache_file . '.lock');
ef5584
			return;
ef5584
		}
ef5584
ef5584
		if (!file_exists($this->cache_file) || (file_exists($this->cache_file . '.lock') && filemtime($this->cache_file) > time() - $config['queue_interval']))
ef5584
		{
ef5584
			return;
ef5584
		}
ef5584
ef5584
		$fp = @fopen($this->cache_file . '.lock', 'wb');
ef5584
		fclose($fp);
ef5584
		@chmod($this->cache_file . '.lock', 0777);
ef5584
ef5584
		include($this->cache_file);
ef5584
ef5584
		foreach ($this->queue_data as $object => $data_ary)
ef5584
		{
ef5584
			@set_time_limit(0);
ef5584
ef5584
			if (!isset($data_ary['package_size']))
ef5584
			{
ef5584
				$data_ary['package_size'] = 0;
ef5584
			}
ef5584
ef5584
			$package_size = $data_ary['package_size'];
ef5584
			$num_items = (!$package_size || sizeof($data_ary['data']) < $package_size) ? sizeof($data_ary['data']) : $package_size;
ef5584
ef5584
			// If the amount of emails to be sent is way more than package_size than we need to increase it to prevent backlogs...
ef5584
			if (sizeof($data_ary['data']) > $package_size * 2.5)
ef5584
			{
ef5584
				$num_items = sizeof($data_ary['data']);
ef5584
			}
ef5584
ef5584
			switch ($object)
ef5584
			{
ef5584
				case 'email':
ef5584
					// Delete the email queued objects if mailing is disabled
ef5584
					if (!$config['email_enable'])
ef5584
					{
ef5584
						unset($this->queue_data['email']);
ef5584
						continue 2;
ef5584
					}
ef5584
				break;
ef5584
ef5584
				case 'jabber':
ef5584
					if (!$config['jab_enable'])
ef5584
					{
ef5584
						unset($this->queue_data['jabber']);
ef5584
						continue 2;
ef5584
					}
ef5584
ef5584
					include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
ef5584
					$this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], $config['jab_password'], $config['jab_use_ssl']);
ef5584
ef5584
					if (!$this->jabber->connect())
ef5584
					{
ef5584
						messenger::error('JABBER', $user->lang['ERR_JAB_CONNECT']);
ef5584
						continue 2;
ef5584
					}
ef5584
ef5584
					if (!$this->jabber->login())
ef5584
					{
ef5584
						messenger::error('JABBER', $user->lang['ERR_JAB_AUTH']);
ef5584
						continue 2;
ef5584
					}
ef5584
ef5584
				break;
ef5584
ef5584
				default:
ef5584
					return;
ef5584
			}
ef5584
ef5584
			for ($i = 0; $i < $num_items; $i++)
ef5584
			{
ef5584
				// Make variables available...
ef5584
				extract(array_shift($this->queue_data[$object]['data']));
ef5584
ef5584
				switch ($object)
ef5584
				{
ef5584
					case 'email':
ef5584
						$err_msg = '';
ef5584
						$to = (!$to) ? 'undisclosed-recipients:;' : $to;
ef5584
ef5584
						if ($config['smtp_delivery'])
ef5584
						{
ef5584
							$result = smtpmail($addresses, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $err_msg, $headers);
ef5584
						}
ef5584
						else
ef5584
						{
ef5584
							ob_start();
ef5584
							$result = $config['email_function_name']($to, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $headers);
ef5584
							$err_msg = ob_get_clean();
ef5584
						}
ef5584
ef5584
						if (!$result)
ef5584
						{
ef5584
							@unlink($this->cache_file . '.lock');
ef5584
ef5584
							messenger::error('EMAIL', $err_msg);
ef5584
							continue 2;
ef5584
						}
ef5584
					break;
ef5584
ef5584
					case 'jabber':
ef5584
						foreach ($addresses as $address)
ef5584
						{
ef5584
							if ($this->jabber->send_message($address, $msg, $subject) === false)
ef5584
							{
ef5584
								messenger::error('JABBER', $this->jabber->get_log());
ef5584
								continue 3;
ef5584
							}
ef5584
						}
ef5584
					break;
ef5584
				}
ef5584
			}
ef5584
ef5584
			// No more data for this object? Unset it
ef5584
			if (!sizeof($this->queue_data[$object]['data']))
ef5584
			{
ef5584
				unset($this->queue_data[$object]);
ef5584
			}
ef5584
ef5584
			// Post-object processing
ef5584
			switch ($object)
ef5584
			{
ef5584
				case 'jabber':
ef5584
					// Hang about a couple of secs to ensure the messages are
ef5584
					// handled, then disconnect
ef5584
					$this->jabber->disconnect();
ef5584
				break;
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (!sizeof($this->queue_data))
ef5584
		{
ef5584
			@unlink($this->cache_file);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			if ($fp = @fopen($this->cache_file, 'wb'))
ef5584
			{
ef5584
				@flock($fp, LOCK_EX);
ef5584
				fwrite($fp, "queue_data = unserialize(" . var_export(serialize($this->queue_data), true) . ");\n\n?>");
ef5584
				@flock($fp, LOCK_UN);
ef5584
				fclose($fp);
ef5584
ef5584
				phpbb_chmod($this->cache_file, CHMOD_WRITE);
ef5584
			}
ef5584
		}
ef5584
ef5584
		@unlink($this->cache_file . '.lock');
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Save queue
ef5584
	*/
ef5584
	function save()
ef5584
	{
ef5584
		if (!sizeof($this->data))
ef5584
		{
ef5584
			return;
ef5584
		}
ef5584
ef5584
		if (file_exists($this->cache_file))
ef5584
		{
ef5584
			include($this->cache_file);
ef5584
ef5584
			foreach ($this->queue_data as $object => $data_ary)
ef5584
			{
ef5584
				if (isset($this->data[$object]) && sizeof($this->data[$object]))
ef5584
				{
ef5584
					$this->data[$object]['data'] = array_merge($data_ary['data'], $this->data[$object]['data']);
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$this->data[$object]['data'] = $data_ary['data'];
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		if ($fp = @fopen($this->cache_file, 'w'))
ef5584
		{
ef5584
			@flock($fp, LOCK_EX);
ef5584
			fwrite($fp, "queue_data = unserialize(" . var_export(serialize($this->data), true) . ");\n\n?>");
ef5584
			@flock($fp, LOCK_UN);
ef5584
			fclose($fp);
ef5584
ef5584
			phpbb_chmod($this->cache_file, CHMOD_WRITE);
ef5584
		}
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* Replacement or substitute for PHP's mail command
ef5584
*/
ef5584
function smtpmail($addresses, $subject, $message, &$err_msg, $headers = '')
ef5584
{
ef5584
	global $config, $user;
ef5584
ef5584
	// Fix any bare linefeeds in the message to make it RFC821 Compliant.
ef5584
	$message = preg_replace("#(?
ef5584
ef5584
	if ($headers != '')
ef5584
	{
ef5584
		if (is_array($headers))
ef5584
		{
ef5584
			$headers = (sizeof($headers) > 1) ? join("\n", $headers) : $headers[0];
ef5584
		}
ef5584
		$headers = chop($headers);
ef5584
ef5584
		// Make sure there are no bare linefeeds in the headers
ef5584
		$headers = preg_replace('#(?
ef5584
ef5584
		// Ok this is rather confusing all things considered,
ef5584
		// but we have to grab bcc and cc headers and treat them differently
ef5584
		// Something we really didn't take into consideration originally
ef5584
		$header_array = explode("\r\n", $headers);
ef5584
		$headers = '';
ef5584
ef5584
		foreach ($header_array as $header)
ef5584
		{
ef5584
			if (strpos(strtolower($header), 'cc:') === 0 || strpos(strtolower($header), 'bcc:') === 0)
ef5584
			{
ef5584
				$header = '';
ef5584
			}
ef5584
			$headers .= ($header != '') ? $header . "\r\n" : '';
ef5584
		}
ef5584
ef5584
		$headers = chop($headers);
ef5584
	}
ef5584
ef5584
	if (trim($subject) == '')
ef5584
	{
ef5584
		$err_msg = (isset($user->lang['NO_EMAIL_SUBJECT'])) ? $user->lang['NO_EMAIL_SUBJECT'] : 'No email subject specified';
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	if (trim($message) == '')
ef5584
	{
ef5584
		$err_msg = (isset($user->lang['NO_EMAIL_MESSAGE'])) ? $user->lang['NO_EMAIL_MESSAGE'] : 'Email message was blank';
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	$mail_rcpt = $mail_to = $mail_cc = array();
ef5584
ef5584
	// Build correct addresses for RCPT TO command and the client side display (TO, CC)
ef5584
	if (isset($addresses['to']) && sizeof($addresses['to']))
ef5584
	{
ef5584
		foreach ($addresses['to'] as $which_ary)
ef5584
		{
ef5584
			$mail_to[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
ef5584
			$mail_rcpt['to'][] = '<' . trim($which_ary['email']) . '>';
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (isset($addresses['bcc']) && sizeof($addresses['bcc']))
ef5584
	{
ef5584
		foreach ($addresses['bcc'] as $which_ary)
ef5584
		{
ef5584
			$mail_rcpt['bcc'][] = '<' . trim($which_ary['email']) . '>';
ef5584
		}
ef5584
	}
ef5584
ef5584
	if (isset($addresses['cc']) && sizeof($addresses['cc']))
ef5584
	{
ef5584
		foreach ($addresses['cc'] as $which_ary)
ef5584
		{
ef5584
			$mail_cc[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
ef5584
			$mail_rcpt['cc'][] = '<' . trim($which_ary['email']) . '>';
ef5584
		}
ef5584
	}
ef5584
ef5584
	$smtp = new smtp_class();
ef5584
ef5584
	$errno = 0;
ef5584
	$errstr = '';
ef5584
ef5584
	$smtp->add_backtrace('Connecting to ' . $config['smtp_host'] . ':' . $config['smtp_port']);
ef5584
ef5584
	// Ok we have error checked as much as we can to this point let's get on it already.
ef5584
	ob_start();
ef5584
	$smtp->socket = fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 20);
ef5584
	$error_contents = ob_get_clean();
ef5584
ef5584
	if (!$smtp->socket)
ef5584
	{
ef5584
		if ($errstr)
ef5584
		{
ef5584
			$errstr = utf8_convert_message($errstr);
ef5584
		}
ef5584
ef5584
		$err_msg = (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
ef5584
		$err_msg .= ($error_contents) ? '

' . htmlspecialchars($error_contents) : '';
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Wait for reply
ef5584
	if ($err_msg = $smtp->server_parse('220', __LINE__))
ef5584
	{
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Let me in. This function handles the complete authentication process
ef5584
	if ($err_msg = $smtp->log_into_server($config['smtp_host'], $config['smtp_username'], $config['smtp_password'], $config['smtp_auth_method']))
ef5584
	{
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// From this point onward most server response codes should be 250
ef5584
	// Specify who the mail is from....
ef5584
	$smtp->server_send('MAIL FROM:<' . $config['board_email'] . '>');
ef5584
	if ($err_msg = $smtp->server_parse('250', __LINE__))
ef5584
	{
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Specify each user to send to and build to header.
ef5584
	$to_header = implode(', ', $mail_to);
ef5584
	$cc_header = implode(', ', $mail_cc);
ef5584
ef5584
	// Now tell the MTA to send the Message to the following people... [TO, BCC, CC]
ef5584
	$rcpt = false;
ef5584
	foreach ($mail_rcpt as $type => $mail_to_addresses)
ef5584
	{
ef5584
		foreach ($mail_to_addresses as $mail_to_address)
ef5584
		{
ef5584
			// Add an additional bit of error checking to the To field.
ef5584
			if (preg_match('#[^ ]+\@[^ ]+#', $mail_to_address))
ef5584
			{
ef5584
				$smtp->server_send("RCPT TO:$mail_to_address");
ef5584
				if ($err_msg = $smtp->server_parse('250', __LINE__))
ef5584
				{
ef5584
					// We continue... if users are not resolved we do not care
ef5584
					if ($smtp->numeric_response_code != 550)
ef5584
					{
ef5584
						$smtp->close_session($err_msg);
ef5584
						return false;
ef5584
					}
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$rcpt = true;
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
	}
ef5584
ef5584
	// We try to send messages even if a few people do not seem to have valid email addresses, but if no one has, we have to exit here.
ef5584
	if (!$rcpt)
ef5584
	{
ef5584
		$user->session_begin();
ef5584
		$err_msg .= '

';
ef5584
		$err_msg .= (isset($user->lang['INVALID_EMAIL_LOG'])) ? sprintf($user->lang['INVALID_EMAIL_LOG'], htmlspecialchars($mail_to_address)) : '' . htmlspecialchars($mail_to_address) . ' possibly an invalid email address?';
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Ok now we tell the server we are ready to start sending data
ef5584
	$smtp->server_send('DATA');
ef5584
ef5584
	// This is the last response code we look for until the end of the message.
ef5584
	if ($err_msg = $smtp->server_parse('354', __LINE__))
ef5584
	{
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Send the Subject Line...
ef5584
	$smtp->server_send("Subject: $subject");
ef5584
ef5584
	// Now the To Header.
ef5584
	$to_header = ($to_header == '') ? 'undisclosed-recipients:;' : $to_header;
ef5584
	$smtp->server_send("To: $to_header");
ef5584
ef5584
	// Now the CC Header.
ef5584
	if ($cc_header != '')
ef5584
	{
ef5584
		$smtp->server_send("CC: $cc_header");
ef5584
	}
ef5584
ef5584
	// Now any custom headers....
ef5584
	$smtp->server_send("$headers\r\n");
ef5584
ef5584
	// Ok now we are ready for the message...
ef5584
	$smtp->server_send($message);
ef5584
ef5584
	// Ok the all the ingredients are mixed in let's cook this puppy...
ef5584
	$smtp->server_send('.');
ef5584
	if ($err_msg = $smtp->server_parse('250', __LINE__))
ef5584
	{
ef5584
		$smtp->close_session($err_msg);
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	// Now tell the server we are done and close the socket...
ef5584
	$smtp->server_send('QUIT');
ef5584
	$smtp->close_session($err_msg);
ef5584
ef5584
	return true;
ef5584
}
ef5584
ef5584
/**
ef5584
* SMTP Class
ef5584
* Auth Mechanisms originally taken from the AUTH Modules found within the PHP Extension and Application Repository (PEAR)
ef5584
* See docs/AUTHORS for more details
ef5584
* @package phpBB3
ef5584
*/
ef5584
class smtp_class
ef5584
{
ef5584
	var $server_response = '';
ef5584
	var $socket = 0;
ef5584
	var $responses = array();
ef5584
	var $commands = array();
ef5584
	var $numeric_response_code = 0;
ef5584
ef5584
	var $backtrace = false;
ef5584
	var $backtrace_log = array();
ef5584
ef5584
	function smtp_class()
ef5584
	{
ef5584
		// Always create a backtrace for admins to identify SMTP problems
ef5584
		$this->backtrace = true;
ef5584
		$this->backtrace_log = array();
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Add backtrace message for debugging
ef5584
	*/
ef5584
	function add_backtrace($message)
ef5584
	{
ef5584
		if ($this->backtrace)
ef5584
		{
ef5584
			$this->backtrace_log[] = utf8_htmlspecialchars($message);
ef5584
		}
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Send command to smtp server
ef5584
	*/
ef5584
	function server_send($command, $private_info = false)
ef5584
	{
ef5584
		fputs($this->socket, $command . "\r\n");
ef5584
ef5584
		(!$private_info) ? $this->add_backtrace("# $command") : $this->add_backtrace('# Omitting sensitive information');
ef5584
ef5584
		// We could put additional code here
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* We use the line to give the support people an indication at which command the error occurred
ef5584
	*/
ef5584
	function server_parse($response, $line)
ef5584
	{
ef5584
		global $user;
ef5584
ef5584
		$this->server_response = '';
ef5584
		$this->responses = array();
ef5584
		$this->numeric_response_code = 0;
ef5584
ef5584
		while (substr($this->server_response, 3, 1) != ' ')
ef5584
		{
ef5584
			if (!($this->server_response = fgets($this->socket, 256)))
ef5584
			{
ef5584
				return (isset($user->lang['NO_EMAIL_RESPONSE_CODE'])) ? $user->lang['NO_EMAIL_RESPONSE_CODE'] : 'Could not get mail server response codes';
ef5584
			}
ef5584
			$this->responses[] = substr(rtrim($this->server_response), 4);
ef5584
			$this->numeric_response_code = (int) substr($this->server_response, 0, 3);
ef5584
ef5584
			$this->add_backtrace("LINE: $line <- {$this->server_response}");
ef5584
		}
ef5584
ef5584
		if (!(substr($this->server_response, 0, 3) == $response))
ef5584
		{
ef5584
			$this->numeric_response_code = (int) substr($this->server_response, 0, 3);
ef5584
			return (isset($user->lang['EMAIL_SMTP_ERROR_RESPONSE'])) ? sprintf($user->lang['EMAIL_SMTP_ERROR_RESPONSE'], $line, $this->server_response) : "Ran into problems sending Mail at Line $line. Response: $this->server_response";
ef5584
		}
ef5584
ef5584
		return 0;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Close session
ef5584
	*/
ef5584
	function close_session(&$err_msg)
ef5584
	{
ef5584
		fclose($this->socket);
ef5584
ef5584
		if ($this->backtrace)
ef5584
		{
ef5584
			$message = '

Backtrace

' . implode('
', $this->backtrace_log) . '

';
ef5584
			$err_msg .= $message;
ef5584
		}
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Log into server and get possible auth codes if neccessary
ef5584
	*/
ef5584
	function log_into_server($hostname, $username, $password, $default_auth_method)
ef5584
	{
ef5584
		global $user;
ef5584
ef5584
		$err_msg = '';
ef5584
		$local_host = (function_exists('php_uname')) ? php_uname('n') : $user->host;
ef5584
ef5584
		// If we are authenticating through pop-before-smtp, we
ef5584
		// have to login ones before we get authenticated
ef5584
		// NOTE: on some configurations the time between an update of the auth database takes so
ef5584
		// long that the first email send does not work. This is not a biggie on a live board (only
ef5584
		// the install mail will most likely fail) - but on a dynamic ip connection this might produce
ef5584
		// severe problems and is not fixable!
ef5584
		if ($default_auth_method == 'POP-BEFORE-SMTP' && $username && $password)
ef5584
		{
ef5584
			global $config;
ef5584
ef5584
			$errno = 0;
ef5584
			$errstr = '';
ef5584
ef5584
			$this->server_send("QUIT");
ef5584
			fclose($this->socket);
ef5584
ef5584
			$result = $this->pop_before_smtp($hostname, $username, $password);
ef5584
			$username = $password = $default_auth_method = '';
ef5584
ef5584
			// We need to close the previous session, else the server is not
ef5584
			// able to get our ip for matching...
ef5584
			if (!$this->socket = @fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 10))
ef5584
			{
ef5584
				if ($errstr)
ef5584
				{
ef5584
					$errstr = utf8_convert_message($errstr);
ef5584
				}
ef5584
ef5584
				$err_msg = (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
ef5584
				return $err_msg;
ef5584
			}
ef5584
ef5584
			// Wait for reply
ef5584
			if ($err_msg = $this->server_parse('220', __LINE__))
ef5584
			{
ef5584
				$this->close_session($err_msg);
ef5584
				return $err_msg;
ef5584
			}
ef5584
		}
ef5584
ef5584
		// Try EHLO first
ef5584
		$this->server_send("EHLO {$local_host}");
ef5584
		if ($err_msg = $this->server_parse('250', __LINE__))
ef5584
		{
ef5584
			// a 503 response code means that we're already authenticated
ef5584
			if ($this->numeric_response_code == 503)
ef5584
			{
ef5584
				return false;
ef5584
			}
ef5584
ef5584
			// If EHLO fails, we try HELO
ef5584
			$this->server_send("HELO {$local_host}");
ef5584
			if ($err_msg = $this->server_parse('250', __LINE__))
ef5584
			{
ef5584
				return ($this->numeric_response_code == 503) ? false : $err_msg;
ef5584
			}
ef5584
		}
ef5584
ef5584
		foreach ($this->responses as $response)
ef5584
		{
ef5584
			$response = explode(' ', $response);
ef5584
			$response_code = $response[0];
ef5584
			unset($response[0]);
ef5584
			$this->commands[$response_code] = implode(' ', $response);
ef5584
		}
ef5584
ef5584
		// If we are not authenticated yet, something might be wrong if no username and passwd passed
ef5584
		if (!$username || !$password)
ef5584
		{
ef5584
			return false;
ef5584
		}
ef5584
ef5584
		if (!isset($this->commands['AUTH']))
ef5584
		{
ef5584
			return (isset($user->lang['SMTP_NO_AUTH_SUPPORT'])) ? $user->lang['SMTP_NO_AUTH_SUPPORT'] : 'SMTP server does not support authentication';
ef5584
		}
ef5584
ef5584
		// Get best authentication method
ef5584
		$available_methods = explode(' ', $this->commands['AUTH']);
ef5584
ef5584
		// Define the auth ordering if the default auth method was not found
ef5584
		$auth_methods = array('PLAIN', 'LOGIN', 'CRAM-MD5', 'DIGEST-MD5');
ef5584
		$method = '';
ef5584
ef5584
		if (in_array($default_auth_method, $available_methods))
ef5584
		{
ef5584
			$method = $default_auth_method;
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			foreach ($auth_methods as $_method)
ef5584
			{
ef5584
				if (in_array($_method, $available_methods))
ef5584
				{
ef5584
					$method = $_method;
ef5584
					break;
ef5584
				}
ef5584
			}
ef5584
		}
ef5584
ef5584
		if (!$method)
ef5584
		{
ef5584
			return (isset($user->lang['NO_SUPPORTED_AUTH_METHODS'])) ? $user->lang['NO_SUPPORTED_AUTH_METHODS'] : 'No supported authentication methods';
ef5584
		}
ef5584
ef5584
		$method = strtolower(str_replace('-', '_', $method));
ef5584
		return $this->$method($username, $password);
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Pop before smtp authentication
ef5584
	*/
ef5584
	function pop_before_smtp($hostname, $username, $password)
ef5584
	{
ef5584
		global $user;
ef5584
ef5584
		if (!$this->socket = @fsockopen($hostname, 110, $errno, $errstr, 10))
ef5584
		{
ef5584
			if ($errstr)
ef5584
			{
ef5584
				$errstr = utf8_convert_message($errstr);
ef5584
			}
ef5584
ef5584
			return (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
ef5584
		}
ef5584
ef5584
		$this->server_send("USER $username", true);
ef5584
		if ($err_msg = $this->server_parse('+OK', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		$this->server_send("PASS $password", true);
ef5584
		if ($err_msg = $this->server_parse('+OK', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		$this->server_send('QUIT');
ef5584
		fclose($this->socket);
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Plain authentication method
ef5584
	*/
ef5584
	function plain($username, $password)
ef5584
	{
ef5584
		$this->server_send('AUTH PLAIN');
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return ($this->numeric_response_code == 503) ? false : $err_msg;
ef5584
		}
ef5584
ef5584
		$base64_method_plain = base64_encode("\0" . $username . "\0" . $password);
ef5584
		$this->server_send($base64_method_plain, true);
ef5584
		if ($err_msg = $this->server_parse('235', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* Login authentication method
ef5584
	*/
ef5584
	function login($username, $password)
ef5584
	{
ef5584
		$this->server_send('AUTH LOGIN');
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return ($this->numeric_response_code == 503) ? false : $err_msg;
ef5584
		}
ef5584
ef5584
		$this->server_send(base64_encode($username), true);
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		$this->server_send(base64_encode($password), true);
ef5584
		if ($err_msg = $this->server_parse('235', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* cram_md5 authentication method
ef5584
	*/
ef5584
	function cram_md5($username, $password)
ef5584
	{
ef5584
		$this->server_send('AUTH CRAM-MD5');
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return ($this->numeric_response_code == 503) ? false : $err_msg;
ef5584
		}
ef5584
ef5584
		$md5_challenge = base64_decode($this->responses[0]);
ef5584
		$password = (strlen($password) > 64) ? pack('H32', md5($password)) : ((strlen($password) < 64) ? str_pad($password, 64, chr(0)) : $password);
ef5584
		$md5_digest = md5((substr($password, 0, 64) ^ str_repeat(chr(0x5C), 64)) . (pack('H32', md5((substr($password, 0, 64) ^ str_repeat(chr(0x36), 64)) . $md5_challenge))));
ef5584
ef5584
		$base64_method_cram_md5 = base64_encode($username . ' ' . $md5_digest);
ef5584
ef5584
		$this->server_send($base64_method_cram_md5, true);
ef5584
		if ($err_msg = $this->server_parse('235', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		return false;
ef5584
	}
ef5584
ef5584
	/**
ef5584
	* digest_md5 authentication method
ef5584
	* A real pain in the ***
ef5584
	*/
ef5584
	function digest_md5($username, $password)
ef5584
	{
ef5584
		global $config, $user;
ef5584
ef5584
		$this->server_send('AUTH DIGEST-MD5');
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return ($this->numeric_response_code == 503) ? false : $err_msg;
ef5584
		}
ef5584
ef5584
		$md5_challenge = base64_decode($this->responses[0]);
ef5584
ef5584
		// Parse the md5 challenge - from AUTH_SASL (PEAR)
ef5584
		$tokens = array();
ef5584
		while (preg_match('/^([a-z-]+)=("[^"]+(?
ef5584
		{
ef5584
			// Ignore these as per rfc2831
ef5584
			if ($matches[1] == 'opaque' || $matches[1] == 'domain')
ef5584
			{
ef5584
				$md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
ef5584
				continue;
ef5584
			}
ef5584
ef5584
			// Allowed multiple "realm" and "auth-param"
ef5584
			if (!empty($tokens[$matches[1]]) && ($matches[1] == 'realm' || $matches[1] == 'auth-param'))
ef5584
			{
ef5584
				if (is_array($tokens[$matches[1]]))
ef5584
				{
ef5584
					$tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
ef5584
				}
ef5584
				else
ef5584
				{
ef5584
					$tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
ef5584
				}
ef5584
			}
ef5584
			else if (!empty($tokens[$matches[1]])) // Any other multiple instance = failure
ef5584
			{
ef5584
				$tokens = array();
ef5584
				break;
ef5584
			}
ef5584
			else
ef5584
			{
ef5584
				$tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
ef5584
			}
ef5584
ef5584
			// Remove the just parsed directive from the challenge
ef5584
			$md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
ef5584
		}
ef5584
ef5584
		// Realm
ef5584
		if (empty($tokens['realm']))
ef5584
		{
ef5584
			$tokens['realm'] = (function_exists('php_uname')) ? php_uname('n') : $user->host;
ef5584
		}
ef5584
ef5584
		// Maxbuf
ef5584
		if (empty($tokens['maxbuf']))
ef5584
		{
ef5584
			$tokens['maxbuf'] = 65536;
ef5584
		}
ef5584
ef5584
		// Required: nonce, algorithm
ef5584
		if (empty($tokens['nonce']) || empty($tokens['algorithm']))
ef5584
		{
ef5584
			$tokens = array();
ef5584
		}
ef5584
		$md5_challenge = $tokens;
ef5584
ef5584
		if (!empty($md5_challenge))
ef5584
		{
ef5584
			$str = '';
ef5584
			for ($i = 0; $i < 32; $i++)
ef5584
			{
ef5584
				$str .= chr(mt_rand(0, 255));
ef5584
			}
ef5584
			$cnonce = base64_encode($str);
ef5584
ef5584
			$digest_uri = 'smtp/' . $config['smtp_host'];
ef5584
ef5584
			$auth_1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $username, $md5_challenge['realm'], $password))), $md5_challenge['nonce'], $cnonce);
ef5584
			$auth_2 = 'AUTHENTICATE:' . $digest_uri;
ef5584
			$response_value = md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($auth_1), $md5_challenge['nonce'], $cnonce, md5($auth_2)));
ef5584
ef5584
			$input_string = sprintf('username="%s",realm="%s",nonce="%s",cnonce="%s",nc="00000001",qop=auth,digest-uri="%s",response=%s,%d', $username, $md5_challenge['realm'], $md5_challenge['nonce'], $cnonce, $digest_uri, $response_value, $md5_challenge['maxbuf']);
ef5584
		}
ef5584
		else
ef5584
		{
ef5584
			return (isset($user->lang['INVALID_DIGEST_CHALLENGE'])) ? $user->lang['INVALID_DIGEST_CHALLENGE'] : 'Invalid digest challenge';
ef5584
		}
ef5584
ef5584
		$base64_method_digest_md5 = base64_encode($input_string);
ef5584
		$this->server_send($base64_method_digest_md5, true);
ef5584
		if ($err_msg = $this->server_parse('334', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		$this->server_send(' ');
ef5584
		if ($err_msg = $this->server_parse('235', __LINE__))
ef5584
		{
ef5584
			return $err_msg;
ef5584
		}
ef5584
ef5584
		return false;
ef5584
	}
ef5584
}
ef5584
ef5584
/**
ef5584
* Encodes the given string for proper display in UTF-8.
ef5584
*
ef5584
* This version is using base64 encoded data. The downside of this
ef5584
* is if the mail client does not understand this encoding the user
ef5584
* is basically doomed with an unreadable subject.
ef5584
*
ef5584
* Please note that this version fully supports RFC 2045 section 6.8.
ef5584
*/
ef5584
function mail_encode($str)
ef5584
{
ef5584
	// define start delimimter, end delimiter and spacer
ef5584
	$start = "=?UTF-8?B?";
ef5584
	$end = "?=";
ef5584
	$spacer = $end . ' ' . $start;
ef5584
	$split_length = 64;
ef5584
ef5584
	$encoded_str = base64_encode($str);
ef5584
ef5584
	// If encoded string meets the limits, we just return with the correct data.
ef5584
	if (strlen($encoded_str) <= $split_length)
ef5584
	{
ef5584
		return $start . $encoded_str . $end;
ef5584
	}
ef5584
ef5584
	// If there is only ASCII data, we just return what we want, correctly splitting the lines.
ef5584
	if (strlen($str) === utf8_strlen($str))
ef5584
	{
ef5584
		return $start . implode($spacer, str_split($encoded_str, $split_length)) . $end;
ef5584
	}
ef5584
ef5584
	// UTF-8 data, compose encoded lines
ef5584
	$array = utf8_str_split($str);
ef5584
	$str = '';
ef5584
ef5584
	while (sizeof($array))
ef5584
	{
ef5584
		$text = '';
ef5584
ef5584
		while (sizeof($array) && intval((strlen($text . $array[0]) + 2) / 3) << 2 <= $split_length)
ef5584
		{
ef5584
			$text .= array_shift($array);
ef5584
		}
ef5584
ef5584
		$str .= $start . base64_encode($text) . $end . ' ';
ef5584
	}
ef5584
ef5584
	return substr($str, 0, -1);
ef5584
}
ef5584
ef5584
?>