You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SMTP.php 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. <?php
  2. /** vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 5 and 7 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2015 Jon Parise and Chuck Hagenbuch |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 3.01 of the PHP license, |
  9. // | that is bundled with this package in the file LICENSE, and is |
  10. // | available at through the world-wide-web at |
  11. // | http://www.php.net/license/3_01.txt. |
  12. // | If you did not receive a copy of the PHP license and are unable to |
  13. // | obtain it through the world-wide-web, please send a note to |
  14. // | license@php.net so we can mail you a copy immediately. |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Chuck Hagenbuch <chuck@horde.org> |
  17. // | Jon Parise <jon@php.net> |
  18. // | Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar> |
  19. // +----------------------------------------------------------------------+
  20. require_once 'PEAR.php';
  21. require_once 'Net/Socket.php';
  22. /**
  23. * Provides an implementation of the SMTP protocol using PEAR's
  24. * Net_Socket class.
  25. *
  26. * @package Net_SMTP
  27. * @author Chuck Hagenbuch <chuck@horde.org>
  28. * @author Jon Parise <jon@php.net>
  29. * @author Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar>
  30. *
  31. * @example basic.php A basic implementation of the Net_SMTP package.
  32. */
  33. class Net_SMTP
  34. {
  35. /**
  36. * The server to connect to.
  37. * @var string
  38. */
  39. public $host = 'localhost';
  40. /**
  41. * The port to connect to.
  42. * @var int
  43. */
  44. public $port = 25;
  45. /**
  46. * The value to give when sending EHLO or HELO.
  47. * @var string
  48. */
  49. public $localhost = 'localhost';
  50. /**
  51. * List of supported authentication methods, in preferential order.
  52. * @var array
  53. */
  54. public $auth_methods = array();
  55. /**
  56. * Use SMTP command pipelining (specified in RFC 2920) if the SMTP
  57. * server supports it.
  58. *
  59. * When pipeling is enabled, rcptTo(), mailFrom(), sendFrom(),
  60. * somlFrom() and samlFrom() do not wait for a response from the
  61. * SMTP server but return immediately.
  62. *
  63. * @var bool
  64. */
  65. public $pipelining = false;
  66. /**
  67. * Number of pipelined commands.
  68. * @var int
  69. */
  70. protected $pipelined_commands = 0;
  71. /**
  72. * Should debugging output be enabled?
  73. * @var boolean
  74. */
  75. protected $debug = false;
  76. /**
  77. * Debug output handler.
  78. * @var callback
  79. */
  80. protected $debug_handler = null;
  81. /**
  82. * The socket resource being used to connect to the SMTP server.
  83. * @var resource
  84. */
  85. protected $socket = null;
  86. /**
  87. * Array of socket options that will be passed to Net_Socket::connect().
  88. * @see stream_context_create()
  89. * @var array
  90. */
  91. protected $socket_options = null;
  92. /**
  93. * The socket I/O timeout value in seconds.
  94. * @var int
  95. */
  96. protected $timeout = 0;
  97. /**
  98. * The most recent server response code.
  99. * @var int
  100. */
  101. protected $code = -1;
  102. /**
  103. * The most recent server response arguments.
  104. * @var array
  105. */
  106. protected $arguments = array();
  107. /**
  108. * Stores the SMTP server's greeting string.
  109. * @var string
  110. */
  111. protected $greeting = null;
  112. /**
  113. * Stores detected features of the SMTP server.
  114. * @var array
  115. */
  116. protected $esmtp = array();
  117. /**
  118. * Instantiates a new Net_SMTP object, overriding any defaults
  119. * with parameters that are passed in.
  120. *
  121. * If you have SSL support in PHP, you can connect to a server
  122. * over SSL using an 'ssl://' prefix:
  123. *
  124. * // 465 is a common smtps port.
  125. * $smtp = new Net_SMTP('ssl://mail.host.com', 465);
  126. * $smtp->connect();
  127. *
  128. * @param string $host The server to connect to.
  129. * @param integer $port The port to connect to.
  130. * @param string $localhost The value to give when sending EHLO or HELO.
  131. * @param boolean $pipelining Use SMTP command pipelining
  132. * @param integer $timeout Socket I/O timeout in seconds.
  133. * @param array $socket_options Socket stream_context_create() options.
  134. *
  135. * @since 1.0
  136. */
  137. public function __construct($host = null, $port = null, $localhost = null,
  138. $pipelining = false, $timeout = 0, $socket_options = null
  139. ) {
  140. if (isset($host)) {
  141. $this->host = $host;
  142. }
  143. if (isset($port)) {
  144. $this->port = $port;
  145. }
  146. if (isset($localhost)) {
  147. $this->localhost = $localhost;
  148. }
  149. $this->pipelining = $pipelining;
  150. $this->socket = new Net_Socket();
  151. $this->socket_options = $socket_options;
  152. $this->timeout = $timeout;
  153. /* Include the Auth_SASL package. If the package is available, we
  154. * enable the authentication methods that depend upon it. */
  155. if (@include_once 'Auth/SASL.php') {
  156. $this->setAuthMethod('CRAM-MD5', array($this, 'authCramMD5'));
  157. $this->setAuthMethod('DIGEST-MD5', array($this, 'authDigestMD5'));
  158. }
  159. /* These standard authentication methods are always available. */
  160. $this->setAuthMethod('LOGIN', array($this, 'authLogin'), false);
  161. $this->setAuthMethod('PLAIN', array($this, 'authPlain'), false);
  162. }
  163. /**
  164. * Set the socket I/O timeout value in seconds plus microseconds.
  165. *
  166. * @param integer $seconds Timeout value in seconds.
  167. * @param integer $microseconds Additional value in microseconds.
  168. *
  169. * @since 1.5.0
  170. */
  171. public function setTimeout($seconds, $microseconds = 0)
  172. {
  173. return $this->socket->setTimeout($seconds, $microseconds);
  174. }
  175. /**
  176. * Set the value of the debugging flag.
  177. *
  178. * @param boolean $debug New value for the debugging flag.
  179. * @param callback $handler Debug handler callback
  180. *
  181. * @since 1.1.0
  182. */
  183. public function setDebug($debug, $handler = null)
  184. {
  185. $this->debug = $debug;
  186. $this->debug_handler = $handler;
  187. }
  188. /**
  189. * Write the given debug text to the current debug output handler.
  190. *
  191. * @param string $message Debug mesage text.
  192. *
  193. * @since 1.3.3
  194. */
  195. protected function debug($message)
  196. {
  197. if ($this->debug) {
  198. if ($this->debug_handler) {
  199. call_user_func_array(
  200. $this->debug_handler, array(&$this, $message)
  201. );
  202. } else {
  203. echo "DEBUG: $message\n";
  204. }
  205. }
  206. }
  207. /**
  208. * Send the given string of data to the server.
  209. *
  210. * @param string $data The string of data to send.
  211. *
  212. * @return mixed The number of bytes that were actually written,
  213. * or a PEAR_Error object on failure.
  214. *
  215. * @since 1.1.0
  216. */
  217. protected function send($data)
  218. {
  219. $this->debug("Send: $data");
  220. $result = $this->socket->write($data);
  221. if (!$result || PEAR::isError($result)) {
  222. $msg = $result ? $result->getMessage() : "unknown error";
  223. return PEAR::raiseError("Failed to write to socket: $msg");
  224. }
  225. return $result;
  226. }
  227. /**
  228. * Send a command to the server with an optional string of
  229. * arguments. A carriage return / linefeed (CRLF) sequence will
  230. * be appended to each command string before it is sent to the
  231. * SMTP server - an error will be thrown if the command string
  232. * already contains any newline characters. Use send() for
  233. * commands that must contain newlines.
  234. *
  235. * @param string $command The SMTP command to send to the server.
  236. * @param string $args A string of optional arguments to append
  237. * to the command.
  238. *
  239. * @return mixed The result of the send() call.
  240. *
  241. * @since 1.1.0
  242. */
  243. protected function put($command, $args = '')
  244. {
  245. if (!empty($args)) {
  246. $command .= ' ' . $args;
  247. }
  248. if (strcspn($command, "\r\n") !== strlen($command)) {
  249. return PEAR::raiseError('Commands cannot contain newlines');
  250. }
  251. return $this->send($command . "\r\n");
  252. }
  253. /**
  254. * Read a reply from the SMTP server. The reply consists of a response
  255. * code and a response message.
  256. *
  257. * @param mixed $valid The set of valid response codes. These
  258. * may be specified as an array of integer
  259. * values or as a single integer value.
  260. * @param bool $later Do not parse the response now, but wait
  261. * until the last command in the pipelined
  262. * command group
  263. *
  264. * @return mixed True if the server returned a valid response code or
  265. * a PEAR_Error object is an error condition is reached.
  266. *
  267. * @since 1.1.0
  268. *
  269. * @see getResponse
  270. */
  271. protected function parseResponse($valid, $later = false)
  272. {
  273. $this->code = -1;
  274. $this->arguments = array();
  275. if ($later) {
  276. $this->pipelined_commands++;
  277. return true;
  278. }
  279. for ($i = 0; $i <= $this->pipelined_commands; $i++) {
  280. while ($line = $this->socket->readLine()) {
  281. $this->debug("Recv: $line");
  282. /* If we receive an empty line, the connection was closed. */
  283. if (empty($line)) {
  284. $this->disconnect();
  285. return PEAR::raiseError('Connection was closed');
  286. }
  287. /* Read the code and store the rest in the arguments array. */
  288. $code = substr($line, 0, 3);
  289. $this->arguments[] = trim(substr($line, 4));
  290. /* Check the syntax of the response code. */
  291. if (is_numeric($code)) {
  292. $this->code = (int)$code;
  293. } else {
  294. $this->code = -1;
  295. break;
  296. }
  297. /* If this is not a multiline response, we're done. */
  298. if (substr($line, 3, 1) != '-') {
  299. break;
  300. }
  301. }
  302. }
  303. $this->pipelined_commands = 0;
  304. /* Compare the server's response code with the valid code/codes. */
  305. if (is_int($valid) && ($this->code === $valid)) {
  306. return true;
  307. } elseif (is_array($valid) && in_array($this->code, $valid, true)) {
  308. return true;
  309. }
  310. return PEAR::raiseError('Invalid response code received from server', $this->code);
  311. }
  312. /**
  313. * Issue an SMTP command and verify its response.
  314. *
  315. * @param string $command The SMTP command string or data.
  316. * @param mixed $valid The set of valid response codes. These
  317. * may be specified as an array of integer
  318. * values or as a single integer value.
  319. *
  320. * @return mixed True on success or a PEAR_Error object on failure.
  321. *
  322. * @since 1.6.0
  323. */
  324. public function command($command, $valid)
  325. {
  326. if (PEAR::isError($error = $this->put($command))) {
  327. return $error;
  328. }
  329. if (PEAR::isError($error = $this->parseResponse($valid))) {
  330. return $error;
  331. }
  332. return true;
  333. }
  334. /**
  335. * Return a 2-tuple containing the last response from the SMTP server.
  336. *
  337. * @return array A two-element array: the first element contains the
  338. * response code as an integer and the second element
  339. * contains the response's arguments as a string.
  340. *
  341. * @since 1.1.0
  342. */
  343. public function getResponse()
  344. {
  345. return array($this->code, join("\n", $this->arguments));
  346. }
  347. /**
  348. * Return the SMTP server's greeting string.
  349. *
  350. * @return string A string containing the greeting string, or null if
  351. * a greeting has not been received.
  352. *
  353. * @since 1.3.3
  354. */
  355. public function getGreeting()
  356. {
  357. return $this->greeting;
  358. }
  359. /**
  360. * Attempt to connect to the SMTP server.
  361. *
  362. * @param int $timeout The timeout value (in seconds) for the
  363. * socket connection attempt.
  364. * @param bool $persistent Should a persistent socket connection
  365. * be used?
  366. *
  367. * @return mixed Returns a PEAR_Error with an error message on any
  368. * kind of failure, or true on success.
  369. * @since 1.0
  370. */
  371. public function connect($timeout = null, $persistent = false)
  372. {
  373. $this->greeting = null;
  374. $result = $this->socket->connect(
  375. $this->host, $this->port, $persistent, $timeout, $this->socket_options
  376. );
  377. if (PEAR::isError($result)) {
  378. return PEAR::raiseError(
  379. 'Failed to connect socket: ' . $result->getMessage()
  380. );
  381. }
  382. /*
  383. * Now that we're connected, reset the socket's timeout value for
  384. * future I/O operations. This allows us to have different socket
  385. * timeout values for the initial connection (our $timeout parameter)
  386. * and all other socket operations.
  387. */
  388. if ($this->timeout > 0) {
  389. if (PEAR::isError($error = $this->setTimeout($this->timeout))) {
  390. return $error;
  391. }
  392. }
  393. if (PEAR::isError($error = $this->parseResponse(220))) {
  394. return $error;
  395. }
  396. /* Extract and store a copy of the server's greeting string. */
  397. list(, $this->greeting) = $this->getResponse();
  398. if (PEAR::isError($error = $this->negotiate())) {
  399. return $error;
  400. }
  401. return true;
  402. }
  403. /**
  404. * Attempt to disconnect from the SMTP server.
  405. *
  406. * @return mixed Returns a PEAR_Error with an error message on any
  407. * kind of failure, or true on success.
  408. * @since 1.0
  409. */
  410. public function disconnect()
  411. {
  412. if (PEAR::isError($error = $this->put('QUIT'))) {
  413. return $error;
  414. }
  415. if (PEAR::isError($error = $this->parseResponse(221))) {
  416. return $error;
  417. }
  418. if (PEAR::isError($error = $this->socket->disconnect())) {
  419. return PEAR::raiseError(
  420. 'Failed to disconnect socket: ' . $error->getMessage()
  421. );
  422. }
  423. return true;
  424. }
  425. /**
  426. * Attempt to send the EHLO command and obtain a list of ESMTP
  427. * extensions available, and failing that just send HELO.
  428. *
  429. * @return mixed Returns a PEAR_Error with an error message on any
  430. * kind of failure, or true on success.
  431. *
  432. * @since 1.1.0
  433. */
  434. protected function negotiate()
  435. {
  436. if (PEAR::isError($error = $this->put('EHLO', $this->localhost))) {
  437. return $error;
  438. }
  439. if (PEAR::isError($this->parseResponse(250))) {
  440. /* If the EHLO failed, try the simpler HELO command. */
  441. if (PEAR::isError($error = $this->put('HELO', $this->localhost))) {
  442. return $error;
  443. }
  444. if (PEAR::isError($this->parseResponse(250))) {
  445. return PEAR::raiseError('HELO was not accepted', $this->code);
  446. }
  447. return true;
  448. }
  449. foreach ($this->arguments as $argument) {
  450. $verb = strtok($argument, ' ');
  451. $len = strlen($verb);
  452. $arguments = substr($argument, $len + 1, strlen($argument) - $len - 1);
  453. $this->esmtp[$verb] = $arguments;
  454. }
  455. if (!isset($this->esmtp['PIPELINING'])) {
  456. $this->pipelining = false;
  457. }
  458. return true;
  459. }
  460. /**
  461. * Returns the name of the best authentication method that the server
  462. * has advertised.
  463. *
  464. * @return mixed Returns a string containing the name of the best
  465. * supported authentication method or a PEAR_Error object
  466. * if a failure condition is encountered.
  467. * @since 1.1.0
  468. */
  469. protected function getBestAuthMethod()
  470. {
  471. $available_methods = explode(' ', $this->esmtp['AUTH']);
  472. foreach ($this->auth_methods as $method => $callback) {
  473. if (in_array($method, $available_methods)) {
  474. return $method;
  475. }
  476. }
  477. return PEAR::raiseError('No supported authentication methods');
  478. }
  479. /**
  480. * Attempt to do SMTP authentication.
  481. *
  482. * @param string $uid The userid to authenticate as.
  483. * @param string $pwd The password to authenticate with.
  484. * @param string $method The requested authentication method. If none is
  485. * specified, the best supported method will be used.
  486. * @param bool $tls Flag indicating whether or not TLS should be attempted.
  487. * @param string $authz An optional authorization identifier. If specified, this
  488. * identifier will be used as the authorization proxy.
  489. *
  490. * @return mixed Returns a PEAR_Error with an error message on any
  491. * kind of failure, or true on success.
  492. * @since 1.0
  493. */
  494. public function auth($uid, $pwd , $method = '', $tls = true, $authz = '')
  495. {
  496. /* We can only attempt a TLS connection if one has been requested,
  497. * we're running PHP 5.1.0 or later, have access to the OpenSSL
  498. * extension, are connected to an SMTP server which supports the
  499. * STARTTLS extension, and aren't already connected over a secure
  500. * (SSL) socket connection. */
  501. if ($tls && version_compare(PHP_VERSION, '5.1.0', '>=')
  502. && extension_loaded('openssl') && isset($this->esmtp['STARTTLS'])
  503. && strncasecmp($this->host, 'ssl://', 6) !== 0
  504. ) {
  505. /* Start the TLS connection attempt. */
  506. if (PEAR::isError($result = $this->put('STARTTLS'))) {
  507. return $result;
  508. }
  509. if (PEAR::isError($result = $this->parseResponse(220))) {
  510. return $result;
  511. }
  512. if (isset($this->socket_options['ssl']['crypto_method'])) {
  513. $crypto_method = $this->socket_options['ssl']['crypto_method'];
  514. } else {
  515. /* STREAM_CRYPTO_METHOD_TLS_ANY_CLIENT constant does not exist
  516. * and STREAM_CRYPTO_METHOD_SSLv23_CLIENT constant is
  517. * inconsistent across PHP versions. */
  518. $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT
  519. | @STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  520. | @STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
  521. }
  522. if (PEAR::isError($result = $this->socket->enableCrypto(true, $crypto_method))) {
  523. return $result;
  524. } elseif ($result !== true) {
  525. return PEAR::raiseError('STARTTLS failed');
  526. }
  527. /* Send EHLO again to recieve the AUTH string from the
  528. * SMTP server. */
  529. $this->negotiate();
  530. }
  531. if (empty($this->esmtp['AUTH'])) {
  532. return PEAR::raiseError('SMTP server does not support authentication');
  533. }
  534. /* If no method has been specified, get the name of the best
  535. * supported method advertised by the SMTP server. */
  536. if (empty($method)) {
  537. if (PEAR::isError($method = $this->getBestAuthMethod())) {
  538. /* Return the PEAR_Error object from _getBestAuthMethod(). */
  539. return $method;
  540. }
  541. } else {
  542. $method = strtoupper($method);
  543. if (!array_key_exists($method, $this->auth_methods)) {
  544. return PEAR::raiseError("$method is not a supported authentication method");
  545. }
  546. }
  547. if (!isset($this->auth_methods[$method])) {
  548. return PEAR::raiseError("$method is not a supported authentication method");
  549. }
  550. if (!is_callable($this->auth_methods[$method], false)) {
  551. return PEAR::raiseError("$method authentication method cannot be called");
  552. }
  553. if (is_array($this->auth_methods[$method])) {
  554. list($object, $method) = $this->auth_methods[$method];
  555. $result = $object->{$method}($uid, $pwd, $authz, $this);
  556. } else {
  557. $func = $this->auth_methods[$method];
  558. $result = $func($uid, $pwd, $authz, $this);
  559. }
  560. /* If an error was encountered, return the PEAR_Error object. */
  561. if (PEAR::isError($result)) {
  562. return $result;
  563. }
  564. return true;
  565. }
  566. /**
  567. * Add a new authentication method.
  568. *
  569. * @param string $name The authentication method name (e.g. 'PLAIN')
  570. * @param mixed $callback The authentication callback (given as the name of a
  571. * function or as an (object, method name) array).
  572. * @param bool $prepend Should the new method be prepended to the list of
  573. * available methods? This is the default behavior,
  574. * giving the new method the highest priority.
  575. *
  576. * @return mixed True on success or a PEAR_Error object on failure.
  577. *
  578. * @since 1.6.0
  579. */
  580. public function setAuthMethod($name, $callback, $prepend = true)
  581. {
  582. if (!is_string($name)) {
  583. return PEAR::raiseError('Method name is not a string');
  584. }
  585. if (!is_string($callback) && !is_array($callback)) {
  586. return PEAR::raiseError('Method callback must be string or array');
  587. }
  588. if (is_array($callback)) {
  589. if (!is_object($callback[0]) || !is_string($callback[1])) {
  590. return PEAR::raiseError('Bad mMethod callback array');
  591. }
  592. }
  593. if ($prepend) {
  594. $this->auth_methods = array_merge(
  595. array($name => $callback), $this->auth_methods
  596. );
  597. } else {
  598. $this->auth_methods[$name] = $callback;
  599. }
  600. return true;
  601. }
  602. /**
  603. * Authenticates the user using the DIGEST-MD5 method.
  604. *
  605. * @param string $uid The userid to authenticate as.
  606. * @param string $pwd The password to authenticate with.
  607. * @param string $authz The optional authorization proxy identifier.
  608. *
  609. * @return mixed Returns a PEAR_Error with an error message on any
  610. * kind of failure, or true on success.
  611. * @since 1.1.0
  612. */
  613. protected function authDigestMD5($uid, $pwd, $authz = '')
  614. {
  615. if (PEAR::isError($error = $this->put('AUTH', 'DIGEST-MD5'))) {
  616. return $error;
  617. }
  618. /* 334: Continue authentication request */
  619. if (PEAR::isError($error = $this->parseResponse(334))) {
  620. /* 503: Error: already authenticated */
  621. if ($this->code === 503) {
  622. return true;
  623. }
  624. return $error;
  625. }
  626. $digest = Auth_SASL::factory('digest-md5');
  627. $challenge = base64_decode($this->arguments[0]);
  628. $auth_str = base64_encode(
  629. $digest->getResponse($uid, $pwd, $challenge, $this->host, "smtp", $authz)
  630. );
  631. if (PEAR::isError($error = $this->put($auth_str))) {
  632. return $error;
  633. }
  634. /* 334: Continue authentication request */
  635. if (PEAR::isError($error = $this->parseResponse(334))) {
  636. return $error;
  637. }
  638. /* We don't use the protocol's third step because SMTP doesn't
  639. * allow subsequent authentication, so we just silently ignore
  640. * it. */
  641. if (PEAR::isError($error = $this->put(''))) {
  642. return $error;
  643. }
  644. /* 235: Authentication successful */
  645. if (PEAR::isError($error = $this->parseResponse(235))) {
  646. return $error;
  647. }
  648. }
  649. /**
  650. * Authenticates the user using the CRAM-MD5 method.
  651. *
  652. * @param string $uid The userid to authenticate as.
  653. * @param string $pwd The password to authenticate with.
  654. * @param string $authz The optional authorization proxy identifier.
  655. *
  656. * @return mixed Returns a PEAR_Error with an error message on any
  657. * kind of failure, or true on success.
  658. * @since 1.1.0
  659. */
  660. protected function authCRAMMD5($uid, $pwd, $authz = '')
  661. {
  662. if (PEAR::isError($error = $this->put('AUTH', 'CRAM-MD5'))) {
  663. return $error;
  664. }
  665. /* 334: Continue authentication request */
  666. if (PEAR::isError($error = $this->parseResponse(334))) {
  667. /* 503: Error: already authenticated */
  668. if ($this->code === 503) {
  669. return true;
  670. }
  671. return $error;
  672. }
  673. $challenge = base64_decode($this->arguments[0]);
  674. $cram = Auth_SASL::factory('cram-md5');
  675. $auth_str = base64_encode($cram->getResponse($uid, $pwd, $challenge));
  676. if (PEAR::isError($error = $this->put($auth_str))) {
  677. return $error;
  678. }
  679. /* 235: Authentication successful */
  680. if (PEAR::isError($error = $this->parseResponse(235))) {
  681. return $error;
  682. }
  683. }
  684. /**
  685. * Authenticates the user using the LOGIN method.
  686. *
  687. * @param string $uid The userid to authenticate as.
  688. * @param string $pwd The password to authenticate with.
  689. * @param string $authz The optional authorization proxy identifier.
  690. *
  691. * @return mixed Returns a PEAR_Error with an error message on any
  692. * kind of failure, or true on success.
  693. * @since 1.1.0
  694. */
  695. protected function authLogin($uid, $pwd, $authz = '')
  696. {
  697. if (PEAR::isError($error = $this->put('AUTH', 'LOGIN'))) {
  698. return $error;
  699. }
  700. /* 334: Continue authentication request */
  701. if (PEAR::isError($error = $this->parseResponse(334))) {
  702. /* 503: Error: already authenticated */
  703. if ($this->code === 503) {
  704. return true;
  705. }
  706. return $error;
  707. }
  708. if (PEAR::isError($error = $this->put(base64_encode($uid)))) {
  709. return $error;
  710. }
  711. /* 334: Continue authentication request */
  712. if (PEAR::isError($error = $this->parseResponse(334))) {
  713. return $error;
  714. }
  715. if (PEAR::isError($error = $this->put(base64_encode($pwd)))) {
  716. return $error;
  717. }
  718. /* 235: Authentication successful */
  719. if (PEAR::isError($error = $this->parseResponse(235))) {
  720. return $error;
  721. }
  722. return true;
  723. }
  724. /**
  725. * Authenticates the user using the PLAIN method.
  726. *
  727. * @param string $uid The userid to authenticate as.
  728. * @param string $pwd The password to authenticate with.
  729. * @param string $authz The optional authorization proxy identifier.
  730. *
  731. * @return mixed Returns a PEAR_Error with an error message on any
  732. * kind of failure, or true on success.
  733. * @since 1.1.0
  734. */
  735. protected function authPlain($uid, $pwd, $authz = '')
  736. {
  737. if (PEAR::isError($error = $this->put('AUTH', 'PLAIN'))) {
  738. return $error;
  739. }
  740. /* 334: Continue authentication request */
  741. if (PEAR::isError($error = $this->parseResponse(334))) {
  742. /* 503: Error: already authenticated */
  743. if ($this->code === 503) {
  744. return true;
  745. }
  746. return $error;
  747. }
  748. $auth_str = base64_encode($authz . chr(0) . $uid . chr(0) . $pwd);
  749. if (PEAR::isError($error = $this->put($auth_str))) {
  750. return $error;
  751. }
  752. /* 235: Authentication successful */
  753. if (PEAR::isError($error = $this->parseResponse(235))) {
  754. return $error;
  755. }
  756. return true;
  757. }
  758. /**
  759. * Send the HELO command.
  760. *
  761. * @param string $domain The domain name to say we are.
  762. *
  763. * @return mixed Returns a PEAR_Error with an error message on any
  764. * kind of failure, or true on success.
  765. * @since 1.0
  766. */
  767. public function helo($domain)
  768. {
  769. if (PEAR::isError($error = $this->put('HELO', $domain))) {
  770. return $error;
  771. }
  772. if (PEAR::isError($error = $this->parseResponse(250))) {
  773. return $error;
  774. }
  775. return true;
  776. }
  777. /**
  778. * Return the list of SMTP service extensions advertised by the server.
  779. *
  780. * @return array The list of SMTP service extensions.
  781. * @since 1.3
  782. */
  783. public function getServiceExtensions()
  784. {
  785. return $this->esmtp;
  786. }
  787. /**
  788. * Send the MAIL FROM: command.
  789. *
  790. * @param string $sender The sender (reverse path) to set.
  791. * @param string $params String containing additional MAIL parameters,
  792. * such as the NOTIFY flags defined by RFC 1891
  793. * or the VERP protocol.
  794. *
  795. * If $params is an array, only the 'verp' option
  796. * is supported. If 'verp' is true, the XVERP
  797. * parameter is appended to the MAIL command.
  798. * If the 'verp' value is a string, the full
  799. * XVERP=value parameter is appended.
  800. *
  801. * @return mixed Returns a PEAR_Error with an error message on any
  802. * kind of failure, or true on success.
  803. * @since 1.0
  804. */
  805. public function mailFrom($sender, $params = null)
  806. {
  807. $args = "FROM:<$sender>";
  808. /* Support the deprecated array form of $params. */
  809. if (is_array($params) && isset($params['verp'])) {
  810. if ($params['verp'] === true) {
  811. $args .= ' XVERP';
  812. } elseif (trim($params['verp'])) {
  813. $args .= ' XVERP=' . $params['verp'];
  814. }
  815. } elseif (is_string($params) && !empty($params)) {
  816. $args .= ' ' . $params;
  817. }
  818. if (PEAR::isError($error = $this->put('MAIL', $args))) {
  819. return $error;
  820. }
  821. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  822. return $error;
  823. }
  824. return true;
  825. }
  826. /**
  827. * Send the RCPT TO: command.
  828. *
  829. * @param string $recipient The recipient (forward path) to add.
  830. * @param string $params String containing additional RCPT parameters,
  831. * such as the NOTIFY flags defined by RFC 1891.
  832. *
  833. * @return mixed Returns a PEAR_Error with an error message on any
  834. * kind of failure, or true on success.
  835. *
  836. * @since 1.0
  837. */
  838. public function rcptTo($recipient, $params = null)
  839. {
  840. $args = "TO:<$recipient>";
  841. if (is_string($params)) {
  842. $args .= ' ' . $params;
  843. }
  844. if (PEAR::isError($error = $this->put('RCPT', $args))) {
  845. return $error;
  846. }
  847. if (PEAR::isError($error = $this->parseResponse(array(250, 251), $this->pipelining))) {
  848. return $error;
  849. }
  850. return true;
  851. }
  852. /**
  853. * Quote the data so that it meets SMTP standards.
  854. *
  855. * This is provided as a separate public function to facilitate
  856. * easier overloading for the cases where it is desirable to
  857. * customize the quoting behavior.
  858. *
  859. * @param string &$data The message text to quote. The string must be passed
  860. * by reference, and the text will be modified in place.
  861. *
  862. * @since 1.2
  863. */
  864. public function quotedata(&$data)
  865. {
  866. /* Because a single leading period (.) signifies an end to the
  867. * data, legitimate leading periods need to be "doubled" ('..'). */
  868. $data = preg_replace('/^\./m', '..', $data);
  869. /* Change Unix (\n) and Mac (\r) linefeeds into CRLF's (\r\n). */
  870. $data = preg_replace('/(?:\r\n|\n|\r(?!\n))/', "\r\n", $data);
  871. }
  872. /**
  873. * Send the DATA command.
  874. *
  875. * @param mixed $data The message data, either as a string or an open
  876. * file resource.
  877. * @param string $headers The message headers. If $headers is provided,
  878. * $data is assumed to contain only body data.
  879. *
  880. * @return mixed Returns a PEAR_Error with an error message on any
  881. * kind of failure, or true on success.
  882. * @since 1.0
  883. */
  884. public function data($data, $headers = null)
  885. {
  886. /* Verify that $data is a supported type. */
  887. if (!is_string($data) && !is_resource($data)) {
  888. return PEAR::raiseError('Expected a string or file resource');
  889. }
  890. /* Start by considering the size of the optional headers string. We
  891. * also account for the addition 4 character "\r\n\r\n" separator
  892. * sequence. */
  893. $size = (is_null($headers)) ? 0 : strlen($headers) + 4;
  894. if (is_resource($data)) {
  895. $stat = fstat($data);
  896. if ($stat === false) {
  897. return PEAR::raiseError('Failed to get file size');
  898. }
  899. $size += $stat['size'];
  900. } else {
  901. $size += strlen($data);
  902. }
  903. /* RFC 1870, section 3, subsection 3 states "a value of zero indicates
  904. * that no fixed maximum message size is in force". Furthermore, it
  905. * says that if "the parameter is omitted no information is conveyed
  906. * about the server's fixed maximum message size". */
  907. $limit = (isset($this->esmtp['SIZE'])) ? $this->esmtp['SIZE'] : 0;
  908. if ($limit > 0 && $size >= $limit) {
  909. $this->disconnect();
  910. return PEAR::raiseError('Message size exceeds server limit');
  911. }
  912. /* Initiate the DATA command. */
  913. if (PEAR::isError($error = $this->put('DATA'))) {
  914. return $error;
  915. }
  916. if (PEAR::isError($error = $this->parseResponse(354))) {
  917. return $error;
  918. }
  919. /* If we have a separate headers string, send it first. */
  920. if (!is_null($headers)) {
  921. $this->quotedata($headers);
  922. if (PEAR::isError($result = $this->send($headers . "\r\n\r\n"))) {
  923. return $result;
  924. }
  925. /* Subtract the headers size now that they've been sent. */
  926. $size -= strlen($headers) + 4;
  927. }
  928. /* Now we can send the message body data. */
  929. if (is_resource($data)) {
  930. /* Stream the contents of the file resource out over our socket
  931. * connection, line by line. Each line must be run through the
  932. * quoting routine. */
  933. while (strlen($line = fread($data, 8192)) > 0) {
  934. /* If the last character is an newline, we need to grab the
  935. * next character to check to see if it is a period. */
  936. while (!feof($data)) {
  937. $char = fread($data, 1);
  938. $line .= $char;
  939. if ($char != "\n") {
  940. break;
  941. }
  942. }
  943. $this->quotedata($line);
  944. if (PEAR::isError($result = $this->send($line))) {
  945. return $result;
  946. }
  947. }
  948. $last = $line;
  949. } else {
  950. /*
  951. * Break up the data by sending one chunk (up to 512k) at a time.
  952. * This approach reduces our peak memory usage.
  953. */
  954. for ($offset = 0; $offset < $size;) {
  955. $end = $offset + 512000;
  956. /*
  957. * Ensure we don't read beyond our data size or span multiple
  958. * lines. quotedata() can't properly handle character data
  959. * that's split across two line break boundaries.
  960. */
  961. if ($end >= $size) {
  962. $end = $size;
  963. } else {
  964. for (; $end < $size; $end++) {
  965. if ($data[$end] != "\n") {
  966. break;
  967. }
  968. }
  969. }
  970. /* Extract our chunk and run it through the quoting routine. */
  971. $chunk = substr($data, $offset, $end - $offset);
  972. $this->quotedata($chunk);
  973. /* If we run into a problem along the way, abort. */
  974. if (PEAR::isError($result = $this->send($chunk))) {
  975. return $result;
  976. }
  977. /* Advance the offset to the end of this chunk. */
  978. $offset = $end;
  979. }
  980. $last = $chunk;
  981. }
  982. /* Don't add another CRLF sequence if it's already in the data */
  983. $terminator = (substr($last, -2) == "\r\n" ? '' : "\r\n") . ".\r\n";
  984. /* Finally, send the DATA terminator sequence. */
  985. if (PEAR::isError($result = $this->send($terminator))) {
  986. return $result;
  987. }
  988. /* Verify that the data was successfully received by the server. */
  989. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  990. return $error;
  991. }
  992. return true;
  993. }
  994. /**
  995. * Send the SEND FROM: command.
  996. *
  997. * @param string $path The reverse path to send.
  998. *
  999. * @return mixed Returns a PEAR_Error with an error message on any
  1000. * kind of failure, or true on success.
  1001. * @since 1.2.6
  1002. */
  1003. public function sendFrom($path)
  1004. {
  1005. if (PEAR::isError($error = $this->put('SEND', "FROM:<$path>"))) {
  1006. return $error;
  1007. }
  1008. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1009. return $error;
  1010. }
  1011. return true;
  1012. }
  1013. /**
  1014. * Send the SOML FROM: command.
  1015. *
  1016. * @param string $path The reverse path to send.
  1017. *
  1018. * @return mixed Returns a PEAR_Error with an error message on any
  1019. * kind of failure, or true on success.
  1020. * @since 1.2.6
  1021. */
  1022. public function somlFrom($path)
  1023. {
  1024. if (PEAR::isError($error = $this->put('SOML', "FROM:<$path>"))) {
  1025. return $error;
  1026. }
  1027. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1028. return $error;
  1029. }
  1030. return true;
  1031. }
  1032. /**
  1033. * Send the SAML FROM: command.
  1034. *
  1035. * @param string $path The reverse path to send.
  1036. *
  1037. * @return mixed Returns a PEAR_Error with an error message on any
  1038. * kind of failure, or true on success.
  1039. * @since 1.2.6
  1040. */
  1041. public function samlFrom($path)
  1042. {
  1043. if (PEAR::isError($error = $this->put('SAML', "FROM:<$path>"))) {
  1044. return $error;
  1045. }
  1046. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1047. return $error;
  1048. }
  1049. return true;
  1050. }
  1051. /**
  1052. * Send the RSET command.
  1053. *
  1054. * @return mixed Returns a PEAR_Error with an error message on any
  1055. * kind of failure, or true on success.
  1056. * @since 1.0
  1057. */
  1058. public function rset()
  1059. {
  1060. if (PEAR::isError($error = $this->put('RSET'))) {
  1061. return $error;
  1062. }
  1063. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1064. return $error;
  1065. }
  1066. return true;
  1067. }
  1068. /**
  1069. * Send the VRFY command.
  1070. *
  1071. * @param string $string The string to verify
  1072. *
  1073. * @return mixed Returns a PEAR_Error with an error message on any
  1074. * kind of failure, or true on success.
  1075. * @since 1.0
  1076. */
  1077. public function vrfy($string)
  1078. {
  1079. /* Note: 251 is also a valid response code */
  1080. if (PEAR::isError($error = $this->put('VRFY', $string))) {
  1081. return $error;
  1082. }
  1083. if (PEAR::isError($error = $this->parseResponse(array(250, 252)))) {
  1084. return $error;
  1085. }
  1086. return true;
  1087. }
  1088. /**
  1089. * Send the NOOP command.
  1090. *
  1091. * @return mixed Returns a PEAR_Error with an error message on any
  1092. * kind of failure, or true on success.
  1093. * @since 1.0
  1094. */
  1095. public function noop()
  1096. {
  1097. if (PEAR::isError($error = $this->put('NOOP'))) {
  1098. return $error;
  1099. }
  1100. if (PEAR::isError($error = $this->parseResponse(250))) {
  1101. return $error;
  1102. }
  1103. return true;
  1104. }
  1105. /**
  1106. * Backwards-compatibility method. identifySender()'s functionality is
  1107. * now handled internally.
  1108. *
  1109. * @return boolean This method always return true.
  1110. *
  1111. * @since 1.0
  1112. */
  1113. public function identifySender()
  1114. {
  1115. return true;
  1116. }
  1117. }