Passed
Push — master ( 2cf712...95a54c )
by Marcus
06:39
created

SMTP::connect()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 40
rs 8.3466
c 0
b 0
f 0
cc 7
nc 7
nop 4
1
<?php
2
/**
3
 * PHPMailer RFC821 SMTP email transport class.
4
 * PHP Version 5.5.
5
 *
6
 * @see       https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
7
 *
8
 * @author    Marcus Bointon (Synchro/coolbru) <[email protected]>
9
 * @author    Jim Jagielski (jimjag) <[email protected]>
10
 * @author    Andy Prevost (codeworxtech) <[email protected]>
11
 * @author    Brent R. Matzelle (original founder)
12
 * @copyright 2012 - 2019 Marcus Bointon
13
 * @copyright 2010 - 2012 Jim Jagielski
14
 * @copyright 2004 - 2009 Andy Prevost
15
 * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
16
 * @note      This program is distributed in the hope that it will be useful - WITHOUT
17
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18
 * FITNESS FOR A PARTICULAR PURPOSE.
19
 */
20
21
namespace PHPMailer\PHPMailer;
22
23
/**
24
 * PHPMailer RFC821 SMTP email transport class.
25
 * Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
26
 *
27
 * @author Chris Ryan
28
 * @author Marcus Bointon <[email protected]>
29
 */
30
class SMTP
31
{
32
    /**
33
     * The PHPMailer SMTP version number.
34
     *
35
     * @var string
36
     */
37
    const VERSION = '6.1.6';
38
39
    /**
40
     * SMTP line break constant.
41
     *
42
     * @var string
43
     */
44
    const LE = "\r\n";
45
46
    /**
47
     * The SMTP port to use if one is not specified.
48
     *
49
     * @var int
50
     */
51
    const DEFAULT_PORT = 25;
52
53
    /**
54
     * The maximum line length allowed by RFC 5321 section 4.5.3.1.6,
55
     * *excluding* a trailing CRLF break.
56
     *
57
     * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.6
58
     *
59
     * @var int
60
     */
61
    const MAX_LINE_LENGTH = 998;
62
63
    /**
64
     * The maximum line length allowed for replies in RFC 5321 section 4.5.3.1.5,
65
     * *including* a trailing CRLF line break.
66
     *
67
     * @see https://tools.ietf.org/html/rfc5321#section-4.5.3.1.5
68
     *
69
     * @var int
70
     */
71
    const MAX_REPLY_LENGTH = 512;
72
73
    /**
74
     * Debug level for no output.
75
     *
76
     * @var int
77
     */
78
    const DEBUG_OFF = 0;
79
80
    /**
81
     * Debug level to show client -> server messages.
82
     *
83
     * @var int
84
     */
85
    const DEBUG_CLIENT = 1;
86
87
    /**
88
     * Debug level to show client -> server and server -> client messages.
89
     *
90
     * @var int
91
     */
92
    const DEBUG_SERVER = 2;
93
94
    /**
95
     * Debug level to show connection status, client -> server and server -> client messages.
96
     *
97
     * @var int
98
     */
99
    const DEBUG_CONNECTION = 3;
100
101
    /**
102
     * Debug level to show all messages.
103
     *
104
     * @var int
105
     */
106
    const DEBUG_LOWLEVEL = 4;
107
108
    /**
109
     * Debug output level.
110
     * Options:
111
     * * self::DEBUG_OFF (`0`) No debug output, default
112
     * * self::DEBUG_CLIENT (`1`) Client commands
113
     * * self::DEBUG_SERVER (`2`) Client commands and server responses
114
     * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
115
     * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages.
116
     *
117
     * @var int
118
     */
119
    public $do_debug = self::DEBUG_OFF;
120
121
    /**
122
     * How to handle debug output.
123
     * Options:
124
     * * `echo` Output plain-text as-is, appropriate for CLI
125
     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
126
     * * `error_log` Output to error log as configured in php.ini
127
     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
128
     *
129
     * ```php
130
     * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
131
     * ```
132
     *
133
     * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
134
     * level output is used:
135
     *
136
     * ```php
137
     * $mail->Debugoutput = new myPsr3Logger;
138
     * ```
139
     *
140
     * @var string|callable|\Psr\Log\LoggerInterface
141
     */
142
    public $Debugoutput = 'echo';
143
144
    /**
145
     * Whether to use VERP.
146
     *
147
     * @see http://en.wikipedia.org/wiki/Variable_envelope_return_path
148
     * @see http://www.postfix.org/VERP_README.html Info on VERP
149
     *
150
     * @var bool
151
     */
152
    public $do_verp = false;
153
154
    /**
155
     * The timeout value for connection, in seconds.
156
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
157
     * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
158
     *
159
     * @see http://tools.ietf.org/html/rfc2821#section-4.5.3.2
160
     *
161
     * @var int
162
     */
163
    public $Timeout = 300;
164
165
    /**
166
     * How long to wait for commands to complete, in seconds.
167
     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
168
     *
169
     * @var int
170
     */
171
    public $Timelimit = 300;
172
173
    /**
174
     * Patterns to extract an SMTP transaction id from reply to a DATA command.
175
     * The first capture group in each regex will be used as the ID.
176
     * MS ESMTP returns the message ID, which may not be correct for internal tracking.
177
     *
178
     * @var string[]
179
     */
180
    protected $smtp_transaction_id_patterns = [
181
        'exim' => '/[\d]{3} OK id=(.*)/',
182
        'sendmail' => '/[\d]{3} 2.0.0 (.*) Message/',
183
        'postfix' => '/[\d]{3} 2.0.0 Ok: queued as (.*)/',
184
        'Microsoft_ESMTP' => '/[0-9]{3} 2.[\d].0 (.*)@(?:.*) Queued mail for delivery/',
185
        'Amazon_SES' => '/[\d]{3} Ok (.*)/',
186
        'SendGrid' => '/[\d]{3} Ok: queued as (.*)/',
187
        'CampaignMonitor' => '/[\d]{3} 2.0.0 OK:([a-zA-Z\d]{48})/',
188
    ];
189
190
    /**
191
     * The last transaction ID issued in response to a DATA command,
192
     * if one was detected.
193
     *
194
     * @var string|bool|null
195
     */
196
    protected $last_smtp_transaction_id;
197
198
    /**
199
     * The socket for the server connection.
200
     *
201
     * @var ?resource
202
     */
203
    protected $smtp_conn;
204
205
    /**
206
     * Error information, if any, for the last SMTP command.
207
     *
208
     * @var array
209
     */
210
    protected $error = [
211
        'error' => '',
212
        'detail' => '',
213
        'smtp_code' => '',
214
        'smtp_code_ex' => '',
215
    ];
216
217
    /**
218
     * The reply the server sent to us for HELO.
219
     * If null, no HELO string has yet been received.
220
     *
221
     * @var string|null
222
     */
223
    protected $helo_rply;
224
225
    /**
226
     * The set of SMTP extensions sent in reply to EHLO command.
227
     * Indexes of the array are extension names.
228
     * Value at index 'HELO' or 'EHLO' (according to command that was sent)
229
     * represents the server name. In case of HELO it is the only element of the array.
230
     * Other values can be boolean TRUE or an array containing extension options.
231
     * If null, no HELO/EHLO string has yet been received.
232
     *
233
     * @var array|null
234
     */
235
    protected $server_caps;
236
237
    /**
238
     * The most recent reply received from the server.
239
     *
240
     * @var string
241
     */
242
    protected $last_reply = '';
243
244
    /**
245
     * Output debugging info via a user-selected method.
246
     *
247
     * @param string $str   Debug string to output
248
     * @param int    $level The debug level of this message; see DEBUG_* constants
249
     *
250
     * @see SMTP::$Debugoutput
251
     * @see SMTP::$do_debug
252
     */
253
    protected function edebug($str, $level = 0)
254
    {
255
        if ($level > $this->do_debug) {
256
            return;
257
        }
258
        //Is this a PSR-3 logger?
259
        if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
260
            $this->Debugoutput->debug($str);
261
262
            return;
263
        }
264
        //Avoid clash with built-in function names
265
        if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
266
            call_user_func($this->Debugoutput, $str, $level);
267
268
            return;
269
        }
270
        switch ($this->Debugoutput) {
271
            case 'error_log':
272
                //Don't output, just log
273
                error_log($str);
274
                break;
275
            case 'html':
276
                //Cleans up output a bit for a better looking, HTML-safe output
277
                echo gmdate('Y-m-d H:i:s'), ' ', htmlentities(
278
                    preg_replace('/[\r\n]+/', '', $str),
279
                    ENT_QUOTES,
280
                    'UTF-8'
281
                ), "<br>\n";
282
                break;
283
            case 'echo':
284
            default:
285
                //Normalize line breaks
286
                $str = preg_replace('/\r\n|\r/m', "\n", $str);
287
                echo gmdate('Y-m-d H:i:s'),
288
                "\t",
289
                    //Trim trailing space
290
                trim(
291
                    //Indent for readability, except for trailing break
292
                    str_replace(
293
                        "\n",
294
                        "\n                   \t                  ",
295
                        trim($str)
296
                    )
297
                ),
298
                "\n";
299
        }
300
    }
301
302
    /**
303
     * Connect to an SMTP server.
304
     *
305
     * @param string $host    SMTP server IP or host name
306
     * @param int    $port    The port number to connect to
307
     * @param int    $timeout How long to wait for the connection to open
308
     * @param array  $options An array of options for stream_context_create()
309
     *
310
     * @return bool
311
     */
312
    public function connect($host, $port = null, $timeout = 30, $options = [])
313
    {
314
        // Clear errors to avoid confusion
315
        $this->setError('');
316
        // Make sure we are __not__ connected
317
        if ($this->connected()) {
318
            // Already connected, generate error
319
            $this->setError('Already connected to a server');
320
321
            return false;
322
        }
323
        if (empty($port)) {
324
            $port = self::DEFAULT_PORT;
325
        }
326
        // Connect to the SMTP server
327
        $this->edebug(
328
            "Connection: opening to $host:$port, timeout=$timeout, options=" .
329
            (count($options) > 0 ? var_export($options, true) : 'array()'),
330
            self::DEBUG_CONNECTION
331
        );
332
333
        $this->smtp_conn = $this->getSMTPConnection($host, $port, $timeout, $options);
334
335
        $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
336
        // SMTP server can take longer to respond, give longer timeout for first read
337
        // Windows does not have support for this timeout function
338
        if (strpos(PHP_OS, 'WIN') !== 0) {
339
            $max = (int) ini_get('max_execution_time');
340
            // Don't bother if unlimited
341
            if (0 !== $max && $timeout > $max) {
342
                @set_time_limit($timeout);
343
            }
344
            stream_set_timeout($this->smtp_conn, $timeout, 0);
345
        }
346
        // Get any announcement
347
        $announce = $this->get_lines();
348
        $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
349
350
        return true;
351
    }
352
353
    /**
354
     * Create connection to the SMTP server.
355
     *
356
     * @param string $host    SMTP server IP or host name
357
     * @param int    $port    The port number to connect to
358
     * @param int    $timeout How long to wait for the connection to open
359
     * @param array  $options An array of options for stream_context_create()
360
     *
361
     * @return false|resource
362
     */
363
    protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = [])
364
    {
365
        static $streamok;
366
        //This is enabled by default since 5.0.0 but some providers disable it
367
        //Check this once and cache the result
368
        if (null === $streamok) {
369
            $streamok = function_exists('stream_socket_client');
370
        }
371
372
        $errno = 0;
373
        $errstr = '';
374
        if ($streamok) {
375
            $socket_context = stream_context_create($options);
376
            set_error_handler([$this, 'errorHandler']);
377
            $connection = stream_socket_client(
378
                $host . ':' . $port,
379
                $errno,
380
                $errstr,
381
                $timeout,
382
                STREAM_CLIENT_CONNECT,
383
                $socket_context
384
            );
385
            restore_error_handler();
386
        } else {
387
            //Fall back to fsockopen which should work in more places, but is missing some features
388
            $this->edebug(
389
                'Connection: stream_socket_client not available, falling back to fsockopen',
390
                self::DEBUG_CONNECTION
391
            );
392
            set_error_handler([$this, 'errorHandler']);
393
            $connection = fsockopen(
394
                $host,
395
                $port,
396
                $errno,
397
                $errstr,
398
                $timeout
399
            );
400
            restore_error_handler();
401
        }
402
403
        // Verify we connected properly
404
        if (!is_resource($connection)) {
405
            $this->setError(
406
                'Failed to connect to server',
407
                '',
408
                (string) $errno,
409
                $errstr
410
            );
411
            $this->edebug(
412
                'SMTP ERROR: ' . $this->error['error']
413
                . ": $errstr ($errno)",
414
                self::DEBUG_CLIENT
415
            );
416
417
            return false;
418
        }
419
420
        return $connection;
421
    }
422
423
    /**
424
     * Initiate a TLS (encrypted) session.
425
     *
426
     * @return bool
427
     */
428
    public function startTLS()
429
    {
430
        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
431
            return false;
432
        }
433
434
        //Allow the best TLS version(s) we can
435
        $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
436
437
        //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
438
        //so add them back in manually if we can
439
        if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
440
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
441
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
442
        }
443
444
        // Begin encrypted connection
445
        set_error_handler([$this, 'errorHandler']);
446
        $crypto_ok = stream_socket_enable_crypto(
447
            $this->smtp_conn,
448
            true,
449
            $crypto_method
450
        );
451
        restore_error_handler();
452
453
        return (bool) $crypto_ok;
454
    }
455
456
    /**
457
     * Perform SMTP authentication.
458
     * Must be run after hello().
459
     *
460
     * @see    hello()
461
     *
462
     * @param string $username The user name
463
     * @param string $password The password
464
     * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
465
     * @param OAuth  $OAuth    An optional OAuth instance for XOAUTH2 authentication
466
     *
467
     * @return bool True if successfully authenticated
468
     */
469
    public function authenticate(
470
        $username,
471
        $password,
472
        $authtype = null,
473
        $OAuth = null
474
    ) {
475
        if (!$this->server_caps) {
476
            $this->setError('Authentication is not allowed before HELO/EHLO');
477
478
            return false;
479
        }
480
481
        if (array_key_exists('EHLO', $this->server_caps)) {
482
            // SMTP extensions are available; try to find a proper authentication method
483
            if (!array_key_exists('AUTH', $this->server_caps)) {
484
                $this->setError('Authentication is not allowed at this stage');
485
                // 'at this stage' means that auth may be allowed after the stage changes
486
                // e.g. after STARTTLS
487
488
                return false;
489
            }
490
491
            $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);
492
            $this->edebug(
493
                'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
494
                self::DEBUG_LOWLEVEL
495
            );
496
497
            //If we have requested a specific auth type, check the server supports it before trying others
498
            if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) {
499
                $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);
500
                $authtype = null;
501
            }
502
503
            if (empty($authtype)) {
504
                //If no auth mechanism is specified, attempt to use these, in this order
505
                //Try CRAM-MD5 first as it's more secure than the others
506
                foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
507
                    if (in_array($method, $this->server_caps['AUTH'], true)) {
508
                        $authtype = $method;
509
                        break;
510
                    }
511
                }
512
                if (empty($authtype)) {
513
                    $this->setError('No supported authentication methods found');
514
515
                    return false;
516
                }
517
                $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
518
            }
519
520
            if (!in_array($authtype, $this->server_caps['AUTH'], true)) {
521
                $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
522
523
                return false;
524
            }
525
        } elseif (empty($authtype)) {
526
            $authtype = 'LOGIN';
527
        }
528
        switch ($authtype) {
529
            case 'PLAIN':
530
                // Start authentication
531
                if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
532
                    return false;
533
                }
534
                // Send encoded username and password
535
                if (!$this->sendCommand(
536
                    'User & Password',
537
                    base64_encode("\0" . $username . "\0" . $password),
538
                    235
539
                )
540
                ) {
541
                    return false;
542
                }
543
                break;
544
            case 'LOGIN':
545
                // Start authentication
546
                if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
547
                    return false;
548
                }
549
                if (!$this->sendCommand('Username', base64_encode($username), 334)) {
550
                    return false;
551
                }
552
                if (!$this->sendCommand('Password', base64_encode($password), 235)) {
553
                    return false;
554
                }
555
                break;
556
            case 'CRAM-MD5':
557
                // Start authentication
558
                if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
559
                    return false;
560
                }
561
                // Get the challenge
562
                $challenge = base64_decode(substr($this->last_reply, 4));
563
564
                // Build the response
565
                $response = $username . ' ' . $this->hmac($challenge, $password);
566
567
                // send encoded credentials
568
                return $this->sendCommand('Username', base64_encode($response), 235);
569
            case 'XOAUTH2':
570
                //The OAuth instance must be set up prior to requesting auth.
571
                if (null === $OAuth) {
572
                    return false;
573
                }
574
                $oauth = $OAuth->getOauth64();
575
576
                // Start authentication
577
                if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
578
                    return false;
579
                }
580
                break;
581
            default:
582
                $this->setError("Authentication method \"$authtype\" is not supported");
583
584
                return false;
585
        }
586
587
        return true;
588
    }
589
590
    /**
591
     * Calculate an MD5 HMAC hash.
592
     * Works like hash_hmac('md5', $data, $key)
593
     * in case that function is not available.
594
     *
595
     * @param string $data The data to hash
596
     * @param string $key  The key to hash with
597
     *
598
     * @return string
599
     */
600
    protected function hmac($data, $key)
601
    {
602
        if (function_exists('hash_hmac')) {
603
            return hash_hmac('md5', $data, $key);
604
        }
605
606
        // The following borrowed from
607
        // http://php.net/manual/en/function.mhash.php#27225
608
609
        // RFC 2104 HMAC implementation for php.
610
        // Creates an md5 HMAC.
611
        // Eliminates the need to install mhash to compute a HMAC
612
        // by Lance Rushing
613
614
        $bytelen = 64; // byte length for md5
615
        if (strlen($key) > $bytelen) {
616
            $key = pack('H*', md5($key));
617
        }
618
        $key = str_pad($key, $bytelen, chr(0x00));
619
        $ipad = str_pad('', $bytelen, chr(0x36));
620
        $opad = str_pad('', $bytelen, chr(0x5c));
621
        $k_ipad = $key ^ $ipad;
622
        $k_opad = $key ^ $opad;
623
624
        return md5($k_opad . pack('H*', md5($k_ipad . $data)));
625
    }
626
627
    /**
628
     * Check connection state.
629
     *
630
     * @return bool True if connected
631
     */
632
    public function connected()
633
    {
634
        if (is_resource($this->smtp_conn)) {
635
            $sock_status = stream_get_meta_data($this->smtp_conn);
636
            if ($sock_status['eof']) {
637
                // The socket is valid but we are not connected
638
                $this->edebug(
639
                    'SMTP NOTICE: EOF caught while checking if connected',
640
                    self::DEBUG_CLIENT
641
                );
642
                $this->close();
643
644
                return false;
645
            }
646
647
            return true; // everything looks good
648
        }
649
650
        return false;
651
    }
652
653
    /**
654
     * Close the socket and clean up the state of the class.
655
     * Don't use this function without first trying to use QUIT.
656
     *
657
     * @see quit()
658
     */
659
    public function close()
660
    {
661
        $this->setError('');
662
        $this->server_caps = null;
663
        $this->helo_rply = null;
664
        if (is_resource($this->smtp_conn)) {
665
            // close the connection and cleanup
666
            fclose($this->smtp_conn);
667
            $this->smtp_conn = null; //Makes for cleaner serialization
668
            $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
669
        }
670
    }
671
672
    /**
673
     * Send an SMTP DATA command.
674
     * Issues a data command and sends the msg_data to the server,
675
     * finializing the mail transaction. $msg_data is the message
676
     * that is to be send with the headers. Each header needs to be
677
     * on a single line followed by a <CRLF> with the message headers
678
     * and the message body being separated by an additional <CRLF>.
679
     * Implements RFC 821: DATA <CRLF>.
680
     *
681
     * @param string $msg_data Message data to send
682
     *
683
     * @return bool
684
     */
685
    public function data($msg_data)
686
    {
687
        //This will use the standard timelimit
688
        if (!$this->sendCommand('DATA', 'DATA', 354)) {
689
            return false;
690
        }
691
692
        /* The server is ready to accept data!
693
         * According to rfc821 we should not send more than 1000 characters on a single line (including the LE)
694
         * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
695
         * smaller lines to fit within the limit.
696
         * We will also look for lines that start with a '.' and prepend an additional '.'.
697
         * NOTE: this does not count towards line-length limit.
698
         */
699
700
        // Normalize line breaks before exploding
701
        $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
702
703
        /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
704
         * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
705
         * process all lines before a blank line as headers.
706
         */
707
708
        $field = substr($lines[0], 0, strpos($lines[0], ':'));
709
        $in_headers = false;
710
        if (!empty($field) && strpos($field, ' ') === false) {
711
            $in_headers = true;
712
        }
713
714
        foreach ($lines as $line) {
715
            $lines_out = [];
716
            if ($in_headers && $line === '') {
717
                $in_headers = false;
718
            }
719
            //Break this line up into several smaller lines if it's too long
720
            //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
721
            while (isset($line[self::MAX_LINE_LENGTH])) {
722
                //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
723
                //so as to avoid breaking in the middle of a word
724
                $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
725
                //Deliberately matches both false and 0
726
                if (!$pos) {
727
                    //No nice break found, add a hard break
728
                    $pos = self::MAX_LINE_LENGTH - 1;
729
                    $lines_out[] = substr($line, 0, $pos);
730
                    $line = substr($line, $pos);
731
                } else {
732
                    //Break at the found point
733
                    $lines_out[] = substr($line, 0, $pos);
734
                    //Move along by the amount we dealt with
735
                    $line = substr($line, $pos + 1);
736
                }
737
                //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
738
                if ($in_headers) {
739
                    $line = "\t" . $line;
740
                }
741
            }
742
            $lines_out[] = $line;
743
744
            //Send the lines to the server
745
            foreach ($lines_out as $line_out) {
746
                //RFC2821 section 4.5.2
747
                if (!empty($line_out) && $line_out[0] === '.') {
748
                    $line_out = '.' . $line_out;
749
                }
750
                $this->client_send($line_out . static::LE, 'DATA');
751
            }
752
        }
753
754
        //Message data has been sent, complete the command
755
        //Increase timelimit for end of DATA command
756
        $savetimelimit = $this->Timelimit;
757
        $this->Timelimit *= 2;
758
        $result = $this->sendCommand('DATA END', '.', 250);
759
        $this->recordLastTransactionID();
760
        //Restore timelimit
761
        $this->Timelimit = $savetimelimit;
762
763
        return $result;
764
    }
765
766
    /**
767
     * Send an SMTP HELO or EHLO command.
768
     * Used to identify the sending server to the receiving server.
769
     * This makes sure that client and server are in a known state.
770
     * Implements RFC 821: HELO <SP> <domain> <CRLF>
771
     * and RFC 2821 EHLO.
772
     *
773
     * @param string $host The host name or IP to connect to
774
     *
775
     * @return bool
776
     */
777
    public function hello($host = '')
778
    {
779
        //Try extended hello first (RFC 2821)
780
        return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host);
781
    }
782
783
    /**
784
     * Send an SMTP HELO or EHLO command.
785
     * Low-level implementation used by hello().
786
     *
787
     * @param string $hello The HELO string
788
     * @param string $host  The hostname to say we are
789
     *
790
     * @return bool
791
     *
792
     * @see hello()
793
     */
794
    protected function sendHello($hello, $host)
795
    {
796
        $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
797
        $this->helo_rply = $this->last_reply;
798
        if ($noerror) {
799
            $this->parseHelloFields($hello);
800
        } else {
801
            $this->server_caps = null;
802
        }
803
804
        return $noerror;
805
    }
806
807
    /**
808
     * Parse a reply to HELO/EHLO command to discover server extensions.
809
     * In case of HELO, the only parameter that can be discovered is a server name.
810
     *
811
     * @param string $type `HELO` or `EHLO`
812
     */
813
    protected function parseHelloFields($type)
814
    {
815
        $this->server_caps = [];
816
        $lines = explode("\n", $this->helo_rply);
817
818
        foreach ($lines as $n => $s) {
819
            //First 4 chars contain response code followed by - or space
820
            $s = trim(substr($s, 4));
821
            if (empty($s)) {
822
                continue;
823
            }
824
            $fields = explode(' ', $s);
825
            if (!empty($fields)) {
826
                if (!$n) {
827
                    $name = $type;
828
                    $fields = $fields[0];
829
                } else {
830
                    $name = array_shift($fields);
831
                    switch ($name) {
832
                        case 'SIZE':
833
                            $fields = ($fields ? $fields[0] : 0);
834
                            break;
835
                        case 'AUTH':
836
                            if (!is_array($fields)) {
837
                                $fields = [];
838
                            }
839
                            break;
840
                        default:
841
                            $fields = true;
842
                    }
843
                }
844
                $this->server_caps[$name] = $fields;
845
            }
846
        }
847
    }
848
849
    /**
850
     * Send an SMTP MAIL command.
851
     * Starts a mail transaction from the email address specified in
852
     * $from. Returns true if successful or false otherwise. If True
853
     * the mail transaction is started and then one or more recipient
854
     * commands may be called followed by a data command.
855
     * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
856
     *
857
     * @param string $from Source address of this message
858
     *
859
     * @return bool
860
     */
861
    public function mail($from)
862
    {
863
        $useVerp = ($this->do_verp ? ' XVERP' : '');
864
865
        return $this->sendCommand(
866
            'MAIL FROM',
867
            'MAIL FROM:<' . $from . '>' . $useVerp,
868
            250
869
        );
870
    }
871
872
    /**
873
     * Send an SMTP QUIT command.
874
     * Closes the socket if there is no error or the $close_on_error argument is true.
875
     * Implements from RFC 821: QUIT <CRLF>.
876
     *
877
     * @param bool $close_on_error Should the connection close if an error occurs?
878
     *
879
     * @return bool
880
     */
881
    public function quit($close_on_error = true)
882
    {
883
        $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
884
        $err = $this->error; //Save any error
885
        if ($noerror || $close_on_error) {
886
            $this->close();
887
            $this->error = $err; //Restore any error from the quit command
888
        }
889
890
        return $noerror;
891
    }
892
893
    /**
894
     * Send an SMTP RCPT command.
895
     * Sets the TO argument to $toaddr.
896
     * Returns true if the recipient was accepted false if it was rejected.
897
     * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
898
     *
899
     * @param string $address The address the message is being sent to
900
     * @param string $dsn     Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE
901
     *                        or DELAY. If you specify NEVER all other notifications are ignored.
902
     *
903
     * @return bool
904
     */
905
    public function recipient($address, $dsn = '')
906
    {
907
        if (empty($dsn)) {
908
            $rcpt = 'RCPT TO:<' . $address . '>';
909
        } else {
910
            $dsn = strtoupper($dsn);
911
            $notify = [];
912
913
            if (strpos($dsn, 'NEVER') !== false) {
914
                $notify[] = 'NEVER';
915
            } else {
916
                foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {
917
                    if (strpos($dsn, $value) !== false) {
918
                        $notify[] = $value;
919
                    }
920
                }
921
            }
922
923
            $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);
924
        }
925
926
        return $this->sendCommand(
927
            'RCPT TO',
928
            $rcpt,
929
            [250, 251]
930
        );
931
    }
932
933
    /**
934
     * Send an SMTP RSET command.
935
     * Abort any transaction that is currently in progress.
936
     * Implements RFC 821: RSET <CRLF>.
937
     *
938
     * @return bool True on success
939
     */
940
    public function reset()
941
    {
942
        return $this->sendCommand('RSET', 'RSET', 250);
943
    }
944
945
    /**
946
     * Send a command to an SMTP server and check its return code.
947
     *
948
     * @param string    $command       The command name - not sent to the server
949
     * @param string    $commandstring The actual command to send
950
     * @param int|array $expect        One or more expected integer success codes
951
     *
952
     * @return bool True on success
953
     */
954
    protected function sendCommand($command, $commandstring, $expect)
955
    {
956
        if (!$this->connected()) {
957
            $this->setError("Called $command without being connected");
958
959
            return false;
960
        }
961
        //Reject line breaks in all commands
962
        if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) {
963
            $this->setError("Command '$command' contained line breaks");
964
965
            return false;
966
        }
967
        $this->client_send($commandstring . static::LE, $command);
968
969
        $this->last_reply = $this->get_lines();
970
        // Fetch SMTP code and possible error code explanation
971
        $matches = [];
972
        if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) {
973
            $code = (int) $matches[1];
974
            $code_ex = (count($matches) > 2 ? $matches[2] : null);
975
            // Cut off error code from each response line
976
            $detail = preg_replace(
977
                "/{$code}[ -]" .
978
                ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',
979
                '',
980
                $this->last_reply
981
            );
982
        } else {
983
            // Fall back to simple parsing if regex fails
984
            $code = (int) substr($this->last_reply, 0, 3);
985
            $code_ex = null;
986
            $detail = substr($this->last_reply, 4);
987
        }
988
989
        $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
990
991
        if (!in_array($code, (array) $expect, true)) {
992
            $this->setError(
993
                "$command command failed",
994
                $detail,
995
                $code,
996
                $code_ex
997
            );
998
            $this->edebug(
999
                'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
1000
                self::DEBUG_CLIENT
1001
            );
1002
1003
            return false;
1004
        }
1005
1006
        $this->setError('');
1007
1008
        return true;
1009
    }
1010
1011
    /**
1012
     * Send an SMTP SAML command.
1013
     * Starts a mail transaction from the email address specified in $from.
1014
     * Returns true if successful or false otherwise. If True
1015
     * the mail transaction is started and then one or more recipient
1016
     * commands may be called followed by a data command. This command
1017
     * will send the message to the users terminal if they are logged
1018
     * in and send them an email.
1019
     * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.
1020
     *
1021
     * @param string $from The address the message is from
1022
     *
1023
     * @return bool
1024
     */
1025
    public function sendAndMail($from)
1026
    {
1027
        return $this->sendCommand('SAML', "SAML FROM:$from", 250);
1028
    }
1029
1030
    /**
1031
     * Send an SMTP VRFY command.
1032
     *
1033
     * @param string $name The name to verify
1034
     *
1035
     * @return bool
1036
     */
1037
    public function verify($name)
1038
    {
1039
        return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);
1040
    }
1041
1042
    /**
1043
     * Send an SMTP NOOP command.
1044
     * Used to keep keep-alives alive, doesn't actually do anything.
1045
     *
1046
     * @return bool
1047
     */
1048
    public function noop()
1049
    {
1050
        return $this->sendCommand('NOOP', 'NOOP', 250);
1051
    }
1052
1053
    /**
1054
     * Send an SMTP TURN command.
1055
     * This is an optional command for SMTP that this class does not support.
1056
     * This method is here to make the RFC821 Definition complete for this class
1057
     * and _may_ be implemented in future.
1058
     * Implements from RFC 821: TURN <CRLF>.
1059
     *
1060
     * @return bool
1061
     */
1062
    public function turn()
1063
    {
1064
        $this->setError('The SMTP TURN command is not implemented');
1065
        $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
1066
1067
        return false;
1068
    }
1069
1070
    /**
1071
     * Send raw data to the server.
1072
     *
1073
     * @param string $data    The data to send
1074
     * @param string $command Optionally, the command this is part of, used only for controlling debug output
1075
     *
1076
     * @return int|bool The number of bytes sent to the server or false on error
1077
     */
1078
    public function client_send($data, $command = '')
1079
    {
1080
        //If SMTP transcripts are left enabled, or debug output is posted online
1081
        //it can leak credentials, so hide credentials in all but lowest level
1082
        if (self::DEBUG_LOWLEVEL > $this->do_debug &&
1083
            in_array($command, ['User & Password', 'Username', 'Password'], true)) {
1084
            $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);
1085
        } else {
1086
            $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
1087
        }
1088
        set_error_handler([$this, 'errorHandler']);
1089
        $result = fwrite($this->smtp_conn, $data);
1090
        restore_error_handler();
1091
1092
        return $result;
1093
    }
1094
1095
    /**
1096
     * Get the latest error.
1097
     *
1098
     * @return array
1099
     */
1100
    public function getError()
1101
    {
1102
        return $this->error;
1103
    }
1104
1105
    /**
1106
     * Get SMTP extensions available on the server.
1107
     *
1108
     * @return array|null
1109
     */
1110
    public function getServerExtList()
1111
    {
1112
        return $this->server_caps;
1113
    }
1114
1115
    /**
1116
     * Get metadata about the SMTP server from its HELO/EHLO response.
1117
     * The method works in three ways, dependent on argument value and current state:
1118
     *   1. HELO/EHLO has not been sent - returns null and populates $this->error.
1119
     *   2. HELO has been sent -
1120
     *     $name == 'HELO': returns server name
1121
     *     $name == 'EHLO': returns boolean false
1122
     *     $name == any other string: returns null and populates $this->error
1123
     *   3. EHLO has been sent -
1124
     *     $name == 'HELO'|'EHLO': returns the server name
1125
     *     $name == any other string: if extension $name exists, returns True
1126
     *       or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
1127
     *
1128
     * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
1129
     *
1130
     * @return string|bool|null
1131
     */
1132
    public function getServerExt($name)
1133
    {
1134
        if (!$this->server_caps) {
1135
            $this->setError('No HELO/EHLO was sent');
1136
1137
            return;
1138
        }
1139
1140
        if (!array_key_exists($name, $this->server_caps)) {
1141
            if ('HELO' === $name) {
1142
                return $this->server_caps['EHLO'];
1143
            }
1144
            if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) {
1145
                return false;
1146
            }
1147
            $this->setError('HELO handshake was used; No information about server extensions available');
1148
1149
            return;
1150
        }
1151
1152
        return $this->server_caps[$name];
1153
    }
1154
1155
    /**
1156
     * Get the last reply from the server.
1157
     *
1158
     * @return string
1159
     */
1160
    public function getLastReply()
1161
    {
1162
        return $this->last_reply;
1163
    }
1164
1165
    /**
1166
     * Read the SMTP server's response.
1167
     * Either before eof or socket timeout occurs on the operation.
1168
     * With SMTP we can tell if we have more lines to read if the
1169
     * 4th character is '-' symbol. If it is a space then we don't
1170
     * need to read anything else.
1171
     *
1172
     * @return string
1173
     */
1174
    protected function get_lines()
1175
    {
1176
        // If the connection is bad, give up straight away
1177
        if (!is_resource($this->smtp_conn)) {
1178
            return '';
1179
        }
1180
        $data = '';
1181
        $endtime = 0;
1182
        stream_set_timeout($this->smtp_conn, $this->Timeout);
1183
        if ($this->Timelimit > 0) {
1184
            $endtime = time() + $this->Timelimit;
1185
        }
1186
        $selR = [$this->smtp_conn];
1187
        $selW = null;
1188
        while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
1189
            //Must pass vars in here as params are by reference
1190
            if (!stream_select($selR, $selW, $selW, $this->Timelimit)) {
1191
                $this->edebug(
1192
                    'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)',
1193
                    self::DEBUG_LOWLEVEL
1194
                );
1195
                break;
1196
            }
1197
            //Deliberate noise suppression - errors are handled afterwards
1198
            $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);
1199
            $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
1200
            $data .= $str;
1201
            // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
1202
            // or 4th character is a space or a line break char, we are done reading, break the loop.
1203
            // String array access is a significant micro-optimisation over strlen
1204
            if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") {
1205
                break;
1206
            }
1207
            // Timed-out? Log and break
1208
            $info = stream_get_meta_data($this->smtp_conn);
1209
            if ($info['timed_out']) {
1210
                $this->edebug(
1211
                    'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)',
1212
                    self::DEBUG_LOWLEVEL
1213
                );
1214
                break;
1215
            }
1216
            // Now check if reads took too long
1217
            if ($endtime && time() > $endtime) {
1218
                $this->edebug(
1219
                    'SMTP -> get_lines(): timelimit reached (' .
1220
                    $this->Timelimit . ' sec)',
1221
                    self::DEBUG_LOWLEVEL
1222
                );
1223
                break;
1224
            }
1225
        }
1226
1227
        return $data;
1228
    }
1229
1230
    /**
1231
     * Enable or disable VERP address generation.
1232
     *
1233
     * @param bool $enabled
1234
     */
1235
    public function setVerp($enabled = false)
1236
    {
1237
        $this->do_verp = $enabled;
1238
    }
1239
1240
    /**
1241
     * Get VERP address generation mode.
1242
     *
1243
     * @return bool
1244
     */
1245
    public function getVerp()
1246
    {
1247
        return $this->do_verp;
1248
    }
1249
1250
    /**
1251
     * Set error messages and codes.
1252
     *
1253
     * @param string $message      The error message
1254
     * @param string $detail       Further detail on the error
1255
     * @param string $smtp_code    An associated SMTP error code
1256
     * @param string $smtp_code_ex Extended SMTP code
1257
     */
1258
    protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
1259
    {
1260
        $this->error = [
1261
            'error' => $message,
1262
            'detail' => $detail,
1263
            'smtp_code' => $smtp_code,
1264
            'smtp_code_ex' => $smtp_code_ex,
1265
        ];
1266
    }
1267
1268
    /**
1269
     * Set debug output method.
1270
     *
1271
     * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it
1272
     */
1273
    public function setDebugOutput($method = 'echo')
1274
    {
1275
        $this->Debugoutput = $method;
1276
    }
1277
1278
    /**
1279
     * Get debug output method.
1280
     *
1281
     * @return string
1282
     */
1283
    public function getDebugOutput()
1284
    {
1285
        return $this->Debugoutput;
1286
    }
1287
1288
    /**
1289
     * Set debug output level.
1290
     *
1291
     * @param int $level
1292
     */
1293
    public function setDebugLevel($level = 0)
1294
    {
1295
        $this->do_debug = $level;
1296
    }
1297
1298
    /**
1299
     * Get debug output level.
1300
     *
1301
     * @return int
1302
     */
1303
    public function getDebugLevel()
1304
    {
1305
        return $this->do_debug;
1306
    }
1307
1308
    /**
1309
     * Set SMTP timeout.
1310
     *
1311
     * @param int $timeout The timeout duration in seconds
1312
     */
1313
    public function setTimeout($timeout = 0)
1314
    {
1315
        $this->Timeout = $timeout;
1316
    }
1317
1318
    /**
1319
     * Get SMTP timeout.
1320
     *
1321
     * @return int
1322
     */
1323
    public function getTimeout()
1324
    {
1325
        return $this->Timeout;
1326
    }
1327
1328
    /**
1329
     * Reports an error number and string.
1330
     *
1331
     * @param int    $errno   The error number returned by PHP
1332
     * @param string $errmsg  The error message returned by PHP
1333
     * @param string $errfile The file the error occurred in
1334
     * @param int    $errline The line number the error occurred on
1335
     */
1336
    protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
1337
    {
1338
        $notice = 'Connection failed.';
1339
        $this->setError(
1340
            $notice,
1341
            $errmsg,
1342
            (string) $errno
1343
        );
1344
        $this->edebug(
1345
            "$notice Error #$errno: $errmsg [$errfile line $errline]",
1346
            self::DEBUG_CONNECTION
1347
        );
1348
    }
1349
1350
    /**
1351
     * Extract and return the ID of the last SMTP transaction based on
1352
     * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
1353
     * Relies on the host providing the ID in response to a DATA command.
1354
     * If no reply has been received yet, it will return null.
1355
     * If no pattern was matched, it will return false.
1356
     *
1357
     * @return bool|string|null
1358
     */
1359
    protected function recordLastTransactionID()
1360
    {
1361
        $reply = $this->getLastReply();
1362
1363
        if (empty($reply)) {
1364
            $this->last_smtp_transaction_id = null;
1365
        } else {
1366
            $this->last_smtp_transaction_id = false;
1367
            foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
1368
                $matches = [];
1369
                if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
1370
                    $this->last_smtp_transaction_id = trim($matches[1]);
1371
                    break;
1372
                }
1373
            }
1374
        }
1375
1376
        return $this->last_smtp_transaction_id;
1377
    }
1378
1379
    /**
1380
     * Get the queue/transaction ID of the last SMTP transaction
1381
     * If no reply has been received yet, it will return null.
1382
     * If no pattern was matched, it will return false.
1383
     *
1384
     * @return bool|string|null
1385
     *
1386
     * @see recordLastTransactionID()
1387
     */
1388
    public function getLastTransactionID()
1389
    {
1390
        return $this->last_smtp_transaction_id;
1391
    }
1392
}
1393