Completed
Push — master ( 527733...42d287 )
by zyt
11s
created

Validator::attemptConnection()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 5
nop 3
crap 4
1
<?php
2
3
namespace SMTPValidateEmail;
4
5
use \SMTPValidateEmail\Exceptions\Exception as Exception;
6
use \SMTPValidateEmail\Exceptions\Timeout as TimeoutException;
7
use \SMTPValidateEmail\Exceptions\NoTimeout as NoTimeoutException;
8
use \SMTPValidateEmail\Exceptions\NoConnection as NoConnectionException;
9
use \SMTPValidateEmail\Exceptions\UnexpectedResponse as UnexpectedResponseException;
10
use \SMTPValidateEmail\Exceptions\NoHelo as NoHeloException;
11
use \SMTPValidateEmail\Exceptions\NoMailFrom as NoMailFromException;
12
use \SMTPValidateEmail\Exceptions\NoResponse as NoResponseException;
13
use \SMTPValidateEmail\Exceptions\SendFailed as SendFailedException;
14
15
class Validator
16
{
17
18
    public $log = [];
19
20
    /**
21
     * Print stuff as it happens or not
22
     *
23
     * @var bool
24
     */
25
    public $debug = false;
26
27
    /**
28
     * Default smtp port to connect to
29
     *
30
     * @var int
31
     */
32
    public $connect_port = 25;
33
34
    /**
35
     * Are "catch-all" accounts considered valid or not?
36
     * If not, the class checks for a "catch-all" and if it determines the box
37
     * has a "catch-all", sets all the emails on that domain as invalid.
38
     *
39
     * @var bool
40
     */
41
    public $catchall_is_valid = true;
42
43
    /**
44
     * Whether to perform the "catch-all" test or not
45
     *
46
     * @var bool
47
     */
48
    public $catchall_test = false; // Set to true to perform a catchall test
49
50
    /**
51
     * Being unable to communicate with the remote MTA could mean an address
52
     * is invalid, but it might not, depending on your use case, set the
53
     * value appropriately.
54
     *
55
     * @var bool
56
     */
57
    public $no_comm_is_valid = false;
58
59
    /**
60
     * Being unable to connect with the remote host could mean a server
61
     * configuration issue, but it might not, depending on your use case,
62
     * set the value appropriately.
63
     */
64
    public $no_conn_is_valid = false;
65
66
    /**
67
     * Whether "greylisted" responses are considered as valid or invalid addresses
68
     *
69
     * @var bool
70
     */
71
    public $greylisted_considered_valid = true;
72
73
    /**
74
     * Stream context arguments for connection socket, necessary to initiate
75
     * Server IP (in case reverse IP), see: https://stackoverflow.com/a/8968016
76
     */
77
    public $stream_context_args = [];
78
79
    /**
80
     * Timeout values for various commands (in seconds) per RFC 2821
81
     *
82
     * @var array
83
     */
84
    protected $command_timeouts = [
85
        'ehlo' => 120,
86
        'helo' => 120,
87
        'tls'  => 180, // start tls
88
        'mail' => 300, // mail from
89
        'rcpt' => 300, // rcpt to,
90
        'rset' => 30,
91
        'quit' => 60,
92
        'noop' => 60
93
    ];
94
95
    const CRLF = "\r\n";
96
97
    // Some smtp response codes
98
    const SMTP_CONNECT_SUCCESS = 220;
99
    const SMTP_QUIT_SUCCESS    = 221;
100
    const SMTP_GENERIC_SUCCESS = 250;
101
    const SMTP_USER_NOT_LOCAL  = 251;
102
    const SMTP_CANNOT_VRFY     = 252;
103
104
    const SMTP_SERVICE_UNAVAILABLE = 421;
105
106
    // 450 Requested mail action not taken: mailbox unavailable (e.g.,
107
    // mailbox busy or temporarily blocked for policy reasons)
108
    const SMTP_MAIL_ACTION_NOT_TAKEN = 450;
109
    // 451 Requested action aborted: local error in processing
110
    const SMTP_MAIL_ACTION_ABORTED = 451;
111
    // 452 Requested action not taken: insufficient system storage
112
    const SMTP_REQUESTED_ACTION_NOT_TAKEN = 452;
113
114
    // 500 Syntax error (may be due to a denied command)
115
    const SMTP_SYNTAX_ERROR = 500;
116
    // 502 Comment not implemented
117
    const SMTP_NOT_IMPLEMENTED = 502;
118
    // 503 Bad sequence of commands (may be due to a denied command)
119
    const SMTP_BAD_SEQUENCE = 503;
120
121
    // 550 Requested action not taken: mailbox unavailable (e.g., mailbox
122
    // not found, no access, or command rejected for policy reasons)
123
    const SMTP_MBOX_UNAVAILABLE = 550;
124
125
    // 554 Seen this from hotmail MTAs, in response to RSET :(
126
    const SMTP_TRANSACTION_FAILED = 554;
127
128
    /**
129
     * List of response codes considered as "greylisted"
130
     *
131
     * @var array
132
     */
133
    private $greylisted = [
134
        self::SMTP_MAIL_ACTION_NOT_TAKEN,
135
        self::SMTP_MAIL_ACTION_ABORTED,
136
        self::SMTP_REQUESTED_ACTION_NOT_TAKEN
137
    ];
138
139
    /**
140
     * Internal states we can be in
141
     *
142
     * @var array
143
     */
144
    private $state = [
145
        'helo' => false,
146
        'mail' => false,
147
        'rcpt' => false
148
    ];
149
150
    /**
151
     * Holds the socket connection resource
152
     *
153
     * @var resource
154
     */
155
    private $socket;
156
157
    /**
158
     * Holds all the domains we'll validate accounts on
159
     *
160
     * @var array
161
     */
162
    private $domains = [];
163
164
    /**
165
     * @var array
166
     */
167
    private $domains_info = [];
168
169
    /**
170
     * Default connect timeout for each MTA attempted (seconds)
171
     *
172
     * @var int
173
     */
174
    private $connect_timeout = 10;
175
176
    /**
177
     * Default sender username
178
     *
179
     * @var string
180
     */
181
    private $from_user = 'user';
182
183
    /**
184
     * Default sender host
185
     *
186
     * @var string
187
     */
188
    private $from_domain = 'localhost';
189
190
    /**
191
     * The host we're currently connected to
192
     *
193
     * @var string|null
194
     */
195
    private $host = null;
196
197
    /**
198
     * List of validation results
199
     *
200
     * @var array
201
     */
202
    private $results = [];
203
204
    /**
205
     * @param array|string $emails Email(s) to validate
206
     * @param string|null $sender Sender's email address
207
     */
208 15
    public function __construct($emails = [], $sender = null)
209
    {
210 15
        if (!empty($emails)) {
211 10
            $this->setEmails($emails);
212
        }
213 15
        if (null !== $sender) {
214 10
            $this->setSender($sender);
215
        }
216 15
    }
217
218
    /**
219
     * Disconnects from the SMTP server if needed to release resources
220
     */
221 15
    public function __destruct()
222
    {
223 15
        $this->disconnect(false);
224 15
    }
225
226 3
    public function acceptsAnyRecipient($domain)
227
    {
228 3
        if (!$this->catchall_test) {
229 1
            return false;
230
        }
231
232 2
        $test     = 'catch-all-test-' . time();
233 2
        $accepted = $this->rcpt($test . '@' . $domain);
234 2
        if ($accepted) {
235
            // Success on a non-existing address is a "catch-all"
236 2
            $this->domains_info[$domain]['catchall'] = true;
237 2
            return true;
238
        }
239
240
        // Log when we get disconnected while trying catchall detection
241
        $this->noop();
242
        if (!$this->connected()) {
243
            $this->debug('Disconnected after trying a non-existing recipient on ' . $domain);
244
        }
245
246
        /**
247
         * N.B.:
248
         * Disconnects are considered as a non-catch-all case this way, but
249
         * that might not always be the case.
250
         */
251
        return false;
252
    }
253
254
    /**
255
     * @param string $domain
256
     * @return array
257
     */
258 9
    protected function buildMxs($domain)
259
    {
260 9
        $mxs = [];
261
262
        // Query the MX records for the current domain
263 9
        list($hosts, $weights) = $this->mxQuery($domain);
264
265
        // Sort out the MX priorities
266 9
        foreach ($hosts as $k => $host) {
267
            $mxs[$host] = $weights[$k];
268
        }
269 9
        asort($mxs);
270
271
        // Add the hostname itself with 0 weight (RFC 2821)
272 9
        $mxs[$domain] = 0;
273
274 9
        return $mxs;
275
    }
276
277
    /**
278
     * @param array $mxs
279
     * @param string $domain
280
     * @param string $users
281
     * @return void
282
     */
283 9
    protected function attemptConnection(array $mxs, $domain, $users)
284
    {
285
        // Try each host, $_weight unused in the foreach body, but array_keys() doesn't guarantee the order
286 9
        foreach ($mxs as $host => $_weight) {
287
            // try connecting to the remote host
288
            try {
289 9
                $this->connect($host);
290 5
                if ($this->connected()) {
291 5
                    break;
292
                }
293 4
            } catch (NoConnectionException $e) {
294
                // Unable to connect to host, so these addresses are invalid?
295 4
                $this->debug('Unable to connect. Exception caught: ' . $e->getMessage());
296
                //$this->setDomainResults($users, $domain, $this->no_conn_is_valid);
297
            }
298
        }
299 9
    }
300
301
    /**
302
     * Performs validation of specified email addresses.
303
     *
304
     * @param array|string $emails Emails to validate (or a single one as a string)
305
     * @param string|null $sender Sender email address
306
     * @return array List of emails and their results
307
     */
308 10
    public function validate($emails = [], $sender = null)
309
    {
310 10
        $this->results = [];
311
312 10
        if (!empty($emails)) {
313 1
            $this->setEmails($emails);
314
        }
315 10
        if (null !== $sender) {
316 1
            $this->setSender($sender);
317
        }
318
319 10
        if (empty($this->domains)) {
320 1
            return $this->results;
321
        }
322
323 9
        $this->loop();
324
325 8
        return $this->getResults();
326
    }
327
328
    /**
329
     * @return void
330
     */
331 9
    protected function loop()
332
    {
333
        // Query the MTAs on each domain if we have them
334 9
        foreach ($this->domains as $domain => $users) {
335 9
            $mxs = $this->buildMxs($domain);
336
337 9
            $this->debug('MX records (' . $domain . '): ' . print_r($mxs, true));
338 9
            $this->domains_info[$domain]          = [];
339 9
            $this->domains_info[$domain]['users'] = $users;
340 9
            $this->domains_info[$domain]['mxs']   = $mxs;
341
342
            // Set default results as though we can't communicate at all...
343 9
            $this->setDomainResults($users, $domain, $this->no_conn_is_valid);
344 9
            $this->attemptConnection($mxs, $domain, $users);
345 9
            $this->performSmtpDance($domain, $users);
346
        }
347 8
    }
348
349 9
    protected function performSmtpDance($domain, array $users)
350
    {
351
        // Are we connected?
352 9
        if ($this->connected()) {
353
            try {
354
                // Say helo, and continue if we can talk
355 5
                if ($this->helo()) {
356
                    // try issuing MAIL FROM
357 4
                    if (!$this->mail($this->from_user . '@' . $this->from_domain)) {
358
                        // MAIL FROM not accepted, we can't talk
359 1
                        $this->setDomainResults($users, $domain, $this->no_comm_is_valid);
360
                    }
361
362
                    /**
363
                     * If we're still connected, proceed (cause we might get
364
                     * disconnected, or banned, or greylisted temporarily etc.)
365
                     * see mail() for more
366
                     */
367 4
                    if ($this->connected()) {
368 3
                        $this->noop();
369
370
                        // Attempt a catch-all test for the domain (if configured to do so)
371 3
                        $is_catchall_domain = $this->acceptsAnyRecipient($domain);
372
373
                        // If a catchall domain is detected, and we consider
374
                        // accounts on such domains as invalid, mark all the
375
                        // users as invalid and move on
376 3
                        if ($is_catchall_domain) {
377 2
                            if (!$this->catchall_is_valid) {
378 1
                                $this->setDomainResults($users, $domain, $this->catchall_is_valid);
379 1
                                return;
380
                            }
381
                        }
382
383
                        // If we're still connected, try issuing rcpts
384 2
                        if ($this->connected()) {
385 2
                            $this->noop();
386
                            // RCPT for each user
387 2
                            foreach ($users as $user) {
388 2
                                $address                 = $user . '@' . $domain;
389 2
                                $this->results[$address] = $this->rcpt($address);
390 2
                                $this->noop();
391
                            }
392
                        }
393
394
                        // Saying bye-bye if we're still connected, cause we're done here
395 2
                        if ($this->connected()) {
396
                            // Issue a RSET for all the things we just made the MTA do
397 2
                            $this->rset();
398 3
                            $this->disconnect();
399
                        }
400
                    }
401 3
                } else {
402
                    // We didn't get a good response to helo and should be disconnected already
403
                    //$this->setDomainResults($users, $domain, $this->no_comm_is_valid);
404
                }
405 1
            } catch (UnexpectedResponseException $e) {
406
                // Unexpected responses handled as $this->no_comm_is_valid, that way anyone can
407
                // decide for themselves if such results are considered valid or not
408
                $this->setDomainResults($users, $domain, $this->no_comm_is_valid);
409 1
            } catch (TimeoutException $e) {
410
                // A timeout is a comm failure, so treat the results on that domain
411
                // according to $this->no_comm_is_valid as well
412
                $this->setDomainResults($users, $domain, $this->no_comm_is_valid);
413
            }
414
        }
415 7
    }
416
417
    /**
418
     * Get validation results
419
     *
420
     * @param bool $include_domains_info Whether to include extra info in the results
421
     *
422
     * @return array
423
     */
424 9
    public function getResults($include_domains_info = true)
425
    {
426 9
        if ($include_domains_info) {
427 9
            $this->results['domains'] = $this->domains_info;
428
        } else {
429 1
            unset($this->results['domains']);
430
        }
431
432 9
        return $this->results;
433
    }
434
435
    /**
436
     * Helper to set results for all the users on a domain to a specific value
437
     *
438
     * @param array $users Users (usernames)
439
     * @param string $domain The domain for the users/usernames
440
     * @param bool $val Value to set
441
     *
442
     * @return void
443
     */
444 9
    private function setDomainResults(array $users, $domain, $val)
445
    {
446 9
        foreach ($users as $user) {
447 9
            $this->results[$user . '@' . $domain] = $val;
448
        }
449 9
    }
450
451
    /**
452
     * Returns true if we're connected to an MTA
453
     *
454
     * @return bool
455
     */
456 15
    protected function connected()
457
    {
458 15
        return is_resource($this->socket);
459
    }
460
461
    /**
462
     * Tries to connect to the specified host on the pre-configured port.
463
     *
464
     * @param string $host Host to connect to
465
     *
466
     * @throws NoConnectionException
467
     * @throws NoTimeoutException
468
     *
469
     * @return void
470
     */
471 9
    protected function connect($host)
472
    {
473 9
        $remote_socket = $host . ':' . $this->connect_port;
474 9
        $errnum        = 0;
475 9
        $errstr        = '';
476 9
        $this->host    = $remote_socket;
477
478
        // Open connection
479 9
        $this->debug('Connecting to ' . $this->host);
480
        // @codingStandardsIgnoreLine
481 9
        $this->socket = /** @scrutinizer ignore-unhandled */ @stream_socket_client(
0 ignored issues
show
Documentation Bug introduced by
It seems like @stream_socket_client($t...->stream_context_args)) can also be of type false. However, the property $socket is declared as type resource. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
482 9
            $this->host,
483 9
            $errnum,
484 9
            $errstr,
485 9
            $this->connect_timeout,
486 9
            STREAM_CLIENT_CONNECT,
487 9
            stream_context_create($this->stream_context_args)
488
        );
489
490
        // Check and throw if not connected
491 9
        if (!$this->connected()) {
492 4
            $this->debug('Connect failed: ' . $errstr . ', error number: ' . $errnum . ', host: ' . $this->host);
493 4
            throw new NoConnectionException('Cannot open a connection to remote host (' . $this->host . ')');
494
        }
495
496 5
        $result = stream_set_timeout($this->socket, $this->connect_timeout);
497 5
        if (!$result) {
498
            throw new NoTimeoutException('Cannot set timeout');
499
        }
500
501 5
        $this->debug('Connected to ' . $this->host . ' successfully');
502 5
    }
503
504
    /**
505
     * Disconnects the currently connected MTA.
506
     *
507
     * @param bool $quit Whether to send QUIT command before closing the socket on our end
508
     *
509
     * @return void
510
     */
511 15
    protected function disconnect($quit = true)
512
    {
513 15
        if ($quit) {
514 2
            $this->quit();
515
        }
516
517 15
        if ($this->connected()) {
518 5
            $this->debug('Closing socket to ' . $this->host);
519 5
            fclose($this->socket);
520
        }
521
522 15
        $this->host = null;
523 15
        $this->resetState();
524 15
    }
525
526
    /**
527
     * Resets internal state flags to defaults
528
     *
529
     * @return void
530
     */
531 15
    private function resetState()
532
    {
533 15
        $this->state['helo'] = false;
534 15
        $this->state['mail'] = false;
535 15
        $this->state['rcpt'] = false;
536 15
    }
537
538
    /**
539
     * Sends a HELO/EHLO sequence.
540
     *
541
     * @todo Implement TLS
542
     *
543
     * @return bool|null True if successful, false otherwise. Null if already done.
544
     */
545 5
    protected function helo()
546
    {
547
        // Don't do it if already done
548 5
        if ($this->state['helo']) {
549
            return null;
550
        }
551
552 5
        $result = false;
553
        try {
554 5
            $this->expect(self::SMTP_CONNECT_SUCCESS, $this->command_timeouts['helo']);
555 5
            $this->ehlo();
556
557
            // Session started
558 4
            $this->state['helo'] = true;
559
560
            // Are we going for a TLS connection?
561
            /*
562
            if ($this->tls) {
563
                // send STARTTLS, wait 3 minutes
564
                $this->send('STARTTLS');
565
                $this->expect(self::SMTP_CONNECT_SUCCESS, $this->command_timeouts['tls']);
566
                $result = stream_socket_enable_crypto($this->socket, true,
567
                    STREAM_CRYPTO_METHOD_TLS_CLIENT);
568
                if (!$result) {
569
                    throw new SMTP_Validate_Email_Exception_No_TLS('Cannot enable TLS');
570
                }
571
            }
572
            */
573
574 4
            $result = true;
575 1
        } catch (UnexpectedResponseException $e) {
576
            // Connected, but got an unexpected response, so disconnect
577
            $result = false;
578
            $this->debug('Unexpected response after connecting: ' . $e->getMessage());
579
            $this->disconnect(false);
580
        }
581
582 4
        return $result;
583
    }
584
585
    /**
586
     * Sends `EHLO` or `HELO`, depending on what's supported by the remote host.
587
     *
588
     * @return void
589
     */
590 5
    protected function ehlo()
591
    {
592
        try {
593
            // Modern
594 5
            $this->send('EHLO ' . $this->from_domain);
595 4
            $this->expect(self::SMTP_GENERIC_SUCCESS, $this->command_timeouts['ehlo']);
596 1
        } catch (UnexpectedResponseException $e) {
597
            // Legacy
598
            $this->send('HELO ' . $this->from_domain);
599
            $this->expect(self::SMTP_GENERIC_SUCCESS, $this->command_timeouts['helo']);
600
        }
601 4
    }
602
603
    /**
604
     * Sends a `MAIL FROM` command which indicates the sender.
605
     *
606
     * @param string $from The "From:" address
607
     *
608
     * @throws NoHeloException
609
     *
610
     * @return bool Whether the command was accepted or not
611
     */
612 4
    protected function mail($from)
613
    {
614 4
        if (!$this->state['helo']) {
615
            throw new NoHeloException('Need HELO before MAIL FROM');
616
        }
617
618
        // Issue MAIL FROM, 5 minute timeout
619 4
        $this->send('MAIL FROM:<' . $from . '>');
620
621
        try {
622 4
            $this->expect(self::SMTP_GENERIC_SUCCESS, $this->command_timeouts['mail']);
623
624
            // Set state flags
625 3
            $this->state['mail'] = true;
626 3
            $this->state['rcpt'] = false;
627
628 3
            $result = true;
629 1
        } catch (UnexpectedResponseException $e) {
630 1
            $result = false;
631
632
            // Got something unexpected in response to MAIL FROM
633 1
            $this->debug("Unexpected response to MAIL FROM\n:" . $e->getMessage());
634
635
            // Hotmail has been known to do this + was closing the connection
636
            // forcibly on their end, so we're killing the socket here too
637 1
            $this->disconnect(false);
638
        }
639
640 4
        return $result;
641
    }
642
643
    /**
644
     * Sends a RCPT TO command to indicate a recipient.
645
     *
646
     * @param string $to Recipient's email address
647
     * @throws NoMailFromException
648
     *
649
     * @return bool Whether the recipient was accepted or not
650
     */
651 3
    protected function rcpt($to)
652
    {
653
        // Need to have issued MAIL FROM first
654 3
        if (!$this->state['mail']) {
655
            throw new NoMailFromException('Need MAIL FROM before RCPT TO');
656
        }
657
658 3
        $valid          = false;
659
        $expected_codes = [
660 3
            self::SMTP_GENERIC_SUCCESS,
661 3
            self::SMTP_USER_NOT_LOCAL
662
        ];
663
664 3
        if ($this->greylisted_considered_valid) {
665 3
            $expected_codes = array_merge($expected_codes, $this->greylisted);
666
        }
667
668
        // Issue RCPT TO, 5 minute timeout
669
        try {
670 3
            $this->send('RCPT TO:<' . $to . '>');
671
            // Handle response
672
            try {
673 3
                $this->expect($expected_codes, $this->command_timeouts['rcpt']);
674 3
                $this->state['rcpt'] = true;
675 3
                $valid               = true;
676
            } catch (UnexpectedResponseException $e) {
677 3
                $this->debug('Unexpected response to RCPT TO: ' . $e->getMessage());
678
            }
679
        } catch (Exception $e) {
680
            $this->debug('Sending RCPT TO failed: ' . $e->getMessage());
681
        }
682
683 3
        return $valid;
684
    }
685
686
    /**
687
     * Sends a RSET command and resets certain parts of internal state.
688
     *
689
     * @return void
690
     */
691 2
    protected function rset()
692
    {
693 2
        $this->send('RSET');
694
695
        // MS ESMTP doesn't follow RFC according to ZF tracker, see [ZF-1377]
696
        $expected = [
697 2
            self::SMTP_GENERIC_SUCCESS,
698 2
            self::SMTP_CONNECT_SUCCESS,
699 2
            self::SMTP_NOT_IMPLEMENTED,
700
            // hotmail returns this o_O
701 2
            self::SMTP_TRANSACTION_FAILED
702
        ];
703 2
        $this->expect($expected, $this->command_timeouts['rset'], true);
704 2
        $this->state['mail'] = false;
705 2
        $this->state['rcpt'] = false;
706 2
    }
707
708
    /**
709
     * Sends a QUIT command.
710
     *
711
     * @return void
712
     */
713 2
    protected function quit()
714
    {
715
        // Although RFC says QUIT can be issued at any time, we won't
716 2
        if ($this->state['helo']) {
717 2
            $this->send('QUIT');
718 2
            $this->expect(
719 2
                [self::SMTP_GENERIC_SUCCESS,self::SMTP_QUIT_SUCCESS],
720 2
                $this->command_timeouts['quit'],
721 2
                true
722
            );
723
        }
724 2
    }
725
726
    /**
727
     * Sends a NOOP command.
728
     *
729
     * @return void
730
     */
731 3
    protected function noop()
732
    {
733 3
        $this->send('NOOP');
734
735
        /**
736
         * The `SMTP` string is here to fix issues with some bad RFC implementations.
737
         * Found at least 1 server replying to NOOP without any code.
738
         */
739
        $expected_codes = [
740 3
            'SMTP',
741 3
            self::SMTP_BAD_SEQUENCE,
742 3
            self::SMTP_NOT_IMPLEMENTED,
743 3
            self::SMTP_GENERIC_SUCCESS,
744 3
            self::SMTP_SYNTAX_ERROR,
745 3
            self::SMTP_CONNECT_SUCCESS
746
        ];
747 3
        $this->expect($expected_codes, $this->command_timeouts['noop'], true);
748 3
    }
749
750
    /**
751
     * Sends a command to the remote host.
752
     *
753
     * @param string $cmd The command to send
754
     *
755
     * @return int|bool Number of bytes written to the stream
756
     * @throws NoConnectionException
757
     * @throws SendFailedException
758
     */
759 5
    protected function send($cmd)
760
    {
761
        // Must be connected
762 5
        $this->throwIfNotConnected();
763
764 4
        $this->debug('send>>>: ' . $cmd);
765
        // Write the cmd to the connection stream
766 4
        $result = fwrite($this->socket, $cmd . self::CRLF);
767
768
        // Did it work?
769 4
        if (false === $result) {
770
            throw new SendFailedException('Send failed on: ' . $this->host);
771
        }
772
773 4
        return $result;
774
    }
775
776
    /**
777
     * Receives a response line from the remote host.
778
     *
779
     * @param int $timeout Timeout in seconds
780
     *
781
     * @return string
782
     *
783
     * @throws NoConnectionException
784
     * @throws TimeoutException
785
     * @throws NoResponseException
786
     */
787 5
    protected function recv($timeout = null)
788
    {
789
        // Must be connected
790 5
        $this->throwIfNotConnected();
791
792
        // Has a custom timeout been specified?
793 5
        if (null !== $timeout) {
794 5
            stream_set_timeout($this->socket, $timeout);
795
        }
796
797
        // Retrieve response
798 5
        $line = fgets($this->socket, 1024);
799 5
        $this->debug('<<<recv: ' . $line);
800
801
        // Have we timed out?
802 5
        $info = stream_get_meta_data($this->socket);
803 5
        if (!empty($info['timed_out'])) {
804
            throw new TimeoutException('Timed out in recv');
805
        }
806
807
        // Did we actually receive anything?
808 5
        if (false === $line) {
809 1
            throw new NoResponseException('No response in recv');
810
        }
811
812 4
        return $line;
813
    }
814
815
    /**
816
     * Receives lines from the remote host and looks for expected response codes.
817
     *
818
     * @param int|int[]|array|string $codes List of one or more expected response codes
819
     * @param int $timeout The timeout for this individual command, if any
820
     * @param bool $empty_response_allowed When true, empty responses are allowed
821
     *
822
     * @return string The last text message received
823
     *
824
     * @throws UnexpectedResponseException
825
     */
826 5
    protected function expect($codes, $timeout = null, $empty_response_allowed = false)
827
    {
828 5
        if (!is_array($codes)) {
829 5
            $codes = (array) $codes;
830
        }
831
832 5
        $code = null;
833 5
        $text = '';
834
835
        try {
836 5
            $line = $this->recv($timeout);
837 4
            $text = $line;
838 4
            while (preg_match('/^[0-9]+-/', $line)) {
839 4
                $line  = $this->recv($timeout);
840 4
                $text .= $line;
841
            }
842 4
            sscanf($line, '%d%s', $code, $text);
843
            // TODO/FIXME: This is terrible to read/comprehend
844 4
            if ($code == self::SMTP_SERVICE_UNAVAILABLE ||
845 4
                (false === $empty_response_allowed && (null === $code || !in_array($code, $codes)))) {
846 4
                throw new UnexpectedResponseException($line);
847
            }
848 2
        } catch (NoResponseException $e) {
849
            /**
850
             * No response in expect() probably means that the remote server
851
             * forcibly closed the connection so lets clean up on our end as well?
852
             */
853 1
            $this->debug('No response in expect(): ' . $e->getMessage());
854 1
            $this->disconnect(false);
855
        }
856
857 5
        return $text;
858
    }
859
860
    /**
861
     * Splits the email address string into its respective user and domain parts
862
     * and returns those as an array.
863
     *
864
     * @param string $email Email address
865
     *
866
     * @return array ['user', 'domain']
867
     */
868 11
    protected function splitEmail($email)
869
    {
870 11
        $parts  = explode('@', $email);
871 11
        $domain = array_pop($parts);
872 11
        $user   = implode('@', $parts);
873
874 11
        return [$user, $domain];
875
    }
876
877
    /**
878
     * Sets the email addresses that should be validated.
879
     *
880
     * @param array|string $emails List of email addresses (or a single one a string).
881
     *
882
     * @return void
883
     */
884 10
    public function setEmails($emails)
885
    {
886 10
        if (!is_array($emails)) {
887 9
            $emails = (array) $emails;
888
        }
889
890 10
        $this->domains = [];
891
892 10
        foreach ($emails as $email) {
893 10
            list($user, $domain) = $this->splitEmail($email);
894 10
            if (!isset($this->domains[$domain])) {
895 10
                $this->domains[$domain] = [];
896
            }
897 10
            $this->domains[$domain][] = $user;
898
        }
899 10
    }
900
901
    /**
902
     * Sets the email address to use as the sender/validator.
903
     *
904
     * @param string $email
905
     *
906
     * @return void
907
     */
908 10
    public function setSender($email)
909
    {
910 10
        $parts             = $this->splitEmail($email);
911 10
        $this->from_user   = $parts[0];
912 10
        $this->from_domain = $parts[1];
913 10
    }
914
915
    /**
916
     * Queries the DNS server for MX entries of a certain domain.
917
     *
918
     * @param string $domain The domain for which to retrieve MX records
919
     * @return array MX hosts and their weights
920
     */
921 9
    protected function mxQuery($domain)
922
    {
923 9
        $hosts  = [];
924 9
        $weight = [];
925 9
        getmxrr($domain, $hosts, $weight);
926
927 9
        return [$hosts, $weight];
928
    }
929
930
    /**
931
     * Throws if not currently connected.
932
     *
933
     * @return void
934
     * @throws NoConnectionException
935
     */
936 5
    private function throwIfNotConnected()
937
    {
938 5
        if (!$this->connected()) {
939 1
            throw new NoConnectionException('No connection');
940
        }
941 5
    }
942
943
    /**
944
     * Debug helper. If it detects a CLI env, it just dumps given `$str` on a
945
     * new line, otherwise it prints stuff <pre>.
946
     *
947
     * @param string $str
948
     *
949
     * @return void
950
     */
951 9
    private function debug($str)
952
    {
953 9
        $str = $this->stamp($str);
954 9
        $this->log($str);
955 9
        if ($this->debug) {
956 1
            if ('cli' !== PHP_SAPI) {
957
                $str = '<br/><pre>' . htmlspecialchars($str) . '</pre>';
958
            }
959 1
            echo "\n" . $str;
960
        }
961 9
    }
962
963
    /**
964
     * Adds a message to the log array
965
     *
966
     * @param string $msg
967
     *
968
     * @return void
969
     */
970 9
    private function log($msg)
971
    {
972 9
        $this->log[] = $msg;
973 9
    }
974
975
    /**
976
     * Prepends the given $msg with the current date and time inside square brackets.
977
     *
978
     * @param string $msg
979
     *
980
     * @return string
981
     */
982 9
    private function stamp($msg)
983
    {
984 9
        $date = \DateTime::createFromFormat('U.u', sprintf('%.f', microtime(true)))->format('Y-m-d\TH:i:s.uO');
985 9
        $line = '[' . $date . '] ' . $msg;
986
987 9
        return $line;
988
    }
989
990
    /**
991
     * Returns the log array
992
     *
993
     * @return array
994
     */
995 4
    public function getLog()
996
    {
997 4
        return $this->log;
998
    }
999
1000
    /**
1001
     * Truncates the log array
1002
     *
1003
     * @return void
1004
     */
1005 1
    public function clearLog()
1006
    {
1007 1
        $this->log = [];
1008 1
    }
1009
1010
    /**
1011
     * Compat for old lower_cased method calls.
1012
     *
1013
     * @param string $name
1014
     * @param array  $args
1015
     *
1016
     * @return void
1017
     */
1018 2
    public function __call($name, $args)
1019
    {
1020 2
        $camelized = self::camelize($name);
1021 2
        if (\method_exists($this, $camelized)) {
1022 2
            return \call_user_func_array([$this, $camelized], $args);
1023
        } else {
1024 1
            trigger_error('Fatal error: Call to undefined method ' . self::class . '::' . $name . '()', E_USER_ERROR);
1025
        }
1026
    }
1027
1028
    /**
1029
     * Set the desired connect timeout.
1030
     *
1031
     * @param int $timeout Connect timeout in seconds
1032
     *
1033
     * @return void
1034
     */
1035 7
    public function setConnectTimeout($timeout)
1036
    {
1037 7
        $this->connect_timeout = (int) $timeout;
1038 7
    }
1039
1040
    /**
1041
     * Get the current connect timeout.
1042
     *
1043
     * @return int
1044
     */
1045 1
    public function getConnectTimeout()
1046
    {
1047 1
        return $this->connect_timeout;
1048
    }
1049
1050
    /**
1051
     * Set connect port.
1052
     *
1053
     * @param int $port
1054
     *
1055
     * @return void
1056
     */
1057 6
    public function setConnectPort($port)
1058
    {
1059 6
        $this->connect_port = (int) $port;
1060 6
    }
1061
1062
    /**
1063
     * Get current connect port.
1064
     *
1065
     * @return int
1066
     */
1067 1
    public function getConnectPort()
1068
    {
1069 1
        return $this->connect_port;
1070
    }
1071
1072
    /**
1073
     * Turn on "catch-all" detection.
1074
     *
1075
     * @return void
1076
     */
1077 3
    public function enableCatchAllTest()
1078
    {
1079 3
        $this->catchall_test = true;
1080 3
    }
1081
1082
    /**
1083
     * Turn off "catch-all" detection.
1084
     *
1085
     * @return void
1086
     */
1087 1
    public function disableCatchAllTest()
1088
    {
1089 1
        $this->catchall_test = false;
1090 1
    }
1091
1092
    /**
1093
     * Returns whether "catch-all" test is to be performed or not.
1094
     *
1095
     * @return bool
1096
     */
1097 1
    public function isCatchAllEnabled()
1098
    {
1099 1
        return $this->catchall_test;
1100
    }
1101
1102
    /**
1103
     * Set whether "catch-all" results are considered valid or not.
1104
     *
1105
     * @param bool $flag When true, "catch-all" accounts are considered valid
1106
     *
1107
     * @return void
1108
     */
1109 2
    public function setCatchAllValidity($flag)
1110
    {
1111 2
        $this->catchall_is_valid = (bool) $flag;
1112 2
    }
1113
1114
    /**
1115
     * Get current state of "catch-all" validity flag.
1116
     *
1117
     * @return bool
1118
     */
1119 1
    public function getCatchAllValidity()
1120
    {
1121 1
        return $this->catchall_is_valid;
1122
    }
1123
1124
    /**
1125
     * Camelizes a string.
1126
     *
1127
     * @param string $id A string to camelize
1128
     *
1129
     * @return string The camelized string
1130
     */
1131 2
    private static function camelize($id)
1132
    {
1133 2
        return strtr(
1134 2
            ucwords(
1135 2
                strtr(
1136 2
                    $id,
1137 2
                    ['_' => ' ', '.' => '_ ', '\\' => '_ ']
1138
                )
1139
            ),
1140 2
            [' ' => '']
1141
        );
1142
    }
1143
}
1144