root/trunk/roundcubemail/program/lib/imap.inc

Revision 3247, 63.9 KB (checked in by alec, 5 days ago)

- Fix sorting by date of messages without date header on servers without SORT (#1486286)

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