source: github/program/lib/imap.inc @ d6584f7

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