composer package updates
[openemr.git] / vendor / zendframework / zend-mail / src / Protocol / Smtp.php
blob5ebfd283b3cd57b9b15d7047b576d3f68bbf2f6c
1 <?php
2 /**
3 * @see https://github.com/zendframework/zend-mail for the canonical source repository
4 * @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com)
5 * @license https://github.com/zendframework/zend-mail/blob/master/LICENSE.md New BSD License
6 */
8 namespace Zend\Mail\Protocol;
10 /**
11 * SMTP implementation of Zend\Mail\Protocol\AbstractProtocol
13 * Minimum implementation according to RFC2821: EHLO, MAIL FROM, RCPT TO, DATA,
14 * RSET, NOOP, QUIT
16 class Smtp extends AbstractProtocol
18 use ProtocolTrait;
20 /**
21 * The transport method for the socket
23 * @var string
25 protected $transport = 'tcp';
27 /**
28 * Indicates that a session is requested to be secure
30 * @var string
32 protected $secure;
34 /**
35 * Indicates an smtp session has been started by the HELO command
37 * @var bool
39 protected $sess = false;
41 /**
42 * Indicates an smtp AUTH has been issued and authenticated
44 * @var bool
46 protected $auth = false;
48 /**
49 * Indicates a MAIL command has been issued
51 * @var bool
53 protected $mail = false;
55 /**
56 * Indicates one or more RCTP commands have been issued
58 * @var bool
60 protected $rcpt = false;
62 /**
63 * Indicates that DATA has been issued and sent
65 * @var bool
67 protected $data = null;
69 /**
70 * Whether or not send QUIT command
72 * @var bool
74 protected $useCompleteQuit = true;
76 /**
77 * Constructor.
79 * The first argument may be an array of all options. If so, it must include
80 * the 'host' and 'port' keys in order to ensure that all required values
81 * are present.
83 * @param string|array $host
84 * @param null|int $port
85 * @param null|array $config
86 * @throws Exception\InvalidArgumentException
88 public function __construct($host = '127.0.0.1', $port = null, array $config = null)
90 // Did we receive a configuration array?
91 if (is_array($host)) {
92 // Merge config array with principal array, if provided
93 if (is_array($config)) {
94 $config = array_replace_recursive($host, $config);
95 } else {
96 $config = $host;
99 // Look for a host key; if none found, use default value
100 if (isset($config['host'])) {
101 $host = $config['host'];
102 } else {
103 $host = '127.0.0.1';
106 // Look for a port key; if none found, use default value
107 if (isset($config['port'])) {
108 $port = $config['port'];
109 } else {
110 $port = null;
114 // If we don't have a config array, initialize it
115 if (null === $config) {
116 $config = [];
119 if (isset($config['ssl'])) {
120 switch (strtolower($config['ssl'])) {
121 case 'tls':
122 $this->secure = 'tls';
123 break;
125 case 'ssl':
126 $this->transport = 'ssl';
127 $this->secure = 'ssl';
128 if ($port === null) {
129 $port = 465;
131 break;
133 case '':
134 // fall-through
135 case 'none':
136 break;
138 default:
139 throw new Exception\InvalidArgumentException($config['ssl'] . ' is unsupported SSL type');
143 if (array_key_exists('use_complete_quit', $config)) {
144 $this->setUseCompleteQuit($config['use_complete_quit']);
147 // If no port has been specified then check the master PHP ini file. Defaults to 25 if the ini setting is null.
148 if ($port === null) {
149 if (($port = ini_get('smtp_port')) == '') {
150 $port = 25;
154 parent::__construct($host, $port);
158 * Set whether or not send QUIT command
160 * @param bool $useCompleteQuit use complete quit
161 * @return bool
163 public function setUseCompleteQuit($useCompleteQuit)
165 return $this->useCompleteQuit = (bool) $useCompleteQuit;
169 * Whether or not send QUIT command
171 * @return bool
173 public function useCompleteQuit()
175 return $this->useCompleteQuit;
179 * Connect to the server with the parameters given in the constructor.
181 * @return bool
183 public function connect()
185 return $this->_connect($this->transport . '://' . $this->host . ':' . $this->port);
190 * Initiate HELO/EHLO sequence and set flag to indicate valid smtp session
192 * @param string $host The client hostname or IP address (default: 127.0.0.1)
193 * @throws Exception\RuntimeException
195 public function helo($host = '127.0.0.1')
197 // Respect RFC 2821 and disallow HELO attempts if session is already initiated.
198 if ($this->sess === true) {
199 throw new Exception\RuntimeException('Cannot issue HELO to existing session');
202 // Validate client hostname
203 if (! $this->validHost->isValid($host)) {
204 throw new Exception\RuntimeException(implode(', ', $this->validHost->getMessages()));
207 // Initiate helo sequence
208 $this->_expect(220, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
209 $this->ehlo($host);
211 // If a TLS session is required, commence negotiation
212 if ($this->secure == 'tls') {
213 $this->_send('STARTTLS');
214 $this->_expect(220, 180);
215 if (! stream_socket_enable_crypto($this->socket, true, $this->getCryptoMethod())) {
216 throw new Exception\RuntimeException('Unable to connect via TLS');
218 $this->ehlo($host);
221 $this->startSession();
222 $this->auth();
226 * Returns the perceived session status
228 * @return bool
230 public function hasSession()
232 return $this->sess;
236 * Send EHLO or HELO depending on capabilities of smtp host
238 * @param string $host The client hostname or IP address (default: 127.0.0.1)
239 * @throws \Exception|Exception\ExceptionInterface
241 protected function ehlo($host)
243 // Support for older, less-compliant remote servers. Tries multiple attempts of EHLO or HELO.
244 try {
245 $this->_send('EHLO ' . $host);
246 $this->_expect(250, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
247 } catch (Exception\ExceptionInterface $e) {
248 $this->_send('HELO ' . $host);
249 $this->_expect(250, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
255 * Issues MAIL command
257 * @param string $from Sender mailbox
258 * @throws Exception\RuntimeException
260 public function mail($from)
262 if ($this->sess !== true) {
263 throw new Exception\RuntimeException('A valid session has not been started');
266 $this->_send('MAIL FROM:<' . $from . '>');
267 $this->_expect(250, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
269 // Set mail to true, clear recipients and any existing data flags as per 4.1.1.2 of RFC 2821
270 $this->mail = true;
271 $this->rcpt = false;
272 $this->data = false;
277 * Issues RCPT command
279 * @param string $to Receiver(s) mailbox
280 * @throws Exception\RuntimeException
282 public function rcpt($to)
284 if ($this->mail !== true) {
285 throw new Exception\RuntimeException('No sender reverse path has been supplied');
288 // Set rcpt to true, as per 4.1.1.3 of RFC 2821
289 $this->_send('RCPT TO:<' . $to . '>');
290 $this->_expect([250, 251], 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
291 $this->rcpt = true;
296 * Issues DATA command
298 * @param string $data
299 * @throws Exception\RuntimeException
301 public function data($data)
303 // Ensure recipients have been set
304 if ($this->rcpt !== true) { // Per RFC 2821 3.3 (page 18)
305 throw new Exception\RuntimeException('No recipient forward path has been supplied');
308 $this->_send('DATA');
309 $this->_expect(354, 120); // Timeout set for 2 minutes as per RFC 2821 4.5.3.2
311 if (($fp = fopen("php://temp", "r+")) === false) {
312 throw new Exception\RuntimeException('cannot fopen');
314 if (fwrite($fp, $data) === false) {
315 throw new Exception\RuntimeException('cannot fwrite');
317 unset($data);
318 rewind($fp);
320 // max line length is 998 char + \r\n = 1000
321 while (($line = stream_get_line($fp, 1000, "\n")) !== false) {
322 $line = rtrim($line, "\r");
323 if (isset($line[0]) && $line[0] === '.') {
324 // Escape lines prefixed with a '.'
325 $line = '.' . $line;
327 $this->_send($line);
329 fclose($fp);
331 $this->_send('.');
332 $this->_expect(250, 600); // Timeout set for 10 minutes as per RFC 2821 4.5.3.2
333 $this->data = true;
338 * Issues the RSET command end validates answer
340 * Can be used to restore a clean smtp communication state when a
341 * transaction has been cancelled or commencing a new transaction.
343 public function rset()
345 $this->_send('RSET');
346 // MS ESMTP doesn't follow RFC, see [ZF-1377]
347 $this->_expect([250, 220]);
349 $this->mail = false;
350 $this->rcpt = false;
351 $this->data = false;
355 * Issues the NOOP command end validates answer
357 * Not used by Zend\Mail, could be used to keep a connection alive or check if it is still open.
360 public function noop()
362 $this->_send('NOOP');
363 $this->_expect(250, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
367 * Issues the VRFY command end validates answer
369 * Not used by Zend\Mail.
371 * @param string $user User Name or eMail to verify
373 public function vrfy($user)
375 $this->_send('VRFY ' . $user);
376 $this->_expect([250, 251, 252], 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
380 * Issues the QUIT command and clears the current session
383 public function quit()
385 if ($this->sess) {
386 $this->auth = false;
388 if ($this->useCompleteQuit()) {
389 $this->_send('QUIT');
390 $this->_expect(221, 300); // Timeout set for 5 minutes as per RFC 2821 4.5.3.2
393 $this->stopSession();
398 * Default authentication method
400 * This default method is implemented by AUTH adapters to properly authenticate to a remote host.
402 * @throws Exception\RuntimeException
404 public function auth()
406 if ($this->auth === true) {
407 throw new Exception\RuntimeException('Already authenticated for this session');
412 * Closes connection
415 public function disconnect()
417 $this->_disconnect();
420 // @codingStandardsIgnoreStart
422 * Disconnect from remote host and free resource
424 protected function _disconnect()
426 // @codingStandardsIgnoreEnd
428 // Make sure the session gets closed
429 $this->quit();
430 parent::_disconnect();
434 * Start mail session
437 protected function startSession()
439 $this->sess = true;
443 * Stop mail session
446 protected function stopSession()
448 $this->sess = false;