PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/core/model/modx/mail/phpmailer/class.smtp.php

http://github.com/modxcms/revolution
PHP | 1276 lines | 661 code | 93 blank | 522 comment | 82 complexity | c8655d13a11f1bd467869d1800b6df46 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, BSD-3-Clause, LGPL-2.1
  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.28';
  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.28';
  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, NTLM, CRAM-MD5, XOAUTH2)
  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', 'NTLM', 'XOAUTH2') 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 'XOAUTH2':
  435. //If the OAuth Instance is not set. Can be a case when PHPMailer is used
  436. //instead of PHPMailerOAuth
  437. if (is_null($OAuth)) {
  438. return false;
  439. }
  440. $oauth = $OAuth->getOauth64();
  441. // Start authentication
  442. if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
  443. return false;
  444. }
  445. break;
  446. case 'NTLM':
  447. /*
  448. * ntlm_sasl_client.php
  449. * Bundled with Permission
  450. *
  451. * How to telnet in windows:
  452. * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
  453. * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
  454. */
  455. require_once 'extras/ntlm_sasl_client.php';
  456. $temp = new stdClass;
  457. $ntlm_client = new ntlm_sasl_client_class;
  458. //Check that functions are available
  459. if (!$ntlm_client->initialize($temp)) {
  460. $this->setError($temp->error);
  461. $this->edebug(
  462. 'You need to enable some modules in your php.ini file: '
  463. . $this->error['error'],
  464. self::DEBUG_CLIENT
  465. );
  466. return false;
  467. }
  468. //msg1
  469. $msg1 = $ntlm_client->typeMsg1($realm, $workstation); //msg1
  470. if (!$this->sendCommand(
  471. 'AUTH NTLM',
  472. 'AUTH NTLM ' . base64_encode($msg1),
  473. 334
  474. )
  475. ) {
  476. return false;
  477. }
  478. //Though 0 based, there is a white space after the 3 digit number
  479. //msg2
  480. $challenge = substr($this->last_reply, 3);
  481. $challenge = base64_decode($challenge);
  482. $ntlm_res = $ntlm_client->NTLMResponse(
  483. substr($challenge, 24, 8),
  484. $password
  485. );
  486. //msg3
  487. $msg3 = $ntlm_client->typeMsg3(
  488. $ntlm_res,
  489. $username,
  490. $realm,
  491. $workstation
  492. );
  493. // send encoded username
  494. return $this->sendCommand('Username', base64_encode($msg3), 235);
  495. case 'CRAM-MD5':
  496. // Start authentication
  497. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  498. return false;
  499. }
  500. // Get the challenge
  501. $challenge = base64_decode(substr($this->last_reply, 4));
  502. // Build the response
  503. $response = $username . ' ' . $this->hmac($challenge, $password);
  504. // send encoded credentials
  505. return $this->sendCommand('Username', base64_encode($response), 235);
  506. default:
  507. $this->setError("Authentication method \"$authtype\" is not supported");
  508. return false;
  509. }
  510. return true;
  511. }
  512. /**
  513. * Calculate an MD5 HMAC hash.
  514. * Works like hash_hmac('md5', $data, $key)
  515. * in case that function is not available
  516. * @param string $data The data to hash
  517. * @param string $key The key to hash with
  518. * @access protected
  519. * @return string
  520. */
  521. protected function hmac($data, $key)
  522. {
  523. if (function_exists('hash_hmac')) {
  524. return hash_hmac('md5', $data, $key);
  525. }
  526. // The following borrowed from
  527. // http://php.net/manual/en/function.mhash.php#27225
  528. // RFC 2104 HMAC implementation for php.
  529. // Creates an md5 HMAC.
  530. // Eliminates the need to install mhash to compute a HMAC
  531. // by Lance Rushing
  532. $bytelen = 64; // byte length for md5
  533. if (strlen($key) > $bytelen) {
  534. $key = pack('H*', md5($key));
  535. }
  536. $key = str_pad($key, $bytelen, chr(0x00));
  537. $ipad = str_pad('', $bytelen, chr(0x36));
  538. $opad = str_pad('', $bytelen, chr(0x5c));
  539. $k_ipad = $key ^ $ipad;
  540. $k_opad = $key ^ $opad;
  541. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  542. }
  543. /**
  544. * Check connection state.
  545. * @access public
  546. * @return boolean True if connected.
  547. */
  548. public function connected()
  549. {
  550. if (is_resource($this->smtp_conn)) {
  551. $sock_status = stream_get_meta_data($this->smtp_conn);
  552. if ($sock_status['eof']) {
  553. // The socket is valid but we are not connected
  554. $this->edebug(
  555. 'SMTP NOTICE: EOF caught while checking if connected',
  556. self::DEBUG_CLIENT
  557. );
  558. $this->close();
  559. return false;
  560. }
  561. return true; // everything looks good
  562. }
  563. return false;
  564. }
  565. /**
  566. * Close the socket and clean up the state of the class.
  567. * Don't use this function without first trying to use QUIT.
  568. * @see quit()
  569. * @access public
  570. * @return void
  571. */
  572. public function close()
  573. {
  574. $this->setError('');
  575. $this->server_caps = null;
  576. $this->helo_rply = null;
  577. if (is_resource($this->smtp_conn)) {
  578. // close the connection and cleanup
  579. fclose($this->smtp_conn);
  580. $this->smtp_conn = null; //Makes for cleaner serialization
  581. $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  582. }
  583. }
  584. /**
  585. * Send an SMTP DATA command.
  586. * Issues a data command and sends the msg_data to the server,
  587. * finializing the mail transaction. $msg_data is the message
  588. * that is to be send with the headers. Each header needs to be
  589. * on a single line followed by a <CRLF> with the message headers
  590. * and the message body being separated by and additional <CRLF>.
  591. * Implements rfc 821: DATA <CRLF>
  592. * @param string $msg_data Message data to send
  593. * @access public
  594. * @return boolean
  595. */
  596. public function data($msg_data)
  597. {
  598. //This will use the standard timelimit
  599. if (!$this->sendCommand('DATA', 'DATA', 354)) {
  600. return false;
  601. }
  602. /* The server is ready to accept data!
  603. * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  604. * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  605. * smaller lines to fit within the limit.
  606. * We will also look for lines that start with a '.' and prepend an additional '.'.
  607. * NOTE: this does not count towards line-length limit.
  608. */
  609. // Normalize line breaks before exploding
  610. $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  611. /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  612. * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  613. * process all lines before a blank line as headers.
  614. */
  615. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  616. $in_headers = false;
  617. if (!empty($field) && strpos($field, ' ') === false) {
  618. $in_headers = true;
  619. }
  620. foreach ($lines as $line) {
  621. $lines_out = array();
  622. if ($in_headers and $line == '') {
  623. $in_headers = false;
  624. }
  625. //Break this line up into several smaller lines if it's too long
  626. //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
  627. while (isset($line[self::MAX_LINE_LENGTH])) {
  628. //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  629. //so as to avoid breaking in the middle of a word
  630. $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  631. //Deliberately matches both false and 0
  632. if (!$pos) {
  633. //No nice break found, add a hard break
  634. $pos = self::MAX_LINE_LENGTH - 1;
  635. $lines_out[] = substr($line, 0, $pos);
  636. $line = substr($line, $pos);
  637. } else {
  638. //Break at the found point
  639. $lines_out[] = substr($line, 0, $pos);
  640. //Move along by the amount we dealt with
  641. $line = substr($line, $pos + 1);
  642. }
  643. //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
  644. if ($in_headers) {
  645. $line = "\t" . $line;
  646. }
  647. }
  648. $lines_out[] = $line;
  649. //Send the lines to the server
  650. foreach ($lines_out as $line_out) {
  651. //RFC2821 section 4.5.2
  652. if (!empty($line_out) and $line_out[0] == '.') {
  653. $line_out = '.' . $line_out;
  654. }
  655. $this->client_send($line_out . self::CRLF);
  656. }
  657. }
  658. //Message data has been sent, complete the command
  659. //Increase timelimit for end of DATA command
  660. $savetimelimit = $this->Timelimit;
  661. $this->Timelimit = $this->Timelimit * 2;
  662. $result = $this->sendCommand('DATA END', '.', 250);
  663. $this->recordLastTransactionID();
  664. //Restore timelimit
  665. $this->Timelimit = $savetimelimit;
  666. return $result;
  667. }
  668. /**
  669. * Send an SMTP HELO or EHLO command.
  670. * Used to identify the sending server to the receiving server.
  671. * This makes sure that client and server are in a known state.
  672. * Implements RFC 821: HELO <SP> <domain> <CRLF>
  673. * and RFC 2821 EHLO.
  674. * @param string $host The host name or IP to connect to
  675. * @access public
  676. * @return boolean
  677. */
  678. public function hello($host = '')
  679. {
  680. //Try extended hello first (RFC 2821)
  681. return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  682. }
  683. /**
  684. * Send an SMTP HELO or EHLO command.
  685. * Low-level implementation used by hello()
  686. * @see hello()
  687. * @param string $hello The HELO string
  688. * @param string $host The hostname to say we are
  689. * @access protected
  690. * @return boolean
  691. */
  692. protected function sendHello($hello, $host)
  693. {
  694. $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  695. $this->helo_rply = $this->last_reply;
  696. if ($noerror) {
  697. $this->parseHelloFields($hello);
  698. } else {
  699. $this->server_caps = null;
  700. }
  701. return $noerror;
  702. }
  703. /**
  704. * Parse a reply to HELO/EHLO command to discover server extensions.
  705. * In case of HELO, the only parameter that can be discovered is a server name.
  706. * @access protected
  707. * @param string $type - 'HELO' or 'EHLO'
  708. */
  709. protected function parseHelloFields($type)
  710. {
  711. $this->server_caps = array();
  712. $lines = explode("\n", $this->helo_rply);
  713. foreach ($lines as $n => $s) {
  714. //First 4 chars contain response code followed by - or space
  715. $s = trim(substr($s, 4));
  716. if (empty($s)) {
  717. continue;
  718. }
  719. $fields = explode(' ', $s);
  720. if (!empty($fields)) {
  721. if (!$n) {
  722. $name = $type;
  723. $fields = $fields[0];
  724. } else {
  725. $name = array_shift($fields);
  726. switch ($name) {
  727. case 'SIZE':
  728. $fields = ($fields ? $fields[0] : 0);
  729. break;
  730. case 'AUTH':
  731. if (!is_array($fields)) {
  732. $fields = array();
  733. }
  734. break;
  735. default:
  736. $fields = true;
  737. }
  738. }
  739. $this->server_caps[$name] = $fields;
  740. }
  741. }
  742. }
  743. /**
  744. * Send an SMTP MAIL command.
  745. * Starts a mail transaction from the email address specified in
  746. * $from. Returns true if successful or false otherwise. If True
  747. * the mail transaction is started and then one or more recipient
  748. * commands may be called followed by a data command.
  749. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  750. * @param string $from Source address of this message
  751. * @access public
  752. * @return boolean
  753. */
  754. public function mail($from)
  755. {
  756. $useVerp = ($this->do_verp ? ' XVERP' : '');
  757. return $this->sendCommand(
  758. 'MAIL FROM',
  759. 'MAIL FROM:<' . $from . '>' . $useVerp,
  760. 250
  761. );
  762. }
  763. /**
  764. * Send an SMTP QUIT command.
  765. * Closes the socket if there is no error or the $close_on_error argument is true.
  766. * Implements from rfc 821: QUIT <CRLF>
  767. * @param boolean $close_on_error Should the connection close if an error occurs?
  768. * @access public
  769. * @return boolean
  770. */
  771. public function quit($close_on_error = true)
  772. {
  773. $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  774. $err = $this->error; //Save any error
  775. if ($noerror or $close_on_error) {
  776. $this->close();
  777. $this->error = $err; //Restore any error from the quit command
  778. }
  779. return $noerror;
  780. }
  781. /**
  782. * Send an SMTP RCPT command.
  783. * Sets the TO argument to $toaddr.
  784. * Returns true if the recipient was accepted false if it was rejected.
  785. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  786. * @param string $address The address the message is being sent to
  787. * @access public
  788. * @return boolean
  789. */
  790. public function recipient($address)
  791. {
  792. return $this->sendCommand(
  793. 'RCPT TO',
  794. 'RCPT TO:<' . $address . '>',
  795. array(250, 251)
  796. );
  797. }
  798. /**
  799. * Send an SMTP RSET command.
  800. * Abort any transaction that is currently in progress.
  801. * Implements rfc 821: RSET <CRLF>
  802. * @access public
  803. * @return boolean True on success.
  804. */
  805. public function reset()
  806. {
  807. return $this->sendCommand('RSET', 'RSET', 250);
  808. }
  809. /**
  810. * Send a command to an SMTP server and check its return code.
  811. * @param string $command The command name - not sent to the server
  812. * @param string $commandstring The actual command to send
  813. * @param integer|array $expect One or more expected integer success codes
  814. * @access protected
  815. * @return boolean True on success.
  816. */
  817. protected function sendCommand($command, $commandstring, $expect)
  818. {
  819. if (!$this->connected()) {
  820. $this->setError("Called $command without being connected");
  821. return false;
  822. }
  823. //Reject line breaks in all commands
  824. if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
  825. $this->setError("Command '$command' contained line breaks");
  826. return false;
  827. }
  828. $this->client_send($commandstring . self::CRLF);
  829. $this->last_reply = $this->get_lines();
  830. // Fetch SMTP code and possible error code explanation
  831. $matches = array();
  832. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  833. $code = $matches[1];
  834. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  835. // Cut off error code from each response line
  836. $detail = preg_replace(
  837. "/{$code}[ -]" .
  838. ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
  839. '',
  840. $this->last_reply
  841. );
  842. } else {
  843. // Fall back to simple parsing if regex fails
  844. $code = substr($this->last_reply, 0, 3);
  845. $code_ex = null;
  846. $detail = substr($this->last_reply, 4);
  847. }
  848. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  849. if (!in_array($code, (array)$expect)) {
  850. $this->setError(
  851. "$command command failed",
  852. $detail,
  853. $code,
  854. $code_ex
  855. );
  856. $this->edebug(
  857. 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  858. self::DEBUG_CLIENT
  859. );
  860. return false;
  861. }
  862. $this->setError('');
  863. return true;
  864. }
  865. /**
  866. * Send an SMTP SAML command.
  867. * Starts a mail transaction from the email address specified in $from.
  868. * Returns true if successful or false otherwise. If True
  869. * the mail transaction is started and then one or more recipient
  870. * commands may be called followed by a data command. This command
  871. * will send the message to the users terminal if they are logged
  872. * in and send them an email.
  873. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  874. * @param string $from The address the message is from
  875. * @access public
  876. * @return boolean
  877. */
  878. public function sendAndMail($from)
  879. {
  880. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  881. }
  882. /**
  883. * Send an SMTP VRFY command.
  884. * @param string $name The name to verify
  885. * @access public
  886. * @return boolean
  887. */
  888. public function verify($name)
  889. {
  890. return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  891. }
  892. /**
  893. * Send an SMTP NOOP command.
  894. * Used to keep keep-alives alive, doesn't actually do anything
  895. * @access public
  896. * @return boolean
  897. */
  898. public function noop()
  899. {
  900. return $this->sendCommand('NOOP', 'NOOP', 250);
  901. }
  902. /**
  903. * Send an SMTP TURN command.
  904. * This is an optional command for SMTP that this class does not support.
  905. * This method is here to make the RFC821 Definition complete for this class
  906. * and _may_ be implemented in future
  907. * Implements from rfc 821: TURN <CRLF>
  908. * @access public
  909. * @return boolean
  910. */
  911. public function turn()
  912. {
  913. $this->setError('The SMTP TURN command is not implemented');
  914. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  915. return false;
  916. }
  917. /**
  918. * Send raw data to the server.
  919. * @param string $data The data to send
  920. * @access public
  921. * @return integer|boolean The number of bytes sent to the server or false on error
  922. */
  923. public function client_send($data)
  924. {
  925. $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  926. set_error_handler(array($this, 'errorHandler'));
  927. $result = fwrite($this->smtp_conn, $data);
  928. restore_error_handler();
  929. return $result;
  930. }
  931. /**
  932. * Get the latest error.
  933. * @access public
  934. * @return array
  935. */
  936. public function getError()
  937. {
  938. return $this->error;
  939. }
  940. /**
  941. * Get SMTP extensions available on the server
  942. * @access public
  943. * @return array|null
  944. */
  945. public function getServerExtList()
  946. {
  947. return $this->server_caps;
  948. }
  949. /**
  950. * A multipurpose method
  951. * The method works in three ways, dependent on argument value and current state
  952. * 1. HELO/EHLO was not sent - returns null and set up $this->error
  953. * 2. HELO was sent
  954. * $name = 'HELO': returns server name
  955. * $name = 'EHLO': returns boolean false
  956. * $name = any string: returns null and set up $this->error
  957. * 3. EHLO was sent
  958. * $name = 'HELO'|'EHLO': returns server name
  959. * $name = any string: if extension $name exists, returns boolean True
  960. * or its options. Otherwise returns boolean False
  961. * In other words, one can use this method to detect 3 conditions:
  962. * - null returned: handshake was not or we don't know about ext (refer to $this->error)
  963. * - false returned: the requested feature exactly not exists
  964. * - positive value returned: the requested feature exists
  965. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  966. * @return mixed
  967. */
  968. public function getServerExt($name)
  969. {
  970. if (!$this->server_caps) {
  971. $this->setError('No HELO/EHLO was sent');
  972. return null;
  973. }
  974. // the tight logic knot ;)
  975. if (!array_key_exists($name, $this->server_caps)) {
  976. if ($name == 'HELO') {
  977. return $this->server_caps['EHLO'];
  978. }
  979. if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  980. return false;
  981. }
  982. $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  983. return null;
  984. }
  985. return $this->server_caps[$name];
  986. }
  987. /**
  988. * Get the last reply from the server.
  989. * @access public
  990. * @return string
  991. */
  992. public function getLastReply()
  993. {
  994. return $this->last_reply;
  995. }
  996. /**
  997. * Read the SMTP server's response.
  998. * Either before eof or socket timeout occurs on the operation.
  999. * With SMTP we can tell if we have more lines to read if the
  1000. * 4th character is '-' symbol. If it is a space then we don't
  1001. * need to read anything else.
  1002. * @access protected
  1003. * @return string
  1004. */
  1005. protected function get_lines()
  1006. {
  1007. // If the connection is bad, give up straight away
  1008. if (!is_resource($this->smtp_conn)) {
  1009. return '';
  1010. }
  1011. $data = '';
  1012. $endtime = 0;
  1013. stream_set_timeout($this->smtp_conn, $this->Timeout);
  1014. if ($this->Timelimit > 0) {
  1015. $endtime = time() + $this->Timelimit;
  1016. }
  1017. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  1018. $str = @fgets($this->smtp_conn, 515);
  1019. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  1020. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  1021. $data .= $str;
  1022. // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
  1023. // or 4th character is a space, we are done reading, break the loop,
  1024. // string array access is a micro-optimisation over strlen
  1025. if (!isset($str[3]) or (isset($str[3]) and $str[3] == ' ')) {
  1026. break;
  1027. }
  1028. // Timed-out? Log and break
  1029. $info = stream_get_meta_data($this->smtp_conn);
  1030. if ($info['timed_out']) {
  1031. $this->edebug(
  1032. 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  1033. self::DEBUG_LOWLEVEL
  1034. );
  1035. break;
  1036. }
  1037. // Now check if reads took too long
  1038. if ($endtime and time() > $endtime) {
  1039. $this->edebug(
  1040. 'SMTP -> get_lines(): timelimit reached (' .
  1041. $this->Timelimit . ' sec)',
  1042. self::DEBUG_LOWLEVEL
  1043. );
  1044. break;
  1045. }
  1046. }
  1047. return $data;
  1048. }
  1049. /**
  1050. * Enable or disable VERP address generation.
  1051. * @param boolean $enabled
  1052. */
  1053. public function setVerp($enabled = false)
  1054. {
  1055. $this->do_verp = $enabled;
  1056. }
  1057. /**
  1058. * Get VERP address generation mode.
  1059. * @return boolean
  1060. */
  1061. public function getVerp()
  1062. {
  1063. return $this->do_verp;
  1064. }
  1065. /**
  1066. * Set error messages and codes.
  1067. * @param string $message The error message
  1068. * @param string $detail Further detail on the error
  1069. * @param string $smtp_code An associated SMTP error code
  1070. * @param string $smtp_code_ex Extended SMTP code
  1071. */
  1072. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  1073. {
  1074. $this->error = array(
  1075. 'error' => $message,
  1076. 'detail' => $detail,
  1077. 'smtp_code' => $smtp_code,
  1078. 'smtp_code_ex' => $smtp_code_ex
  1079. );
  1080. }
  1081. /**
  1082. * Set debug output method.
  1083. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
  1084. */
  1085. public function setDebugOutput($method = 'echo')
  1086. {
  1087. $this->Debugoutput = $method;
  1088. }
  1089. /**
  1090. * Get debug output method.
  1091. * @return string
  1092. */
  1093. public function getDebugOutput()
  1094. {
  1095. return $this->Debugoutput;
  1096. }
  1097. /**
  1098. * Set debug output level.
  1099. * @param integer $level
  1100. */
  1101. public function setDebugLevel($level = 0)
  1102. {
  1103. $this->do_debug = $level;
  1104. }
  1105. /**
  1106. * Get debug output level.
  1107. * @return integer
  1108. */
  1109. public function getDebugLevel()
  1110. {
  1111. return $this->do_debug;
  1112. }
  1113. /**
  1114. * Set SMTP timeout.
  1115. * @param integer $timeout
  1116. */
  1117. public function setTimeout($timeout = 0)
  1118. {
  1119. $this->Timeout = $timeout;
  1120. }
  1121. /**
  1122. * Get SMTP timeout.
  1123. * @return integer
  1124. */
  1125. public function getTimeout()
  1126. {
  1127. return $this->Timeout;
  1128. }
  1129. /**
  1130. * Reports an error number and string.
  1131. * @param integer $errno The error number returned by PHP.
  1132. * @param string $errmsg The error message returned by PHP.
  1133. * @param string $errfile The file the error occurred in
  1134. * @param integer $errline The line number the error occurred on
  1135. */
  1136. protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
  1137. {
  1138. $notice = 'Connection failed.';
  1139. $this->setError(
  1140. $notice,
  1141. $errno,
  1142. $errmsg
  1143. );
  1144. $this->edebug(
  1145. $notice . ' Error #' . $errno . ': ' . $errmsg . " [$errfile line $errline]",
  1146. self::DEBUG_CONNECTION
  1147. );
  1148. }
  1149. /**
  1150. * Extract and return the ID of the last SMTP transaction based on
  1151. * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
  1152. * Relies on the host providing the ID in response to a DATA command.
  1153. * If no reply has been received yet, it will return null.
  1154. * If no pattern was matched, it will return false.
  1155. * @return bool|null|string
  1156. */
  1157. protected function recordLastTransactionID()
  1158. {
  1159. $reply = $this->getLastReply();
  1160. if (empty($reply)) {
  1161. $this->last_smtp_transaction_id = null;
  1162. } else {
  1163. $this->last_smtp_transaction_id = false;
  1164. foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
  1165. if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
  1166. $this->last_smtp_transaction_id = $matches[1];
  1167. }
  1168. }
  1169. }
  1170. return $this->last_smtp_transaction_id;
  1171. }
  1172. /**
  1173. * Get the queue/transaction ID of the last SMTP transaction
  1174. * If no reply has been received yet, it will return null.
  1175. * If no pattern was matched, it will return false.
  1176. * @return bool|null|string
  1177. * @see recordLastTransactionID()
  1178. */
  1179. public function getLastTransactionID()
  1180. {
  1181. return $this->last_smtp_transaction_id;
  1182. }
  1183. }