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