Update phpMailer to 5.2.26

Signed-off-by: Michael Kaufmann (d00p) <d00p@froxlor.org>
This commit is contained in:
Michael Kaufmann (d00p)
2018-01-26 17:18:12 +01:00
parent 3fb92259a8
commit fcd0dddfd5
2 changed files with 590 additions and 544 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,88 +1,88 @@
<?php <?php
/** /**
* PHPMailer RFC821 SMTP email transport class. * PHPMailer RFC821 SMTP email transport class.
* PHP Version 5 * PHP Version 5
* @package PHPMailer * @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk> * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com> * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net> * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder) * @author Brent R. Matzelle (original founder)
* @copyright 2014 Marcus Bointon * @copyright 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost * @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT * @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. * FITNESS FOR A PARTICULAR PURPOSE.
*/ */
/** /**
* PHPMailer RFC821 SMTP email transport class. * PHPMailer RFC821 SMTP email transport class.
* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server. * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
* @package PHPMailer * @package PHPMailer
* @author Chris Ryan * @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk> * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/ */
class SMTP class SMTP
{ {
/** /**
* The PHPMailer SMTP version number. * The PHPMailer SMTP version number.
* @var string * @var string
*/ */
const VERSION = '5.2.21'; const VERSION = '5.2.26';
/** /**
* SMTP line break constant. * SMTP line break constant.
* @var string * @var string
*/ */
const CRLF = "\r\n"; const CRLF = "\r\n";
/** /**
* The SMTP port to use if one is not specified. * The SMTP port to use if one is not specified.
* @var integer * @var integer
*/ */
const DEFAULT_SMTP_PORT = 25; const DEFAULT_SMTP_PORT = 25;
/** /**
* The maximum line length allowed by RFC 2822 section 2.1.1 * The maximum line length allowed by RFC 2822 section 2.1.1
* @var integer * @var integer
*/ */
const MAX_LINE_LENGTH = 998; const MAX_LINE_LENGTH = 998;
/** /**
* Debug level for no output * Debug level for no output
*/ */
const DEBUG_OFF = 0; const DEBUG_OFF = 0;
/** /**
* Debug level to show client -> server messages * Debug level to show client -> server messages
*/ */
const DEBUG_CLIENT = 1; const DEBUG_CLIENT = 1;
/** /**
* Debug level to show client -> server and server -> client messages * Debug level to show client -> server and server -> client messages
*/ */
const DEBUG_SERVER = 2; const DEBUG_SERVER = 2;
/** /**
* Debug level to show connection status, client -> server and server -> client messages * Debug level to show connection status, client -> server and server -> client messages
*/ */
const DEBUG_CONNECTION = 3; const DEBUG_CONNECTION = 3;
/** /**
* Debug level to show all messages * Debug level to show all messages
*/ */
const DEBUG_LOWLEVEL = 4; const DEBUG_LOWLEVEL = 4;
/** /**
* The PHPMailer SMTP Version number. * The PHPMailer SMTP Version number.
* @var string * @var string
* @deprecated Use the `VERSION` constant instead * @deprecated Use the `VERSION` constant instead
* @see SMTP::VERSION * @see SMTP::VERSION
*/ */
public $Version = '5.2.21'; public $Version = '5.2.26';
/** /**
* SMTP server port number. * SMTP server port number.
* @var integer * @var integer
@@ -90,7 +90,7 @@ class SMTP
* @see SMTP::DEFAULT_SMTP_PORT * @see SMTP::DEFAULT_SMTP_PORT
*/ */
public $SMTP_PORT = 25; public $SMTP_PORT = 25;
/** /**
* SMTP reply line ending. * SMTP reply line ending.
* @var string * @var string
@@ -98,7 +98,7 @@ class SMTP
* @see SMTP::CRLF * @see SMTP::CRLF
*/ */
public $CRLF = "\r\n"; public $CRLF = "\r\n";
/** /**
* Debug output level. * Debug output level.
* Options: * Options:
@@ -110,7 +110,7 @@ class SMTP
* @var integer * @var integer
*/ */
public $do_debug = self::DEBUG_OFF; public $do_debug = self::DEBUG_OFF;
/** /**
* How to handle debug output. * How to handle debug output.
* Options: * Options:
@@ -125,7 +125,7 @@ class SMTP
* @var string|callable * @var string|callable
*/ */
public $Debugoutput = 'echo'; public $Debugoutput = 'echo';
/** /**
* Whether to use VERP. * Whether to use VERP.
* @link http://en.wikipedia.org/wiki/Variable_envelope_return_path * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
@@ -133,7 +133,7 @@ class SMTP
* @var boolean * @var boolean
*/ */
public $do_verp = false; public $do_verp = false;
/** /**
* The timeout value for connection, in seconds. * The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
@@ -142,31 +142,36 @@ class SMTP
* @var integer * @var integer
*/ */
public $Timeout = 300; public $Timeout = 300;
/** /**
* How long to wait for commands to complete, in seconds. * How long to wait for commands to complete, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2 * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @var integer * @var integer
*/ */
public $Timelimit = 300; public $Timelimit = 300;
/** /**
* @var array patterns to extract smtp transaction id from smtp reply * @var array Patterns to extract an SMTP transaction id from reply to a DATA command.
* Only first capture group will be use, use non-capturing group to deal with it * The first capture group in each regex will be used as the ID.
* Extend this class to override this property to fulfil your needs.
*/ */
protected $smtp_transaction_id_patterns = array( protected $smtp_transaction_id_patterns = array(
'exim' => '/[0-9]{3} OK id=(.*)/', 'exim' => '/[0-9]{3} OK id=(.*)/',
'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/', 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/' 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
); );
/**
* @var string The last transaction ID issued in response to a DATA command,
* if one was detected
*/
protected $last_smtp_transaction_id;
/** /**
* The socket for the server connection. * The socket for the server connection.
* @var resource * @var resource
*/ */
protected $smtp_conn; protected $smtp_conn;
/** /**
* Error information, if any, for the last SMTP command. * Error information, if any, for the last SMTP command.
* @var array * @var array
@@ -177,14 +182,14 @@ class SMTP
'smtp_code' => '', 'smtp_code' => '',
'smtp_code_ex' => '' 'smtp_code_ex' => ''
); );
/** /**
* The reply the server sent to us for HELO. * The reply the server sent to us for HELO.
* If null, no HELO string has yet been received. * If null, no HELO string has yet been received.
* @var string|null * @var string|null
*/ */
protected $helo_rply = null; protected $helo_rply = null;
/** /**
* The set of SMTP extensions sent in reply to EHLO command. * The set of SMTP extensions sent in reply to EHLO command.
* Indexes of the array are extension names. * Indexes of the array are extension names.
@@ -195,13 +200,13 @@ class SMTP
* @var array|null * @var array|null
*/ */
protected $server_caps = null; protected $server_caps = null;
/** /**
* The most recent reply received from the server. * The most recent reply received from the server.
* @var string * @var string
*/ */
protected $last_reply = ''; protected $last_reply = '';
/** /**
* Output debugging info via a user-selected method. * Output debugging info via a user-selected method.
* @see SMTP::$Debugoutput * @see SMTP::$Debugoutput
@@ -227,12 +232,11 @@ class SMTP
break; break;
case 'html': case 'html':
//Cleans up output a bit for a better looking, HTML-safe output //Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities( echo gmdate('Y-m-d H:i:s') . ' ' . htmlentities(
preg_replace('/[\r\n]+/', '', $str), preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES, ENT_QUOTES,
'UTF-8' 'UTF-8'
) ) . "<br>\n";
. "<br>\n";
break; break;
case 'echo': case 'echo':
default: default:
@@ -242,10 +246,10 @@ class SMTP
"\n", "\n",
"\n \t ", "\n \t ",
trim($str) trim($str)
)."\n"; ) . "\n";
} }
} }
/** /**
* Connect to an SMTP server. * Connect to an SMTP server.
* @param string $host SMTP server IP or host name * @param string $host SMTP server IP or host name
@@ -276,7 +280,8 @@ class SMTP
} }
// Connect to the SMTP server // Connect to the SMTP server
$this->edebug( $this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), "Connection: opening to $host:$port, timeout=$timeout, options=" .
var_export($options, true),
self::DEBUG_CONNECTION self::DEBUG_CONNECTION
); );
$errno = 0; $errno = 0;
@@ -339,7 +344,7 @@ class SMTP
$this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER); $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
return true; return true;
} }
/** /**
* Initiate a TLS (encrypted) session. * Initiate a TLS (encrypted) session.
* @access public * @access public
@@ -350,28 +355,28 @@ class SMTP
if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
return false; return false;
} }
//Allow the best TLS version(s) we can //Allow the best TLS version(s) we can
$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT; $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
//PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
//so add them back in manually if we can //so add them back in manually if we can
if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) { if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
$crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT; $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
} }
// Begin encrypted connection // Begin encrypted connection
if (!stream_socket_enable_crypto( set_error_handler(array($this, 'errorHandler'));
$crypto_ok = stream_socket_enable_crypto(
$this->smtp_conn, $this->smtp_conn,
true, true,
$crypto_method $crypto_method
)) { );
return false; restore_error_handler();
} return $crypto_ok;
return true;
} }
/** /**
* Perform SMTP authentication. * Perform SMTP authentication.
* Must be run after hello(). * Must be run after hello().
@@ -396,23 +401,22 @@ class SMTP
$this->setError('Authentication is not allowed before HELO/EHLO'); $this->setError('Authentication is not allowed before HELO/EHLO');
return false; return false;
} }
if (array_key_exists('EHLO', $this->server_caps)) { if (array_key_exists('EHLO', $this->server_caps)) {
// SMTP extensions are available. Let's try to find a proper authentication method // SMTP extensions are available; try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) { if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage'); $this->setError('Authentication is not allowed at this stage');
// 'at this stage' means that auth may be allowed after the stage changes // 'at this stage' means that auth may be allowed after the stage changes
// e.g. after STARTTLS // e.g. after STARTTLS
return false; return false;
} }
self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL); self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
self::edebug( self::edebug(
'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
self::DEBUG_LOWLEVEL self::DEBUG_LOWLEVEL
); );
if (empty($authtype)) { if (empty($authtype)) {
foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) { foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN', 'NTLM', 'XOAUTH2') as $method) {
if (in_array($method, $this->server_caps['AUTH'])) { if (in_array($method, $this->server_caps['AUTH'])) {
@@ -424,9 +428,9 @@ class SMTP
$this->setError('No supported authentication methods found'); $this->setError('No supported authentication methods found');
return false; return false;
} }
self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL); self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
} }
if (!in_array($authtype, $this->server_caps['AUTH'])) { if (!in_array($authtype, $this->server_caps['AUTH'])) {
$this->setError("The requested authentication method \"$authtype\" is not supported by the server"); $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
return false; return false;
@@ -469,7 +473,7 @@ class SMTP
return false; return false;
} }
$oauth = $OAuth->getOauth64(); $oauth = $OAuth->getOauth64();
// Start authentication // Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false; return false;
@@ -499,7 +503,7 @@ class SMTP
} }
//msg1 //msg1
$msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1 $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand( if (!$this->sendCommand(
'AUTH NTLM', 'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1), 'AUTH NTLM ' . base64_encode($msg1),
@@ -532,10 +536,10 @@ class SMTP
} }
// Get the challenge // Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4)); $challenge = base64_decode(substr($this->last_reply, 4));
// Build the response // Build the response
$response = $username . ' ' . $this->hmac($challenge, $password); $response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials // send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235); return $this->sendCommand('Username', base64_encode($response), 235);
default: default:
@@ -544,13 +548,13 @@ class SMTP
} }
return true; return true;
} }
/** /**
* Calculate an MD5 HMAC hash. * Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key) * Works like hash_hmac('md5', $data, $key)
* in case that function is not available * in case that function is not available
* @param string $data The data to hash * @param string $data The data to hash
* @param string $key The key to hash with * @param string $key The key to hash with
* @access protected * @access protected
* @return string * @return string
*/ */
@@ -559,15 +563,15 @@ class SMTP
if (function_exists('hash_hmac')) { if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key); return hash_hmac('md5', $data, $key);
} }
// The following borrowed from // The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225 // http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php. // RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC. // Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC // Eliminates the need to install mhash to compute a HMAC
// by Lance Rushing // by Lance Rushing
$bytelen = 64; // byte length for md5 $bytelen = 64; // byte length for md5
if (strlen($key) > $bytelen) { if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key)); $key = pack('H*', md5($key));
@@ -577,10 +581,10 @@ class SMTP
$opad = str_pad('', $bytelen, chr(0x5c)); $opad = str_pad('', $bytelen, chr(0x5c));
$k_ipad = $key ^ $ipad; $k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad; $k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data))); return md5($k_opad . pack('H*', md5($k_ipad . $data)));
} }
/** /**
* Check connection state. * Check connection state.
* @access public * @access public
@@ -603,7 +607,7 @@ class SMTP
} }
return false; return false;
} }
/** /**
* Close the socket and clean up the state of the class. * Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT. * Don't use this function without first trying to use QUIT.
@@ -623,7 +627,7 @@ class SMTP
$this->edebug('Connection: closed', self::DEBUG_CONNECTION); $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
} }
} }
/** /**
* Send an SMTP DATA command. * Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server, * Issues a data command and sends the msg_data to the server,
@@ -642,7 +646,7 @@ class SMTP
if (!$this->sendCommand('DATA', 'DATA', 354)) { if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false; return false;
} }
/* The server is ready to accept data! /* The server is ready to accept data!
* According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF) * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
@@ -650,21 +654,21 @@ class SMTP
* We will also look for lines that start with a '.' and prepend an additional '.'. * We will also look for lines that start with a '.' and prepend an additional '.'.
* NOTE: this does not count towards line-length limit. * NOTE: this does not count towards line-length limit.
*/ */
// Normalize line breaks before exploding // Normalize line breaks before exploding
$lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data)); $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header and we will * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
* process all lines before a blank line as headers. * process all lines before a blank line as headers.
*/ */
$field = substr($lines[0], 0, strpos($lines[0], ':')); $field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false; $in_headers = false;
if (!empty($field) && strpos($field, ' ') === false) { if (!empty($field) && strpos($field, ' ') === false) {
$in_headers = true; $in_headers = true;
} }
foreach ($lines as $line) { foreach ($lines as $line) {
$lines_out = array(); $lines_out = array();
if ($in_headers and $line == '') { if ($in_headers and $line == '') {
@@ -694,7 +698,7 @@ class SMTP
} }
} }
$lines_out[] = $line; $lines_out[] = $line;
//Send the lines to the server //Send the lines to the server
foreach ($lines_out as $line_out) { foreach ($lines_out as $line_out) {
//RFC2821 section 4.5.2 //RFC2821 section 4.5.2
@@ -704,17 +708,18 @@ class SMTP
$this->client_send($line_out . self::CRLF); $this->client_send($line_out . self::CRLF);
} }
} }
//Message data has been sent, complete the command //Message data has been sent, complete the command
//Increase timelimit for end of DATA command //Increase timelimit for end of DATA command
$savetimelimit = $this->Timelimit; $savetimelimit = $this->Timelimit;
$this->Timelimit = $this->Timelimit * 2; $this->Timelimit = $this->Timelimit * 2;
$result = $this->sendCommand('DATA END', '.', 250); $result = $this->sendCommand('DATA END', '.', 250);
$this->recordLastTransactionID();
//Restore timelimit //Restore timelimit
$this->Timelimit = $savetimelimit; $this->Timelimit = $savetimelimit;
return $result; return $result;
} }
/** /**
* Send an SMTP HELO or EHLO command. * Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server. * Used to identify the sending server to the receiving server.
@@ -730,7 +735,7 @@ class SMTP
//Try extended hello first (RFC 2821) //Try extended hello first (RFC 2821)
return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host)); return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
} }
/** /**
* Send an SMTP HELO or EHLO command. * Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello() * Low-level implementation used by hello()
@@ -751,7 +756,7 @@ class SMTP
} }
return $noerror; return $noerror;
} }
/** /**
* Parse a reply to HELO/EHLO command to discover server extensions. * Parse a reply to HELO/EHLO command to discover server extensions.
* In case of HELO, the only parameter that can be discovered is a server name. * In case of HELO, the only parameter that can be discovered is a server name.
@@ -762,7 +767,7 @@ class SMTP
{ {
$this->server_caps = array(); $this->server_caps = array();
$lines = explode("\n", $this->helo_rply); $lines = explode("\n", $this->helo_rply);
foreach ($lines as $n => $s) { foreach ($lines as $n => $s) {
//First 4 chars contain response code followed by - or space //First 4 chars contain response code followed by - or space
$s = trim(substr($s, 4)); $s = trim(substr($s, 4));
@@ -793,7 +798,7 @@ class SMTP
} }
} }
} }
/** /**
* Send an SMTP MAIL command. * Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in * Starts a mail transaction from the email address specified in
@@ -814,7 +819,7 @@ class SMTP
250 250
); );
} }
/** /**
* Send an SMTP QUIT command. * Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true. * Closes the socket if there is no error or the $close_on_error argument is true.
@@ -833,7 +838,7 @@ class SMTP
} }
return $noerror; return $noerror;
} }
/** /**
* Send an SMTP RCPT command. * Send an SMTP RCPT command.
* Sets the TO argument to $toaddr. * Sets the TO argument to $toaddr.
@@ -851,7 +856,7 @@ class SMTP
array(250, 251) array(250, 251)
); );
} }
/** /**
* Send an SMTP RSET command. * Send an SMTP RSET command.
* Abort any transaction that is currently in progress. * Abort any transaction that is currently in progress.
@@ -863,7 +868,7 @@ class SMTP
{ {
return $this->sendCommand('RSET', 'RSET', 250); return $this->sendCommand('RSET', 'RSET', 250);
} }
/** /**
* Send a command to an SMTP server and check its return code. * Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server * @param string $command The command name - not sent to the server
@@ -884,7 +889,7 @@ class SMTP
return false; return false;
} }
$this->client_send($commandstring . self::CRLF); $this->client_send($commandstring . self::CRLF);
$this->last_reply = $this->get_lines(); $this->last_reply = $this->get_lines();
// Fetch SMTP code and possible error code explanation // Fetch SMTP code and possible error code explanation
$matches = array(); $matches = array();
@@ -893,7 +898,8 @@ class SMTP
$code_ex = (count($matches) > 2 ? $matches[2] : null); $code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line // Cut off error code from each response line
$detail = preg_replace( $detail = preg_replace(
"/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", "/{$code}[ -]" .
($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
'', '',
$this->last_reply $this->last_reply
); );
@@ -903,9 +909,9 @@ class SMTP
$code_ex = null; $code_ex = null;
$detail = substr($this->last_reply, 4); $detail = substr($this->last_reply, 4);
} }
$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER); $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
if (!in_array($code, (array)$expect)) { if (!in_array($code, (array)$expect)) {
$this->setError( $this->setError(
"$command command failed", "$command command failed",
@@ -919,11 +925,11 @@ class SMTP
); );
return false; return false;
} }
$this->setError(''); $this->setError('');
return true; return true;
} }
/** /**
* Send an SMTP SAML command. * Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from. * Starts a mail transaction from the email address specified in $from.
@@ -941,7 +947,7 @@ class SMTP
{ {
return $this->sendCommand('SAML', "SAML FROM:$from", 250); return $this->sendCommand('SAML', "SAML FROM:$from", 250);
} }
/** /**
* Send an SMTP VRFY command. * Send an SMTP VRFY command.
* @param string $name The name to verify * @param string $name The name to verify
@@ -952,7 +958,7 @@ class SMTP
{ {
return $this->sendCommand('VRFY', "VRFY $name", array(250, 251)); return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
} }
/** /**
* Send an SMTP NOOP command. * Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything * Used to keep keep-alives alive, doesn't actually do anything
@@ -963,7 +969,7 @@ class SMTP
{ {
return $this->sendCommand('NOOP', 'NOOP', 250); return $this->sendCommand('NOOP', 'NOOP', 250);
} }
/** /**
* Send an SMTP TURN command. * Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support. * This is an optional command for SMTP that this class does not support.
@@ -979,7 +985,7 @@ class SMTP
$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT); $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
return false; return false;
} }
/** /**
* Send raw data to the server. * Send raw data to the server.
* @param string $data The data to send * @param string $data The data to send
@@ -989,9 +995,12 @@ class SMTP
public function client_send($data) public function client_send($data)
{ {
$this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT); $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
return fwrite($this->smtp_conn, $data); set_error_handler(array($this, 'errorHandler'));
$result = fwrite($this->smtp_conn, $data);
restore_error_handler();
return $result;
} }
/** /**
* Get the latest error. * Get the latest error.
* @access public * @access public
@@ -1001,7 +1010,7 @@ class SMTP
{ {
return $this->error; return $this->error;
} }
/** /**
* Get SMTP extensions available on the server * Get SMTP extensions available on the server
* @access public * @access public
@@ -1011,7 +1020,7 @@ class SMTP
{ {
return $this->server_caps; return $this->server_caps;
} }
/** /**
* A multipurpose method * A multipurpose method
* The method works in three ways, dependent on argument value and current state * The method works in three ways, dependent on argument value and current state
@@ -1037,7 +1046,7 @@ class SMTP
$this->setError('No HELO/EHLO was sent'); $this->setError('No HELO/EHLO was sent');
return null; return null;
} }
// the tight logic knot ;) // the tight logic knot ;)
if (!array_key_exists($name, $this->server_caps)) { if (!array_key_exists($name, $this->server_caps)) {
if ($name == 'HELO') { if ($name == 'HELO') {
@@ -1049,10 +1058,10 @@ class SMTP
$this->setError('HELO handshake was used. Client knows nothing about server extensions'); $this->setError('HELO handshake was used. Client knows nothing about server extensions');
return null; return null;
} }
return $this->server_caps[$name]; return $this->server_caps[$name];
} }
/** /**
* Get the last reply from the server. * Get the last reply from the server.
* @access public * @access public
@@ -1062,7 +1071,7 @@ class SMTP
{ {
return $this->last_reply; return $this->last_reply;
} }
/** /**
* Read the SMTP server's response. * Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation. * Either before eof or socket timeout occurs on the operation.
@@ -1089,8 +1098,10 @@ class SMTP
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL); $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL); $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
$data .= $str; $data .= $str;
// If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
if ((isset($str[3]) and $str[3] == ' ')) { // or 4th character is a space, we are done reading, break the loop,
// string array access is a micro-optimisation over strlen
if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
break; break;
} }
// Timed-out? Log and break // Timed-out? Log and break
@@ -1105,7 +1116,7 @@ class SMTP
// Now check if reads took too long // Now check if reads took too long
if ($endtime and time() > $endtime) { if ($endtime and time() > $endtime) {
$this->edebug( $this->edebug(
'SMTP -> get_lines(): timelimit reached ('. 'SMTP -> get_lines(): timelimit reached (' .
$this->Timelimit . ' sec)', $this->Timelimit . ' sec)',
self::DEBUG_LOWLEVEL self::DEBUG_LOWLEVEL
); );
@@ -1114,7 +1125,7 @@ class SMTP
} }
return $data; return $data;
} }
/** /**
* Enable or disable VERP address generation. * Enable or disable VERP address generation.
* @param boolean $enabled * @param boolean $enabled
@@ -1123,7 +1134,7 @@ class SMTP
{ {
$this->do_verp = $enabled; $this->do_verp = $enabled;
} }
/** /**
* Get VERP address generation mode. * Get VERP address generation mode.
* @return boolean * @return boolean
@@ -1132,7 +1143,7 @@ class SMTP
{ {
return $this->do_verp; return $this->do_verp;
} }
/** /**
* Set error messages and codes. * Set error messages and codes.
* @param string $message The error message * @param string $message The error message
@@ -1149,7 +1160,7 @@ class SMTP
'smtp_code_ex' => $smtp_code_ex 'smtp_code_ex' => $smtp_code_ex
); );
} }
/** /**
* Set debug output method. * Set debug output method.
* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
@@ -1158,7 +1169,7 @@ class SMTP
{ {
$this->Debugoutput = $method; $this->Debugoutput = $method;
} }
/** /**
* Get debug output method. * Get debug output method.
* @return string * @return string
@@ -1167,7 +1178,7 @@ class SMTP
{ {
return $this->Debugoutput; return $this->Debugoutput;
} }
/** /**
* Set debug output level. * Set debug output level.
* @param integer $level * @param integer $level
@@ -1176,7 +1187,7 @@ class SMTP
{ {
$this->do_debug = $level; $this->do_debug = $level;
} }
/** /**
* Get debug output level. * Get debug output level.
* @return integer * @return integer
@@ -1185,7 +1196,7 @@ class SMTP
{ {
return $this->do_debug; return $this->do_debug;
} }
/** /**
* Set SMTP timeout. * Set SMTP timeout.
* @param integer $timeout * @param integer $timeout
@@ -1194,7 +1205,7 @@ class SMTP
{ {
$this->Timeout = $timeout; $this->Timeout = $timeout;
} }
/** /**
* Get SMTP timeout. * Get SMTP timeout.
* @return integer * @return integer
@@ -1203,47 +1214,63 @@ class SMTP
{ {
return $this->Timeout; return $this->Timeout;
} }
/** /**
* Reports an error number and string. * Reports an error number and string.
* @param integer $errno The error number returned by PHP. * @param integer $errno The error number returned by PHP.
* @param string $errmsg The error message returned by PHP. * @param string $errmsg The error message returned by PHP.
* @param string $errfile The file the error occurred in
* @param integer $errline The line number the error occurred on
*/ */
protected function errorHandler($errno, $errmsg) protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
{ {
$notice = 'Connection: Failed to connect to server.'; $notice = 'Connection failed.';
$this->setError( $this->setError(
$notice, $notice,
$errno, $errno,
$errmsg $errmsg
); );
$this->edebug( $this->edebug(
$notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg, $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]",
self::DEBUG_CONNECTION self::DEBUG_CONNECTION
); );
} }
/** /**
* Will return the ID of the last smtp transaction based on a list of patterns provided * Extract and return the ID of the last SMTP transaction based on
* in SMTP::$smtp_transaction_id_patterns. * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
* Relies on the host providing the ID in response to a DATA command.
* If no reply has been received yet, it will return null. * If no reply has been received yet, it will return null.
* If no pattern has been matched, it will return false. * If no pattern was matched, it will return false.
* @return bool|null|string * @return bool|null|string
*/ */
protected function recordLastTransactionID()
{
$reply = $this->getLastReply();
if (empty($reply)) {
$this->last_smtp_transaction_id = null;
} else {
$this->last_smtp_transaction_id = false;
foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
$this->last_smtp_transaction_id = $matches[1];
}
}
}
return $this->last_smtp_transaction_id;
}
/**
* Get the queue/transaction ID of the last SMTP transaction
* If no reply has been received yet, it will return null.
* If no pattern was matched, it will return false.
* @return bool|null|string
* @see recordLastTransactionID()
*/
public function getLastTransactionID() public function getLastTransactionID()
{ {
$reply = $this->getLastReply(); return $this->last_smtp_transaction_id;
if (empty($reply)) {
return null;
}
foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
return $matches[1];
}
}
return false;
} }
} }