-
Notifications
You must be signed in to change notification settings - Fork 4
/
hm-imap-base.php
1623 lines (1531 loc) · 57.2 KB
/
hm-imap-base.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-base.php: Base class for a 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
*/
/* base functions for IMAP communication */
class Hm_IMAP_Base {
public $cached_response = false; // flag to indicate we are using a cached response
protected $handle = false; // fsockopen handle to the IMAP server
protected $debug = array(); // debug messages
protected $commands = array(); // list of IMAP commands issued
protected $responses = array(); // list of raw IMAP responses
protected $current_command = false; // current/latest IMAP command issued
protected $max_read = false; // limit on allowable read size
protected $command_count = 0; // current command number
protected $cache_data = array(); // cache data
protected $supported_extensions = array(); // IMAP extensions in the CAPABILITY response
protected $enabled_extensions = array(); // IMAP extensions validated by the ENABLE response
protected $capability = false; // IMAP CAPABILITY response
protected $server_id = array(); // server ID response values
/* attributes that can be set for the IMAP connaction */
protected $config = array('server', 'port', 'tls', 'read_only',
'utf7_folders', 'auth', 'search_charset', 'sort_speedup', 'folder_max',
'use_cache', 'max_history', 'blacklisted_extensions', 'app_name', 'app_version',
'app_vendor', 'app_support_url', 'cache_limit', 'no_caps');
/* supported extensions */
protected $client_extensions = array('SORT', 'COMPRESS', 'NAMESPACE', 'CONDSTORE',
'ENABLE', 'QRESYNC', 'MOVE', 'SPECIAL-USE', 'LIST-STATUS', 'UNSELECT', 'ID', 'X-GM-EXT-1',
'ESEARCH', 'ESORT', 'QUOTA', 'LIST-EXTENDED');
/* extensions to declare with ENABLE */
protected $declared_extensions = array('CONDSTORE', 'QRESYNC');
/**
* increment the imap command prefix such that it counts
* up on each command sent. ('A1', 'A2', ...)
*
* @return int new command count
*/
private function command_number() {
$this->command_count += 1;
return $this->command_count;
}
/**
* Read IMAP literal found during parse_line().
*
* @param $size int size of the IMAP literal to read
* @param $max int max size to allow
* @param $current int current size read
* @param $line_length int amount to read in using fgets()
*
* @return array the data read and any "left over" data
* that was inadvertantly on the same line as
* the last fgets result
*/
private function read_literal($size, $max, $current, $line_length) {
$left_over = false;
$literal_data = $this->fgets($line_length);
$lit_size = strlen($literal_data);
$current += $lit_size;
while ($lit_size < $size) {
$chunk = $this->fgets($line_length);
$chunk_size = strlen($chunk);
$lit_size += $chunk_size;
$current += $chunk_size;
$literal_data .= $chunk;
if ($max && $current > $max) {
$this->max_read = true;
break;
}
}
if ($this->max_read) {
while ($lit_size < $size) {
$temp = $this->fgets($line_length);
$lit_size += strlen($temp);
}
}
elseif ($size < strlen($literal_data)) {
$left_over = substr($literal_data, $size);
$literal_data = substr($literal_data, 0, $size);
}
return array($literal_data, $left_over);
}
/**
* IMAP message part numbers are like one half integer and one half string :) This
* routine "increments" them correctly
*
* @param $part string IMAP part number
*
* @return string part number incremented by one
*/
protected function update_part_num($part) {
if (!strstr($part, '.')) {
$part++;
}
else {
$parts = explode('.', $part);
$parts[(count($parts) - 1)]++;
$part = implode('.', $parts);
}
return $part;
}
/**
* break up a "line" response from imap. If we find
* a literal we read ahead on the stream and include it.
*
* @param $line string data read from the IMAP server
* @param $current_size int size of current read operation
* @param $max int maximum input size to allow
* @param $line_length int chunk size to read literals with
*
* @return array a line continuation marker and the parsed data
* from the IMAP server
*/
protected function parse_line($line, $current_size, $max, $line_length) {
/* make it a bit easier to find "atoms" */
$line = str_replace(')(', ') (', $line);
/* will hold the line parts */
$parts = array();
/* flag to control if the line continues */
$line_cont = false;
/* line size */
$len = strlen($line);
/* walk through the line */
for ($i=0;$i<$len;$i++) {
/* this will hold one "atom" from the parsed line */
$chunk = '';
/* if we hit a newline exit the loop */
if ($line{$i} == "\r" || $line{$i} == "\n") {
$line_cont = false;
break;
}
/* skip spaces */
if ($line{$i} == ' ') {
continue;
}
/* capture special chars as "atoms" */
elseif ($line{$i} == '*' || $line{$i} == '[' || $line{$i} == ']' || $line{$i} == '(' || $line{$i} == ')') {
$chunk = $line{$i};
}
/* regex match a quoted string */
elseif ($line{$i} == '"') {
if (preg_match("/^(\"[^\"\\\]*(?:\\\.[^\"\\\]*)*\")/", substr($line, $i), $matches)) {
$chunk = substr($matches[1], 1, -1);
}
$i += strlen($chunk) + 1;
}
/* IMAP literal */
elseif ($line{$i} == '{') {
$end = strpos($line, '}');
if ($end !== false) {
$literal_size = substr($line, ($i + 1), ($end - $i - 1));
}
$lit_result = $this->read_literal($literal_size, $max, $current_size, $line_length);
$chunk = $lit_result[0];
if (!isset($lit_result[1]) || $lit_result[1] != "\r\n") {
$line_cont = true;
}
$i = $len;
}
/* all other atoms */
else {
$marker = -1;
/* don't include these three trailing chars in the atom */
foreach (array(' ', ')', ']') as $v) {
$tmp_marker = strpos($line, $v, $i);
if ($tmp_marker !== false && ($marker == -1 || $tmp_marker < $marker)) {
$marker = $tmp_marker;
}
}
/* slice out the chunk */
if ($marker !== false && $marker !== -1) {
$chunk = substr($line, $i, ($marker - $i));
$i += strlen($chunk) - 1;
}
else {
$chunk = rtrim(substr($line, $i));
$i += strlen($chunk);
}
}
/* if we found a worthwhile chunk add it to the results set */
if ($chunk) {
$parts[] = $chunk;
}
}
return array($line_cont, $parts);
}
/**
* wrapper around fgets using $this->handle
*
* @param $len int max read length for fgets
*
* @return string data read from the IMAP server
*/
protected function fgets($len=false) {
if (is_resource($this->handle) && !feof($this->handle)) {
if ($len) {
return fgets($this->handle, $len);
}
else {
return fgets($this->handle);
}
}
return '';
}
/**
* loop through "lines" returned from imap and parse them with parse_line() and read_literal.
* it can return the lines in a raw format, or parsed into atoms. It also supports a maximum
* number of lines to return, in case we did something stupid like list a loaded unix homedir
*
* @param $max int max size of response allowed
* @param $chunked bool flag to parse the data into IMAP "atoms"
* @param $line_length chunk size to read in literals using fgets
* @param $sort bool flag for non-compliant sort result parsing speed up
*
* @return array of parsed or raw results
*/
protected function get_response($max=false, $chunked=false, $line_length=8192, $sort=false) {
/* defaults and results containers */
$result = array();
$current_size = 0;
$chunked_result = array();
$last_line_cont = false;
$line_cont = false;
$c = -1;
$n = -1;
/* start of do -> while loop to read from the IMAP server */
do {
$n++;
/* if we loose connection to the server while reading terminate */
if (!is_resource($this->handle) || feof($this->handle)) {
break;
}
/* read in a line up to 8192 bytes */
$result[$n] = $this->fgets($line_length);
/* keep track of how much we have read and break out if we max out. This can
* happen on large messages. We need this check to ensure we don't exhaust available
* memory */
$current_size += strlen($result[$n]);
if ($max && $current_size > $max) {
$this->max_read = true;
break;
}
/* if the line is longer than 8192 bytes keep appending more reads until we find
* an end of line char. Keep checking the max read length as we go */
while(substr($result[$n], -2) != "\r\n" && substr($result[$n], -1) != "\n") {
if (!is_resource($this->handle) || feof($this->handle)) {
break;
}
$result[$n] .= $this->fgets($line_length);
if ($result[$n] === false) {
break;
}
$current_size += strlen($result[$n]);
if ($max && $current_size > $max) {
$this->max_read = true;
break 2;
}
}
/* check line continuation marker and grab previous index and parsed chunks */
if ($line_cont) {
$last_line_cont = true;
$pres = $n - 1;
if ($chunks) {
$pchunk = $c;
}
}
/* If we are using quick parsing of the IMAP SORT response we know the results are simply space
* delimited UIDs so quickly explode(). Otherwise we have to follow the spec and look for quoted
* strings and literals in the parse_line() routine. */
if ($sort) {
$line_cont = false;
$chunks = explode(' ', trim($result[$n]));
}
/* properly parse the line */
else {
list($line_cont, $chunks) = $this->parse_line($result[$n], $current_size, $max, $line_length);
}
/* merge lines that should have been recieved as one and add to results */
if ($chunks && !$last_line_cont) {
$c++;
}
if ($last_line_cont) {
$result[$pres] .= ' '.implode(' ', $chunks);
if ($chunks) {
$line_bits = array_merge($chunked_result[$pchunk], $chunks);
$chunked_result[$pchunk] = $line_bits;
}
$last_line_cont = false;
}
/* add line and parsed bits to result set */
else {
$result[$n] = implode(' ', $chunks);
if ($chunked) {
$chunked_result[$c] = $chunks;
}
}
/* check for untagged error condition. This represents a server problem but there is no reason
* we can't attempt to recover with the partial response we received up until this point */
if (substr(strtoupper($result[$n]), 0, 6) == '* BYE ') {
break;
}
/* end outer loop when we receive the tagged response line */
} while (substr($result[$n], 0, strlen('A'.$this->command_count)) != 'A'.$this->command_count);
/* return either raw or parsed result */
$this->responses[] = $result;
if ($chunked) {
$result = $chunked_result;
}
if ($this->current_command && isset($this->commands[$this->current_command])) {
$start_time = $this->commands[$this->current_command];
$this->commands[$this->current_command] = microtime(true) - $start_time;
if (count($this->commands) >= $this->max_history) {
array_shift($this->commands);
array_shift($this->responses);
}
}
return $result;
}
/**
* put a prefix on a command and send it to the server
*
* @param $command string/array IMAP command
* @param $piped bool if true builds a command set out of $command
*
* @return void
*/
protected function send_command($command) {
$this->cached_response = false;
$command = 'A'.$this->command_number().' '.$command;
/* send the command out to the server */
if (is_resource($this->handle)) {
$res = @fputs($this->handle, $command);
if (!$res) {
$this->debug[] = 'Error communicating with IMAP server: '.trim($command);
}
}
/* save the command and time for the IMAP debug output option */
if (strstr($command, 'LOGIN')) {
$command = 'LOGIN';
}
$this->commands[trim($command)] = microtime( true );
$this->current_command = trim($command);
}
/**
* determine if an imap response returned an "OK", returns true or false
*
* @param $data array parsed IMAP response
* @param $chunked bool flag defining the type of $data
*
* @return bool true to indicate a success response from the IMAP server
*/
protected function check_response($data, $chunked=false, $log_failures=true) {
$result = false;
/* find the last bit of the parsed response and look for the OK atom */
if ($chunked) {
if (!empty($data) && isset($data[(count($data) - 1)])) {
$vals = $data[(count($data) - 1)];
if ($vals[0] == 'A'.$this->command_count) {
if (strtoupper($vals[1]) == 'OK') {
$result = true;
}
}
}
}
/* pattern match the last line of a raw response */
else {
$line = array_pop($data);
if (preg_match("/^A".$this->command_count." OK/i", $line)) {
$result = true;
}
}
if (!$result && $log_failures) {
$this->debug[] = 'Command FAILED: '.$this->current_command;
}
return $result;
}
/**
* convert UTF-7 encoded forlder names to UTF-8
*
* @param $string string mailbox name to encode
*
* @return encoded mailbox
*/
protected function utf7_decode($string) {
if ($this->utf7_folders) {
$string = mb_convert_encoding($string, "UTF-8", "UTF7-IMAP" );
}
return $string;
}
/**
* convert UTF-8 encoded forlder names to UTF-7
*
* @param $string string mailbox name to decode
*
* @return decoded mailbox
*/
protected function utf7_encode($string) {
if ($this->utf7_folders) {
$string = mb_convert_encoding($string, "UTF7-IMAP", "UTF-8" );
}
return $string;
}
/**
* type checks
*
* @param $val string value to check
* @param $type string type of value to check against
*
* @return bool true if the type check passed
*/
protected function input_validate($val, $type) {
$imap_search_charsets = array(
'UTF-8',
'US-ASCII',
'',
);
$imap_keywords = array(
'ARRIVAL', 'DATE', 'FROM', 'SUBJECT',
'CC', 'TO', 'SIZE', 'UNSEEN',
'SEEN', 'FLAGGED', 'UNFLAGGED', 'ANSWERED',
'UNANSWERED', 'DELETED', 'UNDELETED', 'TEXT',
'ALL', 'DRAFT', 'NEW', 'RECENT', 'OLD', 'UNDRAFT'
);
$valid = false;
switch ($type) {
case 'search_str':
if (preg_match("/^[^\r\n]+$/", $val)) {
$valid = true;
}
break;
case 'msg_part':
if (preg_match("/^[\d\.]+$/", $val)) {
$valid = true;
}
break;
case 'charset':
if (!$val || in_array(strtoupper($val), $imap_search_charsets)) {
$valid = true;
}
break;
case 'uid':
if (ctype_digit((string) $val)) {
$valid = true;
}
break;
case 'uid_list';
if (preg_match("/^(\d+\s*,*\s*|(\d+|\*):(\d+|\*))+$/", $val)) {
$valid = true;
}
break;
case 'mailbox';
if (preg_match("/^[^\r\n]+$/", $val)) {
$valid = true;
}
break;
case 'keyword';
if (in_array(strtoupper($val), $imap_keywords)) {
$valid = true;
}
break;
}
return $valid;
}
/*
* check for hacky stuff
*
* @param $val string value to check
* @param $type string type the value should match
*
* @return bool true if the value matches the type spec
*/
protected function is_clean($val, $type) {
if (!$this->input_validate($val, $type)) {
$this->debug[] = 'INVALID IMAP INPUT DETECTED: '.$type.' : '.$val;
return false;
}
return true;
}
/**
* overwrite defaults with supplied config array
*
* @param $config array associative array of configuration options
*
* @return void
*/
protected function apply_config( $config ) {
foreach($config as $key => $val) {
if (in_array($key, $this->config)) {
$this->{$key} = $val;
}
}
}
}
/* IMAP specific parsing routines */
class Hm_IMAP_Parser extends Hm_IMAP_Base {
/**
* A single message part structure. This is a MIME type in the message that does NOT contain
* any other attachments or additonal MIME types
*
* @param $array array low level parsed BODYSTRUCTURE response segment
*
* @return array strucutre representing the MIME format
*/
protected function parse_single_part($array) {
$vals = $array[0];
array_shift($vals);
array_pop($vals);
$atts = array('name', 'filename', 'type', 'subtype', 'charset', 'id', 'description', 'encoding',
'size', 'lines', 'md5', 'disposition', 'language', 'location', 'att_size', 'c_date', 'm_date');
$res = array();
if (count($vals) > 7) {
$res['type'] = strtolower(trim(array_shift($vals)));
$res['subtype'] = strtolower(trim(array_shift($vals)));
if ($vals[0] == '(') {
array_shift($vals);
while($vals[0] != ')') {
if (isset($vals[0]) && isset($vals[1])) {
$res[strtolower($vals[0])] = $vals[1];
$vals = array_splice($vals, 2);
}
}
array_shift($vals);
}
else {
array_shift($vals);
}
$res['id'] = array_shift($vals);
$res['description'] = array_shift($vals);
$res['encoding'] = strtolower(array_shift($vals));
$res['size'] = array_shift($vals);
if ($res['type'] == 'text' && isset($vals[0])) {
$res['lines'] = array_shift($vals);
}
if (isset($vals[0]) && $vals[0] != ')') {
$res['md5'] = array_shift($vals);
}
if (isset($vals[0]) && $vals[0] == '(') {
array_shift($vals);
}
if (isset($vals[0]) && $vals[0] != ')') {
$res['disposition'] = array_shift($vals);
if (strtolower($res['disposition']) == 'attachment' && $vals[0] == '(') {
array_shift($vals);
$len = count($vals);
$flds = array('filename' => 'name', 'size' => 'att_size', 'creation-date' => 'c_date', 'modification-date' => 'm_date');
$index = 0;
for ($i=0;$i<$len;$i++) {
if ($vals[$i] == ')') {
$index = $i;
break;
}
if (isset($vals[$i]) && isset($flds[strtolower($vals[$i])]) && isset($vals[($i + 1)]) && $vals[($i + 1)] != ')') {
$res[$flds[strtolower($vals[$i])]] = $vals[($i + 1)];
$i++;
}
}
if ($index) {
array_splice($vals, 0, $index);
}
else {
array_shift($vals);
}
while ($vals[0] == ')') {
array_shift($vals);
}
}
}
if (isset($vals[0])) {
$res['language'] = array_shift($vals);
}
if (isset($vals[0])) {
$res['location'] = array_shift($vals);
}
foreach ($atts as $v) {
if (!isset($res[$v]) || trim(strtoupper($res[$v])) == 'NIL') {
$res[$v] = false;
}
else {
if ($v == 'charset') {
$res[$v] = strtolower(trim($res[$v]));
}
else {
$res[$v] = trim($res[$v]);
}
}
}
if (!isset($res['name'])) {
$res['name'] = 'message';
}
}
return $res;
}
/**
* filter out alternative mime types to simplify the end result
*
* @param $struct array nested array representing structure
* @param $filter string mime type to prioritize
* @param $parent_type string parent type to limit to
* @param $cnt counter used in recursion
*
* @return $array filtered structure array excluding alternatives
*/
protected function filter_alternatives($struct, $filter, $parent_type=false, $cnt=0) {
$filtered = array();
if (!is_array($struct) || empty($struct)) {
return array($filtered, $cnt);
}
if (!$parent_type) {
if (isset($struct['subtype'])) {
$parent_type = $struct['subtype'];
}
}
foreach ($struct as $index => $value) {
if ($parent_type == 'alternative' && isset($value['subtype']) && $value['subtype'] != $filter) {
$cnt += 1;
}
else {
$filtered[$index] = $value;
}
if (isset($value['subs']) && is_array($value['subs'])) {
if (isset($struct['subtype'])) {
$parent_type = $struct['subtype'];
}
else {
$parent_type = false;
}
list($filtered[$index]['subs'], $cnt) = $this->filter_alternatives($value['subs'], $filter, $parent_type, $cnt);
}
}
return array($filtered, $cnt);
}
/**
* parse a multi-part mime message part
*
* @param $array array low level parsed BODYSTRUCTURE response segment
* @param $part_num int IMAP message part number
*
* @return array structure representing the MIME format
*/
protected function parse_multi_part($array, $part_num) {
$struct = array();
$index = 0;
foreach ($array as $vals) {
if ($vals[0] != '(') {
break;
}
$type = strtolower($vals[1]);
$sub = strtolower($vals[2]);
$part_type = 1;
switch ($type) {
case 'message':
switch ($sub) {
case 'delivery-status':
case 'external-body':
case 'disposition-notification':
case 'rfc822-headers':
break;
default:
$part_type = 2;
break;
}
break;
}
if ($vals[0] == '(' && $vals[1] == '(') {
$part_type = 3;
}
if ($part_type == 1) {
$struct[$part_num] = $this->parse_single_part(array($vals));
$part_num = $this->update_part_num($part_num);
}
elseif ($part_type == 2) {
$parts = $this->split_toplevel_result($vals);
$struct[$part_num] = $this->parse_rfc822($parts[0], $part_num);
$part_num = $this->update_part_num($part_num);
}
else {
$parts = $this->split_toplevel_result($vals);
$struct[$part_num]['subs'] = $this->parse_multi_part($parts, $part_num.'.1');
$part_num = $this->update_part_num($part_num);
}
$index++;
}
if (isset($array[$index][0])) {
$struct['type'] = 'message';
$struct['subtype'] = $array[$index][0];
}
return $struct;
}
/**
* Parse a rfc822 message "container" part type
*
* @param $array array low level parsed BODYSTRUCTURE response segment
* @param $part_num int IMAP message part number
*
* @return array strucutre representing the MIME format
*/
protected function parse_rfc822($array, $part_num) {
$res = array();
array_shift($array);
$res['type'] = strtolower(trim(array_shift($array)));
$res['subtype'] = strtolower(trim(array_shift($array)));
if ($array[0] == '(') {
array_shift($array);
while($array[0] != ')') {
if (isset($array[0]) && isset($array[1])) {
$res[strtolower($array[0])] = $array[1];
$array = array_splice($array, 2);
}
}
array_shift($array);
}
else {
array_shift($array);
}
$res['id'] = array_shift($array);
$res['description'] = array_shift($array);
$res['encoding'] = strtolower(array_shift($array));
$res['size'] = array_shift($array);
$envelope = array();
if ($array[0] == '(') {
array_shift($array);
$index = 0;
$level = 1;
foreach ($array as $i => $v) {
if ($level == 0) {
$index = $i;
break;
}
$envelope[] = $v;
if ($v == '(') {
$level++;
}
if ($v == ')') {
$level--;
}
}
if ($index) {
$array = array_splice($array, $index);
}
}
$res = $this->parse_envelope($envelope, $res);
$parts = $this->split_toplevel_result($array);
$res['subs'] = $this->parse_multi_part($parts, $part_num.'.1', $part_num);
return $res;
}
/**
* helper function for parsing bodystruct responses
*
* @param $array array low level parsed BODYSTRUCTURE response segment
*
* @return array low level parsed data split at specific points in the result
*/
protected function split_toplevel_result($array) {
if (empty($array) || $array[1] != '(') {
return array($array);
}
$level = 0;
$i = 0;
$res = array();
foreach ($array as $val) {
if ($val == '(') {
$level++;
}
$res[$i][] = $val;
if ($val == ')') {
$level--;
}
if ($level == 1) {
$i++;
}
}
return array_splice($res, 1, -1);
}
/**
* parse an envelope address
*
* @param $array array parsed sections from a BODYSTRUCTURE envelope address
*
* @return string string representation of the address
*/
protected function parse_envelope_address($array) {
$count = count($array) - 1;
$string = '';
$name = false;
$mail = false;
$domain = false;
for ($i = 0;$i<$count;$i+= 6) {
if (isset($array[$i + 1])) {
$name = $array[$i + 1];
}
if (isset($array[$i + 3])) {
$mail = $array[$i + 3];
}
if (isset($array[$i + 4])) {
$domain = $array[$i + 4];
}
if ($name && strtoupper($name) != 'NIL') {
$name = str_replace(array('"', "'"), '', $name);
if ($string != '') {
$string .= ', ';
}
if ($name != $mail.'@'.$domain) {
$string .= '"'.$name.'" ';
}
if ($mail && $domain) {
$string .= $mail.'@'.$domain;
}
}
if ($mail && $domain) {
$string .= $mail.'@'.$domain;
}
$name = false;
$mail = false;
$domain = false;
}
return $string;
}
/**
* parse a message envelope
*
* @param $array array parsed message envelope from a BODYSTRUCTURE response
* @param $res current BODYSTRUCTURE representation
*
* @return array updated $res with message envelope details
*/
protected function parse_envelope($array, $res) {
$flds = array('date', 'subject', 'from', 'sender', 'reply-to', 'to', 'cc', 'bcc', 'in-reply-to', 'message_id');
foreach ($flds as $val) {
if (strtoupper($array[0]) != 'NIL') {
if ($array[0] == '(') {
array_shift($array);
$parts = array();
$index = 0;
$level = 1;
foreach ($array as $i => $v) {
if ($level == 0) {
$index = $i;
break;
}
$parts[] = $v;
if ($v == '(') {
$level++;
}
if ($v == ')') {
$level--;
}
}
if ($index) {
$array = array_splice($array, $index);
$res[$val] = $this->parse_envelope_address($parts);
}
}
else {
$res[$val] = array_shift($array);
}
}
else {
$res[$val] = false;
}
}
return $res;
}
/**
* helper method to grab values from the SELECT response
*
* @param $vals array low level parsed select response segment
* @param $offset int offset in the list to search for a value
* @param $key string value in the array to start from
*
* @return int the adjacent value
*/
protected function get_adjacent_response_value($vals, $offset, $key) {
foreach ($vals as $i => $v) {
$i += $offset;
if (isset($vals[$i]) && $vals[$i] == $key) {
return $v;
}
}
return 0;
}
/**
* helper function to cllect flags from the SELECT response
*
* @param $vals array low level parsed select response segment
*
* @return array list of flags
*/
protected function get_flag_values($vals) {
$collect_flags = false;
$res = array();
foreach ($vals as $i => $v) {
if ($v == ')') {
$collect_flags = false;
}
if ($collect_flags) {
$res[] = $v;
}
if ($v == '(') {
$collect_flags = true;
}
}
return $res;
}
/**
* compare filter keywords against message flags
*
* @param $filter string message type to filter by
* @param $flags string IMAP flag value string
*
* @return bool true if the message matches the filter
*/
protected function flag_match($filter, $flags) {
$res = false;
switch($filter) {
case 'ANSWERED':
case 'SEEN':
case 'DRAFT':
case 'DELETED':
$res = stristr($flags, $filter);
break;
case 'UNSEEN':
case 'UNDRAFT':