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

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