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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. $auth_sasl = new Auth_SASL;
  627. $digest = $auth_sasl->factory('digest-md5');
  628. $challenge = base64_decode($this->arguments[0]);
  629. $auth_str = base64_encode(
  630. $digest->getResponse($uid, $pwd, $challenge, $this->host, "smtp", $authz)
  631. );
  632. if (PEAR::isError($error = $this->put($auth_str))) {
  633. return $error;
  634. }
  635. /* 334: Continue authentication request */
  636. if (PEAR::isError($error = $this->parseResponse(334))) {
  637. return $error;
  638. }
  639. /* We don't use the protocol's third step because SMTP doesn't
  640. * allow subsequent authentication, so we just silently ignore
  641. * it. */
  642. if (PEAR::isError($error = $this->put(''))) {
  643. return $error;
  644. }
  645. /* 235: Authentication successful */
  646. if (PEAR::isError($error = $this->parseResponse(235))) {
  647. return $error;
  648. }
  649. }
  650. /**
  651. * Authenticates the user using the CRAM-MD5 method.
  652. *
  653. * @param string $uid The userid to authenticate as.
  654. * @param string $pwd The password to authenticate with.
  655. * @param string $authz The optional authorization proxy identifier.
  656. *
  657. * @return mixed Returns a PEAR_Error with an error message on any
  658. * kind of failure, or true on success.
  659. * @since 1.1.0
  660. */
  661. protected function authCRAMMD5($uid, $pwd, $authz = '')
  662. {
  663. if (PEAR::isError($error = $this->put('AUTH', 'CRAM-MD5'))) {
  664. return $error;
  665. }
  666. /* 334: Continue authentication request */
  667. if (PEAR::isError($error = $this->parseResponse(334))) {
  668. /* 503: Error: already authenticated */
  669. if ($this->code === 503) {
  670. return true;
  671. }
  672. return $error;
  673. }
  674. $auth_sasl = new Auth_SASL;
  675. $challenge = base64_decode($this->arguments[0]);
  676. $cram = $auth_sasl->factory('cram-md5');
  677. $auth_str = base64_encode($cram->getResponse($uid, $pwd, $challenge));
  678. if (PEAR::isError($error = $this->put($auth_str))) {
  679. return $error;
  680. }
  681. /* 235: Authentication successful */
  682. if (PEAR::isError($error = $this->parseResponse(235))) {
  683. return $error;
  684. }
  685. }
  686. /**
  687. * Authenticates the user using the LOGIN method.
  688. *
  689. * @param string $uid The userid to authenticate as.
  690. * @param string $pwd The password to authenticate with.
  691. * @param string $authz The optional authorization proxy identifier.
  692. *
  693. * @return mixed Returns a PEAR_Error with an error message on any
  694. * kind of failure, or true on success.
  695. * @since 1.1.0
  696. */
  697. protected function authLogin($uid, $pwd, $authz = '')
  698. {
  699. if (PEAR::isError($error = $this->put('AUTH', 'LOGIN'))) {
  700. return $error;
  701. }
  702. /* 334: Continue authentication request */
  703. if (PEAR::isError($error = $this->parseResponse(334))) {
  704. /* 503: Error: already authenticated */
  705. if ($this->code === 503) {
  706. return true;
  707. }
  708. return $error;
  709. }
  710. if (PEAR::isError($error = $this->put(base64_encode($uid)))) {
  711. return $error;
  712. }
  713. /* 334: Continue authentication request */
  714. if (PEAR::isError($error = $this->parseResponse(334))) {
  715. return $error;
  716. }
  717. if (PEAR::isError($error = $this->put(base64_encode($pwd)))) {
  718. return $error;
  719. }
  720. /* 235: Authentication successful */
  721. if (PEAR::isError($error = $this->parseResponse(235))) {
  722. return $error;
  723. }
  724. return true;
  725. }
  726. /**
  727. * Authenticates the user using the PLAIN method.
  728. *
  729. * @param string $uid The userid to authenticate as.
  730. * @param string $pwd The password to authenticate with.
  731. * @param string $authz The optional authorization proxy identifier.
  732. *
  733. * @return mixed Returns a PEAR_Error with an error message on any
  734. * kind of failure, or true on success.
  735. * @since 1.1.0
  736. */
  737. protected function authPlain($uid, $pwd, $authz = '')
  738. {
  739. if (PEAR::isError($error = $this->put('AUTH', 'PLAIN'))) {
  740. return $error;
  741. }
  742. /* 334: Continue authentication request */
  743. if (PEAR::isError($error = $this->parseResponse(334))) {
  744. /* 503: Error: already authenticated */
  745. if ($this->code === 503) {
  746. return true;
  747. }
  748. return $error;
  749. }
  750. $auth_str = base64_encode($authz . chr(0) . $uid . chr(0) . $pwd);
  751. if (PEAR::isError($error = $this->put($auth_str))) {
  752. return $error;
  753. }
  754. /* 235: Authentication successful */
  755. if (PEAR::isError($error = $this->parseResponse(235))) {
  756. return $error;
  757. }
  758. return true;
  759. }
  760. /**
  761. * Send the HELO command.
  762. *
  763. * @param string $domain The domain name to say we are.
  764. *
  765. * @return mixed Returns a PEAR_Error with an error message on any
  766. * kind of failure, or true on success.
  767. * @since 1.0
  768. */
  769. public function helo($domain)
  770. {
  771. if (PEAR::isError($error = $this->put('HELO', $domain))) {
  772. return $error;
  773. }
  774. if (PEAR::isError($error = $this->parseResponse(250))) {
  775. return $error;
  776. }
  777. return true;
  778. }
  779. /**
  780. * Return the list of SMTP service extensions advertised by the server.
  781. *
  782. * @return array The list of SMTP service extensions.
  783. * @since 1.3
  784. */
  785. public function getServiceExtensions()
  786. {
  787. return $this->esmtp;
  788. }
  789. /**
  790. * Send the MAIL FROM: command.
  791. *
  792. * @param string $sender The sender (reverse path) to set.
  793. * @param string $params String containing additional MAIL parameters,
  794. * such as the NOTIFY flags defined by RFC 1891
  795. * or the VERP protocol.
  796. *
  797. * If $params is an array, only the 'verp' option
  798. * is supported. If 'verp' is true, the XVERP
  799. * parameter is appended to the MAIL command.
  800. * If the 'verp' value is a string, the full
  801. * XVERP=value parameter is appended.
  802. *
  803. * @return mixed Returns a PEAR_Error with an error message on any
  804. * kind of failure, or true on success.
  805. * @since 1.0
  806. */
  807. public function mailFrom($sender, $params = null)
  808. {
  809. $args = "FROM:<$sender>";
  810. /* Support the deprecated array form of $params. */
  811. if (is_array($params) && isset($params['verp'])) {
  812. if ($params['verp'] === true) {
  813. $args .= ' XVERP';
  814. } elseif (trim($params['verp'])) {
  815. $args .= ' XVERP=' . $params['verp'];
  816. }
  817. } elseif (is_string($params) && !empty($params)) {
  818. $args .= ' ' . $params;
  819. }
  820. if (PEAR::isError($error = $this->put('MAIL', $args))) {
  821. return $error;
  822. }
  823. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  824. return $error;
  825. }
  826. return true;
  827. }
  828. /**
  829. * Send the RCPT TO: command.
  830. *
  831. * @param string $recipient The recipient (forward path) to add.
  832. * @param string $params String containing additional RCPT parameters,
  833. * such as the NOTIFY flags defined by RFC 1891.
  834. *
  835. * @return mixed Returns a PEAR_Error with an error message on any
  836. * kind of failure, or true on success.
  837. *
  838. * @since 1.0
  839. */
  840. public function rcptTo($recipient, $params = null)
  841. {
  842. $args = "TO:<$recipient>";
  843. if (is_string($params)) {
  844. $args .= ' ' . $params;
  845. }
  846. if (PEAR::isError($error = $this->put('RCPT', $args))) {
  847. return $error;
  848. }
  849. if (PEAR::isError($error = $this->parseResponse(array(250, 251), $this->pipelining))) {
  850. return $error;
  851. }
  852. return true;
  853. }
  854. /**
  855. * Quote the data so that it meets SMTP standards.
  856. *
  857. * This is provided as a separate public function to facilitate
  858. * easier overloading for the cases where it is desirable to
  859. * customize the quoting behavior.
  860. *
  861. * @param string &$data The message text to quote. The string must be passed
  862. * by reference, and the text will be modified in place.
  863. *
  864. * @since 1.2
  865. */
  866. public function quotedata(&$data)
  867. {
  868. /* Because a single leading period (.) signifies an end to the
  869. * data, legitimate leading periods need to be "doubled" ('..'). */
  870. $data = preg_replace('/^\./m', '..', $data);
  871. /* Change Unix (\n) and Mac (\r) linefeeds into CRLF's (\r\n). */
  872. $data = preg_replace('/(?:\r\n|\n|\r(?!\n))/', "\r\n", $data);
  873. }
  874. /**
  875. * Send the DATA command.
  876. *
  877. * @param mixed $data The message data, either as a string or an open
  878. * file resource.
  879. * @param string $headers The message headers. If $headers is provided,
  880. * $data is assumed to contain only body data.
  881. *
  882. * @return mixed Returns a PEAR_Error with an error message on any
  883. * kind of failure, or true on success.
  884. * @since 1.0
  885. */
  886. public function data($data, $headers = null)
  887. {
  888. /* Verify that $data is a supported type. */
  889. if (!is_string($data) && !is_resource($data)) {
  890. return PEAR::raiseError('Expected a string or file resource');
  891. }
  892. /* Start by considering the size of the optional headers string. We
  893. * also account for the addition 4 character "\r\n\r\n" separator
  894. * sequence. */
  895. $size = $headers_size = (is_null($headers)) ? 0 : strlen($headers) + 4;
  896. if (is_resource($data)) {
  897. $stat = fstat($data);
  898. if ($stat === false) {
  899. return PEAR::raiseError('Failed to get file size');
  900. }
  901. $size += $stat['size'];
  902. } else {
  903. $size += strlen($data);
  904. }
  905. /* RFC 1870, section 3, subsection 3 states "a value of zero indicates
  906. * that no fixed maximum message size is in force". Furthermore, it
  907. * says that if "the parameter is omitted no information is conveyed
  908. * about the server's fixed maximum message size". */
  909. $limit = (isset($this->esmtp['SIZE'])) ? $this->esmtp['SIZE'] : 0;
  910. if ($limit > 0 && $size >= $limit) {
  911. $this->disconnect();
  912. return PEAR::raiseError('Message size exceeds server limit');
  913. }
  914. /* Initiate the DATA command. */
  915. if (PEAR::isError($error = $this->put('DATA'))) {
  916. return $error;
  917. }
  918. if (PEAR::isError($error = $this->parseResponse(354))) {
  919. return $error;
  920. }
  921. /* If we have a separate headers string, send it first. */
  922. if (!is_null($headers)) {
  923. $this->quotedata($headers);
  924. if (PEAR::isError($result = $this->send($headers . "\r\n\r\n"))) {
  925. return $result;
  926. }
  927. /* Subtract the headers size now that they've been sent. */
  928. $size -= $headers_size;
  929. }
  930. /* Now we can send the message body data. */
  931. if (is_resource($data)) {
  932. /* Stream the contents of the file resource out over our socket
  933. * connection, line by line. Each line must be run through the
  934. * quoting routine. */
  935. while (strlen($line = fread($data, 8192)) > 0) {
  936. /* If the last character is an newline, we need to grab the
  937. * next character to check to see if it is a period. */
  938. while (!feof($data)) {
  939. $char = fread($data, 1);
  940. $line .= $char;
  941. if ($char != "\n") {
  942. break;
  943. }
  944. }
  945. $this->quotedata($line);
  946. if (PEAR::isError($result = $this->send($line))) {
  947. return $result;
  948. }
  949. }
  950. $last = $line;
  951. } else {
  952. /*
  953. * Break up the data by sending one chunk (up to 512k) at a time.
  954. * This approach reduces our peak memory usage.
  955. */
  956. for ($offset = 0; $offset < $size;) {
  957. $end = $offset + 512000;
  958. /*
  959. * Ensure we don't read beyond our data size or span multiple
  960. * lines. quotedata() can't properly handle character data
  961. * that's split across two line break boundaries.
  962. */
  963. if ($end >= $size) {
  964. $end = $size;
  965. } else {
  966. for (; $end < $size; $end++) {
  967. if ($data[$end] != "\n") {
  968. break;
  969. }
  970. }
  971. }
  972. /* Extract our chunk and run it through the quoting routine. */
  973. $chunk = substr($data, $offset, $end - $offset);
  974. $this->quotedata($chunk);
  975. /* If we run into a problem along the way, abort. */
  976. if (PEAR::isError($result = $this->send($chunk))) {
  977. return $result;
  978. }
  979. /* Advance the offset to the end of this chunk. */
  980. $offset = $end;
  981. }
  982. $last = $chunk;
  983. }
  984. /* Don't add another CRLF sequence if it's already in the data */
  985. $terminator = (substr($last, -2) == "\r\n" ? '' : "\r\n") . ".\r\n";
  986. /* Finally, send the DATA terminator sequence. */
  987. if (PEAR::isError($result = $this->send($terminator))) {
  988. return $result;
  989. }
  990. /* Verify that the data was successfully received by the server. */
  991. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  992. return $error;
  993. }
  994. return true;
  995. }
  996. /**
  997. * Send the SEND FROM: command.
  998. *
  999. * @param string $path The reverse path to send.
  1000. *
  1001. * @return mixed Returns a PEAR_Error with an error message on any
  1002. * kind of failure, or true on success.
  1003. * @since 1.2.6
  1004. */
  1005. public function sendFrom($path)
  1006. {
  1007. if (PEAR::isError($error = $this->put('SEND', "FROM:<$path>"))) {
  1008. return $error;
  1009. }
  1010. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1011. return $error;
  1012. }
  1013. return true;
  1014. }
  1015. /**
  1016. * Send the SOML 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 somlFrom($path)
  1025. {
  1026. if (PEAR::isError($error = $this->put('SOML', "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 SAML 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 samlFrom($path)
  1044. {
  1045. if (PEAR::isError($error = $this->put('SAML', "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 RSET command.
  1055. *
  1056. * @return mixed Returns a PEAR_Error with an error message on any
  1057. * kind of failure, or true on success.
  1058. * @since 1.0
  1059. */
  1060. public function rset()
  1061. {
  1062. if (PEAR::isError($error = $this->put('RSET'))) {
  1063. return $error;
  1064. }
  1065. if (PEAR::isError($error = $this->parseResponse(250, $this->pipelining))) {
  1066. return $error;
  1067. }
  1068. return true;
  1069. }
  1070. /**
  1071. * Send the VRFY command.
  1072. *
  1073. * @param string $string The string to verify
  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 vrfy($string)
  1080. {
  1081. /* Note: 251 is also a valid response code */
  1082. if (PEAR::isError($error = $this->put('VRFY', $string))) {
  1083. return $error;
  1084. }
  1085. if (PEAR::isError($error = $this->parseResponse(array(250, 252)))) {
  1086. return $error;
  1087. }
  1088. return true;
  1089. }
  1090. /**
  1091. * Send the NOOP command.
  1092. *
  1093. * @return mixed Returns a PEAR_Error with an error message on any
  1094. * kind of failure, or true on success.
  1095. * @since 1.0
  1096. */
  1097. public function noop()
  1098. {
  1099. if (PEAR::isError($error = $this->put('NOOP'))) {
  1100. return $error;
  1101. }
  1102. if (PEAR::isError($error = $this->parseResponse(250))) {
  1103. return $error;
  1104. }
  1105. return true;
  1106. }
  1107. /**
  1108. * Backwards-compatibility method. identifySender()'s functionality is
  1109. * now handled internally.
  1110. *
  1111. * @return boolean This method always return true.
  1112. *
  1113. * @since 1.0
  1114. */
  1115. public function identifySender()
  1116. {
  1117. return true;
  1118. }
  1119. }