PageRenderTime 28ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/wp-includes/class-smtp.php

https://gitlab.com/VTTE/sitios-vtte
PHP | 1213 lines | 617 code | 91 blank | 505 comment | 78 complexity | 654534b6c48e0219cd5a45898cad329e MD5 | raw file
  1. <?php
  2. /**
  3. * PHPMailer RFC821 SMTP email transport class.
  4. * PHP Version 5
  5. * @package PHPMailer
  6. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  7. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  8. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  9. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10. * @author Brent R. Matzelle (original founder)
  11. * @copyright 2014 Marcus Bointon
  12. * @copyright 2010 - 2012 Jim Jagielski
  13. * @copyright 2004 - 2009 Andy Prevost
  14. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15. * @note This program is distributed in the hope that it will be useful - WITHOUT
  16. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17. * FITNESS FOR A PARTICULAR PURPOSE.
  18. */
  19. /**
  20. * PHPMailer RFC821 SMTP email transport class.
  21. * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
  22. * @package PHPMailer
  23. * @author Chris Ryan
  24. * @author Marcus Bointon <phpmailer@synchromedia.co.uk>
  25. */
  26. class SMTP
  27. {
  28. /**
  29. * The PHPMailer SMTP version number.
  30. * @var string
  31. */
  32. const VERSION = '5.2.27';
  33. /**
  34. * SMTP line break constant.
  35. * @var string
  36. */
  37. const CRLF = "\r\n";
  38. /**
  39. * The SMTP port to use if one is not specified.
  40. * @var integer
  41. */
  42. const DEFAULT_SMTP_PORT = 25;
  43. /**
  44. * The maximum line length allowed by RFC 2822 section 2.1.1
  45. * @var integer
  46. */
  47. const MAX_LINE_LENGTH = 998;
  48. /**
  49. * Debug level for no output
  50. */
  51. const DEBUG_OFF = 0;
  52. /**
  53. * Debug level to show client -> server messages
  54. */
  55. const DEBUG_CLIENT = 1;
  56. /**
  57. * Debug level to show client -> server and server -> client messages
  58. */
  59. const DEBUG_SERVER = 2;
  60. /**
  61. * Debug level to show connection status, client -> server and server -> client messages
  62. */
  63. const DEBUG_CONNECTION = 3;
  64. /**
  65. * Debug level to show all messages
  66. */
  67. const DEBUG_LOWLEVEL = 4;
  68. /**
  69. * The PHPMailer SMTP Version number.
  70. * @var string
  71. * @deprecated Use the `VERSION` constant instead
  72. * @see SMTP::VERSION
  73. */
  74. public $Version = '5.2.27';
  75. /**
  76. * SMTP server port number.
  77. * @var integer
  78. * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
  79. * @see SMTP::DEFAULT_SMTP_PORT
  80. */
  81. public $SMTP_PORT = 25;
  82. /**
  83. * SMTP reply line ending.
  84. * @var string
  85. * @deprecated Use the `CRLF` constant instead
  86. * @see SMTP::CRLF
  87. */
  88. public $CRLF = "\r\n";
  89. /**
  90. * Debug output level.
  91. * Options:
  92. * * self::DEBUG_OFF (`0`) No debug output, default
  93. * * self::DEBUG_CLIENT (`1`) Client commands
  94. * * self::DEBUG_SERVER (`2`) Client commands and server responses
  95. * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
  96. * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
  97. * @var integer
  98. */
  99. public $do_debug = self::DEBUG_OFF;
  100. /**
  101. * How to handle debug output.
  102. * Options:
  103. * * `echo` Output plain-text as-is, appropriate for CLI
  104. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  105. * * `error_log` Output to error log as configured in php.ini
  106. *
  107. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  108. * <code>
  109. * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  110. * </code>
  111. * @var string|callable
  112. */
  113. public $Debugoutput = 'echo';
  114. /**
  115. * Whether to use VERP.
  116. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  117. * @link http://www.postfix.org/VERP_README.html Info on VERP
  118. * @var boolean
  119. */
  120. public $do_verp = false;
  121. /**
  122. * The timeout value for connection, in seconds.
  123. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  124. * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
  125. * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
  126. * @var integer
  127. */
  128. public $Timeout = 300;
  129. /**
  130. * How long to wait for commands to complete, in seconds.
  131. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  132. * @var integer
  133. */
  134. public $Timelimit = 300;
  135. /**
  136. * @var array Patterns to extract an SMTP transaction id from reply to a DATA command.
  137. * The first capture group in each regex will be used as the ID.
  138. */
  139. protected $smtp_transaction_id_patterns = array(
  140. 'exim' => '/[0-9]{3} OK id=(.*)/',
  141. 'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
  142. 'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
  143. );
  144. /**
  145. * @var string The last transaction ID issued in response to a DATA command,
  146. * if one was detected
  147. */
  148. protected $last_smtp_transaction_id;
  149. /**
  150. * The socket for the server connection.
  151. * @var resource
  152. */
  153. protected $smtp_conn;
  154. /**
  155. * Error information, if any, for the last SMTP command.
  156. * @var array
  157. */
  158. protected $error = array(
  159. 'error' => '',
  160. 'detail' => '',
  161. 'smtp_code' => '',
  162. 'smtp_code_ex' => ''
  163. );
  164. /**
  165. * The reply the server sent to us for HELO.
  166. * If null, no HELO string has yet been received.
  167. * @var string|null
  168. */
  169. protected $helo_rply = null;
  170. /**
  171. * The set of SMTP extensions sent in reply to EHLO command.
  172. * Indexes of the array are extension names.
  173. * Value at index 'HELO' or 'EHLO' (according to command that was sent)
  174. * represents the server name. In case of HELO it is the only element of the array.
  175. * Other values can be boolean TRUE or an array containing extension options.
  176. * If null, no HELO/EHLO string has yet been received.
  177. * @var array|null
  178. */
  179. protected $server_caps = null;
  180. /**
  181. * The most recent reply received from the server.
  182. * @var string
  183. */
  184. protected $last_reply = '';
  185. /**
  186. * Output debugging info via a user-selected method.
  187. * @see SMTP::$Debugoutput
  188. * @see SMTP::$do_debug
  189. * @param string $str Debug string to output
  190. * @param integer $level The debug level of this message; see DEBUG_* constants
  191. * @return void
  192. */
  193. protected function edebug($str, $level = 0)
  194. {
  195. if ($level > $this->do_debug) {
  196. return;
  197. }
  198. //Avoid clash with built-in function names
  199. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  200. call_user_func($this->Debugoutput, $str, $level);
  201. return;
  202. }
  203. switch ($this->Debugoutput) {
  204. case 'error_log':
  205. //Don't output, just log
  206. error_log($str);
  207. break;
  208. case 'html':
  209. //Cleans up output a bit for a better looking, HTML-safe output
  210. echo gmdate('Y-m-d H:i:s') . ' ' . htmlentities(
  211. preg_replace('/[\r\n]+/', '', $str),
  212. ENT_QUOTES,
  213. 'UTF-8'
  214. ) . "<br>\n";
  215. break;
  216. case 'echo':
  217. default:
  218. //Normalize line breaks
  219. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  220. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  221. "\n",
  222. "\n \t ",
  223. trim($str)
  224. ) . "\n";
  225. }
  226. }
  227. /**
  228. * Connect to an SMTP server.
  229. * @param string $host SMTP server IP or host name
  230. * @param integer $port The port number to connect to
  231. * @param integer $timeout How long to wait for the connection to open
  232. * @param array $options An array of options for stream_context_create()
  233. * @access public
  234. * @return boolean
  235. */
  236. public function connect($host, $port = null, $timeout = 30, $options = array())
  237. {
  238. static $streamok;
  239. //This is enabled by default since 5.0.0 but some providers disable it
  240. //Check this once and cache the result
  241. if (is_null($streamok)) {
  242. $streamok = function_exists('stream_socket_client');
  243. }
  244. // Clear errors to avoid confusion
  245. $this->setError('');
  246. // Make sure we are __not__ connected
  247. if ($this->connected()) {
  248. // Already connected, generate error
  249. $this->setError('Already connected to a server');
  250. return false;
  251. }
  252. if (empty($port)) {
  253. $port = self::DEFAULT_SMTP_PORT;
  254. }
  255. // Connect to the SMTP server
  256. $this->edebug(
  257. "Connection: opening to $host:$port, timeout=$timeout, options=" .
  258. var_export($options, true),
  259. self::DEBUG_CONNECTION
  260. );
  261. $errno = 0;
  262. $errstr = '';
  263. if ($streamok) {
  264. $socket_context = stream_context_create($options);
  265. set_error_handler(array($this, 'errorHandler'));
  266. $this->smtp_conn = stream_socket_client(
  267. $host . ":" . $port,
  268. $errno,
  269. $errstr,
  270. $timeout,
  271. STREAM_CLIENT_CONNECT,
  272. $socket_context
  273. );
  274. restore_error_handler();
  275. } else {
  276. //Fall back to fsockopen which should work in more places, but is missing some features
  277. $this->edebug(
  278. "Connection: stream_socket_client not available, falling back to fsockopen",
  279. self::DEBUG_CONNECTION
  280. );
  281. set_error_handler(array($this, 'errorHandler'));
  282. $this->smtp_conn = fsockopen(
  283. $host,
  284. $port,
  285. $errno,
  286. $errstr,
  287. $timeout
  288. );
  289. restore_error_handler();
  290. }
  291. // Verify we connected properly
  292. if (!is_resource($this->smtp_conn)) {
  293. $this->setError(
  294. 'Failed to connect to server',
  295. $errno,
  296. $errstr
  297. );
  298. $this->edebug(
  299. 'SMTP ERROR: ' . $this->error['error']
  300. . ": $errstr ($errno)",
  301. self::DEBUG_CLIENT
  302. );
  303. return false;
  304. }
  305. $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  306. // SMTP server can take longer to respond, give longer timeout for first read
  307. // Windows does not have support for this timeout function
  308. if (substr(PHP_OS, 0, 3) != 'WIN') {
  309. $max = ini_get('max_execution_time');
  310. // Don't bother if unlimited
  311. if ($max != 0 && $timeout > $max) {
  312. @set_time_limit($timeout);
  313. }
  314. stream_set_timeout($this->smtp_conn, $timeout, 0);
  315. }
  316. // Get any announcement
  317. $announce = $this->get_lines();
  318. $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
  319. return true;
  320. }
  321. /**
  322. * Initiate a TLS (encrypted) session.
  323. * @access public
  324. * @return boolean
  325. */
  326. public function startTLS()
  327. {
  328. if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  329. return false;
  330. }
  331. //Allow the best TLS version(s) we can
  332. $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
  333. //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
  334. //so add them back in manually if we can
  335. if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
  336. $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
  337. $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
  338. }
  339. // Begin encrypted connection
  340. set_error_handler(array($this, 'errorHandler'));
  341. $crypto_ok = stream_socket_enable_crypto(
  342. $this->smtp_conn,
  343. true,
  344. $crypto_method
  345. );
  346. restore_error_handler();
  347. return $crypto_ok;
  348. }
  349. /**
  350. * Perform SMTP authentication.
  351. * Must be run after hello().
  352. * @see hello()
  353. * @param string $username The user name
  354. * @param string $password The password
  355. * @param string $authtype The auth type (PLAIN, LOGIN, CRAM-MD5)
  356. * @param string $realm The auth realm for NTLM
  357. * @param string $workstation The auth workstation for NTLM
  358. * @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
  359. * @return bool True if successfully authenticated.* @access public
  360. */
  361. public function authenticate(
  362. $username,
  363. $password,
  364. $authtype = null,
  365. $realm = '',
  366. $workstation = '',
  367. $OAuth = null
  368. ) {
  369. if (!$this->server_caps) {
  370. $this->setError('Authentication is not allowed before HELO/EHLO');
  371. return false;
  372. }
  373. if (array_key_exists('EHLO', $this->server_caps)) {
  374. // SMTP extensions are available; try to find a proper authentication method
  375. if (!array_key_exists('AUTH', $this->server_caps)) {
  376. $this->setError('Authentication is not allowed at this stage');
  377. // 'at this stage' means that auth may be allowed after the stage changes
  378. // e.g. after STARTTLS
  379. return false;
  380. }
  381. self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
  382. self::edebug(
  383. 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
  384. self::DEBUG_LOWLEVEL
  385. );
  386. if (empty($authtype)) {
  387. foreach (array('CRAM-MD5', 'LOGIN', 'PLAIN') as $method) {
  388. if (in_array($method, $this->server_caps['AUTH'])) {
  389. $authtype = $method;
  390. break;
  391. }
  392. }
  393. if (empty($authtype)) {
  394. $this->setError('No supported authentication methods found');
  395. return false;
  396. }
  397. self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
  398. }
  399. if (!in_array($authtype, $this->server_caps['AUTH'])) {
  400. $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  401. return false;
  402. }
  403. } elseif (empty($authtype)) {
  404. $authtype = 'LOGIN';
  405. }
  406. switch ($authtype) {
  407. case 'PLAIN':
  408. // Start authentication
  409. if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  410. return false;
  411. }
  412. // Send encoded username and password
  413. if (!$this->sendCommand(
  414. 'User & Password',
  415. base64_encode("\0" . $username . "\0" . $password),
  416. 235
  417. )
  418. ) {
  419. return false;
  420. }
  421. break;
  422. case 'LOGIN':
  423. // Start authentication
  424. if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  425. return false;
  426. }
  427. if (!$this->sendCommand("Username", base64_encode($username), 334)) {
  428. return false;
  429. }
  430. if (!$this->sendCommand("Password", base64_encode($password), 235)) {
  431. return false;
  432. }
  433. break;
  434. case 'CRAM-MD5':
  435. // Start authentication
  436. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  437. return false;
  438. }
  439. // Get the challenge
  440. $challenge = base64_decode(substr($this->last_reply, 4));
  441. // Build the response
  442. $response = $username . ' ' . $this->hmac($challenge, $password);
  443. // send encoded credentials
  444. return $this->sendCommand('Username', base64_encode($response), 235);
  445. default:
  446. $this->setError("Authentication method \"$authtype\" is not supported");
  447. return false;
  448. }
  449. return true;
  450. }
  451. /**
  452. * Calculate an MD5 HMAC hash.
  453. * Works like hash_hmac('md5', $data, $key)
  454. * in case that function is not available
  455. * @param string $data The data to hash
  456. * @param string $key The key to hash with
  457. * @access protected
  458. * @return string
  459. */
  460. protected function hmac($data, $key)
  461. {
  462. if (function_exists('hash_hmac')) {
  463. return hash_hmac('md5', $data, $key);
  464. }
  465. // The following borrowed from
  466. // http://php.net/manual/en/function.mhash.php#27225
  467. // RFC 2104 HMAC implementation for php.
  468. // Creates an md5 HMAC.
  469. // Eliminates the need to install mhash to compute a HMAC
  470. // by Lance Rushing
  471. $bytelen = 64; // byte length for md5
  472. if (strlen($key) > $bytelen) {
  473. $key = pack('H*', md5($key));
  474. }
  475. $key = str_pad($key, $bytelen, chr(0x00));
  476. $ipad = str_pad('', $bytelen, chr(0x36));
  477. $opad = str_pad('', $bytelen, chr(0x5c));
  478. $k_ipad = $key ^ $ipad;
  479. $k_opad = $key ^ $opad;
  480. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  481. }
  482. /**
  483. * Check connection state.
  484. * @access public
  485. * @return boolean True if connected.
  486. */
  487. public function connected()
  488. {
  489. if (is_resource($this->smtp_conn)) {
  490. $sock_status = stream_get_meta_data($this->smtp_conn);
  491. if ($sock_status['eof']) {
  492. // The socket is valid but we are not connected
  493. $this->edebug(
  494. 'SMTP NOTICE: EOF caught while checking if connected',
  495. self::DEBUG_CLIENT
  496. );
  497. $this->close();
  498. return false;
  499. }
  500. return true; // everything looks good
  501. }
  502. return false;
  503. }
  504. /**
  505. * Close the socket and clean up the state of the class.
  506. * Don't use this function without first trying to use QUIT.
  507. * @see quit()
  508. * @access public
  509. * @return void
  510. */
  511. public function close()
  512. {
  513. $this->setError('');
  514. $this->server_caps = null;
  515. $this->helo_rply = null;
  516. if (is_resource($this->smtp_conn)) {
  517. // close the connection and cleanup
  518. fclose($this->smtp_conn);
  519. $this->smtp_conn = null; //Makes for cleaner serialization
  520. $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  521. }
  522. }
  523. /**
  524. * Send an SMTP DATA command.
  525. * Issues a data command and sends the msg_data to the server,
  526. * finializing the mail transaction. $msg_data is the message
  527. * that is to be send with the headers. Each header needs to be
  528. * on a single line followed by a <CRLF> with the message headers
  529. * and the message body being separated by and additional <CRLF>.
  530. * Implements rfc 821: DATA <CRLF>
  531. * @param string $msg_data Message data to send
  532. * @access public
  533. * @return boolean
  534. */
  535. public function data($msg_data)
  536. {
  537. //This will use the standard timelimit
  538. if (!$this->sendCommand('DATA', 'DATA', 354)) {
  539. return false;
  540. }
  541. /* The server is ready to accept data!
  542. * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  543. * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  544. * smaller lines to fit within the limit.
  545. * We will also look for lines that start with a '.' and prepend an additional '.'.
  546. * NOTE: this does not count towards line-length limit.
  547. */
  548. // Normalize line breaks before exploding
  549. $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  550. /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  551. * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  552. * process all lines before a blank line as headers.
  553. */
  554. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  555. $in_headers = false;
  556. if (!empty($field) && strpos($field, ' ') === false) {
  557. $in_headers = true;
  558. }
  559. foreach ($lines as $line) {
  560. $lines_out = array();
  561. if ($in_headers and $line == '') {
  562. $in_headers = false;
  563. }
  564. //Break this line up into several smaller lines if it's too long
  565. //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
  566. while (isset($line[self::MAX_LINE_LENGTH])) {
  567. //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  568. //so as to avoid breaking in the middle of a word
  569. $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  570. //Deliberately matches both false and 0
  571. if (!$pos) {
  572. //No nice break found, add a hard break
  573. $pos = self::MAX_LINE_LENGTH - 1;
  574. $lines_out[] = substr($line, 0, $pos);
  575. $line = substr($line, $pos);
  576. } else {
  577. //Break at the found point
  578. $lines_out[] = substr($line, 0, $pos);
  579. //Move along by the amount we dealt with
  580. $line = substr($line, $pos + 1);
  581. }
  582. //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
  583. if ($in_headers) {
  584. $line = "\t" . $line;
  585. }
  586. }
  587. $lines_out[] = $line;
  588. //Send the lines to the server
  589. foreach ($lines_out as $line_out) {
  590. //RFC2821 section 4.5.2
  591. if (!empty($line_out) and $line_out[0] == '.') {
  592. $line_out = '.' . $line_out;
  593. }
  594. $this->client_send($line_out . self::CRLF);
  595. }
  596. }
  597. //Message data has been sent, complete the command
  598. //Increase timelimit for end of DATA command
  599. $savetimelimit = $this->Timelimit;
  600. $this->Timelimit = $this->Timelimit * 2;
  601. $result = $this->sendCommand('DATA END', '.', 250);
  602. $this->recordLastTransactionID();
  603. //Restore timelimit
  604. $this->Timelimit = $savetimelimit;
  605. return $result;
  606. }
  607. /**
  608. * Send an SMTP HELO or EHLO command.
  609. * Used to identify the sending server to the receiving server.
  610. * This makes sure that client and server are in a known state.
  611. * Implements RFC 821: HELO <SP> <domain> <CRLF>
  612. * and RFC 2821 EHLO.
  613. * @param string $host The host name or IP to connect to
  614. * @access public
  615. * @return boolean
  616. */
  617. public function hello($host = '')
  618. {
  619. //Try extended hello first (RFC 2821)
  620. return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  621. }
  622. /**
  623. * Send an SMTP HELO or EHLO command.
  624. * Low-level implementation used by hello()
  625. * @see hello()
  626. * @param string $hello The HELO string
  627. * @param string $host The hostname to say we are
  628. * @access protected
  629. * @return boolean
  630. */
  631. protected function sendHello($hello, $host)
  632. {
  633. $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  634. $this->helo_rply = $this->last_reply;
  635. if ($noerror) {
  636. $this->parseHelloFields($hello);
  637. } else {
  638. $this->server_caps = null;
  639. }
  640. return $noerror;
  641. }
  642. /**
  643. * Parse a reply to HELO/EHLO command to discover server extensions.
  644. * In case of HELO, the only parameter that can be discovered is a server name.
  645. * @access protected
  646. * @param string $type - 'HELO' or 'EHLO'
  647. */
  648. protected function parseHelloFields($type)
  649. {
  650. $this->server_caps = array();
  651. $lines = explode("\n", $this->helo_rply);
  652. foreach ($lines as $n => $s) {
  653. //First 4 chars contain response code followed by - or space
  654. $s = trim(substr($s, 4));
  655. if (empty($s)) {
  656. continue;
  657. }
  658. $fields = explode(' ', $s);
  659. if (!empty($fields)) {
  660. if (!$n) {
  661. $name = $type;
  662. $fields = $fields[0];
  663. } else {
  664. $name = array_shift($fields);
  665. switch ($name) {
  666. case 'SIZE':
  667. $fields = ($fields ? $fields[0] : 0);
  668. break;
  669. case 'AUTH':
  670. if (!is_array($fields)) {
  671. $fields = array();
  672. }
  673. break;
  674. default:
  675. $fields = true;
  676. }
  677. }
  678. $this->server_caps[$name] = $fields;
  679. }
  680. }
  681. }
  682. /**
  683. * Send an SMTP MAIL command.
  684. * Starts a mail transaction from the email address specified in
  685. * $from. Returns true if successful or false otherwise. If True
  686. * the mail transaction is started and then one or more recipient
  687. * commands may be called followed by a data command.
  688. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  689. * @param string $from Source address of this message
  690. * @access public
  691. * @return boolean
  692. */
  693. public function mail($from)
  694. {
  695. $useVerp = ($this->do_verp ? ' XVERP' : '');
  696. return $this->sendCommand(
  697. 'MAIL FROM',
  698. 'MAIL FROM:<' . $from . '>' . $useVerp,
  699. 250
  700. );
  701. }
  702. /**
  703. * Send an SMTP QUIT command.
  704. * Closes the socket if there is no error or the $close_on_error argument is true.
  705. * Implements from rfc 821: QUIT <CRLF>
  706. * @param boolean $close_on_error Should the connection close if an error occurs?
  707. * @access public
  708. * @return boolean
  709. */
  710. public function quit($close_on_error = true)
  711. {
  712. $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  713. $err = $this->error; //Save any error
  714. if ($noerror or $close_on_error) {
  715. $this->close();
  716. $this->error = $err; //Restore any error from the quit command
  717. }
  718. return $noerror;
  719. }
  720. /**
  721. * Send an SMTP RCPT command.
  722. * Sets the TO argument to $toaddr.
  723. * Returns true if the recipient was accepted false if it was rejected.
  724. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  725. * @param string $address The address the message is being sent to
  726. * @access public
  727. * @return boolean
  728. */
  729. public function recipient($address)
  730. {
  731. return $this->sendCommand(
  732. 'RCPT TO',
  733. 'RCPT TO:<' . $address . '>',
  734. array(250, 251)
  735. );
  736. }
  737. /**
  738. * Send an SMTP RSET command.
  739. * Abort any transaction that is currently in progress.
  740. * Implements rfc 821: RSET <CRLF>
  741. * @access public
  742. * @return boolean True on success.
  743. */
  744. public function reset()
  745. {
  746. return $this->sendCommand('RSET', 'RSET', 250);
  747. }
  748. /**
  749. * Send a command to an SMTP server and check its return code.
  750. * @param string $command The command name - not sent to the server
  751. * @param string $commandstring The actual command to send
  752. * @param integer|array $expect One or more expected integer success codes
  753. * @access protected
  754. * @return boolean True on success.
  755. */
  756. protected function sendCommand($command, $commandstring, $expect)
  757. {
  758. if (!$this->connected()) {
  759. $this->setError("Called $command without being connected");
  760. return false;
  761. }
  762. //Reject line breaks in all commands
  763. if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
  764. $this->setError("Command '$command' contained line breaks");
  765. return false;
  766. }
  767. $this->client_send($commandstring . self::CRLF);
  768. $this->last_reply = $this->get_lines();
  769. // Fetch SMTP code and possible error code explanation
  770. $matches = array();
  771. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  772. $code = $matches[1];
  773. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  774. // Cut off error code from each response line
  775. $detail = preg_replace(
  776. "/{$code}[ -]" .
  777. ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
  778. '',
  779. $this->last_reply
  780. );
  781. } else {
  782. // Fall back to simple parsing if regex fails
  783. $code = substr($this->last_reply, 0, 3);
  784. $code_ex = null;
  785. $detail = substr($this->last_reply, 4);
  786. }
  787. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  788. if (!in_array($code, (array)$expect)) {
  789. $this->setError(
  790. "$command command failed",
  791. $detail,
  792. $code,
  793. $code_ex
  794. );
  795. $this->edebug(
  796. 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  797. self::DEBUG_CLIENT
  798. );
  799. return false;
  800. }
  801. $this->setError('');
  802. return true;
  803. }
  804. /**
  805. * Send an SMTP SAML command.
  806. * Starts a mail transaction from the email address specified in $from.
  807. * Returns true if successful or false otherwise. If True
  808. * the mail transaction is started and then one or more recipient
  809. * commands may be called followed by a data command. This command
  810. * will send the message to the users terminal if they are logged
  811. * in and send them an email.
  812. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  813. * @param string $from The address the message is from
  814. * @access public
  815. * @return boolean
  816. */
  817. public function sendAndMail($from)
  818. {
  819. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  820. }
  821. /**
  822. * Send an SMTP VRFY command.
  823. * @param string $name The name to verify
  824. * @access public
  825. * @return boolean
  826. */
  827. public function verify($name)
  828. {
  829. return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  830. }
  831. /**
  832. * Send an SMTP NOOP command.
  833. * Used to keep keep-alives alive, doesn't actually do anything
  834. * @access public
  835. * @return boolean
  836. */
  837. public function noop()
  838. {
  839. return $this->sendCommand('NOOP', 'NOOP', 250);
  840. }
  841. /**
  842. * Send an SMTP TURN command.
  843. * This is an optional command for SMTP that this class does not support.
  844. * This method is here to make the RFC821 Definition complete for this class
  845. * and _may_ be implemented in future
  846. * Implements from rfc 821: TURN <CRLF>
  847. * @access public
  848. * @return boolean
  849. */
  850. public function turn()
  851. {
  852. $this->setError('The SMTP TURN command is not implemented');
  853. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  854. return false;
  855. }
  856. /**
  857. * Send raw data to the server.
  858. * @param string $data The data to send
  859. * @access public
  860. * @return integer|boolean The number of bytes sent to the server or false on error
  861. */
  862. public function client_send($data)
  863. {
  864. $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  865. set_error_handler(array($this, 'errorHandler'));
  866. $result = fwrite($this->smtp_conn, $data);
  867. restore_error_handler();
  868. return $result;
  869. }
  870. /**
  871. * Get the latest error.
  872. * @access public
  873. * @return array
  874. */
  875. public function getError()
  876. {
  877. return $this->error;
  878. }
  879. /**
  880. * Get SMTP extensions available on the server
  881. * @access public
  882. * @return array|null
  883. */
  884. public function getServerExtList()
  885. {
  886. return $this->server_caps;
  887. }
  888. /**
  889. * A multipurpose method
  890. * The method works in three ways, dependent on argument value and current state
  891. * 1. HELO/EHLO was not sent - returns null and set up $this->error
  892. * 2. HELO was sent
  893. * $name = 'HELO': returns server name
  894. * $name = 'EHLO': returns boolean false
  895. * $name = any string: returns null and set up $this->error
  896. * 3. EHLO was sent
  897. * $name = 'HELO'|'EHLO': returns server name
  898. * $name = any string: if extension $name exists, returns boolean True
  899. * or its options. Otherwise returns boolean False
  900. * In other words, one can use this method to detect 3 conditions:
  901. * - null returned: handshake was not or we don't know about ext (refer to $this->error)
  902. * - false returned: the requested feature exactly not exists
  903. * - positive value returned: the requested feature exists
  904. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  905. * @return mixed
  906. */
  907. public function getServerExt($name)
  908. {
  909. if (!$this->server_caps) {
  910. $this->setError('No HELO/EHLO was sent');
  911. return null;
  912. }
  913. // the tight logic knot ;)
  914. if (!array_key_exists($name, $this->server_caps)) {
  915. if ($name == 'HELO') {
  916. return $this->server_caps['EHLO'];
  917. }
  918. if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  919. return false;
  920. }
  921. $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  922. return null;
  923. }
  924. return $this->server_caps[$name];
  925. }
  926. /**
  927. * Get the last reply from the server.
  928. * @access public
  929. * @return string
  930. */
  931. public function getLastReply()
  932. {
  933. return $this->last_reply;
  934. }
  935. /**
  936. * Read the SMTP server's response.
  937. * Either before eof or socket timeout occurs on the operation.
  938. * With SMTP we can tell if we have more lines to read if the
  939. * 4th character is '-' symbol. If it is a space then we don't
  940. * need to read anything else.
  941. * @access protected
  942. * @return string
  943. */
  944. protected function get_lines()
  945. {
  946. // If the connection is bad, give up straight away
  947. if (!is_resource($this->smtp_conn)) {
  948. return '';
  949. }
  950. $data = '';
  951. $endtime = 0;
  952. stream_set_timeout($this->smtp_conn, $this->Timeout);
  953. if ($this->Timelimit > 0) {
  954. $endtime = time() + $this->Timelimit;
  955. }
  956. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  957. $str = @fgets($this->smtp_conn, 515);
  958. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  959. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  960. $data .= $str;
  961. // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
  962. // or 4th character is a space, we are done reading, break the loop,
  963. // string array access is a micro-optimisation over strlen
  964. if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
  965. break;
  966. }
  967. // Timed-out? Log and break
  968. $info = stream_get_meta_data($this->smtp_conn);
  969. if ($info['timed_out']) {
  970. $this->edebug(
  971. 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  972. self::DEBUG_LOWLEVEL
  973. );
  974. break;
  975. }
  976. // Now check if reads took too long
  977. if ($endtime and time() > $endtime) {
  978. $this->edebug(
  979. 'SMTP -> get_lines(): timelimit reached (' .
  980. $this->Timelimit . ' sec)',
  981. self::DEBUG_LOWLEVEL
  982. );
  983. break;
  984. }
  985. }
  986. return $data;
  987. }
  988. /**
  989. * Enable or disable VERP address generation.
  990. * @param boolean $enabled
  991. */
  992. public function setVerp($enabled = false)
  993. {
  994. $this->do_verp = $enabled;
  995. }
  996. /**
  997. * Get VERP address generation mode.
  998. * @return boolean
  999. */
  1000. public function getVerp()
  1001. {
  1002. return $this->do_verp;
  1003. }
  1004. /**
  1005. * Set error messages and codes.
  1006. * @param string $message The error message
  1007. * @param string $detail Further detail on the error
  1008. * @param string $smtp_code An associated SMTP error code
  1009. * @param string $smtp_code_ex Extended SMTP code
  1010. */
  1011. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  1012. {
  1013. $this->error = array(
  1014. 'error' => $message,
  1015. 'detail' => $detail,
  1016. 'smtp_code' => $smtp_code,
  1017. 'smtp_code_ex' => $smtp_code_ex
  1018. );
  1019. }
  1020. /**
  1021. * Set debug output method.
  1022. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
  1023. */
  1024. public function setDebugOutput($method = 'echo')
  1025. {
  1026. $this->Debugoutput = $method;
  1027. }
  1028. /**
  1029. * Get debug output method.
  1030. * @return string
  1031. */
  1032. public function getDebugOutput()
  1033. {
  1034. return $this->Debugoutput;
  1035. }
  1036. /**
  1037. * Set debug output level.
  1038. * @param integer $level
  1039. */
  1040. public function setDebugLevel($level = 0)
  1041. {
  1042. $this->do_debug = $level;
  1043. }
  1044. /**
  1045. * Get debug output level.
  1046. * @return integer
  1047. */
  1048. public function getDebugLevel()
  1049. {
  1050. return $this->do_debug;
  1051. }
  1052. /**
  1053. * Set SMTP timeout.
  1054. * @param integer $timeout
  1055. */
  1056. public function setTimeout($timeout = 0)
  1057. {
  1058. $this->Timeout = $timeout;
  1059. }
  1060. /**
  1061. * Get SMTP timeout.
  1062. * @return integer
  1063. */
  1064. public function getTimeout()
  1065. {
  1066. return $this->Timeout;
  1067. }
  1068. /**
  1069. * Reports an error number and string.
  1070. * @param integer $errno The error number returned by PHP.
  1071. * @param string $errmsg The error message returned by PHP.
  1072. * @param string $errfile The file the error occurred in
  1073. * @param integer $errline The line number the error occurred on
  1074. */
  1075. protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
  1076. {
  1077. $notice = 'Connection failed.';
  1078. $this->setError(
  1079. $notice,
  1080. $errno,
  1081. $errmsg
  1082. );
  1083. $this->edebug(
  1084. $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]",
  1085. self::DEBUG_CONNECTION
  1086. );
  1087. }
  1088. /**
  1089. * Extract and return the ID of the last SMTP transaction based on
  1090. * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
  1091. * Relies on the host providing the ID in response to a DATA command.
  1092. * If no reply has been received yet, it will return null.
  1093. * If no pattern was matched, it will return false.
  1094. * @return bool|null|string
  1095. */
  1096. protected function recordLastTransactionID()
  1097. {
  1098. $reply = $this->getLastReply();
  1099. if (empty($reply)) {
  1100. $this->last_smtp_transaction_id = null;
  1101. } else {
  1102. $this->last_smtp_transaction_id = false;
  1103. foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
  1104. if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
  1105. $this->last_smtp_transaction_id = $matches[1];
  1106. }
  1107. }
  1108. }
  1109. return $this->last_smtp_transaction_id;
  1110. }
  1111. /**
  1112. * Get the queue/transaction ID of the last SMTP transaction
  1113. * If no reply has been received yet, it will return null.
  1114. * If no pattern was matched, it will return false.
  1115. * @return bool|null|string
  1116. * @see recordLastTransactionID()
  1117. */
  1118. public function getLastTransactionID()
  1119. {
  1120. return $this->last_smtp_transaction_id;
  1121. }
  1122. }