source: subversion/trunk/roundcubemail/program/lib/imap.inc @ 2735

Last change on this file since 2735 was 2735, checked in by alec, 4 years ago
  • Performance improvements by use UID commands (#1485690)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.9 KB
Line 
1<?php
2/////////////////////////////////////////////////////////
3//     
4//      Iloha IMAP Library (IIL)
5//
6//      (C)Copyright 2002 Ryo Chijiiwa <Ryo@IlohaMail.org>
7//
8//      This file is part of IlohaMail. IlohaMail is free software released
9//      under the GPL license.  See enclosed file COPYING for details, or
10//      see http://www.fsf.org/copyleft/gpl.html
11//
12/////////////////////////////////////////////////////////
13
14/********************************************************
15
16        FILE: include/imap.inc
17        PURPOSE:
18                Provide alternative IMAP library that doesn't rely on the standard
19                C-Client based version.  This allows IlohaMail to function regardless
20                of whether or not the PHP build it's running on has IMAP functionality
21                built-in.
22        USEAGE:
23                Function containing "_C_" in name require connection handler to be
24                passed as one of the parameters.  To obtain connection handler, use
25                iil_Connect()
26        VERSION:
27                IlohaMail-0.9-20050415
28        CHANGES:
29                File altered by Thomas Bruederli <roundcube@gmail.com>
30                to fit enhanced equirements by the RoundCube Webmail:
31                - Added list of server capabilites and check these before invoking commands
32                - Added junk flag to iilBasicHeader
33                - Enhanced error reporting on fsockopen()
34                - Additional parameter for SORT command
35                - Removed Call-time pass-by-reference because deprecated
36                - Parse charset from content-type in iil_C_FetchHeaders()
37                - Enhanced heaer sorting
38                - Pass message as reference in iil_C_Append (to save memory)
39                - Added BCC and REFERENCE to the list of headers to fetch in iil_C_FetchHeaders()
40                - Leave messageID unchanged in iil_C_FetchHeaders()
41                - Avoid stripslahes in iil_Connect()
42                - Escape quotes and backslashes in iil_C_Login()
43                - Added patch to iil_SortHeaders() by Richard Green
44                - Removed <br> from error messages (better for logging)
45                - Added patch to iil_C_Sort() enabling UID SORT commands
46                - Added function iil_C_ID2UID()
47                - Casting date parts in iil_StrToTime() to avoid mktime() warnings
48                - Also acceppt LIST responses in iil_C_ListSubscribed()
49                - Sanity check of $message_set in iil_C_FetchHeaders(), iil_C_FetchHeaderIndex(), iil_C_FetchThreadHeaders()
50                - Implemented UID FETCH in iil_C_FetchHeaders()
51                - Abort do-loop on socket errors (fgets returns false)
52                - $ICL_SSL is not boolean anymore but contains the connection schema (ssl or tls)
53                - Removed some debuggers (echo ...)
54                File altered by Aleksander Machniak <alec@alec.pl>
55                - trim(chop()) replaced by trim()
56                - added iil_Escape()/iil_UnEscape() with support for " and \ in folder names
57                - support \ character in username in iil_C_Login()
58                - fixed iil_MultLine(): use iil_ReadBytes() instead of iil_ReadLine()
59                - fixed iil_C_FetchStructureString() to handle many literal strings in response
60                - removed hardcoded data size in iil_ReadLine()
61                - added iil_PutLine() wrapper for fputs()
62                - code cleanup and identation fixes
63                - removed flush() calls in iil_C_HandlePartBody() to prevent from memory leak (#1485187)
64                - don't return "??" from iil_C_GetQuota()
65                - RFC3501 [7.1] don't call CAPABILITY if was returned in server
66                  optional resposne in iil_Connect(), added iil_C_GetCapability()
67                - remove 'undisclosed-recipients' string from 'To' header
68                - iil_C_HandlePartBody(): added 6th argument and fixed endless loop
69                - added iil_PutLineC()
70                - fixed iil_C_Sort() to support very long and/or divided responses
71                - added BYE/BAD response simple support for endless loop prevention
72                - added 3rd argument in iil_StartsWith* functions
73                - fix iil_C_FetchPartHeader() in some cases by use of iil_C_HandlePartBody()
74                - allow iil_C_HandlePartBody() to fetch whole message
75                - optimize iil_C_FetchHeaders() to use only one FETCH command
76                - added 4th argument to iil_Connect()
77                - allow setting rootdir and delimiter before connect
78                - support multiquota result
79                - include BODYSTRUCTURE in iil_C_FetchHeaders()
80                - added iil_C_FetchMIMEHeaders() function
81                - added \* flag support
82                - use PREG instead of EREG
83                - removed caching functions
84                - handling connection startup response
85                - added UID EXPUNGE support
86                - fixed problem with double quotes and spaces in folder names in LIST and LSUB
87                - rewritten iil_C_FetchHeaderIndex()
88
89********************************************************/
90
91/**
92 * @todo Possibly clean up more CS.
93 * @todo Try to replace most double-quotes with single-quotes.
94 * @todo Split this file into smaller files.
95 * @todo Refactor code.
96 * @todo Replace echo-debugging (make it adhere to config setting and log)
97 */
98
99
100if (!isset($IMAP_USE_HEADER_DATE) || !$IMAP_USE_HEADER_DATE) {
101    $IMAP_USE_INTERNAL_DATE = true;
102}
103
104$GLOBALS['IMAP_FLAGS'] = array(
105    'SEEN'     => '\\Seen',
106    'DELETED'  => '\\Deleted',
107    'RECENT'   => '\\Recent',
108    'ANSWERED' => '\\Answered',
109    'DRAFT'    => '\\Draft',
110    'FLAGGED'  => '\\Flagged',
111    'FORWARDED' => '$Forwarded',
112    'MDNSENT'  => '$MDNSent',
113    '*'        => '\\*',
114);
115
116$iil_error;
117$iil_errornum;
118$iil_selected;
119
120/**
121 * @todo Change class vars to public/private
122 */
123class iilConnection
124{
125        var $fp;
126        var $error;
127        var $errorNum;
128        var $selected;
129        var $message;
130        var $host;
131        var $exists;
132        var $recent;
133        var $rootdir;
134        var $delimiter;
135        var $capability = array();
136        var $permanentflags = array();
137        var $capability_readed = false;
138}
139
140/**
141 * @todo Change class vars to public/private
142 */
143class iilBasicHeader
144{
145        var $id;
146        var $uid;
147        var $subject;
148        var $from;
149        var $to;
150        var $cc;
151        var $replyto;
152        var $in_reply_to;
153        var $date;
154        var $messageID;
155        var $size;
156        var $encoding;
157        var $charset;
158        var $ctype;
159        var $flags;
160        var $timestamp;
161        var $f;
162        var $body_structure;
163        var $internaldate;
164        var $references;
165        var $priority;
166        var $mdn_to;
167        var $mdn_sent = false;
168        var $is_draft = false;
169        var $seen = false;
170        var $deleted = false;
171        var $recent = false;
172        var $answered = false;
173        var $forwarded = false;
174        var $junk = false;
175        var $flagged = false;
176        var $others = array();
177}
178
179/**
180 * @todo Change class vars to public/private
181 */
182class iilThreadHeader
183{
184        var $id;
185        var $sbj;
186        var $irt;
187        var $mid;
188}
189
190function iil_xor($string, $string2) {
191        $result = '';
192        $size = strlen($string);
193        for ($i=0; $i<$size; $i++) {
194                $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
195        }
196        return $result;
197}
198
199function iil_PutLine($fp, $string, $endln=true) {
200        global $my_prefs;
201       
202        if(!empty($my_prefs['debug_mode']))
203                write_log('imap', 'C: '. rtrim($string));
204       
205        return fputs($fp, $string . ($endln ? "\r\n" : ''));
206}
207
208// iil_PutLine replacement with Command Continuation Requests (RFC3501 7.5) support
209function iil_PutLineC($fp, $string, $endln=true) {
210        if ($endln)
211                $string .= "\r\n";
212
213        $res = 0;
214        if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
215                for($i=0, $cnt=count($parts); $i<$cnt; $i++) {
216                        if(preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
217                                $res += iil_PutLine($fp, $parts[$i].$parts[$i+1], false);
218                                $line = iil_ReadLine($fp, 1000);
219                                // handle error in command
220                                if ($line[0] != '+')
221                                        return false;
222                                $i++;
223                        }
224                        else
225                                $res += iil_PutLine($fp, $parts[$i], false);
226                }
227        }
228        return $res;
229}
230
231function iil_ReadLine($fp, $size=1024) {
232        global $my_prefs;
233       
234        $line = '';
235
236        if (!$fp) {
237                return $line;
238        }
239   
240        if (!$size) {
241                $size = 1024;
242        }
243   
244        do {
245                $buffer = fgets($fp, $size);
246                if ($buffer === false) {
247                        break;
248                }
249                if(!empty($my_prefs['debug_mode']))
250                        write_log('imap', 'S: '. chop($buffer));
251                $line .= $buffer;
252        } while ($buffer[strlen($buffer)-1] != "\n");
253       
254        return $line;
255}
256
257function iil_MultLine($fp, $line, $escape=false) {
258        $line = chop($line);
259        if (preg_match('/\{[0-9]+\}$/', $line)) {
260                $out = '';
261       
262                preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
263                $bytes = $a[2][0];
264                while (strlen($out) < $bytes) {
265                        $line = iil_ReadBytes($fp, $bytes);
266                        $out .= $line;
267                }
268
269                $line = $a[1][0] . '"' . ($escape ? iil_Escape($out) : $out) . '"';
270        }
271        return $line;
272}
273
274function iil_ReadBytes($fp, $bytes) {
275        global $my_prefs;
276        $data = '';
277        $len  = 0;
278        do {
279                $d = fread($fp, $bytes-$len);
280                $data .= $d;
281                if ($len == strlen($data)) {
282                        break; //nothing was read -> exit to avoid apache lockups
283                }
284                if(!empty($my_prefs['debug_mode']))
285                        write_log('imap', 'S: '. $d);
286                $len = strlen($data);
287        } while ($len < $bytes);
288       
289        return $data;
290}
291
292function iil_ReadReply($fp) {
293        do {
294                $line = trim(iil_ReadLine($fp, 1024));
295        } while ($line[0] == '*');
296       
297        return $line;
298}
299
300function iil_ParseResult($string) {
301        $a = explode(' ', $string);
302        if (count($a) > 2) {
303                if (strcasecmp($a[1], 'OK') == 0) {
304                        return 0;
305                } else if (strcasecmp($a[1], 'NO') == 0) {
306                        return -1;
307                } else if (strcasecmp($a[1], 'BAD') == 0) {
308                        return -2;
309                } else if (strcasecmp($a[1], 'BYE') == 0) {
310                        return -3;
311                }
312        }
313        return -4;
314}
315
316// check if $string starts with $match (or * BYE/BAD)
317function iil_StartsWith($string, $match, $error=false) {
318        $len = strlen($match);
319        if ($len == 0) {
320                return false;
321        }
322        if (strncmp($string, $match, $len) == 0) {
323                return true;
324        }
325        if ($error && preg_match('/^\* (BYE|BAD) /i', $string)) {
326                return true;
327        }
328        return false;
329}
330
331function iil_StartsWithI($string, $match, $bye=false) {
332        $len = strlen($match);
333        if ($len == 0) {
334                return false;
335        }
336        if (strncasecmp($string, $match, $len) == 0) {
337                return true;
338        }
339        if ($bye && strncmp($string, '* BYE ', 6) == 0) {
340                return true;
341
342        }
343        return false;
344}
345
346function iil_Escape($string)
347{
348        return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
349}
350
351function iil_UnEscape($string)
352{
353        return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
354}
355
356function iil_C_GetCapability(&$conn, $name)
357{
358        if (in_array($name, $conn->capability)) {
359                return true;
360        }
361        else if ($conn->capability_readed) {
362                return false;
363        }
364
365        // get capabilities (only once) because initial
366        // optional CAPABILITY response may differ
367        $conn->capability = array();
368
369        iil_PutLine($conn->fp, "cp01 CAPABILITY");
370        do {
371                $line = trim(iil_ReadLine($conn->fp, 1024));
372                $a = explode(' ', $line);
373                if ($line[0] == '*') {
374                        while (list($k, $w) = each($a)) {
375                                if ($w != '*' && $w != 'CAPABILITY')
376                                        $conn->capability[] = strtoupper($w);
377                        }
378                }
379        } while ($a[0] != 'cp01');
380       
381        $conn->capability_readed = true;
382
383        if (in_array($name, $conn->capability)) {
384                return true;
385        }
386
387        return false;
388}
389
390function iil_C_ClearCapability(&$conn)
391{
392        $conn->capability = array();
393        $conn->capability_readed = false;
394}
395
396function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge) {
397   
398    $ipad = '';
399    $opad = '';
400   
401    // initialize ipad, opad
402    for ($i=0;$i<64;$i++) {
403        $ipad .= chr(0x36);
404        $opad .= chr(0x5C);
405    }
406
407    // pad $pass so it's 64 bytes
408    $padLen = 64 - strlen($pass);
409    for ($i=0;$i<$padLen;$i++) {
410        $pass .= chr(0);
411    }
412   
413    // generate hash
414    $hash  = md5(iil_xor($pass,$opad) . pack("H*", md5(iil_xor($pass, $ipad) . base64_decode($encChallenge))));
415   
416    // generate reply
417    $reply = base64_encode($user . ' ' . $hash);
418   
419    // send result, get reply
420    iil_PutLine($conn->fp, $reply);
421    $line = iil_ReadLine($conn->fp, 1024);
422   
423    // process result
424    $result = iil_ParseResult($line);
425    if ($result == 0) {
426        $conn->error    .= '';
427        $conn->errorNum  = 0;
428        return $conn->fp;
429    }
430
431    if ($result == -3) fclose($conn->fp); // BYE response
432
433    $conn->error    .= 'Authentication for ' . $user . ' failed (AUTH): "';
434    $conn->error    .= htmlspecialchars($line) . '"';
435    $conn->errorNum  = $result;
436
437    return $result;
438}
439
440function iil_C_Login(&$conn, $user, $password) {
441
442    iil_PutLine($conn->fp, 'a001 LOGIN "'.iil_Escape($user).'" "'.iil_Escape($password).'"');
443
444    do {
445        $line = iil_ReadReply($conn->fp);
446        if ($line === false) {
447            break;
448        }
449    } while (!iil_StartsWith($line, 'a001 ', true));
450   
451    // process result
452    $result = iil_ParseResult($line);
453
454    if ($result == 0) {
455        $conn->error    .= '';
456        $conn->errorNum  = 0;
457        return $conn->fp;
458    }
459
460    fclose($conn->fp);
461   
462    $conn->error    .= 'Authentication for ' . $user . ' failed (LOGIN): "';
463    $conn->error    .= htmlspecialchars($line)."\"";
464    $conn->errorNum  = $result;
465
466    return $result;
467}
468
469function iil_ParseNamespace2($str, &$i, $len=0, $l) {
470        if (!$l) {
471            $str = str_replace('NIL', '()', $str);
472        }
473        if (!$len) {
474            $len = strlen($str);
475        }
476        $data      = array();
477        $in_quotes = false;
478        $elem      = 0;
479        for ($i;$i<$len;$i++) {
480                $c = (string)$str[$i];
481                if ($c == '(' && !$in_quotes) {
482                        $i++;
483                        $data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
484                        $elem++;
485                } else if ($c == ')' && !$in_quotes) {
486                        return $data;
487                } else if ($c == '\\') {
488                        $i++;
489                        if ($in_quotes) {
490                                $data[$elem] .= $c.$str[$i];
491                        }
492                } else if ($c == '"') {
493                        $in_quotes = !$in_quotes;
494                        if (!$in_quotes) {
495                                $elem++;
496                        }
497                } else if ($in_quotes) {
498                        $data[$elem].=$c;
499                }
500        }
501        return $data;
502}
503
504function iil_C_NameSpace(&$conn) {
505        global $my_prefs;
506
507        if (isset($my_prefs['rootdir']) && is_string($my_prefs['rootdir'])) {
508                $conn->rootdir = $my_prefs['rootdir'];
509                return true;
510        }
511       
512        if (!iil_C_GetCapability($conn, 'NAMESPACE')) {
513            return false;
514        }
515   
516        iil_PutLine($conn->fp, "ns1 NAMESPACE");
517        do {
518                $line = iil_ReadLine($conn->fp, 1024);
519                if (iil_StartsWith($line, '* NAMESPACE')) {
520                        $i    = 0;
521                        $line = iil_UnEscape($line);
522                        $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
523                }
524        } while (!iil_StartsWith($line, 'ns1', true));
525       
526        if (!is_array($data)) {
527            return false;
528        }
529   
530        $user_space_data = $data[0];
531        if (!is_array($user_space_data)) {
532            return false;
533        }
534   
535        $first_userspace = $user_space_data[0];
536        if (count($first_userspace)!=2) {
537            return false;
538        }
539   
540        $conn->rootdir       = $first_userspace[0];
541        $conn->delimiter     = $first_userspace[1];
542        $my_prefs['rootdir'] = substr($conn->rootdir, 0, -1);
543        $my_prefs['delimiter'] = $conn->delimiter;
544       
545        return true;
546}
547
548function iil_Connect($host, $user, $password, $options=null) { 
549        global $iil_error, $iil_errornum;
550        global $ICL_SSL, $ICL_PORT;
551        global $my_prefs, $IMAP_USE_INTERNAL_DATE;
552       
553        $iil_error = '';
554        $iil_errornum = 0;
555
556        // set some imap options
557        if (is_array($options)) {
558                foreach($options as $optkey => $optval) {
559                        if ($optkey == 'imap') {
560                                $auth_method = $optval;
561                        } else if ($optkey == 'rootdir') {
562                                $my_prefs['rootdir'] = $optval;
563                        } else if ($optkey == 'delimiter') {
564                                $my_prefs['delimiter'] = $optval;
565                        } else if ($optkey == 'debug_mode') {
566                                $my_prefs['debug_mode'] = $optval;
567                        }
568                }
569        }
570
571        if (empty($auth_method))
572                $auth_method = 'check';
573               
574        $message = "INITIAL: $auth_method\n";
575               
576        $result = false;
577       
578        // initialize connection
579        $conn              = new iilConnection;
580        $conn->error       = '';
581        $conn->errorNum    = 0;
582        $conn->selected    = '';
583        $conn->user        = $user;
584        $conn->host        = $host;
585       
586        if ($my_prefs['sort_field'] == 'INTERNALDATE') {
587                $IMAP_USE_INTERNAL_DATE = true;
588        } else if ($my_prefs['sort_field'] == 'DATE') {
589                $IMAP_USE_INTERNAL_DATE = false;
590        }
591        //echo '<!-- conn sort_field: '.$my_prefs['sort_field'].' //-->';
592       
593        //check input
594        if (empty($host)) {
595                $iil_error = "Empty host";
596                $iil_errornum = -1;
597                return false;
598        }
599        if (empty($user)) {
600                $iil_error = "Empty user";
601                $iil_errornum = -1;
602                return false;
603        }
604        if (empty($password)) {
605                $iil_error = "Empty password";
606                $iil_errornum = -1;
607                return false;
608        }
609
610        if (!$ICL_PORT) {
611                $ICL_PORT = 143;
612        }
613        //check for SSL
614        if ($ICL_SSL && $ICL_SSL != 'tls') {
615                $host = $ICL_SSL . '://' . $host;
616        }
617
618        $conn->fp = fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
619        if (!$conn->fp) {
620                $iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
621                $iil_errornum = -2;
622                return false;
623        }
624
625        stream_set_timeout($conn->fp, 10);
626        $line = stream_get_line($conn->fp, 8192, "\r\n");
627
628        // Connected to wrong port or connection error?
629        if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
630                if ($line)
631                        $iil_error = "Wrong startup greeting ($host:$ICL_PORT): $line";
632                else
633                        $iil_error = "Empty startup greeting ($host:$ICL_PORT)";
634                $iil_errornum = -2;
635                return false;
636        }
637       
638        // RFC3501 [7.1] optional CAPABILITY response
639        if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
640                $conn->capability = explode(' ', strtoupper($matches[1]));
641        }
642
643        $conn->message .= $line;
644
645        // TLS connection
646        if ($ICL_SSL == 'tls' && iil_C_GetCapability($conn, 'STARTTLS')) {
647                if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
648                        iil_PutLine($conn->fp, 'stls000 STARTTLS');
649
650                        $line = iil_ReadLine($conn->fp, 4096);
651                        if (!iil_StartsWith($line, 'stls000 OK')) {
652                                $iil_error = "Server responded to STARTTLS with: $line";
653                                $iil_errornum = -2;
654                                return false;
655                        }
656
657                        if (!stream_socket_enable_crypto($conn->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
658                                $iil_error = "Unable to negotiate TLS";
659                                $iil_errornum = -2;
660                                return false;
661                        }
662                       
663                        // Now we're authenticated, capabilities need to be reread
664                        iil_C_ClearCapability($conn);
665                }
666        }
667
668        if (strcasecmp($auth_method, "check") == 0) {
669                //check for supported auth methods
670                if (iil_C_GetCapability($conn, 'AUTH=CRAM-MD5') || iil_C_GetCapability($conn, 'AUTH=CRAM_MD5')) {
671                        $auth_method = 'auth';
672                }
673                else {
674                        //default to plain text auth
675                        $auth_method = 'plain';
676                }
677        }
678
679        if (strcasecmp($auth_method, 'auth') == 0) {
680                $conn->message .= "Trying CRAM-MD5\n";
681
682                //do CRAM-MD5 authentication
683                iil_PutLine($conn->fp, "a000 AUTHENTICATE CRAM-MD5");
684                $line = trim(iil_ReadLine($conn->fp, 1024));
685
686                $conn->message .= "$line\n";
687
688                if ($line[0] == '+') {
689                        $conn->message .= 'Got challenge: ' . htmlspecialchars($line) . "\n";
690
691                        //got a challenge string, try CRAM-5
692                        $result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
693                       
694                        // stop if server sent BYE response
695                        if($result == -3) {
696                                $iil_error = $conn->error;
697                                $iil_errornum = $conn->errorNum;
698                                return false;
699                        }
700                        $conn->message .= "Tried CRAM-MD5: $result \n";
701                } else {
702                        $conn->message .='No challenge ('.htmlspecialchars($line)."), try plain\n";
703                        $auth = 'plain';
704                }
705        }
706               
707        if ((!$result)||(strcasecmp($auth, "plain") == 0)) {
708                //do plain text auth
709                $result = iil_C_Login($conn, $user, $password);
710                $conn->message .= "Tried PLAIN: $result \n";
711        }
712               
713        $conn->message .= $auth;
714                       
715        if (!is_int($result)) {
716                iil_C_Namespace($conn);
717                return $conn;
718        } else {
719                $iil_error = $conn->error;
720                $iil_errornum = $conn->errorNum;
721                return false;
722        }
723}
724
725function iil_Close(&$conn) {
726        if (iil_PutLine($conn->fp, "I LOGOUT")) {
727                fgets($conn->fp, 1024);
728                fclose($conn->fp);
729                $conn->fp = false;
730        }
731}
732
733function iil_ExplodeQuotedString($delimiter, $string) {
734        $result = array();
735        $strlen = strlen($string);
736         
737        for ($q=$p=$i=0; $i < $strlen; $i++) {
738                if ($string[$i] == "\"" && $string[$i-1] != "\\") {
739                        $q = $q ? false : true;
740                }
741                else if (!$q && preg_match("/$delimiter/", $string[$i])) {
742                        $result[] = substr($string, $p, $i - $p);
743                        $p = $i + 1;
744                }
745        }
746
747        $result[] = substr($string, $p);
748        return $result;
749}
750
751function iil_CheckForRecent($host, $user, $password, $mailbox) {
752        if (empty($mailbox)) {
753                $mailbox = 'INBOX';
754        }
755   
756        $conn = iil_Connect($host, $user, $password, 'plain');
757        $fp   = $conn->fp;
758        if ($fp) {
759                iil_PutLine($fp, "a002 EXAMINE \"".iil_Escape($mailbox)."\"");
760                do {
761                        $line=chop(iil_ReadLine($fp, 300));
762                        $a=explode(' ', $line);
763                        if (($a[0] == '*') && (strcasecmp($a[2], 'RECENT') == 0)) {
764                            $result = (int) $a[1];
765                        }
766                } while (!iil_StartsWith($a[0], 'a002', true));
767
768                iil_PutLine($fp, "a003 LOGOUT");
769                fclose($fp);
770        } else {
771            $result = -2;
772        }
773   
774        return $result;
775}
776
777function iil_C_Select(&$conn, $mailbox) {
778
779        if (empty($mailbox)) {
780                return false;
781        }
782        if (strcmp($conn->selected, $mailbox) == 0) {
783                return true;
784        }
785   
786        if (iil_PutLine($conn->fp, "sel1 SELECT \"".iil_Escape($mailbox).'"')) {
787                do {
788                        $line = chop(iil_ReadLine($conn->fp, 300));
789                        $a = explode(' ', $line);
790                        if (count($a) == 3) {
791                                if (strcasecmp($a[2], 'EXISTS') == 0) {
792                                        $conn->exists = (int) $a[1];
793                                }
794                                if (strcasecmp($a[2], 'RECENT') == 0) {
795                                        $conn->recent = (int) $a[1];
796                                }
797                        }
798                        else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
799                                $conn->permanentflags = explode(' ', $match[1]);
800                        }
801                } while (!iil_StartsWith($line, 'sel1', true));
802
803                $a = explode(' ', $line);
804
805                if (strcasecmp($a[1], 'OK') == 0) {
806                        $conn->selected = $mailbox;
807                        return true;
808                }
809        }
810        return false;
811}
812
813function iil_C_CheckForRecent(&$conn, $mailbox) {
814        if (empty($mailbox)) {
815                $mailbox = 'INBOX';
816        }
817   
818        iil_C_Select($conn, $mailbox);
819        if ($conn->selected == $mailbox) {
820                return $conn->recent;
821        }
822        return false;
823}
824
825function iil_C_CountMessages(&$conn, $mailbox, $refresh = false) {
826        if ($refresh) {
827                $conn->selected = '';
828        }
829       
830        iil_C_Select($conn, $mailbox);
831        if ($conn->selected == $mailbox) {
832                return $conn->exists;
833        }
834        return false;
835}
836
837function iil_SplitHeaderLine($string) {
838        $pos=strpos($string, ':');
839        if ($pos>0) {
840                $res[0] = substr($string, 0, $pos);
841                $res[1] = trim(substr($string, $pos+1));
842                return $res;
843        }
844        return $string;
845}
846
847function iil_StrToTime($date) {
848
849        // support non-standard "GMTXXXX" literal
850        $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
851        // if date parsing fails, we have a date in non-rfc format.
852        // remove token from the end and try again
853        while ((($ts = @strtotime($date))===false) || ($ts < 0))
854        {
855                $d = explode(' ', $date);
856                array_pop($d);
857                if (!$d) break;
858                $date = implode(' ', $d);
859        }
860
861        $ts = (int) $ts;
862
863        return $ts < 0 ? 0 : $ts;       
864}
865
866function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE,
867    $encoding = 'US-ASCII') {
868
869        $field = strtoupper($field);
870        if ($field == 'INTERNALDATE') {
871            $field = 'ARRIVAL';
872        }
873       
874        $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
875        'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
876       
877        if (!$fields[$field]) {
878            return false;
879        }
880
881        /*  Do "SELECT" command */
882        if (!iil_C_Select($conn, $mailbox)) {
883            return false;
884        }
885   
886        $is_uid = $is_uid ? 'UID ' : '';
887       
888        if (!empty($add)) {
889            $add = " $add";
890        }
891
892        $command  = 's ' . $is_uid . 'SORT (' . $field . ') ';
893        $command .= $encoding . ' ALL' . $add;
894        $line     = $data = '';
895       
896        if (!iil_PutLineC($conn->fp, $command)) {
897            return false;
898        }
899        do {
900                $line = chop(iil_ReadLine($conn->fp, 1024));
901                if (iil_StartsWith($line, '* SORT')) {
902                        $data .= ($data ? ' ' : '') . substr($line, 7);
903                } else if (preg_match('/^[0-9 ]+$/', $line)) {
904                        $data .= $line;
905                }
906        } while (!iil_StartsWith($line, 's ', true));
907       
908        $result_code = iil_ParseResult($line);
909       
910        if ($result_code != 0) {
911                $conn->error = 'iil_C_Sort: ' . $line . "\n";
912                return false;
913        }
914       
915        $out = explode(' ',$data);
916        return $out;
917}
918
919function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field='', $skip_deleted=true) {
920
921        list($from_idx, $to_idx) = explode(':', $message_set);
922        if (empty($message_set) ||
923                (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
924                return false;
925        }
926
927        $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
928       
929        $fields_a['DATE']         = 1;
930        $fields_a['INTERNALDATE'] = 4;
931        $fields_a['FROM']         = 1;
932        $fields_a['REPLY-TO']     = 1;
933        $fields_a['SENDER']       = 1;
934        $fields_a['TO']           = 1;
935        $fields_a['SUBJECT']      = 1;
936        $fields_a['UID']          = 2;
937        $fields_a['SIZE']         = 2;
938        $fields_a['SEEN']         = 3;
939        $fields_a['RECENT']       = 3;
940        $fields_a['DELETED']      = 3;
941
942        if (!($mode = $fields_a[$index_field])) {
943                return false;
944        }
945
946        /*  Do "SELECT" command */
947        if (!iil_C_Select($conn, $mailbox)) {
948                return false;
949        }
950       
951        // build FETCH command string
952        $key     = 'fhi0';
953        $deleted = $skip_deleted ? ' FLAGS' : '';
954
955        if ($mode == 1)
956                $request = " FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
957        else if ($mode == 2) {
958                if ($index_field == 'SIZE')
959                        $request = " FETCH $message_set (RFC822.SIZE$deleted)";
960                else
961                        $request = " FETCH $message_set ($index_field$deleted)";
962        } else if ($mode == 3)
963                $request = " FETCH $message_set (FLAGS)";
964        else // 4
965                $request = " FETCH $message_set (INTERNALDATE$deleted)";
966
967        $request = $key . $request;
968
969        if (!iil_PutLine($conn->fp, $request))
970                return false;
971
972        $result = array();
973
974        do {
975                $line = chop(iil_ReadLine($conn->fp, 200));
976                $line = iil_MultLine($conn->fp, $line);
977
978                if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
979
980                        $id = $m[1];
981                        $flags = NULL;
982                                       
983                        if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
984                                $flags = explode(' ', strtoupper($matches[1]));
985                                if (in_array('\\DELETED', $flags)) {
986                                        $deleted[$id] = $id;
987                                        continue;
988                                }
989                        }
990
991                        if ($mode == 1) {
992                                if (preg_match('/BODY\[HEADER\.FIELDS \((DATE|FROM|REPLY-TO|SENDER|TO|SUBJECT)\)\] (.*)/', $line, $matches)) {
993                                        $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
994                                        $value = trim($value);
995                                        if ($index_field == 'DATE') {
996                                                $result[$id] = iil_StrToTime($value);
997                                        } else {
998                                                $result[$id] = $value;
999                                        }
1000                                } else {
1001                                        $result[$id] = '';
1002                                }
1003                        } else if ($mode == 2) {
1004                                if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1005                                        $result[$id] = trim($matches[2]);
1006                                } else {
1007                                        $result[$id] = 0;
1008                                }
1009                        } else if ($mode == 3) {
1010                                if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1011                                        $flags = explode(' ', $matches[1]);
1012                                }
1013                                $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1014                        } else if ($mode == 4) {
1015                                if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1016                                        $result[$id] = iil_StrToTime($matches[1]);
1017                                } else {
1018                                        $result[$id] = 0;
1019                                }
1020                        }
1021                }
1022        } while (!iil_StartsWith($line, $key, true));
1023
1024/*
1025        //check number of elements...
1026        if (is_numeric($from_idx) && is_numeric($to_idx)) {
1027                //count how many we should have
1028                $should_have = $to_idx - $from_idx + 1;
1029               
1030                //if we have less, try and fill in the "gaps"
1031                if (count($result) < $should_have) {
1032                        for ($i=$from_idx; $i<=$to_idx; $i++) {
1033                                if (!isset($result[$i])) {
1034                                        $result[$i] = '';
1035                                }
1036                        }
1037                }
1038        }
1039*/
1040        return $result;
1041}
1042
1043function iil_CompressMessageSet($message_set) {
1044        //given a comma delimited list of independent mid's,
1045        //compresses by grouping sequences together
1046       
1047        //if less than 255 bytes long, let's not bother
1048        if (strlen($message_set)<255) {
1049            return $message_set;
1050        }
1051   
1052        //see if it's already been compress
1053        if (strpos($message_set, ':') !== false) {
1054            return $message_set;
1055        }
1056   
1057        //separate, then sort
1058        $ids = explode(',', $message_set);
1059        sort($ids);
1060       
1061        $result = array();
1062        $start  = $prev = $ids[0];
1063
1064        foreach ($ids as $id) {
1065                $incr = $id - $prev;
1066                if ($incr > 1) {                        //found a gap
1067                        if ($start == $prev) {
1068                            $result[] = $prev;  //push single id
1069                        } else {
1070                            $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
1071                        }
1072                        $start = $id;                   //start of new sequence
1073                }
1074                $prev = $id;
1075        }
1076
1077        //handle the last sequence/id
1078        if ($start==$prev) {
1079            $result[] = $prev;
1080        } else {
1081            $result[] = $start.':'.$prev;
1082        }
1083   
1084        //return as comma separated string
1085        return implode(',', $result);
1086}
1087
1088function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids) {
1089        if (!is_array($uids) || count($uids) == 0) {
1090            return array();
1091        }
1092        return iil_C_Search($conn, $mailbox, 'UID ' . implode(',', $uids));
1093}
1094
1095function iil_C_UIDToMID(&$conn, $mailbox, $uid) {
1096        $result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
1097        if (count($result) == 1) {
1098            return $result[0];
1099        }
1100        return false;
1101}
1102
1103function iil_C_FetchUIDs(&$conn,$mailbox) {
1104        global $clock;
1105       
1106        $num = iil_C_CountMessages($conn, $mailbox);
1107        if ($num == 0) {
1108            return array();
1109        }
1110        $message_set = '1' . ($num>1?':' . $num:'');
1111       
1112        return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
1113}
1114
1115function iil_SortThreadHeaders($headers, $index_a, $uids) {
1116        asort($index_a);
1117        $result = array();
1118        foreach ($index_a as $mid=>$foobar) {
1119                $uid = $uids[$mid];
1120                $result[$uid] = $headers[$uid];
1121        }
1122        return $result;
1123}
1124
1125function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set) {
1126        global $clock;
1127        global $index_a;
1128       
1129        list($from_idx, $to_idx) = explode(':', $message_set);
1130        if (empty($message_set) || (isset($to_idx)
1131        && (int)$from_idx > (int)$to_idx)) {
1132                return false;
1133        }
1134
1135        $result = array();
1136        $uids   = iil_C_FetchUIDs($conn, $mailbox);
1137        $debug  = false;
1138       
1139        $message_set = iil_CompressMessageSet($message_set);
1140   
1141        /* if we're missing any, get them */
1142        if ($message_set) {
1143                /* FETCH date,from,subject headers */
1144                $key        = 'fh';
1145                $fp         = $conn->fp;
1146                $request    = $key . " FETCH $message_set ";
1147                $request   .= "(BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])";
1148                $mid_to_id  = array();
1149                if (!iil_PutLine($fp, $request)) {
1150                    return false;
1151                }
1152                do {
1153                        $line = chop(iil_ReadLine($fp, 1024));
1154                        if ($debug) {
1155                            echo $line . "\n";
1156                        }
1157                        if (preg_match('/\{[0-9]+\}$/', $line)) {
1158                                $a       = explode(' ', $line);
1159                                $new = array();
1160
1161                                $new_thhd = new iilThreadHeader;
1162                                $new_thhd->id = $a[1];
1163                                do {
1164                                        $line = chop(iil_ReadLine($fp, 1024), "\r\n");
1165                                        if (iil_StartsWithI($line, 'Message-ID:')
1166                                                || (iil_StartsWithI($line,'In-Reply-To:'))
1167                                                || (iil_StartsWithI($line,'SUBJECT:'))) {
1168
1169                                                $pos        = strpos($line, ':');
1170                                                $field_name = substr($line, 0, $pos);
1171                                                $field_val  = substr($line, $pos+1);
1172
1173                                                $new[strtoupper($field_name)] = trim($field_val);
1174
1175                                        } else if (preg_match('/^\s+/', $line)) {
1176                                                $new[strtoupper($field_name)] .= trim($line);
1177                                        }
1178                                } while ($line[0] != ')');
1179               
1180                                $new_thhd->sbj = $new['SUBJECT'];
1181                                $new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
1182                                $new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
1183                               
1184                                $result[$uids[$new_thhd->id]] = $new_thhd;
1185                        }
1186                } while (!iil_StartsWith($line, 'fh'));
1187        }
1188       
1189        /* sort headers */
1190        if (is_array($index_a)) {
1191                $result = iil_SortThreadHeaders($result, $index_a, $uids);     
1192        }
1193       
1194        //echo 'iil_FetchThreadHeaders:'."\n";
1195        //print_r($result);
1196       
1197        return $result;
1198}
1199
1200function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock) {
1201        global $index_a;
1202
1203        list($from_idx, $to_idx) = explode(':', $message_set);
1204        if (empty($message_set) || (isset($to_idx)
1205                && (int)$from_idx > (int)$to_idx)) {
1206                return false;
1207        }
1208   
1209        $result    = array();
1210        $roots     = array();
1211        $root_mids = array();
1212        $sub_mids  = array();
1213        $strays    = array();
1214        $messages  = array();
1215        $fp        = $conn->fp;
1216        $debug     = false;
1217       
1218        $sbj_filter_pat = '/[a-z]{2,3}(\[[0-9]*\])?:(\s*)/i';
1219       
1220        /*  Do "SELECT" command */
1221        if (!iil_C_Select($conn, $mailbox)) {
1222            return false;
1223        }
1224   
1225        /* FETCH date,from,subject headers */
1226        $mid_to_id = array();
1227        $messages  = array();
1228        $headers   = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
1229        if ($clock) {
1230            $clock->register('fetched headers');
1231        }
1232   
1233        if ($debug) {
1234            print_r($headers);
1235        }
1236   
1237        /* go through header records */
1238        foreach ($headers as $header) {
1239                //$id = $header['i'];
1240                //$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'],
1241                //                      'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
1242                $id  = $header->id;
1243                $new = array('id' => $id, 'MESSAGE-ID' => $header->mid,
1244                        'IN-REPLY-TO' => $header->irt, 'SUBJECT' => $header->sbj);
1245
1246                /* add to message-id -> mid lookup table */
1247                $mid_to_id[$new['MESSAGE-ID']] = $id;
1248               
1249                /* if no subject, use message-id */
1250                if (empty($new['SUBJECT'])) {
1251                    $new['SUBJECT'] = $new['MESSAGE-ID'];
1252                }
1253       
1254                /* if subject contains 'RE:' or has in-reply-to header, it's a reply */
1255                $sbj_pre = '';
1256                $has_re = false;
1257                if (preg_match($sbj_filter_pat, $new['SUBJECT'])) {
1258                    $has_re = true;
1259                }
1260                if ($has_re || $new['IN-REPLY-TO']) {
1261                    $sbj_pre = 'RE:';
1262                }
1263       
1264                /* strip out 're:', 'fw:' etc */
1265                if ($has_re) {
1266                    $sbj = preg_replace($sbj_filter_pat, '', $new['SUBJECT']);
1267                } else {
1268                    $sbj = $new['SUBJECT'];
1269                }
1270                $new['SUBJECT'] = $sbj_pre.$sbj;
1271               
1272               
1273                /* if subject not a known thread-root, add to list */
1274                if ($debug) {
1275                    echo $id . ' ' . $new['SUBJECT'] . "\t" . $new['MESSAGE-ID'] . "\n";
1276                }
1277                $root_id = $roots[$sbj];
1278               
1279                if ($root_id && ($has_re || !$root_in_root[$root_id])) {
1280                        if ($debug) {
1281                            echo "\tfound root: $root_id\n";
1282                        }
1283                        $sub_mids[$new['MESSAGE-ID']] = $root_id;
1284                        $result[$root_id][]           = $id;
1285                } else if (!isset($roots[$sbj]) || (!$has_re && $root_in_root[$root_id])) {
1286                        /* try to use In-Reply-To header to find root
1287                                unless subject contains 'Re:' */
1288                        if ($has_re&&$new['IN-REPLY-TO']) {
1289                                if ($debug) {
1290                                    echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
1291                                }
1292                                //reply to known message?
1293                                $temp = $sub_mids[$new['IN-REPLY-TO']];
1294                               
1295                                if ($temp) {
1296                                        //found it, root:=parent's root
1297                                        if ($debug) {
1298                                            echo "\tfound parent: ".$new['SUBJECT']."\n";
1299                                        }
1300                                        $result[$temp][]              = $id;
1301                                        $sub_mids[$new['MESSAGE-ID']] = $temp;
1302                                        $sbj                          = '';
1303                                } else {
1304                                        //if we can't find referenced parent, it's a "stray"
1305                                        $strays[$id] = $new['IN-REPLY-TO'];
1306                                }
1307                        }
1308                       
1309                        //add subject as root
1310                        if ($sbj) {
1311                                if ($debug) {
1312                                    echo "\t added to root\n";
1313                                }
1314                                $roots[$sbj]                  = $id;
1315                                $root_in_root[$id]            = !$has_re;
1316                                $sub_mids[$new['MESSAGE-ID']] = $id;
1317                                $result[$id]                  = array($id);
1318                        }
1319                        if ($debug) {
1320                            echo $new['MESSAGE-ID'] . "\t" . $sbj . "\n";
1321                        }
1322                }
1323        }
1324       
1325        //now that we've gone through all the messages,
1326        //go back and try and link up the stray threads
1327        if (count($strays) > 0) {
1328                foreach ($strays as $id=>$irt) {
1329                        $root_id = $sub_mids[$irt];
1330                        if (!$root_id || $root_id==$id) {
1331                            continue;
1332                        }
1333                        $result[$root_id] = array_merge($result[$root_id],$result[$id]);
1334                        unset($result[$id]);
1335                }
1336        }
1337       
1338        if ($clock) {
1339            $clock->register('data prepped');
1340        }
1341   
1342        if ($debug) {
1343            print_r($roots);
1344        }
1345
1346        return $result;
1347}
1348
1349function iil_SortThreads(&$tree, $index, $sort_order = 'ASC') {
1350        if (!is_array($tree) || !is_array($index)) {
1351            return false;
1352        }
1353   
1354        //create an id to position lookup table
1355        $i = 0;
1356        foreach ($index as $id=>$val) {
1357                $i++;
1358                $index[$id] = $i;
1359        }
1360        $max = $i+1;
1361       
1362        //for each tree, set array key to position
1363        $itree = array();
1364        foreach ($tree as $id=>$node) {
1365                if (count($tree[$id])<=1) {
1366                        //for "threads" with only one message, key is position of that message
1367                        $n         = $index[$id];
1368                        $itree[$n] = array($n=>$id);
1369                } else {
1370                        //for "threads" with multiple messages,
1371                        $min   = $max;
1372                        $new_a = array();
1373                        foreach ($tree[$id] as $mid) {
1374                                $new_a[$index[$mid]] = $mid;            //create new sub-array mapping position to id
1375                                $pos                 = $index[$mid];
1376                                if ($pos&&$pos<$min) {
1377                                    $min = $index[$mid];        //find smallest position
1378                                }
1379                        }
1380                        $n = $min;      //smallest position of child is thread position
1381                       
1382                        //assign smallest position to root level key
1383                        //set children array to one created above
1384                        ksort($new_a);
1385                        $itree[$n] = $new_a;
1386                }
1387        }
1388       
1389        //sort by key, this basically sorts all threads
1390        ksort($itree);
1391        $i   = 0;
1392        $out = array();
1393        foreach ($itree as $k=>$node) {
1394                $out[$i] = $itree[$k];
1395                $i++;
1396        }
1397       
1398        return $out;
1399}
1400
1401function iil_IndexThreads(&$tree) {
1402        /* creates array mapping mid to thread id */
1403       
1404        if (!is_array($tree)) {
1405            return false;
1406        }
1407   
1408        $t_index = array();
1409        foreach ($tree as $pos=>$kids) {
1410                foreach ($kids as $kid) $t_index[$kid] = $pos;
1411        }
1412       
1413        return $t_index;
1414}
1415
1416function iil_C_FetchHeaders(&$conn, $mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1417{
1418        global $IMAP_USE_INTERNAL_DATE;
1419       
1420        $result = array();
1421        $fp     = $conn->fp;
1422       
1423        /*  Do "SELECT" command */
1424        if (!iil_C_Select($conn, $mailbox)) {
1425                $conn->error = "Couldn't select $mailbox";
1426                return false;
1427        }
1428
1429        $message_set = iil_CompressMessageSet($message_set);
1430
1431        if ($add)
1432                $add = ' '.strtoupper(trim($add));
1433
1434        /* FETCH uid, size, flags and headers */
1435        $key      = 'FH12';
1436        $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1437        $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1438        if ($bodystr)
1439                $request .= "BODYSTRUCTURE ";
1440        $request .= "BODY.PEEK[HEADER.FIELDS ";
1441        $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
1442        $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
1443        $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY".$add.")])";
1444
1445        if (!iil_PutLine($fp, $request)) {
1446                return false;
1447        }
1448        do {
1449                $line = iil_ReadLine($fp, 1024);
1450                $line = iil_MultLine($fp, $line);
1451
1452                $a    = explode(' ', $line);
1453                if (($line[0] == '*') && ($a[2] == 'FETCH')) {
1454                        $id = $a[1];
1455           
1456                        $result[$id]            = new iilBasicHeader;
1457                        $result[$id]->id        = $id;
1458                        $result[$id]->subject   = '';
1459                        $result[$id]->messageID = 'mid:' . $id;
1460
1461                        $lines = array();
1462                        $ln = 0;
1463                        /*
1464                            Sample reply line:
1465                            * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1466                            INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1467                            BODY[HEADER.FIELDS ...
1468                        */
1469
1470                        if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1471                                $str = $matches[1];
1472
1473                                // swap parents with quotes, then explode
1474                                $str = preg_replace('/[()]/', '"', $str);
1475                                $a = iil_ExplodeQuotedString(' ', $str);
1476
1477                                // did we get the right number of replies?
1478                                $parts_count = count($a);
1479                                if ($parts_count>=6) {
1480                                        for ($i=0; $i<$parts_count; $i=$i+2) {
1481                                                if (strcasecmp($a[$i],'UID') == 0)
1482                                                        $result[$id]->uid = $a[$i+1];
1483                                                else if (strcasecmp($a[$i],'RFC822.SIZE') == 0)
1484                                                        $result[$id]->size = $a[$i+1];
1485                                                else if (strcasecmp($a[$i],'INTERNALDATE') == 0)
1486                                                        $time_str = $a[$i+1];
1487                                                else if (strcasecmp($a[$i],'FLAGS') == 0)
1488                                                        $flags_str = $a[$i+1];
1489                                        }
1490
1491                                        $time_str = str_replace('"', '', $time_str);
1492                                       
1493                                        // if time is gmt...
1494                                        $time_str = str_replace('GMT','+0000',$time_str);
1495                                       
1496                                        $result[$id]->internaldate = $time_str;
1497                                        $result[$id]->timestamp = iil_StrToTime($time_str);
1498                                        $result[$id]->date = $time_str;
1499                                }
1500
1501                                // BODYSTRUCTURE
1502                                if($bodystr) {
1503                                        while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1504                                                $line2 = iil_ReadLine($fp, 1024);
1505                                                $line .= iil_MultLine($fp, $line2);
1506                                        }
1507                                        $result[$id]->body_structure = $m[1];
1508                                }
1509
1510                                // the rest of the result
1511                                preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1512                                $reslines = explode("\n", trim($m[1], '"'));
1513                                // re-parse (see below)
1514                                foreach ($reslines as $line) {
1515                                        if (ord($line[0])<=32) {
1516                                                $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1517                                        } else {
1518                                                $lines[++$ln] = trim($line);
1519                                        }
1520                                }
1521                        }
1522
1523                        /*
1524                                Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1525                                So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1526                                process the previous line.  Otherwise, we'll keep adding the strings until we come
1527                                to the next valid header line.
1528                        */
1529       
1530                        do {
1531                                $line = chop(iil_ReadLine($fp, 300), "\r\n");
1532
1533                                // The preg_match below works around communigate imap, which outputs " UID <number>)".
1534                                // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1535                                // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249. 
1536                                // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1537                                // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1538                                // An alternative might be:
1539                                // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1540                                // however, unsure how well this would work with all imap clients.
1541                                if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1542                                    break;
1543                                }
1544
1545                                // handle FLAGS reply after headers (AOL, Zimbra?)
1546                                if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1547                                        $flags_str = $matches[1];
1548                                        break;
1549                                }
1550
1551                                if (ord($line[0])<=32) {
1552                                        $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1553                                } else {
1554                                        $lines[++$ln] = trim($line);
1555                                }
1556                        // patch from "Maksim Rubis" <siburny@hotmail.com>
1557                        } while (trim($line[0]) != ')' && strncmp($line, $key, strlen($key)));
1558
1559                        if (strncmp($line, $key, strlen($key))) {
1560                                // process header, fill iilBasicHeader obj.
1561                                // initialize
1562                                if (is_array($headers)) {
1563                                        reset($headers);
1564                                        while (list($k, $bar) = each($headers)) {
1565                                                $headers[$k] = '';
1566                                        }
1567                                }
1568
1569                                // create array with header field:data
1570                                while ( list($lines_key, $str) = each($lines) ) {
1571                                        list($field, $string) = iil_SplitHeaderLine($str);
1572                                       
1573                                        $field  = strtolower($field);
1574                                        $string = preg_replace('/\n\s*/', ' ', $string);
1575                                       
1576                                        switch ($field) {
1577                                        case 'date';
1578                                                if (!$IMAP_USE_INTERNAL_DATE) {
1579                                                        $result[$id]->date = $string;
1580                                                        $result[$id]->timestamp = iil_StrToTime($string);
1581                                                }
1582                                                break;
1583                                        case 'from':
1584                                                $result[$id]->from = $string;
1585                                                break;
1586                                        case 'to':
1587                                                $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1588                                                break;
1589                                        case 'subject':
1590                                                $result[$id]->subject = $string;
1591                                                break;
1592                                        case 'reply-to':
1593                                                $result[$id]->replyto = $string;
1594                                                break;
1595                                        case 'cc':
1596                                                $result[$id]->cc = $string;
1597                                                break;
1598                                        case 'bcc':
1599                                                $result[$id]->bcc = $string;
1600                                                break;
1601                                        case 'content-transfer-encoding':
1602                                                $result[$id]->encoding = $string;
1603                                                break;
1604                                        case 'content-type':
1605                                                $ctype_parts = explode(";", $string);
1606                                                $result[$id]->ctype = array_shift($ctype_parts);
1607                                                foreach ($ctype_parts as $ctype_add) {
1608                                                        if (preg_match('/charset="?([a-z0-9\-\.\_]+)"?/i',
1609                                                                $ctype_add, $regs)) {
1610                                                                $result[$id]->charset = $regs[1];
1611                                                        }
1612                                                }
1613                                                break;
1614                                        case 'in-reply-to':
1615                                                $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
1616                                                break;
1617                                        case 'references':
1618                                                $result[$id]->references = $string;
1619                                                break;
1620                                        case 'return-receipt-to':
1621                                        case 'disposition-notification-to':
1622                                        case 'x-confirm-reading-to':
1623                                                $result[$id]->mdn_to = $string;
1624                                                break;
1625                                        case 'message-id':
1626                                                $result[$id]->messageID = $string;
1627                                                break;
1628                                        case 'x-priority':
1629                                                if (preg_match('/^(\d+)/', $string, $matches))
1630                                                        $result[$id]->priority = intval($matches[1]);
1631                                                break;
1632                                        default:
1633                                                if (strlen($field) > 2)
1634                                                        $result[$id]->others[$field] = $string;
1635                                                break;
1636                                        } // end switch ()
1637                                } // end while ()
1638                        } else {
1639                                $a = explode(' ', $line);
1640                        }
1641
1642                        // process flags
1643                        if (!empty($flags_str)) {
1644                                $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1645                                $flags_a   = explode(' ', $flags_str);
1646                                       
1647                                if (is_array($flags_a)) {
1648                                        reset($flags_a);
1649                                        while (list(,$val)=each($flags_a)) {
1650                                                if (strcasecmp($val,'Seen') == 0) {
1651                                                    $result[$id]->seen = true;
1652                                                } else if (strcasecmp($val, 'Deleted') == 0) {
1653                                                    $result[$id]->deleted=true;
1654                                                } else if (strcasecmp($val, 'Recent') == 0) {
1655                                                    $result[$id]->recent = true;
1656                                                } else if (strcasecmp($val, 'Answered') == 0) {
1657                                                        $result[$id]->answered = true;
1658                                                } else if (strcasecmp($val, '$Forwarded') == 0) {
1659                                                        $result[$id]->forwarded = true;
1660                                                } else if (strcasecmp($val, 'Draft') == 0) {
1661                                                        $result[$id]->is_draft = true;
1662                                                } else if (strcasecmp($val, '$MDNSent') == 0) {
1663                                                        $result[$id]->mdn_sent = true;
1664                                                } else if (strcasecmp($val, 'Flagged') == 0) {
1665                                                         $result[$id]->flagged = true;
1666                                                }
1667                                        }
1668                                        $result[$id]->flags = $flags_a;
1669                                }
1670                        }
1671                }
1672        } while (strcmp($a[0], $key) != 0);
1673
1674        return $result;
1675}
1676
1677function iil_C_FetchHeader(&$conn, $mailbox, $id, $uidfetch=false, $bodystr=false, $add='') {
1678
1679        $a  = iil_C_FetchHeaders($conn, $mailbox, $id, $uidfetch, $bodystr, $add);
1680        if (is_array($a)) {
1681                return array_shift($a);
1682        }
1683        return false;
1684}
1685
1686function iil_SortHeaders($a, $field, $flag) {
1687        if (empty($field)) {
1688            $field = 'uid';
1689        }
1690        $field = strtolower($field);
1691        if ($field == 'date' || $field == 'internaldate') {
1692            $field = 'timestamp';
1693        }
1694        if (empty($flag)) {
1695            $flag = 'ASC';
1696        }
1697   
1698        $flag     = strtoupper($flag);
1699        $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1700
1701        $c=count($a);
1702        if ($c > 0) {
1703                /*
1704                        Strategy:
1705                        First, we'll create an "index" array.
1706                        Then, we'll use sort() on that array,
1707                        and use that to sort the main array.
1708                */
1709               
1710                // create "index" array
1711                $index = array();
1712                reset($a);
1713                while (list($key, $val)=each($a)) {
1714
1715                        if ($field == 'timestamp') {
1716                                $data = iil_StrToTime($val->date);
1717                                if (!$data) {
1718                                        $data = $val->timestamp;
1719                                }
1720                        } else {
1721                                $data = $val->$field;
1722                                if (is_string($data)) {
1723                                        $data=strtoupper(str_replace($stripArr, '', $data));
1724                                }
1725                        }
1726                        $index[$key]=$data;
1727                }
1728               
1729                // sort index
1730                $i = 0;
1731                if ($flag == 'ASC') {
1732                        asort($index);
1733                } else {
1734                        arsort($index);
1735                }
1736       
1737                // form new array based on index
1738                $result = array();
1739                reset($index);
1740                while (list($key, $val)=each($index)) {
1741                        $result[$key]=$a[$key];
1742                        $i++;
1743                }
1744        }
1745       
1746        return $result;
1747}
1748
1749function iil_C_Expunge(&$conn, $mailbox, $messages=NULL) {
1750
1751        if (iil_C_Select($conn, $mailbox)) {
1752                $c = 0;
1753                $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
1754
1755                iil_PutLine($conn->fp, "exp1 $command");
1756                do {
1757                        $line=chop(iil_ReadLine($conn->fp, 100));
1758                        if ($line[0] == '*') {
1759                                $c++;
1760                        }
1761                } while (!iil_StartsWith($line, 'exp1', true));
1762               
1763                if (iil_ParseResult($line) == 0) {
1764                        $conn->selected = ''; //state has changed, need to reselect                     
1765                        //$conn->exists-=$c;
1766                        return $c;
1767                }
1768                $conn->error = $line;
1769        }
1770       
1771        return -1;
1772}
1773
1774function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod) {
1775        if ($mod != '+' && $mod != '-') {
1776            return -1;
1777        }
1778   
1779        $fp    = $conn->fp;
1780        $flags = $GLOBALS['IMAP_FLAGS'];
1781       
1782        $flag = strtoupper($flag);
1783        $flag = $flags[$flag];
1784   
1785        if (iil_C_Select($conn, $mailbox)) {
1786                $c = 0;
1787                iil_PutLine($fp, "flg UID STORE $messages " . $mod . "FLAGS (" . $flag . ")");
1788                do {
1789                        $line=chop(iil_ReadLine($fp, 100));
1790                        if ($line[0] == '*') {
1791                            $c++;
1792                        }
1793                } while (!iil_StartsWith($line, 'flg', true));
1794
1795                if (iil_ParseResult($line) == 0) {
1796                        return $c;
1797                }
1798                $conn->error = $line;
1799                return -1;
1800        }
1801        $conn->error = 'Select failed';
1802        return -1;
1803}
1804
1805function iil_C_Flag(&$conn, $mailbox, $messages, $flag) {
1806        return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '+');
1807}
1808
1809function iil_C_Unflag(&$conn, $mailbox, $messages, $flag) {
1810        return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '-');
1811}
1812
1813function iil_C_Delete(&$conn, $mailbox, $messages) {
1814        return iil_C_ModFlag($conn, $mailbox, $messages, 'DELETED', '+');
1815}
1816
1817function iil_C_Undelete(&$conn, $mailbox, $messages) {
1818        return iil_C_ModFlag($conn, $mailbox, $messages, 'DELETED', '-');
1819}
1820
1821function iil_C_Unseen(&$conn, $mailbox, $messages) {
1822        return iil_C_ModFlag($conn, $mailbox, $messages, 'SEEN', '-');
1823}
1824
1825function iil_C_Copy(&$conn, $messages, $from, $to) {
1826        $fp = $conn->fp;
1827
1828        if (empty($from) || empty($to)) {
1829            return -1;
1830        }
1831   
1832        if (iil_C_Select($conn, $from)) {
1833                $c=0;
1834               
1835                iil_PutLine($fp, "cpy1 UID COPY $messages \"".iil_Escape($to)."\"");
1836                $line=iil_ReadReply($fp);
1837                return iil_ParseResult($line);
1838        } else {
1839                return -1;
1840        }
1841}
1842
1843function iil_C_CountUnseen(&$conn, $folder) {
1844        $index = iil_C_Search($conn, $folder, 'ALL UNSEEN');
1845        if (is_array($index)) {
1846                if (($cnt = count($index)) && $index[0] != '') {
1847                        return $cnt;
1848                }
1849        }
1850        return false;
1851}
1852
1853function iil_C_UID2ID(&$conn, $folder, $uid) {
1854        if ($uid > 0) {
1855                $id_a = iil_C_Search($conn, $folder, "UID $uid");
1856                if (is_array($id_a) && count($id_a) == 1) {
1857                        return $id_a[0];
1858                }
1859        }
1860        return false;
1861}
1862
1863function iil_C_ID2UID(&$conn, $folder, $id) {
1864        $fp = $conn->fp;
1865        if ($id == 0) {
1866            return      -1;
1867        }
1868        $result = -1;
1869        if (iil_C_Select($conn, $folder)) {
1870                $key = 'FUID';
1871                if (iil_PutLine($fp, "$key FETCH $id (UID)")) {
1872                        do {
1873                                $line=chop(iil_ReadLine($fp, 1024));
1874                                if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1875                                        $result = $r[1];
1876                                }
1877                        } while (!preg_match("/^$key/", $line));
1878                }
1879        }
1880        return $result;
1881}
1882
1883function iil_C_Search(&$conn, $folder, $criteria) {
1884        $fp = $conn->fp;
1885        if (iil_C_Select($conn, $folder)) {
1886                $c = 0;
1887               
1888                $query = 'srch1 SEARCH ' . chop($criteria);
1889                if (!iil_PutLineC($fp, $query)) {
1890                        return false;
1891                }
1892                do {
1893                        $line=trim(iil_ReadLine($fp, 10000));
1894                        if (preg_match('/^\* SEARCH/i', $line)) {
1895                                $str = trim(substr($line, 8));
1896                                $messages = explode(' ', $str);
1897                        }
1898                } while (!iil_StartsWith($line, 'srch1', true));
1899
1900                $result_code = iil_ParseResult($line);
1901                if ($result_code == 0) {
1902                    return $messages;
1903                }
1904                $conn->error = 'iil_C_Search: ' . $line . "\n";
1905                return false;   
1906        }
1907        $conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
1908        return false;
1909}
1910
1911function iil_C_Move(&$conn, $messages, $from, $to) {
1912
1913    if (!$from || !$to) {
1914        return -1;
1915    }
1916   
1917    $r = iil_C_Copy($conn, $messages, $from, $to);
1918
1919    if ($r==0) {
1920        return iil_C_Delete($conn, $from, $messages);
1921    }
1922    return $r;
1923}
1924
1925/**
1926 * Gets the delimiter, for example:
1927 * INBOX.foo -> .
1928 * INBOX/foo -> /
1929 * INBOX\foo -> \
1930 *
1931 * @return mixed A delimiter (string), or false.
1932 * @param object $conn The current connection.
1933 * @see iil_Connect()
1934 */
1935function iil_C_GetHierarchyDelimiter(&$conn) {
1936
1937        global $my_prefs;
1938       
1939        if ($conn->delimiter) {
1940                return $conn->delimiter;
1941        }
1942        if (!empty($my_prefs['delimiter'])) {
1943            return ($conn->delimiter = $my_prefs['delimiter']);
1944        }
1945   
1946        $fp        = $conn->fp;
1947        $delimiter = false;
1948       
1949        //try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
1950        if (!iil_PutLine($fp, 'ghd LIST "" ""')) {
1951            return false;
1952        }
1953   
1954        do {
1955                $line=iil_ReadLine($fp, 500);
1956                if ($line[0] == '*') {
1957                        $line = rtrim($line);
1958                        $a=iil_ExplodeQuotedString(' ', iil_UnEscape($line));
1959                        if ($a[0] == '*') {
1960                            $delimiter = str_replace('"', '', $a[count($a)-2]);
1961                        }
1962                }
1963        } while (!iil_StartsWith($line, 'ghd', true));
1964
1965        if (strlen($delimiter)>0) {
1966            return $delimiter;
1967        }
1968
1969        //if that fails, try namespace extension
1970        //try to fetch namespace data
1971        iil_PutLine($conn->fp, "ns1 NAMESPACE");
1972        do {
1973                $line = iil_ReadLine($conn->fp, 1024);
1974                if (iil_StartsWith($line, '* NAMESPACE')) {
1975                        $i = 0;
1976                        $line = iil_UnEscape($line);
1977                        $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
1978                }
1979        } while (!iil_StartsWith($line, 'ns1', true));
1980               
1981        if (!is_array($data)) {
1982            return false;
1983        }
1984   
1985        //extract user space data (opposed to global/shared space)
1986        $user_space_data = $data[0];
1987        if (!is_array($user_space_data)) {
1988            return false;
1989        }
1990   
1991        //get first element
1992        $first_userspace = $user_space_data[0];
1993        if (!is_array($first_userspace)) {
1994            return false;
1995        }
1996   
1997        //extract delimiter
1998        $delimiter = $first_userspace[1];       
1999
2000        return $delimiter;
2001}
2002
2003function iil_C_ListMailboxes(&$conn, $ref, $mailbox) {
2004        global $IGNORE_FOLDERS;
2005       
2006        $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
2007               
2008        $fp = $conn->fp;
2009       
2010        if (empty($mailbox)) {
2011            $mailbox = '*';
2012        }
2013       
2014        if (empty($ref) && $conn->rootdir) {
2015            $ref = $conn->rootdir;
2016        }
2017   
2018        // send command
2019        if (!iil_PutLine($fp, "lmb LIST \"".$ref."\" \"".iil_Escape($mailbox)."\"")) {
2020            return false;
2021        }
2022   
2023        $i = 0;
2024        // get folder list
2025        do {
2026                $line = iil_ReadLine($fp, 500);
2027                $line = iil_MultLine($fp, $line, true);
2028
2029                $a = explode(' ', $line);
2030                if (($line[0] == '*') && ($a[1] == 'LIST')) {
2031                        $line = rtrim($line);
2032                        // split one line
2033                        $a = iil_ExplodeQuotedString(' ', $line);
2034                        // last string is folder name
2035                        $folder = preg_replace(array('/^"/', '/"$/'), '', iil_UnEscape($a[count($a)-1]));
2036           
2037                        if (empty($ignore) || (!empty($ignore)
2038                                && !preg_match('/'.preg_quote(ignore, '/').'/i', $folder))) {
2039                                $folders[$i] = $folder;
2040                        }
2041           
2042                        // second from last is delimiter
2043                        $delim = trim($a[count($a)-2], '"');
2044                        // is it a container?
2045                        $i++;
2046                }
2047        } while (!iil_StartsWith($line, 'lmb', true));
2048
2049        if (is_array($folders)) {
2050            if (!empty($ref)) {
2051                // if rootdir was specified, make sure it's the first element
2052                // some IMAP servers (i.e. Courier) won't return it
2053                if ($ref[strlen($ref)-1]==$delim)
2054                    $ref = substr($ref, 0, strlen($ref)-1);
2055                if ($folders[0]!=$ref)
2056                    array_unshift($folders, $ref);
2057            }
2058            return $folders;
2059        } else if (iil_ParseResult($line) == 0) {
2060                return array('INBOX');
2061        } else {
2062                $conn->error = $line;
2063                return false;
2064        }
2065}
2066
2067function iil_C_ListSubscribed(&$conn, $ref, $mailbox) {
2068        global $IGNORE_FOLDERS;
2069       
2070        $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
2071       
2072        $fp = $conn->fp;
2073        if (empty($mailbox)) {
2074                $mailbox = '*';
2075        }
2076        if (empty($ref) && $conn->rootdir) {
2077                $ref = $conn->rootdir;
2078        }
2079        $folders = array();
2080
2081        // send command
2082        if (!iil_PutLine($fp, 'lsb LSUB "' . $ref . '" "' . iil_Escape($mailbox).'"')) {
2083                $conn->error = "Couldn't send LSUB command\n";
2084                return false;
2085        }
2086       
2087        $i = 0;
2088       
2089        // get folder list
2090        do {
2091                $line = iil_ReadLine($fp, 500);
2092                $line = iil_MultLine($fp, $line, true);
2093                $a    = explode(' ', $line);
2094       
2095                if (($line[0] == '*') && ($a[1] == 'LSUB' || $a[1] == 'LIST')) {
2096                        $line = rtrim($line);
2097           
2098                        // split one line
2099                        $a = iil_ExplodeQuotedString(' ', $line);
2100                        // last string is folder name
2101                        $folder = preg_replace(array('/^"/', '/"$/'), '', iil_UnEscape($a[count($a)-1]));
2102       
2103                        if ((!in_array($folder, $folders)) && (empty($ignore)
2104                                || (!empty($ignore) && !preg_match('/'.preg_quote(ignore, '/').'/i', $folder)))) {
2105                            $folders[$i] = $folder;
2106                        }
2107           
2108                        // second from last is delimiter
2109                        $delim = trim($a[count($a)-2], '"');
2110           
2111                        // is it a container?
2112                        $i++;
2113                }
2114        } while (!iil_StartsWith($line, 'lsb', true));
2115
2116        if (is_array($folders)) {
2117            if (!empty($ref)) {
2118                // if rootdir was specified, make sure it's the first element
2119                // some IMAP servers (i.e. Courier) won't return it
2120                if ($ref[strlen($ref)-1]==$delim) {
2121                    $ref = substr($ref, 0, strlen($ref)-1);
2122                }
2123                if ($folders[0]!=$ref) {
2124                    array_unshift($folders, $ref);
2125                }
2126            }
2127            return $folders;
2128        }
2129        $conn->error = $line;
2130        return false;
2131}
2132
2133function iil_C_Subscribe(&$conn, $folder) {
2134        $fp = $conn->fp;
2135
2136        $query = 'sub1 SUBSCRIBE "' . iil_Escape($folder). '"';
2137        iil_PutLine($fp, $query);
2138
2139        $line = trim(iil_ReadLine($fp, 10000));
2140        return iil_ParseResult($line);
2141}
2142
2143function iil_C_UnSubscribe(&$conn, $folder) {
2144        $fp = $conn->fp;
2145
2146        $query = 'usub1 UNSUBSCRIBE "' . iil_Escape($folder) . '"';
2147        iil_PutLine($fp, $query);
2148   
2149        $line = trim(iil_ReadLine($fp, 10000));
2150        return iil_ParseResult($line);
2151}
2152
2153function iil_C_FetchMIMEHeaders(&$conn, $mailbox, $id, $parts) {
2154       
2155        $fp     = $conn->fp;
2156
2157        if (!iil_C_Select($conn, $mailbox)) {
2158                return false;
2159        }
2160       
2161        $result = false;
2162        $parts = (array) $parts;
2163        $key = 'fmh0';
2164        $peeks = '';
2165        $idx = 0;
2166
2167        // format request
2168        foreach($parts as $part)
2169                $peeks[] = "BODY.PEEK[$part.MIME]";
2170       
2171        $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2172
2173        // send request
2174        if (!iil_PutLine($fp, $request)) {
2175            return false;
2176        }
2177       
2178        do {
2179                $line = iil_ReadLine($fp, 1000);
2180                $line = iil_MultLine($fp, $line);
2181
2182                if (preg_match('/BODY\[([0-9\.]+)\.MIME\]/', $line, $matches)) {
2183                        $idx = $matches[1];
2184                        $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.MIME\]\s+/', '', $line);
2185                        $result[$idx] = trim($result[$idx], '"');
2186                        $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2187                }
2188        } while (!iil_StartsWith($line, $key, true));
2189
2190        return $result;
2191}
2192
2193function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $is_uid=false, $part=NULL) {
2194
2195        $part = empty($part) ? 'HEADER' : $part.'.MIME';
2196
2197        return iil_C_HandlePartBody($conn, $mailbox, $id, $is_uid, $part);
2198}
2199
2200function iil_C_HandlePartBody(&$conn, $mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL) {
2201       
2202        $fp     = $conn->fp;
2203        $result = false;
2204       
2205        switch ($encoding) {
2206                case 'base64':
2207                        $mode = 1;
2208                break;
2209                case 'quoted-printable':
2210                        $mode = 2;
2211                break;
2212                case 'x-uuencode':
2213                case 'x-uue':
2214                case 'uue':
2215                case 'uuencode':
2216                        $mode = 3;
2217                break;
2218                default:
2219                        $mode = 0;
2220        }
2221       
2222        if (iil_C_Select($conn, $mailbox)) {
2223                $reply_key = '* ' . $id;
2224
2225                // format request
2226                $key     = 'ftch0';
2227                $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2228                // send request
2229                if (!iil_PutLine($fp, $request)) {
2230                    return false;
2231                }
2232
2233                // receive reply line
2234                do {
2235                        $line = chop(iil_ReadLine($fp, 1000));
2236                        $a    = explode(' ', $line);
2237                } while (!($end = iil_StartsWith($line, $key, true)) && $a[2] != 'FETCH');
2238                $len = strlen($line);
2239
2240                // handle empty "* X FETCH ()" response
2241                if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2242                        // one line response, get everything between first and last quotes
2243                        if (substr($line, -4, 3) == 'NIL') {
2244                                // NIL response
2245                                $result = '';
2246                        } else {
2247                                $from = strpos($line, '"') + 1;
2248                                $to   = strrpos($line, '"');
2249                                $len  = $to - $from;
2250                                $result = substr($line, $from, $len);
2251                        }
2252           
2253                        if ($mode == 1)
2254                                $result = base64_decode($result);
2255                        else if ($mode == 2)
2256                                $result = quoted_printable_decode($result);
2257                        else if ($mode == 3)
2258                                $result = convert_uudecode($result);
2259
2260                } else if ($line[$len-1] == '}') {
2261                        //multi-line request, find sizes of content and receive that many bytes
2262                        $from     = strpos($line, '{') + 1;
2263                        $to       = strrpos($line, '}');
2264                        $len      = $to - $from;
2265                        $sizeStr  = substr($line, $from, $len);
2266                        $bytes    = (int)$sizeStr;
2267                        $prev     = '';
2268                       
2269                        while ($bytes > 0) {
2270                                $line      = iil_ReadLine($fp, 1024);
2271                                $len       = strlen($line);
2272               
2273                                if ($len > $bytes) {
2274                                        $line = substr($line, 0, $bytes);
2275                                }
2276                                $bytes -= strlen($line);
2277
2278                                if ($mode == 1) {
2279                                        $line = rtrim($line, "\t\r\n\0\x0B");
2280                                        // create chunks with proper length for base64 decoding
2281                                        $line = $prev.$line;
2282                                        $length = strlen($line);
2283                                        if ($length % 4) {
2284                                                $length = floor($length / 4) * 4;
2285                                                $prev = substr($line, $length);
2286                                                $line = substr($line, 0, $length);
2287                                        }
2288                                        else
2289                                                $prev = '';
2290
2291                                        if ($file)
2292                                                fwrite($file, base64_decode($line));
2293                                        else if ($print)
2294                                                echo base64_decode($line);
2295                                        else
2296                                                $result .= base64_decode($line);
2297                                } else if ($mode == 2) {
2298                                        $line = rtrim($line, "\t\r\0\x0B");
2299                                        if ($file)
2300                                                fwrite($file, quoted_printable_decode($line));
2301                                        else if ($print)
2302                                                echo quoted_printable_decode($line);
2303                                        else
2304                                                $result .= quoted_printable_decode($line);
2305                                } else if ($mode == 3) {
2306                                        $line = rtrim($line, "\t\r\n\0\x0B");
2307                                        if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2308                                                continue;
2309                                        if ($file)
2310                                                fwrite($file, convert_uudecode($line));
2311                                        else if ($print)
2312                                                echo convert_uudecode($line);
2313                                        else
2314                                                $result .= convert_uudecode($line);
2315                                } else {
2316                                        $line = rtrim($line, "\t\r\n\0\x0B");
2317                                        if ($file)
2318                                                fwrite($file, $line . "\n");
2319                                        else if ($print)
2320                                                echo $line . "\n";
2321                                        else
2322                                                $result .= $line . "\n";
2323                                }
2324                        }
2325                }
2326
2327                // read in anything up until last line
2328                if (!$end)
2329                        do {
2330                                $line = iil_ReadLine($fp, 1024);
2331                        } while (!iil_StartsWith($line, $key, true));
2332       
2333                if ($result) {
2334                        $result = rtrim($result, "\t\r\n\0\x0B");
2335                        if ($file) {
2336                                fwrite($file, $result);
2337                        } else if ($print) {
2338                                echo $result;
2339                        } else
2340                                return $result; // substr($result, 0, strlen($result)-1);
2341                }
2342               
2343                return true;
2344        }
2345   
2346        return false;
2347}
2348
2349function iil_C_CreateFolder(&$conn, $folder) {
2350        $fp = $conn->fp;
2351        if (iil_PutLine($fp, 'c CREATE "' . iil_Escape($folder) . '"')) {
2352                do {
2353                        $line=iil_ReadLine($fp, 300);
2354                } while ($line[0] != 'c');
2355        $conn->error = $line;
2356                return (iil_ParseResult($line) == 0);
2357        }
2358        return false;
2359}
2360
2361function iil_C_RenameFolder(&$conn, $from, $to) {
2362        $fp = $conn->fp;
2363        if (iil_PutLine($fp, 'r RENAME "' . iil_Escape($from) . '" "' . iil_Escape($to) . '"')) {
2364                do {
2365                        $line = iil_ReadLine($fp, 300);
2366                } while ($line[0] != 'r');
2367                return (iil_ParseResult($line) == 0);
2368        }
2369        return false;
2370}
2371
2372function iil_C_DeleteFolder(&$conn, $folder) {
2373        $fp = $conn->fp;
2374        if (iil_PutLine($fp, 'd DELETE "' . iil_Escape($folder). '"')) {
2375                do {
2376                        $line=iil_ReadLine($fp, 300);
2377                } while ($line[0] != 'd');
2378                return (iil_ParseResult($line) == 0);
2379        }
2380        $conn->error = "Couldn't send command\n";
2381        return false;
2382}
2383
2384function iil_C_Append(&$conn, $folder, &$message) {
2385        if (!$folder) {
2386                return false;
2387        }
2388        $fp = $conn->fp;
2389
2390        $message = str_replace("\r", '', $message);
2391        $message = str_replace("\n", "\r\n", $message);         
2392
2393        $len = strlen($message);
2394        if (!$len) {
2395                return false;
2396        }
2397
2398        $request = 'A APPEND "' . iil_Escape($folder) .'" (\\Seen) {' . $len . '}';
2399   
2400        if (iil_PutLine($fp, $request)) {
2401                $line=iil_ReadLine($fp, 100);           
2402                $sent = fwrite($fp, $message."\r\n");
2403                do {
2404                        $line=iil_ReadLine($fp, 1000);
2405                } while ($line[0] != 'A');
2406       
2407                $result = (iil_ParseResult($line) == 0);
2408                if (!$result) {
2409                    $conn->error .= $line . "\n";
2410                }
2411                return $result;
2412        }
2413
2414        $conn->error .= "Couldn't send command \"$request\"\n";
2415        return false;
2416}
2417
2418function iil_C_AppendFromFile(&$conn, $folder, $path) {
2419        if (!$folder) {
2420            return false;
2421        }
2422   
2423        //open message file
2424        $in_fp = false;                         
2425        if (file_exists(realpath($path))) {
2426                $in_fp = fopen($path, 'r');
2427        }
2428        if (!$in_fp) {
2429                $conn->error .= "Couldn't open $path for reading\n";
2430                return false;
2431        }
2432       
2433        $fp  = $conn->fp;
2434        $len = filesize($path);
2435        if (!$len) {
2436                return false;
2437        }
2438   
2439        //send APPEND command
2440        $request    = 'A APPEND "' . iil_Escape($folder) . '" (\\Seen) {' . $len . '}';
2441        $bytes_sent = 0;
2442        if (iil_PutLine($fp, $request)) {
2443                $line = iil_ReadLine($fp, 100);
2444                               
2445                //send file
2446                while (!feof($in_fp)) {
2447                        $buffer      = fgets($in_fp, 4096);
2448                        $bytes_sent += strlen($buffer);
2449                        iil_PutLine($fp, $buffer, false);
2450                }
2451                fclose($in_fp);
2452
2453                iil_PutLine($fp, '');
2454
2455                //read response
2456                do {
2457                        $line = iil_ReadLine($fp, 1000);
2458                } while ($line[0] != 'A');
2459                       
2460                $result = (iil_ParseResult($line) == 0);
2461                if (!$result) {
2462                    $conn->error .= $line . "\n";
2463                }
2464       
2465                return $result;
2466        }
2467       
2468        $conn->error .= "Couldn't send command \"$request\"\n";
2469        return false;
2470}
2471
2472function iil_C_FetchStructureString(&$conn, $folder, $id, $is_uid=false) {
2473        $fp     = $conn->fp;
2474        $result = false;
2475       
2476        if (iil_C_Select($conn, $folder)) {
2477                $key = 'F1247';
2478
2479                if (iil_PutLine($fp, $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
2480                        do {
2481                                $line = iil_ReadLine($fp, 5000);
2482                                $line = iil_MultLine($fp, $line);
2483                                list(, $index, $cmd, $rest) = explode(' ', $line);
2484                                if ($cmd != 'FETCH' || $index == $id || preg_match("/^$key/", $line))
2485                                        $result .= $line;
2486                        } while (!preg_match("/^$key/", $line));
2487
2488                        $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -(strlen($result)-strrpos($result, $key)+1)));
2489                }
2490        }
2491        return $result;
2492}
2493
2494function iil_C_GetQuota(&$conn) {
2495/*
2496 * GETQUOTAROOT "INBOX"
2497 * QUOTAROOT INBOX user/rchijiiwa1
2498 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2499 * OK Completed
2500 */
2501        $fp         = $conn->fp;
2502        $result     = false;
2503        $quota_lines = array();
2504       
2505        // get line(s) containing quota info
2506        if (iil_PutLine($fp, 'QUOT1 GETQUOTAROOT "INBOX"')) {
2507                do {
2508                        $line=chop(iil_ReadLine($fp, 5000));
2509                        if (iil_StartsWith($line, '* QUOTA ')) {
2510                                $quota_lines[] = $line;
2511                        }
2512                } while (!iil_StartsWith($line, 'QUOT1', true));
2513        }
2514       
2515        // return false if not found, parse if found
2516        $min_free = PHP_INT_MAX;
2517        foreach ($quota_lines as $key => $quota_line) {
2518                $quota_line   = preg_replace('/[()]/', '', $quota_line);
2519                $parts        = explode(' ', $quota_line);
2520                $storage_part = array_search('STORAGE', $parts);
2521               
2522                if (!$storage_part) continue;
2523       
2524                $used   = intval($parts[$storage_part+1]);
2525                $total  = intval($parts[$storage_part+2]);
2526                $free   = $total - $used;
2527       
2528                // return lowest available space from all quotas
2529                if ($free < $min_free) {
2530                        $min_free = $free;
2531                        $result['used']    = $used;
2532                        $result['total']   = $total;
2533                        $result['percent'] = min(100, round(($used/max(1,$total))*100));
2534                        $result['free']    = 100 - $result['percent'];
2535                }
2536        }
2537        return $result;
2538}
2539
2540function iil_C_ClearFolder(&$conn, $folder) {
2541        $num_in_trash = iil_C_CountMessages($conn, $folder);
2542        if ($num_in_trash > 0) {
2543                iil_C_Delete($conn, $folder, '1:*');
2544        }
2545        return (iil_C_Expunge($conn, $folder) >= 0);
2546}
2547
2548?>
Note: See TracBrowser for help on using the repository browser.