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