Passed
Push — master ( b52fd6...b3650f )
by Marcus
09:39
created

SMTP::connect()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 9.0328
c 0
b 0
f 0
cc 5
nc 5
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
        if ($this->smtp_conn === false) {
336
            //Error info already set inside `getSMTPConnection()`
337
            return false;
338
        }
339
340
        $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
341
342
        // Get any announcement
343
        $announce = $this->get_lines();
344
        $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
345
346
        return true;
347
    }
348
349
    /**
350
     * Create connection to the SMTP server.
351
     *
352
     * @param string $host    SMTP server IP or host name
353
     * @param int    $port    The port number to connect to
354
     * @param int    $timeout How long to wait for the connection to open
355
     * @param array  $options An array of options for stream_context_create()
356
     *
357
     * @return false|resource
358
     */
359
    protected function getSMTPConnection($host, $port = null, $timeout = 30, $options = [])
360
    {
361
        static $streamok;
362
        //This is enabled by default since 5.0.0 but some providers disable it
363
        //Check this once and cache the result
364
        if (null === $streamok) {
365
            $streamok = function_exists('stream_socket_client');
366
        }
367
368
        $errno = 0;
369
        $errstr = '';
370
        if ($streamok) {
371
            $socket_context = stream_context_create($options);
372
            set_error_handler([$this, 'errorHandler']);
373
            $connection = stream_socket_client(
374
                $host . ':' . $port,
375
                $errno,
376
                $errstr,
377
                $timeout,
378
                STREAM_CLIENT_CONNECT,
379
                $socket_context
380
            );
381
            restore_error_handler();
382
        } else {
383
            //Fall back to fsockopen which should work in more places, but is missing some features
384
            $this->edebug(
385
                'Connection: stream_socket_client not available, falling back to fsockopen',
386
                self::DEBUG_CONNECTION
387
            );
388
            set_error_handler([$this, 'errorHandler']);
389
            $connection = fsockopen(
390
                $host,
391
                $port,
392
                $errno,
393
                $errstr,
394
                $timeout
395
            );
396
            restore_error_handler();
397
        }
398
399
        // Verify we connected properly
400
        if (!is_resource($connection)) {
401
            $this->setError(
402
                'Failed to connect to server',
403
                '',
404
                (string) $errno,
405
                $errstr
406
            );
407
            $this->edebug(
408
                'SMTP ERROR: ' . $this->error['error']
409
                . ": $errstr ($errno)",
410
                self::DEBUG_CLIENT
411
            );
412
413
            return false;
414
        }
415
416
        // SMTP server can take longer to respond, give longer timeout for first read
417
        // Windows does not have support for this timeout function
418
        if (strpos(PHP_OS, 'WIN') !== 0) {
419
            $max = (int)ini_get('max_execution_time');
420
            // Don't bother if unlimited
421
            if (0 !== $max && $timeout > $max) {
422
                @set_time_limit($timeout);
423
            }
424
            stream_set_timeout($connection, $timeout, 0);
425
        }
426
427
        return $connection;
428
    }
429
430
    /**
431
     * Initiate a TLS (encrypted) session.
432
     *
433
     * @return bool
434
     */
435
    public function startTLS()
436
    {
437
        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
438
            return false;
439
        }
440
441
        //Allow the best TLS version(s) we can
442
        $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
443
444
        //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
445
        //so add them back in manually if we can
446
        if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
447
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
448
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
449
        }
450
451
        // Begin encrypted connection
452
        set_error_handler([$this, 'errorHandler']);
453
        $crypto_ok = stream_socket_enable_crypto(
454
            $this->smtp_conn,
455
            true,
456
            $crypto_method
457
        );
458
        restore_error_handler();
459
460
        return (bool) $crypto_ok;
461
    }
462
463
    /**
464
     * Perform SMTP authentication.
465
     * Must be run after hello().
466
     *
467
     * @see    hello()
468
     *
469
     * @param string $username The user name
470
     * @param string $password The password
471
     * @param string $authtype The auth type (CRAM-MD5, PLAIN, LOGIN, XOAUTH2)
472
     * @param OAuth  $OAuth    An optional OAuth instance for XOAUTH2 authentication
473
     *
474
     * @return bool True if successfully authenticated
475
     */
476
    public function authenticate(
477
        $username,
478
        $password,
479
        $authtype = null,
480
        $OAuth = null
481
    ) {
482
        if (!$this->server_caps) {
483
            $this->setError('Authentication is not allowed before HELO/EHLO');
484
485
            return false;
486
        }
487
488
        if (array_key_exists('EHLO', $this->server_caps)) {
489
            // SMTP extensions are available; try to find a proper authentication method
490
            if (!array_key_exists('AUTH', $this->server_caps)) {
491
                $this->setError('Authentication is not allowed at this stage');
492
                // 'at this stage' means that auth may be allowed after the stage changes
493
                // e.g. after STARTTLS
494
495
                return false;
496
            }
497
498
            $this->edebug('Auth method requested: ' . ($authtype ?: 'UNSPECIFIED'), self::DEBUG_LOWLEVEL);
499
            $this->edebug(
500
                'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
501
                self::DEBUG_LOWLEVEL
502
            );
503
504
            //If we have requested a specific auth type, check the server supports it before trying others
505
            if (null !== $authtype && !in_array($authtype, $this->server_caps['AUTH'], true)) {
506
                $this->edebug('Requested auth method not available: ' . $authtype, self::DEBUG_LOWLEVEL);
507
                $authtype = null;
508
            }
509
510
            if (empty($authtype)) {
511
                //If no auth mechanism is specified, attempt to use these, in this order
512
                //Try CRAM-MD5 first as it's more secure than the others
513
                foreach (['CRAM-MD5', 'LOGIN', 'PLAIN', 'XOAUTH2'] as $method) {
514
                    if (in_array($method, $this->server_caps['AUTH'], true)) {
515
                        $authtype = $method;
516
                        break;
517
                    }
518
                }
519
                if (empty($authtype)) {
520
                    $this->setError('No supported authentication methods found');
521
522
                    return false;
523
                }
524
                $this->edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
525
            }
526
527
            if (!in_array($authtype, $this->server_caps['AUTH'], true)) {
528
                $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
529
530
                return false;
531
            }
532
        } elseif (empty($authtype)) {
533
            $authtype = 'LOGIN';
534
        }
535
        switch ($authtype) {
536
            case 'PLAIN':
537
                // Start authentication
538
                if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
539
                    return false;
540
                }
541
                // Send encoded username and password
542
                if (!$this->sendCommand(
543
                    'User & Password',
544
                    base64_encode("\0" . $username . "\0" . $password),
545
                    235
546
                )
547
                ) {
548
                    return false;
549
                }
550
                break;
551
            case 'LOGIN':
552
                // Start authentication
553
                if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
554
                    return false;
555
                }
556
                if (!$this->sendCommand('Username', base64_encode($username), 334)) {
557
                    return false;
558
                }
559
                if (!$this->sendCommand('Password', base64_encode($password), 235)) {
560
                    return false;
561
                }
562
                break;
563
            case 'CRAM-MD5':
564
                // Start authentication
565
                if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
566
                    return false;
567
                }
568
                // Get the challenge
569
                $challenge = base64_decode(substr($this->last_reply, 4));
570
571
                // Build the response
572
                $response = $username . ' ' . $this->hmac($challenge, $password);
573
574
                // send encoded credentials
575
                return $this->sendCommand('Username', base64_encode($response), 235);
576
            case 'XOAUTH2':
577
                //The OAuth instance must be set up prior to requesting auth.
578
                if (null === $OAuth) {
579
                    return false;
580
                }
581
                $oauth = $OAuth->getOauth64();
582
583
                // Start authentication
584
                if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
585
                    return false;
586
                }
587
                break;
588
            default:
589
                $this->setError("Authentication method \"$authtype\" is not supported");
590
591
                return false;
592
        }
593
594
        return true;
595
    }
596
597
    /**
598
     * Calculate an MD5 HMAC hash.
599
     * Works like hash_hmac('md5', $data, $key)
600
     * in case that function is not available.
601
     *
602
     * @param string $data The data to hash
603
     * @param string $key  The key to hash with
604
     *
605
     * @return string
606
     */
607
    protected function hmac($data, $key)
608
    {
609
        if (function_exists('hash_hmac')) {
610
            return hash_hmac('md5', $data, $key);
611
        }
612
613
        // The following borrowed from
614
        // http://php.net/manual/en/function.mhash.php#27225
615
616
        // RFC 2104 HMAC implementation for php.
617
        // Creates an md5 HMAC.
618
        // Eliminates the need to install mhash to compute a HMAC
619
        // by Lance Rushing
620
621
        $bytelen = 64; // byte length for md5
622
        if (strlen($key) > $bytelen) {
623
            $key = pack('H*', md5($key));
624
        }
625
        $key = str_pad($key, $bytelen, chr(0x00));
626
        $ipad = str_pad('', $bytelen, chr(0x36));
627
        $opad = str_pad('', $bytelen, chr(0x5c));
628
        $k_ipad = $key ^ $ipad;
629
        $k_opad = $key ^ $opad;
630
631
        return md5($k_opad . pack('H*', md5($k_ipad . $data)));
632
    }
633
634
    /**
635
     * Check connection state.
636
     *
637
     * @return bool True if connected
638
     */
639
    public function connected()
640
    {
641
        if (is_resource($this->smtp_conn)) {
642
            $sock_status = stream_get_meta_data($this->smtp_conn);
643
            if ($sock_status['eof']) {
644
                // The socket is valid but we are not connected
645
                $this->edebug(
646
                    'SMTP NOTICE: EOF caught while checking if connected',
647
                    self::DEBUG_CLIENT
648
                );
649
                $this->close();
650
651
                return false;
652
            }
653
654
            return true; // everything looks good
655
        }
656
657
        return false;
658
    }
659
660
    /**
661
     * Close the socket and clean up the state of the class.
662
     * Don't use this function without first trying to use QUIT.
663
     *
664
     * @see quit()
665
     */
666
    public function close()
667
    {
668
        $this->setError('');
669
        $this->server_caps = null;
670
        $this->helo_rply = null;
671
        if (is_resource($this->smtp_conn)) {
672
            // close the connection and cleanup
673
            fclose($this->smtp_conn);
674
            $this->smtp_conn = null; //Makes for cleaner serialization
675
            $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
676
        }
677
    }
678
679
    /**
680
     * Send an SMTP DATA command.
681
     * Issues a data command and sends the msg_data to the server,
682
     * finializing the mail transaction. $msg_data is the message
683
     * that is to be send with the headers. Each header needs to be
684
     * on a single line followed by a <CRLF> with the message headers
685
     * and the message body being separated by an additional <CRLF>.
686
     * Implements RFC 821: DATA <CRLF>.
687
     *
688
     * @param string $msg_data Message data to send
689
     *
690
     * @return bool
691
     */
692
    public function data($msg_data)
693
    {
694
        //This will use the standard timelimit
695
        if (!$this->sendCommand('DATA', 'DATA', 354)) {
696
            return false;
697
        }
698
699
        /* The server is ready to accept data!
700
         * According to rfc821 we should not send more than 1000 characters on a single line (including the LE)
701
         * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
702
         * smaller lines to fit within the limit.
703
         * We will also look for lines that start with a '.' and prepend an additional '.'.
704
         * NOTE: this does not count towards line-length limit.
705
         */
706
707
        // Normalize line breaks before exploding
708
        $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $msg_data));
709
710
        /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
711
         * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
712
         * process all lines before a blank line as headers.
713
         */
714
715
        $field = substr($lines[0], 0, strpos($lines[0], ':'));
716
        $in_headers = false;
717
        if (!empty($field) && strpos($field, ' ') === false) {
718
            $in_headers = true;
719
        }
720
721
        foreach ($lines as $line) {
722
            $lines_out = [];
723
            if ($in_headers && $line === '') {
724
                $in_headers = false;
725
            }
726
            //Break this line up into several smaller lines if it's too long
727
            //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
728
            while (isset($line[self::MAX_LINE_LENGTH])) {
729
                //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
730
                //so as to avoid breaking in the middle of a word
731
                $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
732
                //Deliberately matches both false and 0
733
                if (!$pos) {
734
                    //No nice break found, add a hard break
735
                    $pos = self::MAX_LINE_LENGTH - 1;
736
                    $lines_out[] = substr($line, 0, $pos);
737
                    $line = substr($line, $pos);
738
                } else {
739
                    //Break at the found point
740
                    $lines_out[] = substr($line, 0, $pos);
741
                    //Move along by the amount we dealt with
742
                    $line = substr($line, $pos + 1);
743
                }
744
                //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
745
                if ($in_headers) {
746
                    $line = "\t" . $line;
747
                }
748
            }
749
            $lines_out[] = $line;
750
751
            //Send the lines to the server
752
            foreach ($lines_out as $line_out) {
753
                //RFC2821 section 4.5.2
754
                if (!empty($line_out) && $line_out[0] === '.') {
755
                    $line_out = '.' . $line_out;
756
                }
757
                $this->client_send($line_out . static::LE, 'DATA');
758
            }
759
        }
760
761
        //Message data has been sent, complete the command
762
        //Increase timelimit for end of DATA command
763
        $savetimelimit = $this->Timelimit;
764
        $this->Timelimit *= 2;
765
        $result = $this->sendCommand('DATA END', '.', 250);
766
        $this->recordLastTransactionID();
767
        //Restore timelimit
768
        $this->Timelimit = $savetimelimit;
769
770
        return $result;
771
    }
772
773
    /**
774
     * Send an SMTP HELO or EHLO command.
775
     * Used to identify the sending server to the receiving server.
776
     * This makes sure that client and server are in a known state.
777
     * Implements RFC 821: HELO <SP> <domain> <CRLF>
778
     * and RFC 2821 EHLO.
779
     *
780
     * @param string $host The host name or IP to connect to
781
     *
782
     * @return bool
783
     */
784
    public function hello($host = '')
785
    {
786
        //Try extended hello first (RFC 2821)
787
        return $this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host);
788
    }
789
790
    /**
791
     * Send an SMTP HELO or EHLO command.
792
     * Low-level implementation used by hello().
793
     *
794
     * @param string $hello The HELO string
795
     * @param string $host  The hostname to say we are
796
     *
797
     * @return bool
798
     *
799
     * @see hello()
800
     */
801
    protected function sendHello($hello, $host)
802
    {
803
        $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
804
        $this->helo_rply = $this->last_reply;
805
        if ($noerror) {
806
            $this->parseHelloFields($hello);
807
        } else {
808
            $this->server_caps = null;
809
        }
810
811
        return $noerror;
812
    }
813
814
    /**
815
     * Parse a reply to HELO/EHLO command to discover server extensions.
816
     * In case of HELO, the only parameter that can be discovered is a server name.
817
     *
818
     * @param string $type `HELO` or `EHLO`
819
     */
820
    protected function parseHelloFields($type)
821
    {
822
        $this->server_caps = [];
823
        $lines = explode("\n", $this->helo_rply);
824
825
        foreach ($lines as $n => $s) {
826
            //First 4 chars contain response code followed by - or space
827
            $s = trim(substr($s, 4));
828
            if (empty($s)) {
829
                continue;
830
            }
831
            $fields = explode(' ', $s);
832
            if (!empty($fields)) {
833
                if (!$n) {
834
                    $name = $type;
835
                    $fields = $fields[0];
836
                } else {
837
                    $name = array_shift($fields);
838
                    switch ($name) {
839
                        case 'SIZE':
840
                            $fields = ($fields ? $fields[0] : 0);
841
                            break;
842
                        case 'AUTH':
843
                            if (!is_array($fields)) {
844
                                $fields = [];
845
                            }
846
                            break;
847
                        default:
848
                            $fields = true;
849
                    }
850
                }
851
                $this->server_caps[$name] = $fields;
852
            }
853
        }
854
    }
855
856
    /**
857
     * Send an SMTP MAIL command.
858
     * Starts a mail transaction from the email address specified in
859
     * $from. Returns true if successful or false otherwise. If True
860
     * the mail transaction is started and then one or more recipient
861
     * commands may be called followed by a data command.
862
     * Implements RFC 821: MAIL <SP> FROM:<reverse-path> <CRLF>.
863
     *
864
     * @param string $from Source address of this message
865
     *
866
     * @return bool
867
     */
868
    public function mail($from)
869
    {
870
        $useVerp = ($this->do_verp ? ' XVERP' : '');
871
872
        return $this->sendCommand(
873
            'MAIL FROM',
874
            'MAIL FROM:<' . $from . '>' . $useVerp,
875
            250
876
        );
877
    }
878
879
    /**
880
     * Send an SMTP QUIT command.
881
     * Closes the socket if there is no error or the $close_on_error argument is true.
882
     * Implements from RFC 821: QUIT <CRLF>.
883
     *
884
     * @param bool $close_on_error Should the connection close if an error occurs?
885
     *
886
     * @return bool
887
     */
888
    public function quit($close_on_error = true)
889
    {
890
        $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
891
        $err = $this->error; //Save any error
892
        if ($noerror || $close_on_error) {
893
            $this->close();
894
            $this->error = $err; //Restore any error from the quit command
895
        }
896
897
        return $noerror;
898
    }
899
900
    /**
901
     * Send an SMTP RCPT command.
902
     * Sets the TO argument to $toaddr.
903
     * Returns true if the recipient was accepted false if it was rejected.
904
     * Implements from RFC 821: RCPT <SP> TO:<forward-path> <CRLF>.
905
     *
906
     * @param string $address The address the message is being sent to
907
     * @param string $dsn     Comma separated list of DSN notifications. NEVER, SUCCESS, FAILURE
908
     *                        or DELAY. If you specify NEVER all other notifications are ignored.
909
     *
910
     * @return bool
911
     */
912
    public function recipient($address, $dsn = '')
913
    {
914
        if (empty($dsn)) {
915
            $rcpt = 'RCPT TO:<' . $address . '>';
916
        } else {
917
            $dsn = strtoupper($dsn);
918
            $notify = [];
919
920
            if (strpos($dsn, 'NEVER') !== false) {
921
                $notify[] = 'NEVER';
922
            } else {
923
                foreach (['SUCCESS', 'FAILURE', 'DELAY'] as $value) {
924
                    if (strpos($dsn, $value) !== false) {
925
                        $notify[] = $value;
926
                    }
927
                }
928
            }
929
930
            $rcpt = 'RCPT TO:<' . $address . '> NOTIFY=' . implode(',', $notify);
931
        }
932
933
        return $this->sendCommand(
934
            'RCPT TO',
935
            $rcpt,
936
            [250, 251]
937
        );
938
    }
939
940
    /**
941
     * Send an SMTP RSET command.
942
     * Abort any transaction that is currently in progress.
943
     * Implements RFC 821: RSET <CRLF>.
944
     *
945
     * @return bool True on success
946
     */
947
    public function reset()
948
    {
949
        return $this->sendCommand('RSET', 'RSET', 250);
950
    }
951
952
    /**
953
     * Send a command to an SMTP server and check its return code.
954
     *
955
     * @param string    $command       The command name - not sent to the server
956
     * @param string    $commandstring The actual command to send
957
     * @param int|array $expect        One or more expected integer success codes
958
     *
959
     * @return bool True on success
960
     */
961
    protected function sendCommand($command, $commandstring, $expect)
962
    {
963
        if (!$this->connected()) {
964
            $this->setError("Called $command without being connected");
965
966
            return false;
967
        }
968
        //Reject line breaks in all commands
969
        if ((strpos($commandstring, "\n") !== false) || (strpos($commandstring, "\r") !== false)) {
970
            $this->setError("Command '$command' contained line breaks");
971
972
            return false;
973
        }
974
        $this->client_send($commandstring . static::LE, $command);
975
976
        $this->last_reply = $this->get_lines();
977
        // Fetch SMTP code and possible error code explanation
978
        $matches = [];
979
        if (preg_match('/^([\d]{3})[ -](?:([\d]\\.[\d]\\.[\d]{1,2}) )?/', $this->last_reply, $matches)) {
980
            $code = (int) $matches[1];
981
            $code_ex = (count($matches) > 2 ? $matches[2] : null);
982
            // Cut off error code from each response line
983
            $detail = preg_replace(
984
                "/{$code}[ -]" .
985
                ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . '/m',
986
                '',
987
                $this->last_reply
988
            );
989
        } else {
990
            // Fall back to simple parsing if regex fails
991
            $code = (int) substr($this->last_reply, 0, 3);
992
            $code_ex = null;
993
            $detail = substr($this->last_reply, 4);
994
        }
995
996
        $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
997
998
        if (!in_array($code, (array) $expect, true)) {
999
            $this->setError(
1000
                "$command command failed",
1001
                $detail,
1002
                $code,
1003
                $code_ex
1004
            );
1005
            $this->edebug(
1006
                'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
1007
                self::DEBUG_CLIENT
1008
            );
1009
1010
            return false;
1011
        }
1012
1013
        $this->setError('');
1014
1015
        return true;
1016
    }
1017
1018
    /**
1019
     * Send an SMTP SAML command.
1020
     * Starts a mail transaction from the email address specified in $from.
1021
     * Returns true if successful or false otherwise. If True
1022
     * the mail transaction is started and then one or more recipient
1023
     * commands may be called followed by a data command. This command
1024
     * will send the message to the users terminal if they are logged
1025
     * in and send them an email.
1026
     * Implements RFC 821: SAML <SP> FROM:<reverse-path> <CRLF>.
1027
     *
1028
     * @param string $from The address the message is from
1029
     *
1030
     * @return bool
1031
     */
1032
    public function sendAndMail($from)
1033
    {
1034
        return $this->sendCommand('SAML', "SAML FROM:$from", 250);
1035
    }
1036
1037
    /**
1038
     * Send an SMTP VRFY command.
1039
     *
1040
     * @param string $name The name to verify
1041
     *
1042
     * @return bool
1043
     */
1044
    public function verify($name)
1045
    {
1046
        return $this->sendCommand('VRFY', "VRFY $name", [250, 251]);
1047
    }
1048
1049
    /**
1050
     * Send an SMTP NOOP command.
1051
     * Used to keep keep-alives alive, doesn't actually do anything.
1052
     *
1053
     * @return bool
1054
     */
1055
    public function noop()
1056
    {
1057
        return $this->sendCommand('NOOP', 'NOOP', 250);
1058
    }
1059
1060
    /**
1061
     * Send an SMTP TURN command.
1062
     * This is an optional command for SMTP that this class does not support.
1063
     * This method is here to make the RFC821 Definition complete for this class
1064
     * and _may_ be implemented in future.
1065
     * Implements from RFC 821: TURN <CRLF>.
1066
     *
1067
     * @return bool
1068
     */
1069
    public function turn()
1070
    {
1071
        $this->setError('The SMTP TURN command is not implemented');
1072
        $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
1073
1074
        return false;
1075
    }
1076
1077
    /**
1078
     * Send raw data to the server.
1079
     *
1080
     * @param string $data    The data to send
1081
     * @param string $command Optionally, the command this is part of, used only for controlling debug output
1082
     *
1083
     * @return int|bool The number of bytes sent to the server or false on error
1084
     */
1085
    public function client_send($data, $command = '')
1086
    {
1087
        //If SMTP transcripts are left enabled, or debug output is posted online
1088
        //it can leak credentials, so hide credentials in all but lowest level
1089
        if (self::DEBUG_LOWLEVEL > $this->do_debug &&
1090
            in_array($command, ['User & Password', 'Username', 'Password'], true)) {
1091
            $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);
1092
        } else {
1093
            $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
1094
        }
1095
        set_error_handler([$this, 'errorHandler']);
1096
        $result = fwrite($this->smtp_conn, $data);
1097
        restore_error_handler();
1098
1099
        return $result;
1100
    }
1101
1102
    /**
1103
     * Get the latest error.
1104
     *
1105
     * @return array
1106
     */
1107
    public function getError()
1108
    {
1109
        return $this->error;
1110
    }
1111
1112
    /**
1113
     * Get SMTP extensions available on the server.
1114
     *
1115
     * @return array|null
1116
     */
1117
    public function getServerExtList()
1118
    {
1119
        return $this->server_caps;
1120
    }
1121
1122
    /**
1123
     * Get metadata about the SMTP server from its HELO/EHLO response.
1124
     * The method works in three ways, dependent on argument value and current state:
1125
     *   1. HELO/EHLO has not been sent - returns null and populates $this->error.
1126
     *   2. HELO has been sent -
1127
     *     $name == 'HELO': returns server name
1128
     *     $name == 'EHLO': returns boolean false
1129
     *     $name == any other string: returns null and populates $this->error
1130
     *   3. EHLO has been sent -
1131
     *     $name == 'HELO'|'EHLO': returns the server name
1132
     *     $name == any other string: if extension $name exists, returns True
1133
     *       or its options (e.g. AUTH mechanisms supported). Otherwise returns False.
1134
     *
1135
     * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
1136
     *
1137
     * @return string|bool|null
1138
     */
1139
    public function getServerExt($name)
1140
    {
1141
        if (!$this->server_caps) {
1142
            $this->setError('No HELO/EHLO was sent');
1143
1144
            return;
1145
        }
1146
1147
        if (!array_key_exists($name, $this->server_caps)) {
1148
            if ('HELO' === $name) {
1149
                return $this->server_caps['EHLO'];
1150
            }
1151
            if ('EHLO' === $name || array_key_exists('EHLO', $this->server_caps)) {
1152
                return false;
1153
            }
1154
            $this->setError('HELO handshake was used; No information about server extensions available');
1155
1156
            return;
1157
        }
1158
1159
        return $this->server_caps[$name];
1160
    }
1161
1162
    /**
1163
     * Get the last reply from the server.
1164
     *
1165
     * @return string
1166
     */
1167
    public function getLastReply()
1168
    {
1169
        return $this->last_reply;
1170
    }
1171
1172
    /**
1173
     * Read the SMTP server's response.
1174
     * Either before eof or socket timeout occurs on the operation.
1175
     * With SMTP we can tell if we have more lines to read if the
1176
     * 4th character is '-' symbol. If it is a space then we don't
1177
     * need to read anything else.
1178
     *
1179
     * @return string
1180
     */
1181
    protected function get_lines()
1182
    {
1183
        // If the connection is bad, give up straight away
1184
        if (!is_resource($this->smtp_conn)) {
1185
            return '';
1186
        }
1187
        $data = '';
1188
        $endtime = 0;
1189
        stream_set_timeout($this->smtp_conn, $this->Timeout);
1190
        if ($this->Timelimit > 0) {
1191
            $endtime = time() + $this->Timelimit;
1192
        }
1193
        $selR = [$this->smtp_conn];
1194
        $selW = null;
1195
        while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
1196
            //Must pass vars in here as params are by reference
1197
            if (!stream_select($selR, $selW, $selW, $this->Timelimit)) {
1198
                $this->edebug(
1199
                    'SMTP -> get_lines(): select timed-out in (' . $this->Timelimit . ' sec)',
1200
                    self::DEBUG_LOWLEVEL
1201
                );
1202
                break;
1203
            }
1204
            //Deliberate noise suppression - errors are handled afterwards
1205
            $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);
1206
            $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
1207
            $data .= $str;
1208
            // If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
1209
            // or 4th character is a space or a line break char, we are done reading, break the loop.
1210
            // String array access is a significant micro-optimisation over strlen
1211
            if (!isset($str[3]) || $str[3] === ' ' || $str[3] === "\r" || $str[3] === "\n") {
1212
                break;
1213
            }
1214
            // Timed-out? Log and break
1215
            $info = stream_get_meta_data($this->smtp_conn);
1216
            if ($info['timed_out']) {
1217
                $this->edebug(
1218
                    'SMTP -> get_lines(): stream timed-out (' . $this->Timeout . ' sec)',
1219
                    self::DEBUG_LOWLEVEL
1220
                );
1221
                break;
1222
            }
1223
            // Now check if reads took too long
1224
            if ($endtime && time() > $endtime) {
1225
                $this->edebug(
1226
                    'SMTP -> get_lines(): timelimit reached (' .
1227
                    $this->Timelimit . ' sec)',
1228
                    self::DEBUG_LOWLEVEL
1229
                );
1230
                break;
1231
            }
1232
        }
1233
1234
        return $data;
1235
    }
1236
1237
    /**
1238
     * Enable or disable VERP address generation.
1239
     *
1240
     * @param bool $enabled
1241
     */
1242
    public function setVerp($enabled = false)
1243
    {
1244
        $this->do_verp = $enabled;
1245
    }
1246
1247
    /**
1248
     * Get VERP address generation mode.
1249
     *
1250
     * @return bool
1251
     */
1252
    public function getVerp()
1253
    {
1254
        return $this->do_verp;
1255
    }
1256
1257
    /**
1258
     * Set error messages and codes.
1259
     *
1260
     * @param string $message      The error message
1261
     * @param string $detail       Further detail on the error
1262
     * @param string $smtp_code    An associated SMTP error code
1263
     * @param string $smtp_code_ex Extended SMTP code
1264
     */
1265
    protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
1266
    {
1267
        $this->error = [
1268
            'error' => $message,
1269
            'detail' => $detail,
1270
            'smtp_code' => $smtp_code,
1271
            'smtp_code_ex' => $smtp_code_ex,
1272
        ];
1273
    }
1274
1275
    /**
1276
     * Set debug output method.
1277
     *
1278
     * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it
1279
     */
1280
    public function setDebugOutput($method = 'echo')
1281
    {
1282
        $this->Debugoutput = $method;
1283
    }
1284
1285
    /**
1286
     * Get debug output method.
1287
     *
1288
     * @return string
1289
     */
1290
    public function getDebugOutput()
1291
    {
1292
        return $this->Debugoutput;
1293
    }
1294
1295
    /**
1296
     * Set debug output level.
1297
     *
1298
     * @param int $level
1299
     */
1300
    public function setDebugLevel($level = 0)
1301
    {
1302
        $this->do_debug = $level;
1303
    }
1304
1305
    /**
1306
     * Get debug output level.
1307
     *
1308
     * @return int
1309
     */
1310
    public function getDebugLevel()
1311
    {
1312
        return $this->do_debug;
1313
    }
1314
1315
    /**
1316
     * Set SMTP timeout.
1317
     *
1318
     * @param int $timeout The timeout duration in seconds
1319
     */
1320
    public function setTimeout($timeout = 0)
1321
    {
1322
        $this->Timeout = $timeout;
1323
    }
1324
1325
    /**
1326
     * Get SMTP timeout.
1327
     *
1328
     * @return int
1329
     */
1330
    public function getTimeout()
1331
    {
1332
        return $this->Timeout;
1333
    }
1334
1335
    /**
1336
     * Reports an error number and string.
1337
     *
1338
     * @param int    $errno   The error number returned by PHP
1339
     * @param string $errmsg  The error message returned by PHP
1340
     * @param string $errfile The file the error occurred in
1341
     * @param int    $errline The line number the error occurred on
1342
     */
1343
    protected function errorHandler($errno, $errmsg, $errfile = '', $errline = 0)
1344
    {
1345
        $notice = 'Connection failed.';
1346
        $this->setError(
1347
            $notice,
1348
            $errmsg,
1349
            (string) $errno
1350
        );
1351
        $this->edebug(
1352
            "$notice Error #$errno: $errmsg [$errfile line $errline]",
1353
            self::DEBUG_CONNECTION
1354
        );
1355
    }
1356
1357
    /**
1358
     * Extract and return the ID of the last SMTP transaction based on
1359
     * a list of patterns provided in SMTP::$smtp_transaction_id_patterns.
1360
     * Relies on the host providing the ID in response to a DATA command.
1361
     * If no reply has been received yet, it will return null.
1362
     * If no pattern was matched, it will return false.
1363
     *
1364
     * @return bool|string|null
1365
     */
1366
    protected function recordLastTransactionID()
1367
    {
1368
        $reply = $this->getLastReply();
1369
1370
        if (empty($reply)) {
1371
            $this->last_smtp_transaction_id = null;
1372
        } else {
1373
            $this->last_smtp_transaction_id = false;
1374
            foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
1375
                $matches = [];
1376
                if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
1377
                    $this->last_smtp_transaction_id = trim($matches[1]);
1378
                    break;
1379
                }
1380
            }
1381
        }
1382
1383
        return $this->last_smtp_transaction_id;
1384
    }
1385
1386
    /**
1387
     * Get the queue/transaction ID of the last SMTP transaction
1388
     * If no reply has been received yet, it will return null.
1389
     * If no pattern was matched, it will return false.
1390
     *
1391
     * @return bool|string|null
1392
     *
1393
     * @see recordLastTransactionID()
1394
     */
1395
    public function getLastTransactionID()
1396
    {
1397
        return $this->last_smtp_transaction_id;
1398
    }
1399
}
1400