SMTP.php 42 KB

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