forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 10
/
fMailbox.php
1523 lines (1320 loc) · 45.4 KB
/
fMailbox.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
/**
* Retrieves and deletes messages from a email account via IMAP or POP3
*
* All headers, text and html content returned by this class are encoded in
* UTF-8. Please see http://flourishlib.com/docs/UTF-8 for more information.
*
* @copyright Copyright (c) 2010-2012 Will Bond
* @author Will Bond [wb] <will@flourishlib.com>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fMailbox
*
*/
class fMailbox
{
const addSMIMEPair = 'fMailbox::addSMIMEPair';
const parseMessage = 'fMailbox::parseMessage';
const reset = 'fMailbox::reset';
/**
* S/MIME certificates and private keys for verification and decryption
*
* @var array
*/
static private $smime_pairs = array();
/**
* Adds an S/MIME certificate, or certificate + private key pair for verification and decryption of S/MIME messages
*
* @param string $email_address The email address the certificate or private key is for
* @param fFile|string $certificate_file The file the S/MIME certificate is stored in - required for verification and decryption
* @param fFile $private_key_file The file the S/MIME private key is stored in - required for decryption only
* @param string $private_key_password The password for the private key
* @return void
*/
static public function addSMIMEPair($email_address, $certificate_file, $private_key_file=NULL, $private_key_password=NULL)
{
if ($private_key_file !== NULL && !$private_key_file instanceof fFile) {
$private_key_file = new fFile($private_key_file);
}
if (!$certificate_file instanceof fFile) {
$certificate_file = new fFile($certificate_file);
}
self::$smime_pairs[strtolower($email_address)] = array(
'certificate' => $certificate_file,
'private_key' => $private_key_file,
'password' => $private_key_password
);
}
/**
* Takes a date, removes comments and cleans up some common formatting inconsistencies
*
* @param string $date The date to clean
* @return string The cleaned date
*/
static private function cleanDate($date)
{
$date = preg_replace('#\([^)]+\)#', ' ', trim($date));
$date = preg_replace('#\s+#', ' ', $date);
$date = preg_replace('#(\d+)-([a-z]+)-(\d{4})#i', '\1 \2 \3', $date);
$date = preg_replace('#^[a-z]+\s*,\s*#i', '', trim($date));
return trim($date);
}
/**
* Decodes encoded-word headers of any encoding into raw UTF-8
*
* @param string $text The header value to decode
* @return string The decoded UTF-8
*/
static private function decodeHeader($text)
{
$parts = preg_split('#(=\?[^\?]+\?[QB]\?[^\?]+\?=)#i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$part_with_encoding = array();
$output = '';
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if (preg_match_all('#=\?([^\?]+)\?([QB])\?([^\?]+)\?=#i', $part, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
if (strtoupper($match[2]) == 'Q') {
$part_string = rawurldecode(strtr(
$match[3],
array(
'=' => '%',
'_' => ' '
)
));
} else {
$part_string = base64_decode($match[3]);
}
$lower_encoding = strtolower($match[1]);
$last_key = count($part_with_encoding) - 1;
if (isset($part_with_encoding[$last_key]) && $part_with_encoding[$last_key]['encoding'] == $lower_encoding) {
$part_with_encoding[$last_key]['string'] .= $part_string;
} else {
$part_with_encoding[] = array('encoding' => $lower_encoding, 'string' => $part_string);
}
}
} else {
$last_key = count($part_with_encoding) - 1;
if (isset($part_with_encoding[$last_key]) && $part_with_encoding[$last_key]['encoding'] == 'iso-8859-1') {
$part_with_encoding[$last_key]['string'] .= $part;
} else {
$part_with_encoding[] = array('encoding' => 'iso-8859-1', 'string' => $part);
}
}
}
foreach ($part_with_encoding as $part) {
$output .= self::iconv($part['encoding'], 'UTF-8', $part['string']);
}
return $output;
}
/**
* Handles an individual part of a multipart message
*
* @param array $info An array of information about the message
* @param array $structure An array describing the structure of the message
* @return array The modified $info array
*/
static private function handlePart($info, $structure)
{
if ($structure['type'] == 'multipart') {
foreach ($structure['parts'] as $part) {
$info = self::handlePart($info, $part);
}
return $info;
}
if ($structure['type'] == 'application' && in_array($structure['subtype'], array('pkcs7-mime', 'x-pkcs7-mime'))) {
$to = NULL;
if (isset($info['headers']['to'][0])) {
$to = $info['headers']['to'][0]['mailbox'];
if (!empty($info['headers']['to'][0]['host'])) {
$to .= '@' . $info['headers']['to'][0]['host'];
}
}
if ($to && !empty(self::$smime_pairs[$to]['private_key'])) {
if (self::handleSMIMEDecryption($info, $structure, self::$smime_pairs[$to])) {
return $info;
}
}
}
if ($structure['type'] == 'application' && in_array($structure['subtype'], array('pkcs7-signature', 'x-pkcs7-signature'))) {
$from = NULL;
if (isset($info['headers']['from'])) {
$from = $info['headers']['from']['mailbox'];
if (!empty($info['headers']['from']['host'])) {
$from .= '@' . $info['headers']['from']['host'];
}
}
if ($from && !empty(self::$smime_pairs[$from]['certificate'])) {
if (self::handleSMIMEVerification($info, $structure, self::$smime_pairs[$from])) {
return $info;
}
}
}
$data = $structure['data'];
if ($structure['encoding'] == 'base64') {
$content = '';
foreach (explode("\r\n", $data) as $line) {
$content .= base64_decode($line);
}
} elseif ($structure['encoding'] == 'quoted-printable') {
$content = quoted_printable_decode($data);
} else {
$content = $data;
}
if ($structure['type'] == 'text') {
$charset = 'iso-8859-1';
foreach ($structure['type_fields'] as $field => $value) {
if (strtolower($field) == 'charset') {
$charset = $value;
break;
}
}
$content = self::iconv($charset, 'UTF-8', $content);
if ($structure['subtype'] == 'html') {
$content = preg_replace('#(content=(["\'])text/html\s*;\s*charset=(["\']?))' . preg_quote($charset, '#') . '(\3\2)#i', '\1utf-8\4', $content);
}
}
// This indicates a content-id which is used for multipart/related
if ($structure['content_id']) {
if (!isset($info['related'])) {
$info['related'] = array();
}
$cid = $structure['content_id'][0] == '<' ? substr($structure['content_id'], 1, -1) : $structure['content_id'];
$info['related']['cid:' . $cid] = array(
'mimetype' => $structure['type'] . '/' . $structure['subtype'],
'data' => $content
);
return $info;
}
$has_disposition = !empty($structure['disposition']);
$is_text = $structure['type'] == 'text' && $structure['subtype'] == 'plain';
$is_html = $structure['type'] == 'text' && $structure['subtype'] == 'html';
// If the part doesn't have a disposition and is not the default text or html, set the disposition to inline
if (!$has_disposition && ((!$is_text || !empty($info['text'])) && (!$is_html || !empty($info['html'])))) {
$is_web_image = $structure['type'] == 'image' && in_array($structure['subtype'], array('gif', 'png', 'jpeg', 'pjpeg'));
$structure['disposition'] = $is_text || $is_html || $is_web_image ? 'inline' : 'attachment';
$structure['disposition_fields'] = array();
$has_disposition = TRUE;
}
// Attachments or inline content
if ($has_disposition) {
$filename = '';
foreach ($structure['disposition_fields'] as $field => $value) {
if (strtolower($field) == 'filename') {
$filename = $value;
break;
}
}
foreach ($structure['type_fields'] as $field => $value) {
if (strtolower($field) == 'name') {
$filename = $value;
break;
}
}
// This automatically handles primary content that has a content-disposition header on it
if ($structure['disposition'] == 'inline' && $filename === '') {
if ($is_text && !isset($info['text'])) {
$info['text'] = $content;
return $info;
}
if ($is_html && !isset($info['html'])) {
$info['html'] = $content;
return $info;
}
}
if (!isset($info[$structure['disposition']])) {
$info[$structure['disposition']] = array();
}
$info[$structure['disposition']][] = array(
'filename' => $filename,
'mimetype' => $structure['type'] . '/' . $structure['subtype'],
'data' => $content
);
return $info;
}
if ($is_text) {
$info['text'] = $content;
return $info;
}
if ($is_html) {
$info['html'] = $content;
return $info;
}
}
/**
* Tries to decrypt an S/MIME message using a private key
*
* @param array &$info The array of information about a message
* @param array $structure The structure of this part
* @param array $smime_pair An associative array containing an S/MIME certificate, private key and password
* @return boolean If the message was decrypted
*/
static private function handleSMIMEDecryption(&$info, $structure, $smime_pair)
{
$plaintext_file = tempnam('', '__fMailbox_');
$ciphertext_file = tempnam('', '__fMailbox_');
$headers = array();
$headers[] = "Content-Type: " . $structure['type'] . '/' . $structure['subtype'];
$headers[] = "Content-Transfer-Encoding: " . $structure['encoding'];
$header = "Content-Disposition: " . $structure['disposition'];
foreach ($structure['disposition_fields'] as $field => $value) {
$header .= '; ' . $field . '="' . $value . '"';
}
$headers[] = $header;
file_put_contents($ciphertext_file, join("\r\n", $headers) . "\r\n\r\n" . $structure['data']);
$private_key = openssl_pkey_get_private(
$smime_pair['private_key']->read(),
$smime_pair['password']
);
$certificate = $smime_pair['certificate']->read();
$result = openssl_pkcs7_decrypt($ciphertext_file, $plaintext_file, $certificate, $private_key);
unlink($ciphertext_file);
if (!$result) {
unlink($plaintext_file);
return FALSE;
}
$contents = file_get_contents($plaintext_file);
$info['raw_message'] = $contents;
$info = self::handlePart($info, self::parseStructure($contents));
$info['decrypted'] = TRUE;
unlink($plaintext_file);
return TRUE;
}
/**
* Takes a message with an S/MIME signature and verifies it if possible
*
* @param array &$info The array of information about a message
* @param array $structure
* @param array $smime_pair An associative array containing an S/MIME certificate file
* @return boolean If the message was verified
*/
static private function handleSMIMEVerification(&$info, $structure, $smime_pair)
{
$certificates_file = tempnam('', '__fMailbox_');
$ciphertext_file = tempnam('', '__fMailbox_');
file_put_contents($ciphertext_file, $info['raw_message']);
$result = openssl_pkcs7_verify(
$ciphertext_file,
PKCS7_NOINTERN | PKCS7_NOVERIFY,
$certificates_file,
array(),
$smime_pair['certificate']->getPath()
);
unlink($ciphertext_file);
unlink($certificates_file);
if (!$result || $result === -1) {
return FALSE;
}
$info['verified'] = TRUE;
return TRUE;
}
/**
* This works around a bug in MAMP 1.9.4+ and PHP 5.3 where iconv()
* does not seem to properly assign the return value to a variable, but
* does work when returning the value.
*
* @param string $in_charset The incoming character encoding
* @param string $out_charset The outgoing character encoding
* @param string $string The string to convert
* @return string The converted string
*/
static private function iconv($in_charset, $out_charset, $string)
{
return iconv($in_charset, $out_charset, $string);
}
/**
* Joins parsed emails into a comma-delimited string
*
* @param array $emails An array of emails split into personal, mailbox and host parts
* @return string An comma-delimited list of emails
*/
static private function joinEmails($emails)
{
$output = '';
foreach ($emails as $email) {
if ($output) { $output .= ', '; }
if (!isset($email[0])) {
$email[0] = !empty($email['personal']) ? $email['personal'] : '';
$email[2] = $email['mailbox'];
$email[3] = !empty($email['host']) ? $email['host'] : '';
}
$address = $email[2];
if (!empty($email[3])) {
$address .= '@' . $email[3];
}
$output .= fEmail::combineNameEmail($email[0], $address);
}
return $output;
}
/**
* Parses a string representation of an email into the persona, mailbox and host parts
*
* @param string $string The email string to parse
* @return array An associative array with the key `mailbox`, and possibly `host` and `personal`
*/
static private function parseEmail($string)
{
$email_regex = '((?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+")(?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))*)@((?:[a-z0-9\\-]+\.)+[a-z]{2,}|\[(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\])';
$name_regex = '((?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+[ \t]*|"[^"\\\\\n\r]+"[ \t]*)(?:\.?[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+[ \t]*|"[^"\\\\\n\r]+"[ \t]*))*)';
if (preg_match('~^[ \t]*' . $name_regex . '[ \t]*<[ \t]*' . $email_regex . '[ \t]*>[ \t]*$~ixD', $string, $match)) {
$match[1] = trim($match[1]);
if ($match[1][0] == '"' && substr($match[1], -1) == '"') {
$match[1] = substr($match[1], 1, -1);
}
return array(
'personal' => self::decodeHeader($match[1]),
'mailbox' => self::decodeHeader($match[2]),
'host' => self::decodeHeader($match[3])
);
} elseif (preg_match('~^[ \t]*(?:<[ \t]*)?' . $email_regex . '(?:[ \t]*>)?[ \t]*$~ixD', $string, $match)) {
return array(
'mailbox' => self::decodeHeader($match[1]),
'host' => self::decodeHeader($match[2])
);
// This handles the outdated practice of including the personal
// part of the email in a comment after the email address
} elseif (preg_match('~^[ \t]*(?:<[ \t]*)?' . $email_regex . '(?:[ \t]*>)?[ \t]*\(([^)]+)\)[ \t]*$~ixD', $string, $match)) {
$match[3] = trim($match[1]);
if ($match[3][0] == '"' && substr($match[3], -1) == '"') {
$match[3] = substr($match[3], 1, -1);
}
return array(
'personal' => self::decodeHeader($match[3]),
'mailbox' => self::decodeHeader($match[1]),
'host' => self::decodeHeader($match[2])
);
}
if (strpos($string, '@') !== FALSE) {
list ($mailbox, $host) = explode('@', $string, 2);
return array(
'mailbox' => self::decodeHeader($mailbox),
'host' => self::decodeHeader($host)
);
}
return array(
'mailbox' => self::decodeHeader($string),
'host' => ''
);
}
/**
* Parses full email headers into an associative array
*
* @param string $headers The header to parse
* @param string $filter Remove any headers that match this
* @return array The parsed headers
*/
static private function parseHeaders($headers, $filter=NULL)
{
$headers = trim($headers);
if (!strlen($headers)) {
return array();
}
$header_lines = preg_split("#\r\n(?!\s)#", $headers);
$single_email_fields = array('from', 'sender', 'reply-to');
$multi_email_fields = array('to', 'cc');
$additional_info_fields = array('content-type', 'content-disposition');
$headers = array();
foreach ($header_lines as $header_line) {
$header_line = preg_replace("#\r\n\s+#", '', $header_line);
list ($header, $value) = preg_split('#:\s*#', $header_line, 2);
$header = strtolower($header);
if (strpos($header, $filter) !== FALSE) {
continue;
}
$is_single_email = in_array($header, $single_email_fields);
$is_multi_email = in_array($header, $multi_email_fields);
$is_additional_info_field = in_array($header, $additional_info_fields);
if ($is_additional_info_field) {
$pieces = preg_split('#;\s*#', $value, 2);
$value = $pieces[0];
$headers[$header] = array('value' => self::decodeHeader($value));
$fields = array();
if (!empty($pieces[1])) {
preg_match_all('#(\w+)=("([^"]+)"|([^\s;]+))(?=;|$)#', $pieces[1], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$fields[$match[1]] = self::decodeHeader(!empty($match[4]) ? $match[4] : $match[3]);
}
}
$headers[$header]['fields'] = $fields;
} elseif ($is_single_email) {
$headers[$header] = self::parseEmail($value);
} elseif ($is_multi_email) {
$strings = array();
preg_match_all('#"[^"]+?"#', $value, $matches, PREG_SET_ORDER);
foreach ($matches as $i => $match) {
$strings[] = $match[0];
$value = preg_replace('#' . preg_quote($match[0], '#') . '#', ':string' . sizeof($strings), $value, 1);
}
preg_match_all('#\([^)]+?\)#', $value, $matches, PREG_SET_ORDER);
foreach ($matches as $i => $match) {
$strings[] = $match[0];
$value = preg_replace('#' . preg_quote($match[0], '#') . '#', ':string' . sizeof($strings), $value, 1);
}
$emails = explode(',', $value);
array_map('trim', $emails);
foreach ($strings as $i => $string) {
$emails = preg_replace(
'#:string' . ($i+1) . '\b#',
strtr($string, array('\\' => '\\\\', '$' => '\\$')),
$emails,
1
);
}
$headers[$header] = array();
foreach ($emails as $email) {
$headers[$header][] = self::parseEmail($email);
}
} elseif ($header == 'references') {
$headers[$header] = array_map(array('fMailbox', 'decodeHeader'), preg_split('#(?<=>)\s+(?=<)#', $value));
} elseif ($header == 'received') {
if (!isset($headers[$header])) {
$headers[$header] = array();
}
$headers[$header][] = preg_replace('#\s+#', ' ', self::decodeHeader($value));
} else {
$headers[$header] = self::decodeHeader($value);
}
}
return $headers;
}
/**
* Parses a MIME message into an associative array of information
*
* The output includes the following keys:
*
* - `'received'`: The date the message was received by the server
* - `'headers'`: An associative array of mail headers, the keys are the header names, in lowercase
*
* And one or more of the following:
*
* - `'text'`: The plaintext body
* - `'html'`: The HTML body
* - `'attachment'`: An array of attachments, each containing:
* - `'filename'`: The name of the file
* - `'mimetype'`: The mimetype of the file
* - `'data'`: The raw contents of the file
* - `'inline'`: An array of inline files, each containing:
* - `'filename'`: The name of the file
* - `'mimetype'`: The mimetype of the file
* - `'data'`: The raw contents of the file
* - `'related'`: An associative array of related files, such as embedded images, with the key `'cid:{content-id}'` and an array value containing:
* - `'mimetype'`: The mimetype of the file
* - `'data'`: The raw contents of the file
* - `'verified'`: If the message contents were verified via an S/MIME certificate - if not verified the smime.p7s will be listed as an attachment
* - `'decrypted'`: If the message contents were decrypted via an S/MIME private key - if not decrypted the smime.p7m will be listed as an attachment
*
* All values in `headers`, `text` and `body` will have been decoded to
* UTF-8. Files in the `attachment`, `inline` and `related` array will all
* retain their original encodings.
*
* @param string $message The full source of the email message
* @param boolean $convert_newlines If `\r\n` should be converted to `\n` in the `text` and `html` parts the message
* @return array The parsed email message - see method description for details
*/
static public function parseMessage($message, $convert_newlines=FALSE)
{
$info = array();
list ($headers, $body) = explode("\r\n\r\n", $message, 2);
$parsed_headers = self::parseHeaders($headers);
$info['received'] = self::cleanDate(preg_replace('#^.*;\s*([^;]+)$#', '\1', $parsed_headers['received'][0]));
$info['headers'] = array();
foreach ($parsed_headers as $header => $value) {
if (substr($header, 0, 8) == 'content-') {
continue;
}
$info['headers'][$header] = $value;
}
$info['raw_headers'] = $headers;
$info['raw_message'] = $message;
$info = self::handlePart($info, self::parseStructure($body, $parsed_headers));
unset($info['raw_message']);
unset($info['raw_headers']);
if ($convert_newlines) {
if (isset($info['text'])) {
$info['text'] = str_replace("\r\n", "\n", $info['text']);
}
if (isset($info['html'])) {
$info['html'] = str_replace("\r\n", "\n", $info['html']);
}
}
if (isset($info['text'])) {
$info['text'] = preg_replace('#\r?\n$#D', '', $info['text']);
}
if (isset($info['html'])) {
$info['html'] = preg_replace('#\r?\n$#D', '', $info['html']);
}
return $info;
}
/**
* Takes a response from an IMAP command and parses it into a
* multi-dimensional array
*
* @param string $text The IMAP command response
* @param boolean $top_level If we are parsing the top level
* @return array The parsed representation of the response text
*/
static private function parseResponse($text, $top_level=FALSE)
{
$regex = '[\\\\\w.\[\]]+|"([^"\\\\]+|\\\\"|\\\\\\\\)*"|\((?:(?1)[ \t]*)*\)';
if (preg_match('#\{(\d+)\}#', $text, $match)) {
$regex = '\{' . $match[1] . '\}\r\n.{' . ($match[1]) . '}|' . $regex;
}
preg_match_all('#(' . $regex . ')#s', $text, $matches, PREG_SET_ORDER);
$output = array();
foreach ($matches as $match) {
if (substr($match[0], 0, 1) == '"') {
$output[] = str_replace('\\"', '"', substr($match[0], 1, -1));
} elseif (substr($match[0], 0, 1) == '(') {
$output[] = self::parseResponse(substr($match[0], 1, -1));
} elseif (substr($match[0], 0, 1) == '{') {
$output[] = preg_replace('#^[^\r]+\r\n#', '', $match[0]);
} else {
$output[] = $match[0];
}
}
if ($top_level) {
$new_output = array();
$total_size = count($output);
for ($i = 0; $i < $total_size; $i = $i + 2) {
$new_output[strtolower($output[$i])] = $output[$i+1];
}
$output = $new_output;
}
return $output;
}
/**
* Takes the raw contents of a MIME message and creates an array that
* describes the structure of the message
*
* @param string $data The contents to get the structure of
* @param string $headers The parsed headers for the message - if not present they will be extracted from the `$data`
* @return array The multi-dimensional, associative array containing the message structure
*/
static private function parseStructure($data, $headers=NULL)
{
if (!$headers) {
list ($headers, $data) = preg_split("#^\r\n|\r\n\r\n#", $data, 2);
$headers = self::parseHeaders($headers);
}
if (!isset($headers['content-type'])) {
$headers['content-type'] = array(
'value' => 'text/plain',
'fields' => array()
);
}
list ($type, $subtype) = explode('/', strtolower($headers['content-type']['value']), 2);
if ($type == 'multipart') {
$structure = array(
'type' => $type,
'subtype' => $subtype,
'parts' => array()
);
$boundary = $headers['content-type']['fields']['boundary'];
$start_pos = strpos($data, '--' . $boundary) + strlen($boundary) + 4;
$end_pos = strrpos($data, '--' . $boundary . '--') - 2;
$sub_contents = explode("\r\n--" . $boundary . "\r\n", substr(
$data,
$start_pos,
$end_pos - $start_pos
));
foreach ($sub_contents as $sub_content) {
$structure['parts'][] = self::parseStructure($sub_content);
}
} else {
$structure = array(
'type' => $type,
'type_fields' => !empty($headers['content-type']['fields']) ? $headers['content-type']['fields'] : array(),
'subtype' => $subtype,
'content_id' => isset($headers['content-id']) ? $headers['content-id'] : NULL,
'encoding' => isset($headers['content-transfer-encoding']) ? strtolower($headers['content-transfer-encoding']) : '8bit',
'disposition' => isset($headers['content-disposition']) ? strtolower($headers['content-disposition']['value']) : NULL,
'disposition_fields' => isset($headers['content-disposition']) ? $headers['content-disposition']['fields'] : array(),
'data' => $data
);
}
return $structure;
}
/**
* Resets the configuration of the class
*
* @internal
*
* @return void
*/
static public function reset()
{
self::$smime_pairs = array();
}
/**
* Takes an associative array and unfolds the keys and values so that the
* result in an integer-indexed array of `0 => key1, 1 => value1, 2 => key2,
* 3 => value2, ...`.
*
* @param array $array The array to unfold
* @return array The unfolded array
*/
static private function unfoldAssociativeArray($array)
{
$new_array = array();
foreach ($array as $key => $value) {
$new_array[] = $key;
$new_array[] = $value;
}
return $new_array;
}
/**
* Whether or not to accept invalid peer certificate
*
* @var boolean
*/
private $accept_invalid_peer = FALSE;
/**
* A counter to use for generating command keys
*
* @var integer
*/
private $command_num = 1;
/**
* The connection resource
*
* @var resource
*/
private $connection;
/**
* If debugging has been enabled
*
* @var boolean
*/
private $debug;
/**
* The server hostname or IP address
*
* @var string
*/
private $host;
/**
* The password for the account
*
* @var string
*/
private $password;
/**
* The port for the server
*
* @var integer
*/
private $port;
/**
* If the connection to the server should be secure
*
* @var boolean
*/
private $secure;
/**
* The timeout for the connection
*
* @var integer
*/
private $timeout = 5;
/**
* The type of mailbox, `'imap'` or `'pop3'`
*
* @var string
*/
private $type;
/**
* The username for the account
*
* @var string
*/
private $username;
/**
* Configures the connection to the server
*
* Please note that the GMail POP3 server does not act like other POP3
* servers and the GMail IMAP server should be used instead. GMail POP3 only
* allows retrieving a message once - during future connections the email
* in question will no longer be available.
*
* @param string $type The type of mailbox, `'pop3'` or `'imap'`
* @param string $host The server hostname or IP address
* @param string $username The user to log in as
* @param string $password The user's password
* @param integer $port The port to connect via - only required if non-standard
* @param boolean $secure If SSL should be used for the connection - this requires the `openssl` extension
* @param integer $timeout The timeout to use when connecting
* @param boolean $accept_invalid_peer If True, don't validate the peer certificate
* @return fMailbox
*/
public function __construct($type, $host, $username, $password, $port=NULL, $secure=FALSE, $timeout=NULL, $accept_invalid_peer=FALSE)
{
if ($timeout === NULL) {
$timeout = ini_get('default_socket_timeout');
}
$valid_types = array('imap', 'pop3');
if (!in_array($type, $valid_types)) {
throw new fProgrammerException(
'The mailbox type specified, %1$s, in invalid. Must be one of: %2$s.',
$type,
join(', ', $valid_types)
);
}
if ($port === NULL) {
if ($type == 'imap') {
$port = !$secure ? 143 : 993;
} else {
$port = !$secure ? 110 : 995;
}
}
if ($secure && !extension_loaded('openssl')) {
throw new fEnvironmentException(
'A secure connection was requested, but the %s extension is not installed',
'openssl'
);
}
$this->type = $type;
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->port = $port;
$this->secure = $secure;
$this->timeout = $timeout;
$this->accept_invalid_peer = $accept_invalid_peer;
}
/**
* Disconnects from the server
*
* @return void
*/
public function __destruct()
{
$this->close();
}
/**
* Closes the connection to the server
*
* @return void
*/
public function close()
{
if (!$this->connection) {
return;
}
if ($this->type == 'imap') {
$this->write('LOGOUT');
} else {
$this->write('QUIT', 1);
}
$this->connection = NULL;
}
/**
* Connects to the server
*
* @return void
*/
private function connect()
{
if ($this->connection) {
return;
}
fCore::startErrorCapture(E_WARNING);
$this->connection = stream_socket_client(
($this->secure ? 'tls://' . $this->host : $this->host) . ':' . $this->port,
$error_number,
$error_string,
$this->timeout,
STREAM_CLIENT_CONNECT,
$this->accept_invalid_peer
? stream_context_create([
'ssl' => [
'verify_peer' => FALSE,
'verify_peer_name' => FALSE
]
])
: stream_context_create()
);
foreach (fCore::stopErrorCapture('#ssl#i') as $error) {
throw new fConnectivityException('There was an error connecting to the server. A secure connection was requested, but was not available. Try a non-secure connection instead.');
}
if (!$this->connection) {
throw new fConnectivityException('There was an error connecting to the server');
}
stream_set_timeout($this->connection, $this->timeout);
if ($this->type == 'imap') {
if (!$this->secure && extension_loaded('openssl')) {
$response = $this->write('CAPABILITY');
if (preg_match('#\bstarttls\b#i', $response[0])) {
$this->write('STARTTLS');
do {
if (isset($res)) {
sleep(0.1);
}
$res = stream_socket_enable_crypto($this->connection, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);
} while ($res === 0);
}
}
$response = $this->write('LOGIN ' . $this->username . ' ' . $this->password);
if (!$response || !preg_match('#^[^ ]+\s+OK#', $response[count($response)-1])) {