-
Notifications
You must be signed in to change notification settings - Fork 4
/
hm-imap.php
2095 lines (1977 loc) · 75.4 KB
/
hm-imap.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
/* hm-imap.php: Generic PHP5 IMAP client library.
This code is derived from the IMAP library used in Hastymail2 (www.hastymail.org)
and is covered by the same license restrictions (GPL2)
Hastymail is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Hastymail is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Hastymail; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* include base classes */
require_once('hm-imap-base.php');
/* public interface to IMAP commands */
class Hm_IMAP extends Hm_IMAP_Cache {
/* config */
/* maximum characters to read in from a request */
public $max_read = false;
/* IMAP server IP address or hostname */
public $server = '127.0.0.1';
/* IP port to connect to. Standard port is 143, TLS is 993 */
public $port = 143;
/* enable TLS when connecting to the IMAP server */
public $tls = false;
/* don't change the account state in any way */
public $read_only = false;
/* convert folder names to utf7 */
public $utf7_folders = false;
/* defaults to LOGIN, CRAM-MD5 also supported but experimental */
public $auth = false;
/* search character set to use. can be US-ASCII, UTF-8, or '' */
public $search_charset = '';
/* sort responses can _probably_ be parsed quickly. This is non-conformant however */
public $sort_speedup = true;
/* use built in caching. strongly recommended */
public $use_cache = true;
/* limit LIST/LSUB responses to this many folders */
public $folder_max = 500;
/* number of commands and responses to keep in memory. */
public $max_history = 1000;
/* default IMAP folder delimiter. Only used if NAMESPACE is not supported */
public $default_delimiter = '/';
/* defailt IMAP mailbox prefix. Only used if NAMESPACE is not supported */
public $default_prefix = '';
/* list of supported IMAP extensions to ignore */
public $blacklisted_extensions = array();
/* maximum number of IMAP commands to cache */
public $cache_limit = 100;
/* query the server for it's CAPABILITY response */
public $no_caps = false;
/* IMAP ID client information */
public $app_name = 'Hm_IMAP';
public $app_version = '3.0';
public $app_vendor = 'Hastymail Development Group';
public $app_support_url = 'http://hastymail.org/contact_us/';
/* holds information about the currently selected mailbox */
public $selected_mailbox = false;
/* special folders defined by the IMAP SPECIAL-USE extension */
public $special_use_mailboxes = array(
'\All' => false,
'\Archive' => false,
'\Drafts' => false,
'\Flagged' => false,
'\Junk' => false,
'\Sent' => false,
'\Trash' => false
);
/* holds the current IMAP connection state */
private $state = 'disconnected';
/* used for message part content streaming */
private $stream_size = 0;
/**
* constructor
*/
public function __construct() {
}
/* ------------------ CONNECT/AUTH ------------------------------------- */
/**
* connect to the imap server
*
* @param $config array list of configuration options for this connections
*
* @return bool true on connection sucess
*/
public function connect( $config ) {
if (isset($config['username']) && isset($config['password'])) {
$this->commands = array();
$this->debug = array();
$this->capability = false;
$this->responses = array();
$this->current_command = false;
$this->apply_config($config);
if ($this->tls) {
$this->server = 'tls://'.$this->server;
}
$this->debug[] = 'Connecting to '.$this->server.' on port '.$this->port;
$this->handle = fsockopen($this->server, $this->port, $errorno, $errorstr, 30);
if (is_resource($this->handle)) {
$this->debug[] = 'Successfully opened port to the IMAP server';
$this->state = 'connected';
return $this->authenticate($config['username'], $config['password']);
}
else {
$this->debug[] = 'Could not connect to the IMAP server';
$this->debug[] = 'fsockopen errors #'.$errorno.'. '.$errorstr;
return false;
}
}
else {
$this->debug[] = 'username and password must be set in the connect() config argument';
return false;
}
}
/**
* close the IMAP connection
*
* @return void
*/
public function disconnect() {
$command = "LOGOUT\r\n";
$this->state = 'disconnected';
$this->selected_mailbox = false;
$this->send_command($command);
$result = $this->get_response();
if (is_resource($this->handle)) {
fclose($this->handle);
}
}
/**
* authenticate the username/password
*
* @param $username IMAP login name
* @param $password IMAP password
*
* @return bool true on sucessful login
*/
public function authenticate($username, $password) {
if (!$this->tls) {
$this->starttls();
}
switch (strtolower($this->auth)) {
case 'cram-md5':
$this->banner = $this->fgets(1024);
$cram1 = 'AUTHENTICATE CRAM-MD5'."\r\n";
$this->send_command($cram1);
$response = $this->get_response();
$challenge = base64_decode(substr(trim($response), 1));
$pass .= str_repeat(chr(0x00), (64-strlen($password)));
$ipad = str_repeat(chr(0x36), 64);
$opad = str_repeat(chr(0x5c), 64);
$digest = bin2hex(pack("H*", md5(($pass ^ $opad).pack("H*", md5(($pass ^ $ipad).$challenge)))));
$challenge_response = base64_encode($username.' '.$digest);
fputs($this->handle, $challenge_response."\r\n");
break;
default:
$login = 'LOGIN "'.str_replace('"', '\"', $username).'" "'.str_replace('"', '\"', $password). "\"\r\n";
$this->send_command($login);
break;
}
$res = $this->get_response();
$authed = false;
if (is_array($res) && !empty($res)) {
$response = array_pop($res);
if (!$this->auth) {
if (isset($res[1])) {
$this->banner = $res[1];
}
if (isset($res[0])) {
$this->banner = $res[0];
}
}
if (stristr($response, 'A'.$this->command_count.' OK')) {
$authed = true;
$this->state = 'authenticated';
}
}
if ( $authed ) {
$this->debug[] = 'Logged in successfully as '.$username;
$this->get_capability();
//$this->enable();
//$this->enable_compression();
}
else {
$this->debug[] = 'Log in for '.$username.' FAILED';
}
return $authed;
}
/**
* attempt starttls
*
* @return void
*/
public function starttls() {
if ($this->is_supported('STARTTLS')) {
$command = "STARTTLS\r\n";
$this->send_command($command);
$response = $this->get_response();
if (!empty($response)) {
$end = array_pop($response);
if (substr($end, 0, strlen('A'.$this->command_count.' OK')) == 'A'.$this->command_count.' OK') {
stream_socket_enable_crypto($this->handle, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
}
else {
$this->debug[] = 'Unexpected results from STARTTLS: '.implode(' ', $response);
}
}
else {
$this->debug[] = 'No response from STARTTLS command';
}
}
}
/* ------------------ UNSELECTED STATE COMMANDS ------------------------ */
/**
* fetch IMAP server capability response
*
* @return string capability response
*/
public function get_capability() {
if ( $this->capability ) {
return $this->capability;
}
else {
if (!$this->no_caps) {
$command = "CAPABILITY\r\n";
$this->send_command($command);
$response = $this->get_response();
$this->capability = $response[0];
$this->debug['CAPS'] = $this->capability;
$this->parse_extensions_from_capability();
return $this->capability;
}
}
}
/**
* get a list of mailbox folders
*
* @param $lsub bool flag to limit results to subscribed folders only
*
* @return array associative array of folder details
*/
public function get_mailbox_list($lsub=false, $mailbox='', $keyword='*') {
/* defaults */
$folders = array();
$excluded = array();
$parents = array();
$delim = false;
$commands = $this->build_list_commands($lsub, $mailbox, $keyword);
$cache_command = implode('', array_map(function($v) { return $v[0]; }, $commands)).(string)$mailbox.(string)$keyword;
$cache = $this->check_cache($cache_command);
if ($cache !== false) {
return $cache;
}
foreach($commands as $vals) {
$command = $vals[0];
$namespace = $vals[1];
$this->send_command($command);
$result = $this->get_response($this->folder_max, true);
/* loop through the "parsed" response. Each iteration is one folder */
foreach ($result as $vals) {
if (in_array('STATUS', $vals)) {
$status_values = $this->parse_status_response(array($vals));
$this->check_mailbox_state_change($status_values);
continue;
}
/* break at the end of the list */
if (!isset($vals[0]) || $vals[0] == 'A'.$this->command_count) {
continue;
}
/* defaults */
$flags = false;
$flag = false;
$delim_flag = false;
$parent = '';
$base_name = '';
$folder_parts = array();
$no_select = false;
$can_have_kids = true;
$has_kids = false;
$marked = false;
$folder_sort_by = 'ARRIVAL';
$check_for_new = false;
/* full folder name, includes an absolute path of parent folders */
$folder = $this->utf7_decode($vals[(count($vals) - 1)]);
/* sometimes LIST responses have dupes */
if (isset($folders[$folder]) || !$folder) {
continue;
}
/* folder flags */
foreach ($vals as $v) {
if ($v == '(') {
$flag = true;
}
elseif ($v == ')') {
$flag = false;
$delim_flag = true;
}
else {
if ($flag) {
$flags .= ' '.$v;
}
if ($delim_flag && !$delim) {
$delim = $v;
$delim_flag = false;
}
}
}
/* get each folder name part of the complete hierarchy */
$folder_parts = array();
if ($delim && strstr($folder, $delim)) {
$temp_parts = explode($delim, $folder);
foreach ($temp_parts as $g) {
if (trim($g)) {
$folder_parts[] = $g;
}
}
}
else {
$folder_parts[] = $folder;
}
/* get the basename part of the folder name. For a folder named "inbox.sent.march"
* with a delimiter of "." the basename would be "march" */
if (isset($folder_parts[(count($folder_parts) - 1)])) {
$base_name = $folder_parts[(count($folder_parts) - 1)];
}
else {
$base_name = $folder;
}
/* determine the parent folder basename if it exists */
if (isset($folder_parts[(count($folder_parts) - 2)])) {
$parent = implode($delim, array_slice($folder_parts, 0, -1));
if ($parent.$delim == $namespace) {
$parent = '';
}
}
/* special use mailbox extension */
if ($this->is_supported('SPECIAL-USE')) {
$special = false;
foreach ($this->special_use_mailboxes as $name => $value) {
if (stristr($flags, $name)) {
$special = $name;
}
}
if ($special) {
$this->special_use_mailboxes[$special] = $folder;
}
}
/* build properties from the flags string */
if (stristr($flags, 'marked')) {
$marked = true;
}
if (stristr($flags, 'noinferiors')) {
$can_have_kids = false;
}
if (($folder == $namespace && $namespace) || stristr($flags, 'haschildren')) {
$has_kids = true;
}
if ($folder != 'INBOX' && $folder != $namespace && stristr($flags, 'noselect')) {
$no_select = true;
}
/* store the results in the big folder list struct */
$folders[$folder] = array('parent' => $parent, 'delim' => $delim, 'name' => $folder,
'name_parts' => $folder_parts, 'basename' => $base_name,
'realname' => $folder, 'namespace' => $namespace, 'marked' => $marked,
'noselect' => $no_select, 'can_have_kids' => $can_have_kids,
'has_kids' => $has_kids);
/* store a parent list used below */
if ($parent && !in_array($parent, $parents)) {
$parents[$parent][] = $folders[$folder];
}
}
}
/* attempt to fix broken hierarchy issues. If a parent folder was not found fabricate
* it in the folder list */
$place_holders = array();
foreach ($parents as $val => $parent_list) {
foreach ($parent_list as $parent) {
$found = false;
foreach ($folders as $i => $vals) {
if ($vals['name'] == $val) {
$folders[$i]['has_kids'] = 1;
$found = true;
break;
}
}
if (!$found) {
if (count($parent['name_parts']) > 1) {
foreach ($parent['name_parts'] as $i => $v) {
$fname = implode($delim, array_slice($parent['name_parts'], 0, ($i + 1)));
$name_parts = array_slice($parent['name_parts'], 0, ($i + 1));
if (!isset($folders[$fname])) {
$freal = $v;
if ($i > 0) {
$fparent = implode($delim, array_slice($parent['name_parts'], 0, $i));
}
else {
$fparent = false;
}
$place_holders[] = $fname;
$folders[$fname] = array('parent' => $fparent, 'delim' => $delim, 'name' => $freal,
'name_parts' => $name_parts, 'basename' => $freal, 'realname' => $fname,
'namespace' => $namespace, 'marked' => false, 'noselect' => true,
'can_have_kids' => true, 'has_kids' => true);
}
}
}
}
}
}
/* ALL account need an inbox. If we did not find one manually add it to the results */
if (!isset($folders['INBOX']) && !$mailbox ) {
$folders = array_merge(array('INBOX' => array(
'name' => 'INBOX', 'basename' => 'INBOX', 'realname' => 'INBOX', 'noselect' => false,
'parent' => false, 'has_kids' => false, 'name_parts' => array(), 'delim' => $delim)), $folders);
}
/* sort and return the list */
ksort($folders);
return $this->cache_return_val($folders, $cache_command);
}
/**
* get IMAP folder namespaces
*
* @return array list of available namespace details
*/
public function get_namespaces() {
if (!$this->is_supported('NAMESPACE')) {
return array(array(
'prefix' => $this->default_prefix,
'delim' => $this->default_delimiter,
'class' => 'personal'
));
}
$data = array();
$command = "NAMESPACE\r\n";
$cache = $this->check_cache($command);
if ($cache !== false) {
return $cache;
}
$this->send_command("NAMESPACE\r\n");
$res = $this->get_response();
$this->namespace_count = 0;
$status = $this->check_response($res);
if ($status) {
if (preg_match("/\* namespace (\(.+\)|NIL) (\(.+\)|NIL) (\(.+\)|NIL)/i", $res[0], $matches)) {
$classes = array(1 => 'personal', 2 => 'other_users', 3 => 'shared');
foreach ($classes as $i => $v) {
if (trim(strtoupper($matches[$i])) == 'NIL') {
continue;
}
$list = str_replace(') (', '),(', substr($matches[$i], 1, -1));
$prefix = '';
$delim = '';
foreach (explode(',', $list) as $val) {
$val = trim($val, ")(\r\n ");
if (strlen($val) == 1) {
$delim = $val;
$prefix = '';
}
else {
$delim = substr($val, -1);
$prefix = trim(substr($val, 0, -1));
}
$this->namespace_count++;
$data[] = array('delim' => $delim, 'prefix' => $prefix, 'class' => $v);
}
}
}
return $this->cache_return_val($data, $command);
}
return $data;
}
/**
* select a mailbox
*
* @param $mailbox string the mailbox to attempt to select
*
* @return array list of information about the selected mailbox
*/
public function select_mailbox($mailbox) {
if (isset($this->selected_mailbox['name']) && $this->selected_mailbox['name'] == $mailbox) {
return $this->poll();
}
$box = $this->utf7_encode(str_replace('"', '\"', $mailbox));
if (!$this->is_clean($box, 'mailbox')) {
return false;
}
if (!$this->read_only) {
$command = "SELECT \"$box\"";
}
else {
$command = "EXAMINE \"$box\"";
}
if ($this->is_supported('QRESYNC')) {
$command .= $this->build_qresync_params();
}
elseif ($this->is_supported('CONDSTORE')) {
$command .= ' (CONDSTORE)';
}
$cached_state = $this->check_cache($command);
$this->send_command($command."\r\n");
$res = $this->get_response(false, true);
$status = $this->check_response($res, true);
$result = array();
if ($status) {
list($qresync, $attributes) = $this->parse_untagged_responses($res);
if (!$qresync) {
$this->check_mailbox_state_change($attributes, $cached_state, $mailbox);
}
else {
$this->debug[] = sprintf('Cache bust avoided on %s with QRESYNC!', $this->selected_mailbox['name']);
}
$result = array(
'selected' => $status,
'uidvalidity' => $attributes['uidvalidity'],
'exists' => $attributes['exists'],
'first_unseen' => $attributes['unseen'],
'uidnext' => $attributes['uidnext'],
'flags' => $attributes['flags'],
'permanentflags' => $attributes['pflags'],
'recent' => $attributes['recent'],
'nomodseq' => $attributes['nomodseq'],
'modseq' => $attributes['modseq'],
);
$this->state = 'selected';
$this->selected_mailbox = array('name' => $box, 'detail' => $result);
return $this->cache_return_val($result, $command);
}
return $result;
}
/**
* issue IMAP status command on a mailbox
*
* @param $mailbox string IMAP mailbox to check
* @param $args array list of properties to fetch
*
* @return array list of attribute values discovered
*/
public function get_mailbox_status($mailbox, $args=array('UNSEEN', 'UIDVALIDITY', 'UIDNEXT', 'MESSAGES', 'RECENT')) {
$command = 'STATUS "'.$this->utf7_encode($mailbox).'" ('.implode(' ', $args).")\r\n";
$this->send_command($command);
$attributes = array();
$response = $this->get_response(false, true);
if ($this->check_response($response, true)) {
$attributes = $this->parse_status_response($response);
$this->check_mailbox_state_change($attributes);
}
return $attributes;
}
/* ------------------ SELECTED STATE COMMANDS -------------------------- */
/**
* use IMAP NOOP to poll for untagged server messages
*
* @return array list of properties that have changed since SELECT
*/
public function poll() {
$result = array();
$command = "NOOP\r\n";
$this->send_command($command);
$res = $this->get_response(false, true);
if ($this->check_response($res, true)) {
list($qresync, $attributes) = $this->parse_untagged_responses($res);
if (!$qresync) {
$this->check_mailbox_state_change($attributes);
}
else {
$this->debug[] = sprintf('Cache bust avoided on %s with QRESYNC!', $this->selected_mailbox['name']);
}
}
return $result;
}
/**
* return a header list for the supplied message uids
*
* TODO: refactor. abstract header line continuation parsing for re-use
*
* @param $uids array/string an array of uids or a valid IMAP sequence set as a string
* @param $raw bool flag to disable decoding header values
*
* @return array list of headers and values for the specified uids
*/
public function get_message_list($uids, $raw=false) {
if (is_array($uids)) {
sort($uids);
$sorted_string = implode(',', $uids);
}
else {
$sorted_string = $uids;
}
if (!$this->is_clean($sorted_string, 'uid_list')) {
return array();
}
$command = 'UID FETCH '.$sorted_string.' (FLAGS INTERNALDATE RFC822.SIZE ';
if ($this->is_supported( 'X-GM-EXT-1' )) {
$command .= 'X-GM-MSGID X-GM-THRID X-GM-LABELS ';
}
$command .= "BODY.PEEK[HEADER.FIELDS (SUBJECT FROM DATE CONTENT-TYPE X-PRIORITY TO LIST-ARCHIVE)])\r\n";
$cache_command = $command.(string)$raw;
$cache = $this->check_cache($cache_command);
if ($cache !== false) {
return $cache;
}
$this->send_command($command);
$res = $this->get_response(false, true);
$status = $this->check_response($res, true);
$tags = array('X-GM-MSGID' => 'google_msg_id', 'X-GM-THRID' => 'google_thread_id', 'X-GM-LABELS' => 'google_labels', 'UID' => 'uid', 'FLAGS' => 'flags', 'RFC822.SIZE' => 'size', 'INTERNALDATE' => 'internal_date');
$junk = array('LIST-ARCHIVE', 'SUBJECT', 'FROM', 'CONTENT-TYPE', 'TO', '(', ')', ']', 'X-PRIORITY', 'DATE');
$flds = array('list-archive' => 'list_archive', 'date' => 'date', 'from' => 'from', 'to' => 'to', 'subject' => 'subject', 'content-type' => 'content_type', 'x-priority' => 'x_priority');
$headers = array();
foreach ($res as $n => $vals) {
if (isset($vals[0]) && $vals[0] == '*') {
$uid = 0;
$size = 0;
$subject = '';
$list_archive = '';
$from = '';
$date = '';
$x_priority = 0;
$content_type = '';
$to = '';
$flags = '';
$internal_date = '';
$google_msg_id = '';
$google_thread_id = '';
$google_labels = '';
$count = count($vals);
for ($i=0;$i<$count;$i++) {
if ($vals[$i] == 'BODY[HEADER.FIELDS') {
$i++;
while(isset($vals[$i]) && in_array(strtoupper($vals[$i]), $junk)) {
$i++;
}
$last_header = false;
$lines = explode("\r\n", $vals[$i]);
foreach ($lines as $line) {
$header = strtolower(substr($line, 0, strpos($line, ':')));
if (!$header || (!isset($flds[$header]) && $last_header)) {
${$flds[$last_header]} .= ' '.trim($line);
}
elseif (isset($flds[$header])) {
${$flds[$header]} = substr($line, (strpos($line, ':') + 1));
$last_header = $header;
}
}
}
elseif (isset($tags[strtoupper($vals[$i])])) {
if (isset($vals[($i + 1)])) {
if (($tags[strtoupper($vals[$i])] == 'flags' || $tags[strtoupper($vals[$i])] == 'google_labels' ) && $vals[$i + 1] == '(') {
$n = 2;
while (isset($vals[$i + $n]) && $vals[$i + $n] != ')') {
$$tags[strtoupper($vals[$i])] .= ' '.$vals[$i + $n];
$n++;
}
$i += $n;
}
else {
$$tags[strtoupper($vals[$i])] = $vals[($i + 1)];
$i++;
}
}
}
}
if ($uid) {
$cset = '';
if (stristr($content_type, 'charset=')) {
if (preg_match("/charset\=([^\s;]+)/", $content_type, $matches)) {
$cset = trim(strtolower(str_replace(array('"', "'"), '', $matches[1])));
}
}
$headers[(string) $uid] = array('uid' => $uid, 'flags' => $flags, 'internal_date' => $internal_date, 'size' => $size,
'date' => $date, 'from' => $from, 'to' => $to, 'subject' => $subject, 'content-type' => $content_type,
'timestamp' => time(), 'charset' => $cset, 'x-priority' => $x_priority, 'google_msg_id' => $google_msg_id,
'google_thread_id' => $google_thread_id, 'google_labels' => $google_labels, 'list_archive' => $list_archive);
if ($raw) {
$headers[$uid] = array_map('trim', $headers[$uid]);
}
else {
$headers[$uid] = array_map(array($this, 'decode_fld'), $headers[$uid]);
}
}
}
}
if ($status) {
return $this->cache_return_val($headers, $cache_command);
}
else {
return $headers;
}
}
/**
* get the IMAP BODYSTRUCTURE of a message
*
* @param $uid int IMAP UID of the message
* @param $filter string alternative MIME message format to prioritize
*
* @return array message structure represented as a nested array
*/
public function get_message_structure($uid) {
if (!$this->is_clean($uid, 'uid')) {
return array();
}
$part_num = 1;
$struct = array();
$command = "UID FETCH $uid BODYSTRUCTURE\r\n";
$cache = $this->check_cache($command);
if ($cache !== false) {
return $cache;
}
$this->send_command($command);
$result = $this->get_response(false, true);
while (isset($result[0][0]) && isset($result[0][1]) && $result[0][0] == '*' && strtoupper($result[0][1]) == 'OK') {
array_shift($result);
}
$status = $this->check_response($result, true);
$response = array();
if (!isset($result[0][4])) {
$status = false;
}
/* TODO: rework, this is pretty fragile */
if ($status) {
if (strtoupper($result[0][6]) == 'MODSEQ') {
$response = array_slice($result[0], 11, -1);
}
elseif (strtoupper($result[0][4]) == 'UID') {
$response = array_slice($result[0], 7, -1);
}
else {
$response = array_slice($result[0], 5, -1);
}
$response = $this->split_toplevel_result($response);
if (count($response) > 1) {
$struct = $this->parse_multi_part($response, 1, 1);
}
else {
$struct[1] = $this->parse_single_part($response);
}
}
if ($status) {
return $this->cache_return_val($struct, $command);
}
return $struct;
}
/**
* get content for a message part
*
* @param $uid int a single IMAP message UID
* @param $message_part string the IMAP message part number
* @param $raw bool flag to enabled fetching the entire message as text
* @param $max int maximum read length to allow.
* @param $struct mixed a message part structure array for decoding and
* charset conversion. bool true for auto discovery
*
* @return string message content
*/
public function get_message_content($uid, $message_part, $max=false, $struct=true) {
if (!$this->is_clean($uid, 'uid')) {
return '';
}
if ($message_part == 0) {
$command = "UID FETCH $uid BODY[]\r\n";
}
else {
if (!$this->is_clean($message_part, 'msg_part')) {
return '';
}
$command = "UID FETCH $uid BODY[$message_part]\r\n";
}
$cache_command = $command.(string)$max;
if ($struct) {
$cache_command .= '1';
}
$cache = $this->check_cache($cache_command);
if ($cache !== false) {
return $cache;
}
$this->send_command($command);
$result = $this->get_response($max, true);
$status = $this->check_response($result, true);
$res = '';
foreach ($result as $vals) {
if ($vals[0] != '*') {
continue;
}
$search = true;
foreach ($vals as $v) {
if ($v != ']' && !$search) {
if ($v == 'NIL') {
$res = '';
break 2;
}
$res = trim(preg_replace("/\s*\)$/", '', $v));
break 2;
}
if (stristr(strtoupper($v), 'BODY')) {
$search = false;
}
}
}
if ($struct === true) {
$full_struct = $this->get_message_structure( $uid );
$part_struct = $this->search_bodystructure( $full_struct, array('imap_part_number' => $message_part));
if (isset($part_struct[$message_part])) {
$struct = $part_struct[$message_part];
}
}
if (is_array($struct)) {
if (isset($struct['encoding']) && $struct['encoding']) {
if ($struct['encoding'] == 'quoted-printable') {
$res = quoted_printable_decode($res);
}
if ($struct['encoding'] == 'base64') {
$res = base64_decode($res);
}
}
if (isset($struct['charset']) && $struct['charset']) {
$res = mb_convert_encoding($res, 'UTF-8', $struct['charset']);
}
}
if ($status) {
return $this->cache_return_val($res, $cache_command);
}
return $res;
}
/**
* use IMAP SEARCH or ESEARCH
/**
* search a field for a keyword
*
* @param $target string message types to search. can be ALL, UNSEEN, ANSWERED, etc
* @param $uids array/string an array of uids or a valid IMAP sequence set as a string (or false for ALL)
* @param $fld string optional field to search
* @param $term string optional search term
*
* @return array list of IMAP message UIDs that match the search
*/
public function search($target='ALL', $uids=false, $fld=false, $term=false, $esearch=array()) {
if (($fld && !$this->is_clean($fld, 'search_str')) || !$this->is_clean($this->search_charset, 'charset') || ($term && !$this->is_clean($term, 'search_str')) || !$this->is_clean($target, 'keyword')) {
return array();
}
if (!empty($uids)) {
if (is_array($uids)) {
$uids = implode(',', $uids);
}
if (!$this->is_clean($uids, 'uid_list')) {
return array();
}
$uids = 'UID '.$uids;
}
else {
$uids = 'ALL';
}
if ($this->search_charset) {
$charset = 'CHARSET '.strtoupper($this->search_charset).' ';
}
else {
$charset = ' ';
}
if ($fld && $term) {
$fld = ' '.$fld.' "'.str_replace('"', '\"', $term).'"';
}
else {
$fld = '';
}
$esearch_enabled = false;
$command = 'UID SEARCH ';
if (!empty($esearch) && $this->is_supported('ESEARCH')) {
$valid = array_filter($esearch, function($v) { return in_array($v, array('MIN', 'MAX', 'COUNT', 'ALL')); });
if (!empty($valid)) {
$esearch_enabled = true;
$command .= 'RETURN ('.implode(' ', $valid).') ';
}
}
$command .= '('.$target.')'.$charset.$uids.$fld."\r\n";
$cache = $this->check_cache($command);
if ($cache !== false) {
return $cache;
}
$this->send_command($command);
$result = $this->get_response(false, true);
$status = $this->check_response($result, true);
$res = array();
$esearch_res = array();
if ($status) {
array_pop($result);
foreach ($result as $vals) {
if (in_array('ESEARCH', $vals)) {
$esearch_res = $this->parse_esearch_response($vals);
continue;
}
elseif (in_array('SEARCH', $vals)) {
foreach ($vals as $v) {
if (ctype_digit((string) $v)) {
$res[] = $v;
}
}
}
}
if ($esearch_enabled) {
$res = $esearch_res;
}
return $this->cache_return_val($res, $command);
}
return $res;
}
/**
* get the headers for the selected message
*
* @param $uid int IMAP message UID
* @param $message_part string IMAP message part number
*
* @return array associate array of message headers
*/
public function get_message_headers($uid, $message_part=false, $raw=false) {
if (!$this->is_clean($uid, 'uid')) {
return array();
}
if ($message_part == 1 || !$message_part) {
$command = "UID FETCH $uid (FLAGS BODY[HEADER])\r\n";
}
else {
if (!$this->is_clean($message_part, 'msg_part')) {
return array();
}
$command = "UID FETCH $uid (FLAGS BODY[$message_part.HEADER])\r\n";