/
smtp.php
1800 lines (1535 loc) · 65.9 KB
/
smtp.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// CubicleSoft PHP SMTP e-mail functions.
// (C) 2018 CubicleSoft. All Rights Reserved.
// Load dependencies.
if (!class_exists("UTF8", false)) require_once str_replace("\\", "/", dirname(__FILE__)) . "/utf8.php";
if (!class_exists("IPAddr", false)) require_once str_replace("\\", "/", dirname(__FILE__)) . "/ipaddr.php";
class SMTP
{
public static $dnsttlcache = array();
private static $depths = array();
// Reduce dependencies. Duplicates code though.
private static function FilenameSafe($filename)
{
return preg_replace('/\s+/', "-", trim(trim(preg_replace('/[^A-Za-z0-9_.\-]/', " ", $filename), ".")));
}
private static function ReplaceNewlines($replacewith, $data)
{
$data = str_replace("\r\n", "\n", $data);
$data = str_replace("\r", "\n", $data);
$data = str_replace("\n", $replacewith, $data);
return $data;
}
// RFC1341 is a hacky workaround to allow 8-bit over 7-bit transport.
// Also known as "Quoted Printable".
public static function ConvertToRFC1341($data, $restrictmore = false)
{
$data2 = "";
// Ranges are limited so that EBCDIC transport works.
// Also, PHP's mail() function doesn't deal well with lines that start with '.'.
// http://us2.php.net/manual/en/function.mail.php
$y = strlen($data);
for ($x = 0; $x < $y; $x++)
{
$currchr = ord($data[$x]);
if ($currchr == 9 || $currchr == 32 || ($currchr >= 37 && $currchr <= 45) || ($currchr >= 47 && $currchr <= 60) || $currchr == 62 || $currchr == 63 || ($currchr >= 65 && $currchr <= 90) || $currchr == 95 || ($currchr >= 97 && $currchr <= 122))
{
if (!$restrictmore) $data2 .= $data[$x];
else if (($currchr >= 48 && $currchr <= 57) || ($currchr >= 65 && $currchr <= 90) || ($currchr >= 97 && $currchr <= 122)) $data2 .= sprintf("=%02X", $currchr);
else $data2 .= $data[$x];
}
else if ($currchr == 13 && $x + 1 < $y && ord($data[$x + 1]) == 10)
{
$data2 .= "\r\n";
$x++;
}
else
{
$data2 .= sprintf("=%02X", $currchr);
}
}
// Break the string on 75 character boundaries and add '=' character.
$data2 = explode("\r\n", $data2);
$result = "";
foreach ($data2 as $currline)
{
$x2 = 0;
$y2 = strlen($currline);
while ($x2 + 75 < $y2)
{
if ($currline[$x2 + 74] == '=')
{
$result .= substr($currline, $x2, 74);
$x2 += 74;
}
else if ($currline[$x2 + 73] == '=')
{
$result .= substr($currline, $x2, 73);
$x2 += 73;
}
else
{
$result .= substr($currline, $x2, 75);
$x2 += 75;
}
$result .= "=\r\n";
}
if ($x2 < $y2) $result .= substr($currline, $x2, $y2 - $x2);
$result .= "\r\n";
}
return $result;
}
public static function ConvertEmailMessageToRFC1341($data, $restrictmore = false)
{
$data = self::ReplaceNewlines("\r\n", $data);
return self::ConvertToRFC1341($data, $restrictmore);
}
// RFC1342 is a hacky workaround to encode headers in e-mails.
public static function ConvertToRFC1342($data, $lang = "UTF-8", $encodeb64 = true)
{
$result = "";
// An individual RFC1342-compliant string can only be 75 characters long, 6 must be markers,
// one must be the encoding method, and at least one must be data (adjusted to 4 required
// spaces to simplify processing).
if (strlen($lang) > 75 - 6 - 1 - 4) return $result;
$lang = strtoupper($lang);
if ($lang != "ISO-8859-1" && $lang != "US-ASCII") $encodeb64 = true;
$maxdatalength = 75 - 6 - strlen($lang) - 1;
if ($encodeb64)
{
$maxdatalength = $maxdatalength * 3 / 4;
$y = strlen($data);
if ($lang == "UTF-8")
{
$x = 0;
$pos = 0;
$size = 0;
while (UTF8::NextChrPos($data, $y, $pos, $size))
{
if ($pos + $size - $x > $maxdatalength)
{
if ($x) $result .= " ";
$result .= "=?" . $lang . "?B?" . base64_encode(substr($data, $x, $pos - $x)) . "?=";
$x = $pos;
}
}
}
else
{
for ($x = 0; $x + $maxdatalength < $y; $x += $maxdatalength)
{
if ($x) $result .= " ";
$result .= "=?" . $lang . "?B?" . base64_encode(substr($data, $x, $maxdatalength)) . "?=";
}
}
if ($x < $y)
{
if ($x) $result .= " ";
$result .= "=?" . $lang . "?B?" . base64_encode(substr($data, $x, $y - $x)) . "?=";
}
}
else
{
// Quoted printable.
$maxdatalength = $maxdatalength / 3;
$y = strlen($data);
for ($x = 0; $x + $maxdatalength < $y; $x += $maxdatalength)
{
if ($x) $result .= " ";
$result .= "=?" . $lang . "?Q?" . str_replace(" ", "_", self::ConvertToRFC1341(substr($data, $x, $maxdatalength), true)) . "?=";
}
if ($x < $y)
{
if ($x) $result .= " ";
$result .= "=?" . $lang . "?Q?" . str_replace(" ", "_", self::ConvertToRFC1341(substr($data, $x, $y - $x), true)) . "?=";
}
}
return $result;
}
private static function SMTP_Translate()
{
$args = func_get_args();
if (!count($args)) return "";
return call_user_func_array((defined("CS_TRANSLATE_FUNC") && function_exists(CS_TRANSLATE_FUNC) ? CS_TRANSLATE_FUNC : "sprintf"), $args);
}
// Takes a potentially invalid e-mail address and attempts to make it valid.
public static function MakeValidEmailAddress($email, $options = array())
{
$email = str_replace("\t", " ", $email);
$email = str_replace("\r", " ", $email);
$email = str_replace("\n", " ", $email);
$email = trim($email);
// Reverse parse out the initial domain/IP address part of the e-mail address.
$domain = "";
$state = "domend";
$cfwsdepth = 0;
while ($email != "" && $state != "")
{
$prevchr = substr($email, -2, 1);
$lastchr = substr($email, -1);
switch ($state)
{
case "domend":
{
if ($lastchr == ")")
{
$laststate = "domain";
$state = "cfws";
}
else if ($lastchr == "]" || $lastchr == "}")
{
$domain .= "]";
$email = trim(substr($email, 0, -1));
$state = "ipaddr";
}
else
{
$state = "domain";
}
break;
}
case "cfws":
{
if ($prevchr == "\\") $email = trim(substr($email, 0, -2));
else if ($lastchr == ")")
{
$email = trim(substr($email, 0, -1));
$depth++;
}
else if ($lastchr == "(")
{
$email = trim(substr($email, 0, -1));
$depth--;
if (!$depth && substr($email, -1) != ")") $state = $laststate;
}
else $email = trim(substr($email, 0, -1));
break;
}
case "ipaddr":
{
if ($lastchr == "[" || $lastchr == "{" || $lastchr == "@")
{
$domain .= "[";
$state = "@";
if ($lastchr == "@") break;
}
else if ($lastchr == "," || $lastchr == ".") $domain .= ".";
else if ($lastchr == ";" || $lastchr == ":") $domain .= ":";
else if (preg_match('/[A-Za-z0-9]/', $lastchr)) $domain .= $lastchr;
$email = trim(substr($email, 0, -1));
break;
}
case "domain":
{
if ($lastchr == "@")
{
$state = "@";
break;
}
else if ($lastchr == ")")
{
$state = "cfws";
$laststate = "@";
break;
}
else if ($lastchr == "," || $lastchr == ".") $domain .= ".";
else if (preg_match('/[A-Za-z0-9-]/', $lastchr)) $domain .= $lastchr;
$email = trim(substr($email, 0, -1));
break;
}
case "@":
{
if ($lastchr == "@") $state = "";
$email = trim(substr($email, 0, -1));
break;
}
}
}
$domain = strrev($domain);
$parts = explode(".", $domain);
foreach ($parts as $num => $part) $parts[$num] = str_replace(" ", "-", trim(str_replace("-", " ", $part)));
$domain = implode(".", $parts);
// Forward parse out the local part of the e-mail address.
// Remove CFWS (comments, folding whitespace).
while (substr($email, 0, 1) == "(")
{
while ($email != "")
{
$currchr = substr($email, 0, 1);
if ($currchr == "\\") $email = trim(substr($email, 2));
else if ($currchr == "(")
{
$depth++;
$email = trim(substr($email, 1));
}
else if ($currchr == ")")
{
$email = trim(substr($email, 1));
$depth--;
if (!$depth && substr($email, 0, 1) != "(") break;
}
}
}
// Process quoted/unquoted string.
$local = "";
if (substr($email, 0, 1) == "\"")
{
$email = substr($email, 1);
while ($email != "")
{
$currchr = substr($email, 0, 1);
$nextchr = substr($email, 1, 1);
if ($currchr == "\\")
{
if ($nextchr == "\\" || $nextchr == "\"")
{
$local .= substr($email, 0, 2);
$email = substr($email, 2);
}
else if (ord($nextchr) >= 33 && ord($nextchr) <= 126)
{
$local .= substr($email, 1, 1);
$email = substr($email, 2);
}
}
else if ($currchr == "\"") break;
else if (ord($currchr) >= 33 && ord($nextchr) <= 126)
{
$local .= substr($email, 0, 1);
$email = substr($email, 1);
}
else $email = substr($email, 1);
}
if (substr($local, -1) != "\"") $local .= "\"";
}
else
{
while ($email != "")
{
$currchr = substr($email, 0, 1);
if (preg_match("/[A-Za-z0-9]/", $currchr) || $currchr == "!" || $currchr == "#" || $currchr == "\$" || $currchr == "%" || $currchr == "&" || $currchr == "'" || $currchr == "*" || $currchr == "+" || $currchr == "-" || $currchr == "/" || $currchr == "=" || $currchr == "?" || $currchr == "^" || $currchr == "_" || $currchr == "`" || $currchr == "{" || $currchr == "|" || $currchr == "}" || $currchr == "~" || $currchr == ".")
{
$local .= $currchr;
$email = substr($email, 1);
}
else break;
}
$local = preg_replace('/[.]+/', ".", $local);
if (substr($local, 0, 1) == ".") $local = substr($local, 1);
if (substr($local, -1) == ".") $local = substr($local, 0, -1);
}
while (substr($local, -2) == "\\\"") $local = substr($local, 0, -2) . "\"";
if ($local == "\"" || $local == "\"\"") $local = "";
// Analyze the domain/IP part and fix any issues.
$domain = preg_replace('/[.]+/', ".", $domain);
if (substr($domain, -1) == "]")
{
if (substr($domain, 0, 1) != "[") $domain = "[" . $domain;
// Process the IP address.
if (strtolower(substr($domain, 0, 6)) == "[ipv6:") $ipaddr = IPAddr::NormalizeIP(substr($domain, 6, -1));
else $ipaddr = IPAddr::NormalizeIP(substr($domain, 1, -1));
if ($ipaddr["ipv4"] != "") $domain = "[" . $ipaddr["ipv4"] . "]";
else $domain = "[IPv6:" . $ipaddr["ipv6"] . "]";
}
else
{
// Process the domain.
if (substr($domain, 0, 1) == ".") $domain = substr($domain, 1);
if (substr($domain, -1) == ".") $domain = substr($domain, 0, -1);
$domain = explode(".", $domain);
foreach ($domain as $num => $part)
{
if (substr($part, 0, 1) == "-") $part = substr($part, 1);
if (substr($part, -1) == "-") $part = substr($part, 0, -1);
if (strlen($part) > 63) $part = substr($part, 0, 63);
$domain[$num] = $part;
}
$domain = implode(".", $domain);
}
// Validate the final lengths.
$y = strlen($local);
$y2 = strlen($domain);
$email = $local . "@" . $domain;
if (!$y) return array("success" => false, "error" => self::SMTP_Translate("Missing local part of e-mail address."), "errorcode" => "missing_local_part", "info" => $email);
if (!$y2) return array("success" => false, "error" => self::SMTP_Translate("Missing domain part of e-mail address."), "errorcode" => "missing_domain_part", "info" => $email);
if ($y > 64 || $y2 > 253 || $y + $y2 + 1 > 253) return array("success" => false, "error" => self::SMTP_Translate("E-mail address is too long."), "errorcode" => "email_too_long", "info" => $email);
// Process results.
if (substr($domain, 0, 1) == "[" && substr($domain, -1) == "]") $result = array("success" => true, "email" => $email, "lookup" => false, "type" => "IP");
else if (isset($options["usedns"]) && $options["usedns"] === false) $result = array("success" => true, "email" => $email, "lookup" => false, "type" => "Domain", "domain" => $domain);
else if ((!isset($options["usednsttlcache"]) || $options["usednsttlcache"] === true) && isset(self::$dnsttlcache[$domain]) && self::$dnsttlcache[$domain] >= time()) $result = array("success" => true, "email" => $email, "lookup" => false, "type" => "CachedDNS", "domain" => $domain);
else
{
// Check for a mail server based on a DNS lookup.
$result = self::GetDNSRecord($domain, array("MX", "A"), (isset($options["nameservers"]) ? $options["nameservers"] : array("8.8.8.8", "8.8.4.4")), (!isset($options["usednsttlcache"]) || $options["usednsttlcache"] === true));
if ($result["success"]) $result = array("success" => true, "email" => $email, "lookup" => true, "type" => $result["type"], "domain" => $domain, "records" => $result["records"]);
}
return $result;
}
public static function UpdateDNSTTLCache()
{
$ts = time();
foreach (self::$dnsttlcache as $domain => $ts2)
{
if ($ts2 > $ts) unset(self::$dnsttlcache[$domain]);
}
}
public static function GetDNSRecord($domain, $types = array("MX", "A"), $nameservers = array("8.8.8.8", "8.8.4.4"), $cache = true)
{
// Check for a mail server based on a DNS lookup.
if (!class_exists("Net_DNS2_Resolver", false)) require_once str_replace("\\", "/", dirname(__FILE__)) . "/Net/DNS2.php";
$resolver = new Net_DNS2_Resolver(array("nameservers" => $nameservers));
try
{
foreach ($types as $type)
{
$response = $resolver->query($domain, $type);
if ($response && count($response->answer))
{
if ($cache)
{
$minttl = -1;
foreach ($response->answer as $answer)
{
if ($minttl < 0 || ($answer->ttl > 0 && $answer->ttl < $minttl)) $minttl = $answer->ttl;
}
self::$dnsttlcache[$domain] = time() + $minttl;
}
return array("success" => true, "type" => $type, "records" => $response);
}
}
return array("success" => false, "error" => self::SMTP_Translate("Invalid domain name or missing DNS record."), "errorcode" => "invalid_domain_or_missing_record", "info" => $domain);
}
catch (Exception $e)
{
return array("success" => false, "error" => self::SMTP_Translate("Invalid domain name. Internal exception occurred."), "errorcode" => "dns_library_exception", "info" => self::SMTP_Translate("%s (%s).", $e->getMessage(), $domain));
}
}
public static function EmailAddressesToNamesAndEmail(&$destnames, &$destaddrs, $emailaddrs, $removenames = false, $options = array())
{
$destnames = array();
$destaddrs = array();
$data = str_replace("\t", " ", $emailaddrs);
$data = str_replace("\r", " ", $data);
$data = str_replace("\n", " ", $data);
$data = trim($data);
// Parse e-mail addresses out of the string with a state engine.
// Parsed in reverse because that is easier than trying to figure out if each address
// starts with a name OR a quoted string for the local part of the e-mail address.
// The e-mail address parsing in this state engine is intentionally incomplete.
// The goal is to identify '"name" <emailaddr>, name <emailaddr>, emailaddr' variations.
$found = false;
while ($data != "")
{
$name = "";
$email = "";
$state = "addrend";
$cfwsdepth = 0;
$inbracket = false;
while ($data != "" && $state != "")
{
$prevchr = substr($data, -2, 1);
$lastchr = substr($data, -1);
switch ($state)
{
case "addrend":
{
if ($lastchr == ">")
{
$data = trim(substr($data, 0, -1));
$inbracket = true;
$state = "domend";
}
else if ($lastchr == "," || $lastchr == ";")
{
$data = trim(substr($data, 0, -1));
}
else $state = "domend";
break;
}
case "domend":
{
if ($lastchr == ")")
{
$laststate = "domain";
$state = "cfws";
}
else if ($lastchr == "]" || $lastchr == "}")
{
$email .= "]";
$data = trim(substr($data, 0, -1));
$state = "ipaddr";
}
else
{
$state = "domain";
}
break;
}
case "cfws":
{
if ($prevchr == "\\") $data = trim(substr($data, 0, -2));
else if ($lastchr == ")")
{
$data = trim(substr($data, 0, -1));
$depth++;
}
else if ($lastchr == "(")
{
$data = trim(substr($data, 0, -1));
$depth--;
if (!$depth && substr($data, -1) != ")") $state = $laststate;
}
else $data = trim(substr($data, 0, -1));
break;
}
case "ipaddr":
{
if ($lastchr == "[" || $lastchr == "{" || $lastchr == "@")
{
$email .= "[";
$state = "@";
if ($lastchr == "@") break;
}
else if ($lastchr == "," || $lastchr == ".") $email .= ".";
else if ($lastchr == ";" || $lastchr == ":") $email .= ":";
else if (preg_match('/[A-Za-z0-9]/', $lastchr)) $email .= $lastchr;
$data = trim(substr($data, 0, -1));
break;
}
case "domain":
{
if ($lastchr == "@")
{
$state = "@";
break;
}
else if ($lastchr == ")")
{
$state = "cfws";
$laststate = "@";
break;
}
else if ($lastchr == "," || $lastchr == ".") $email .= ".";
else if (preg_match('/[A-Za-z0-9-]/', $lastchr)) $email .= $lastchr;
$data = trim(substr($data, 0, -1));
break;
}
case "@":
{
if ($lastchr == "@")
{
$email .= "@";
$state = "localend";
}
$data = trim(substr($data, 0, -1));
break;
}
case "localend":
{
if ($lastchr == ")")
{
$state = "cfws";
$laststate = "localend";
}
else if ($lastchr == "\"")
{
$email .= "\"";
$data = substr($data, 0, -1);
$state = "quotedlocal";
}
else $state = "local";
break;
}
case "quotedlocal":
{
if ($prevchr == "\\")
{
$email .= $lastchar . $prevchr;
$data = substr($data, 0, -2);
}
else if ($lastchr == "\"")
{
$email .= $lastchar;
$data = trim(substr($data, 0, -1));
$state = "localstart";
}
else
{
$email .= $lastchar;
$data = substr($data, 0, -1);
}
break;
}
case "local":
{
if (preg_match("/[A-Za-z0-9]/", $lastchr) || $lastchr == "!" || $lastchr == "#" || $lastchr == "\$" || $lastchr == "%" || $lastchr == "&" || $lastchr == "'" || $lastchr == "*" || $lastchr == "+" || $lastchr == "-" || $lastchr == "/" || $lastchr == "=" || $lastchr == "?" || $lastchr == "^" || $lastchr == "_" || $lastchr == "`" || $lastchr == "{" || $lastchr == "|" || $lastchr == "}" || $lastchr == "~" || $lastchr == ".")
{
$email .= $lastchr;
$data = substr($data, 0, -1);
}
else if ($lastchr == ")")
{
$state = "cfws";
$laststate = "localstart";
}
else if ($inbracket)
{
if ($lastchr == "<") $state = "localstart";
else $data = substr($data, 0, -1);
}
else if ($lastchr == " " || $lastchr == "," || $lastchr == ";") $state = "localstart";
else $data = substr($data, 0, -1);
break;
}
case "localstart":
{
if ($inbracket)
{
if ($lastchr == "<") $state = "nameend";
$data = trim(substr($data, 0, -1));
}
else if ($lastchr == "," || $lastchr == ";") $state = "";
else $data = trim(substr($data, 0, -1));
break;
}
case "nameend":
{
if ($lastchr == "\"")
{
$data = substr($data, 0, -1);
$state = "quotedname";
}
else $state = "name";
break;
}
case "quotedname":
{
if ($prevchr == "\\")
{
$name .= $lastchar . $prevchr;
$data = substr($data, 0, -2);
}
else if ($lastchr == "\"")
{
$data = trim(substr($data, 0, -1));
$state = "";
}
else
{
$name .= $lastchr;
$data = substr($data, 0, -1);
}
break;
}
case "name":
{
if ($lastchr == "," || $lastchr == ";") $state = "";
else
{
$name .= $lastchr;
$data = substr($data, 0, -1);
}
break;
}
}
}
$email = self::MakeValidEmailAddress(strrev($email), $options);
if ($email["success"])
{
if ($removenames) $name = "";
$name = trim(strrev($name));
if (substr($name, 0, 1) == "\"") $name = trim(substr($name, 1));
$name = str_replace("\\\\", "\\", $name);
$name = str_replace("\\\"", "\"", $name);
$destnames[] = $name;
$destaddrs[] = $email["email"];
$found = true;
}
$data = trim($data);
}
$destnames = array_reverse($destnames);
$destaddrs = array_reverse($destaddrs);
return $found;
}
// Takes in a comma-separated list of e-mail addresses and returns appropriate e-mail headers.
public static function EmailAddressesToEmailHeaders($emailaddrs, $headername, $multiple = true, $removenames = false, $options = array())
{
$result = "";
$tempnames = array();
$tempaddrs = array();
self::EmailAddressesToNamesAndEmail($tempnames, $tempaddrs, $emailaddrs, $removenames, $options);
$y = count($tempnames);
for ($x = 0; $x < $y && ($multiple || $result == ""); $x++)
{
$name = $tempnames[$x];
$emailaddr = $tempaddrs[$x];
if ($name != "" && !UTF8::IsASCII($name)) $name = self::ConvertToRFC1342($name) . " ";
else if ($name != "") $name = '"' . $name . '" ';
if ($result != "") $result .= ",\r\n ";
if ($name != "") $result .= $name . '<' . $emailaddr . '>';
else $result .= $emailaddr;
}
if ($result != "" && $headername != "") $result = $headername . ": " . $result . "\r\n";
return $result;
}
public static function GetUserAgent($type)
{
if ($type == "Thunderbird") return "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.0\r\n";
else if ($type == "Thunderbird2") return "X-Mailer: Thunderbird 2.0.0.16 (Windows/20080708)\r\n";
else if ($type == "OutlookExpress") return "X-Mailer: Microsoft Outlook Express 6.00.2900.3198\r\nX-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3198\r\n";
else if ($type == "Exchange") return "X-Mailer: Produced By Microsoft Exchange V6.0.6619.12\r\n";
else if ($type == "OfficeOutlook") return "X-Mailer: Microsoft Office Outlook 12.0\r\n";
return "";
}
public static function GetTimeLeft($start, $limit)
{
if ($limit === false) return false;
$difftime = microtime(true) - $start;
if ($difftime >= $limit) return 0;
return $limit - $difftime;
}
private static function ProcessRateLimit($size, $start, $limit, $async)
{
$difftime = microtime(true) - $start;
if ($difftime > 0.0)
{
if ($size / $difftime > $limit)
{
// Sleeping for some amount of time will equalize the rate.
// So, solve this for $x: $size / ($x + $difftime) = $limit
$amount = ($size - ($limit * $difftime)) / $limit;
if ($async) return microtime(true) + $amount;
else usleep($amount);
}
}
return -1.0;
}
private static function StreamTimedOut($fp)
{
if (!function_exists("stream_get_meta_data")) return false;
$info = stream_get_meta_data($fp);
return $info["timed_out"];
}
// Handles partially read input. Also deals with the hacky workaround to the second bugfix in ProcessState__WriteData().
private static function ProcessState__InternalRead(&$state, $size, $endchar = false)
{
$y = strlen($state["nextread"]);
if ($size <= $y)
{
if ($endchar === false) $pos = $size;
else
{
$pos = strpos($state["nextread"], $endchar);
if ($pos === false) $pos = $size;
else $pos++;
}
$data = substr($state["nextread"], 0, $pos);
$state["nextread"] = (string)substr($state["nextread"], $pos);
return $data;
}
if ($endchar !== false)
{
$pos = strpos($state["nextread"], $endchar);
if ($pos !== false)
{
$data = substr($state["nextread"], 0, $pos + 1);
$state["nextread"] = (string)substr($state["nextread"], $pos + 1);
return $data;
}
}
$data = $state["nextread"];
$state["nextread"] = "";
$size -= $y;
do
{
if ($state["debug"]) $data2 = fread($state["fp"], $size);
else $data2 = @fread($state["fp"], $size);
if ($data2 === false || $data2 === "") return ($data !== "" ? $data : $data2);
if ($endchar !== false)
{
$pos = strpos($data2, $endchar);
if ($pos !== false)
{
$data .= substr($data2, 0, $pos + 1);
$state["nextread"] = (string)substr($data2, $pos + 1);
return $data;
}
}
$data .= $data2;
$size -= strlen($data2);
} while ($size > 0 && $endchar !== false);
return $data;
}
// Reads one or more lines in.
private static function ProcessState__ReadLine(&$state)
{
while (strpos($state["data"], "\n") === false)
{
$data2 = self::ProcessState__InternalRead($state, 116000, "\n");
if ($data2 === false || $data2 === "")
{
if (feof($state["fp"])) return array("success" => false, "error" => self::SMTP_Translate("Remote peer disconnected."), "errorcode" => "peer_disconnected");
else if ($state["async"]) return array("success" => false, "error" => self::SMTP_Translate("Non-blocking read returned no data."), "errorcode" => "no_data");
else if ($data2 === false) return array("success" => false, "error" => self::SMTP_Translate("Underlying stream encountered a read error."), "errorcode" => "stream_read_error");
}
$pos = strpos($data2, "\n");
if ($pos === false)
{
if (feof($state["fp"])) return array("success" => false, "error" => self::SMTP_Translate("Remote peer disconnected."), "errorcode" => "peer_disconnected");
if (self::StreamTimedOut($state["fp"])) return array("success" => false, "error" => self::SMTP_Translate("Underlying stream timed out."), "errorcode" => "stream_timeout_exceeded");
$pos = strlen($data2);
}
if ($state["timeout"] !== false && self::GetTimeLeft($state["startts"], $state["timeout"]) == 0) return array("success" => false, "error" => self::SMTP_Translate("SMTP timeout exceeded."), "errorcode" => "timeout_exceeded");
if (isset($state["options"]["readlinelimit"]) && strlen($state["data"]) + $pos > $state["options"]["readlinelimit"]) return array("success" => false, "error" => self::SMTP_Translate("Read line exceeded limit."), "errorcode" => "read_line_limit_exceeded");
$state["result"]["rawrecvsize"] += strlen($data2);
$state["data"] .= $data2;
if (isset($state["options"]["recvlimit"]) && $state["options"]["recvlimit"] < $state["rawsize"]) return array("success" => false, "error" => self::SMTP_Translate("Received data exceeded limit."), "errorcode" => "receive_limit_exceeded");
if (isset($state["options"]["recvratelimit"])) $state["waituntil"] = self::ProcessRateLimit($state["rawsize"], $state["recvstart"], $state["options"]["recvratelimit"], $state["async"]);
if (isset($state["options"]["debug_callback"]) && is_callable($state["options"]["debug_callback"])) call_user_func_array($state["options"]["debug_callback"], array("rawrecv", $data2, &$state["options"]["debug_callback_opts"]));
else if ($state["debug"]) $state["result"]["rawrecv"] .= $data2;
}
return array("success" => true);
}
// Writes data out.
private static function ProcessState__WriteData(&$state)
{
if ($state["data"] !== "")
{
// Serious bug in PHP core for non-blocking SSL sockets: https://bugs.php.net/bug.php?id=72333
if ($state["secure"] && $state["async"])
{
// This is a huge hack that has a pretty good chance of blocking on the socket.
// Peeling off up to just 4KB at a time helps to minimize that possibility. It's better than guaranteed failure of the socket though.
@stream_set_blocking($state["fp"], 1);
if ($state["debug"]) $result = fwrite($state["fp"], (strlen($state["data"]) > 4096 ? substr($state["data"], 0, 4096) : $state["data"]));
else $result = @fwrite($state["fp"], (strlen($state["data"]) > 4096 ? substr($state["data"], 0, 4096) : $state["data"]));
@stream_set_blocking($state["fp"], 0);
}
else
{
if ($state["debug"]) $result = fwrite($state["fp"], $state["data"]);
else $result = @fwrite($state["fp"], $state["data"]);
}
if ($result === false || feof($state["fp"])) return array("success" => false, "error" => self::SMTP_Translate("A fwrite() failure occurred. Most likely cause: Connection failure."), "errorcode" => "fwrite_failed");
// Serious bug in PHP core for all socket types: https://bugs.php.net/bug.php?id=73535
if ($result === 0)
{
// Temporarily switch to non-blocking sockets and test a one byte read (doesn't matter if data is available or not).
// This is a bigger hack than the first hack above.
if (!$state["async"]) @stream_set_blocking($state["fp"], 0);
if ($state["debug"]) $data2 = fread($state["fp"], 1);
else $data2 = @fread($state["fp"], 1);
if ($data2 === false) return array("success" => false, "error" => self::SMTPTranslate("Underlying stream encountered a read error."), "errorcode" => "stream_read_error");
if ($data2 === "" && feof($state["fp"])) return array("success" => false, "error" => self::SMTPTranslate("Remote peer disconnected."), "errorcode" => "peer_disconnected");
if ($data2 !== "") $state["nextread"] .= $data2;
if (!$state["async"]) @stream_set_blocking($state["fp"], 1);
}
if ($state["timeout"] !== false && self::GetTimeLeft($state["startts"], $state["timeout"]) == 0) return array("success" => false, "error" => self::SMTP_Translate("SMTP timeout exceeded."), "errorcode" => "timeout_exceeded");
$data2 = (string)substr($state["data"], 0, $result);
$state["data"] = (string)substr($state["data"], $result);
$state["result"]["rawsendsize"] += $result;
$state["result"]["rawsendheadersize"] += $result;
if (isset($state["options"]["sendratelimit"]))
{
$state["waituntil"] = self::ProcessRateLimit($state["result"]["rawsendsize"], $state["result"]["connected"], $state["options"]["sendratelimit"], $state["async"]);
if (microtime(true) < $state["waituntil"]) return array("success" => false, "error" => self::SMTP_Translate("Rate limit for non-blocking connection has not been reached."), "errorcode" => "no_data");
}
if (isset($state["options"]["debug_callback"]) && is_callable($state["options"]["debug_callback"])) call_user_func_array($state["options"]["debug_callback"], array("rawsend", $data2, &$state["options"]["debug_callback_opts"]));
else if ($state["debug"]) $state["result"]["rawsend"] .= $data2;
if ($state["async"] && strlen($state["data"])) return array("success" => false, "error" => self::SMTP_Translate("Non-blocking write did not send all data."), "errorcode" => "no_data");
}
return array("success" => true);
}
public static function ForceClose(&$state)
{
if ($state["fp"] !== false)
{
@fclose($state["fp"]);
$state["fp"] = false;
}
if (isset($state["currentfile"]) && $state["currentfile"] !== false)
{
if ($state["currentfile"]["fp"] !== false) @fclose($state["currentfile"]["fp"]);
$state["currentfile"] = false;
}
}
private static function CleanupErrorState(&$state, $result)
{
if (!$result["success"] && $result["errorcode"] !== "no_data")
{
self::ForceClose($state);
$state["error"] = $result;