thomascube
2006-05-05 ded2b7e166d4b0acab09c00f22f379fbabba709a
commit | author | age
4e17e6 1 <?php
T 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()
0284c2 26     VERSION:
T 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)
f88d41 39         - Added BCC and REFERENCE to the list of headers to fetch in iil_C_FetchHeaders()
T 40         - Leave messageID unchanged in iil_C_FetchHeaders()
41         - Avoid stripslahes in iil_Connect()
0d361b 42         - Added patch to iil_SortHeaders() by Richard Green
8c2e58 43         - Removed <br> from error messages (better for logging)
e6f360 44         - Added patch to iil_C_Sort() enabling UID SORT commands
T 45         - Added function iil_C_ID2UID()
0284c2 46         - Removed some debuggers (echo ...)
4e17e6 47
T 48 ********************************************************/
0284c2 49
4e17e6 50
T 51 // changed path to work within roundcube webmail
52 include_once("lib/icl_commons.inc");
53
54
55 if (!$IMAP_USE_HEADER_DATE) $IMAP_USE_INTERNAL_DATE = true;
56 $IMAP_MONTHS=array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12);
57 $IMAP_SERVER_TZ = date('Z');
58
59 $iil_error;
60 $iil_errornum;
61 $iil_selected;
62
63 class iilConnection{
64     var $fp;
65     var $error;
66     var $errorNum;
67     var $selected;
68     var $message;
69     var $host;
70     var $cache;
71     var $uid_cache;
72     var $do_cache;
73     var $exists;
74     var $recent;
75     var $rootdir;
76     var $delimiter;
f3b659 77     var $capability = array();
4e17e6 78 }
T 79
80 class iilBasicHeader{
81     var $id;
82     var $uid;
83     var $subject;
84     var $from;
85     var $to;
86     var $cc;
87     var $replyto;
88     var $in_reply_to;
89     var $date;
90     var $messageID;
91     var $size;
92     var $encoding;
93     var $ctype;
94     var $flags;
95     var $timestamp;
96     var $f;
97     var $seen;
98     var $deleted;
99     var $recent;
100     var $answered;
101     var $junk;
102     var $internaldate;
103     var $is_reply;
104 }
105
106
107 class iilThreadHeader{
108     var $id;
109     var $sbj;
110     var $irt;
111     var $mid;
112 }
113
114
115 function iil_xor($string, $string2){
116     $result = "";
117     $size = strlen($string);
118     for ($i=0; $i<$size; $i++) $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
119         
120     return $result;
121 }
122
123 function iil_ReadLine($fp, $size){
124     $line="";
125     if ($fp){
126         do{
127             $buffer = fgets($fp, 2048);
128             $line.=$buffer;
129         }while($buffer[strlen($buffer)-1]!="\n");
130     }
131     return $line;
132 }
133
134 function iil_MultLine($fp, $line){
135     $line = chop($line);
136     if (ereg('\{[0-9]+\}$', $line)){
137         $out = "";
138         preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
139         $bytes = $a[2][0];
140         while(strlen($out)<$bytes){
141             $out.=chop(iil_ReadLine($fp, 1024));
142         }
143         $line = $a[1][0]."\"$out\"";
144     }
145     return $line;
146 }
147
148 function iil_ReadBytes($fp, $bytes){
149     $data = "";
150     $len = 0;
151     do{
152         $data.=fread($fp, $bytes-$len);
153         $len = strlen($data);
154     }while($len<$bytes);
155     return $data;
156 }
157
158 function iil_ReadReply($fp){
159     do{
160         $line = chop(trim(iil_ReadLine($fp, 1024)));
161     }while($line[0]=="*");
162     
163     return $line;
164 }
165
166 function iil_ParseResult($string){
167     $a=explode(" ", $string);
168     if (count($a) > 2){
169         if (strcasecmp($a[1], "OK")==0) return 0;
170         else if (strcasecmp($a[1], "NO")==0) return -1;
171         else if (strcasecmp($a[1], "BAD")==0) return -2;
172     }else return -3;
173 }
174
175 // check if $string starts with $match
176 function iil_StartsWith($string, $match){
177     $len = strlen($match);
178     if ($len==0) return false;
179     if (strncmp($string, $match, $len)==0) return true;
180     else return false;
181 }
182
183 function iil_StartsWithI($string, $match){
184     $len = strlen($match);
185     if ($len==0) return false;
186     if (strncasecmp($string, $match, $len)==0) return true;
187     else return false;
188 }
189
190
191 function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge){
192     
193     // initialize ipad, opad
194     for ($i=0;$i<64;$i++){
195         $ipad.=chr(0x36);
196         $opad.=chr(0x5C);
197     }
198     // pad $pass so it's 64 bytes
199     $padLen = 64 - strlen($pass);
200     for ($i=0;$i<$padLen;$i++) $pass .= chr(0);
201     // generate hash
202     $hash = md5(iil_xor($pass,$opad).pack("H*",md5(iil_xor($pass, $ipad).base64_decode($encChallenge))));
203     // generate reply
204     $reply = base64_encode($user." ".$hash);
205     
206     // send result, get reply
207     fputs($conn->fp, $reply."\r\n");
208     $line = iil_ReadLine($conn->fp, 1024);
209     
210     // process result
211     if (iil_ParseResult($line)==0){
212         $conn->error .= "";
213         $conn->errorNum = 0;
214         return $conn->fp;
215     }else{
8c2e58 216         $conn->error .= 'Authentication for '.$user.' failed (AUTH): "'.htmlspecialchars($line)."\"";
4e17e6 217         $conn->errorNum = -2;
T 218         return false;
219     }
220 }
221
222 function iil_C_Login(&$conn, $user, $password){
223
224     fputs($conn->fp, "a001 LOGIN $user \"$password\"\r\n");
225         
226     do{
227         $line = iil_ReadReply($conn->fp);
228     }while(!iil_StartsWith($line, "a001 "));
229     $a=explode(" ", $line);
230     if (strcmp($a[1],"OK")==0){
231         $result=$conn->fp;
232         $conn->error.="";
233         $conn->errorNum = 0;
234     }else{
235         $result=false;
236         fclose($conn->fp);
8c2e58 237         $conn->error .= 'Authentication for '.$user.' failed (LOGIN): "'.htmlspecialchars($line)."\"";
4e17e6 238         $conn->errorNum = -2;
T 239     }
240     return $result;
241 }
242
243 function iil_ParseNamespace2($str, &$i, $len=0, $l){
244     if (!$l) $str = str_replace("NIL", "()", $str);
245     if (!$len) $len = strlen($str);
246     $data = array();
247     $in_quotes = false;
248     $elem = 0;
249     for($i;$i<$len;$i++){
250         $c = (string)$str[$i];
251         if ($c=='(' && !$in_quotes){
252             $i++;
253             $data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
254             $elem++;
255         }else if ($c==')' && !$in_quotes) return $data;
256         else if ($c=="\\"){
257             $i++;
258             if ($in_quotes) $data[$elem].=$c.$str[$i];
259         }else if ($c=='"'){
260             $in_quotes = !$in_quotes;
261             if (!$in_quotes) $elem++;
262         }else if ($in_quotes){
263             $data[$elem].=$c;
264         }
265     }
266     return $data;
267 }
268
269 function iil_C_NameSpace(&$conn){
270     global $my_prefs;
271     
f3b659 272     if (!in_array('NAMESPACE', $conn->capability))
T 273       return false;
274     
4e17e6 275     if ($my_prefs["rootdir"]) return true;
T 276     
277     fputs($conn->fp, "ns1 NAMESPACE\r\n");
278     do{
279         $line = iil_ReadLine($conn->fp, 1024);
280         if (iil_StartsWith($line, "* NAMESPACE")){
281             $i = 0;
282             $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
283         }
284     }while(!iil_StartsWith($line, "ns1"));
285     
286     if (!is_array($data)) return false;
287     
288     $user_space_data = $data[0];
289     if (!is_array($user_space_data)) return false;
290     
291     $first_userspace = $user_space_data[0];
292     if (count($first_userspace)!=2) return false;
293     
294     $conn->rootdir = $first_userspace[0];
295     $conn->delimiter = $first_userspace[1];
296     $my_prefs["rootdir"] = substr($conn->rootdir, 0, -1);
297     
298     return true;
299
300 }
301
302 function iil_Connect($host, $user, $password){    
303     global $iil_error, $iil_errornum;
304     global $ICL_SSL, $ICL_PORT;
305     global $IMAP_NO_CACHE;
306     global $my_prefs, $IMAP_USE_INTERNAL_DATE;
307     
308     $iil_error = "";
309     $iil_errornum = 0;
310     
311     //strip slashes
f88d41 312     // $user = stripslashes($user);
T 313     // $password = stripslashes($password);
4e17e6 314     
T 315     //set auth method
316     $auth_method = "plain";
317     if (func_num_args() >= 4){
318         $auth_array = func_get_arg(3);
319         if (is_array($auth_array)) $auth_method = $auth_array["imap"];
320         if (empty($auth_method)) $auth_method = "plain";
321     }
322     $message = "INITIAL: $auth_method\n";
323         
324     $result = false;
325     
326     //initialize connection
327     $conn = new iilConnection;
328     $conn->error="";
329     $conn->errorNum=0;
330     $conn->selected="";
331     $conn->user = $user;
332     $conn->host = $host;
333     $conn->cache = array();
334     $conn->do_cache = (function_exists("cache_write")&&!$IMAP_NO_CACHE);
335     $conn->cache_dirty = array();
336     
337     if ($my_prefs['sort_field']=='INTERNALDATE') $IMAP_USE_INTERNAL_DATE = true;
338     else if ($my_prefs['sort_field']=='DATE') $IMAP_USE_INTERNAL_DATE = false;
339     //echo '<!-- conn sort_field: '.$my_prefs['sort_field'].' //-->';
340     
341     //check input
8c2e58 342     if (empty($host)) $iil_error .= "Invalid host\n";
T 343     if (empty($user)) $iil_error .= "Invalid user\n";
344     if (empty($password)) $iil_error .= "Invalid password\n";
4e17e6 345     if (!empty($iil_error)) return false;
T 346     if (!$ICL_PORT) $ICL_PORT = 143;
347     
348     //check for SSL
349     if ($ICL_SSL){
350         $host = "ssl://".$host;
351     }
352     
353     //open socket connection
9fee0e 354     $conn->fp = @fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
4e17e6 355     if (!$conn->fp){
520c36 356         $iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
4e17e6 357         $iil_errornum = -1;
T 358         return false;
359     }
360
361     $iil_error.="Socket connection established\r\n";
362     $line=iil_ReadLine($conn->fp, 300);
f3b659 363
4e17e6 364     if (strcasecmp($auth_method, "check")==0){
T 365         //check for supported auth methods
366         
367         //default to plain text auth
368         $auth_method = "plain";
369             
370         //check for CRAM-MD5
371         fputs($conn->fp, "cp01 CAPABILITY\r\n");
372         do{
373         $line = trim(chop(iil_ReadLine($conn->fp, 100)));
42b113 374         $conn->message.="$line\n";
4e17e6 375             $a = explode(" ", $line);
T 376             if ($line[0]=="*"){
377                 while ( list($k, $w) = each($a) ){
f3b659 378                     if ($w!='*' && $w!='CAPABILITY')
T 379                         $conn->capability[] = $w;
4e17e6 380                     if ((strcasecmp($w, "AUTH=CRAM_MD5")==0)||
T 381                         (strcasecmp($w, "AUTH=CRAM-MD5")==0)){
382                             $auth_method = "auth";
383                         }
384                 }
385             }
386         }while($a[0]!="cp01");
387     }
388
389     if (strcasecmp($auth_method, "auth")==0){
390         $conn->message.="Trying CRAM-MD5\n";
391         //do CRAM-MD5 authentication
392         fputs($conn->fp, "a000 AUTHENTICATE CRAM-MD5\r\n");
393         $line = trim(chop(iil_ReadLine($conn->fp, 1024)));
42b113 394         $conn->message.="$line\n";
4e17e6 395         if ($line[0]=="+"){
T 396             $conn->message.='Got challenge: '.htmlspecialchars($line)."\n";
397             //got a challenge string, try CRAM-5
398             $result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
399             $conn->message.= "Tried CRAM-MD5: $result \n";
400         }else{
401             $conn->message.='No challenge ('.htmlspecialchars($line)."), try plain\n";
402             $auth = "plain";
403         }
404     }
405         
406     if ((!$result)||(strcasecmp($auth, "plain")==0)){
407         //do plain text auth
408         $result = iil_C_Login($conn, $user, $password);
409         $conn->message.="Tried PLAIN: $result \n";
410     }
411         
412     $conn->message .= $auth;
413             
414     if ($result){
415         iil_C_Namespace($conn);
416         return $conn;
417     }else{
418         $iil_error = $conn->error;
419         $iil_errornum = $conn->errorNum;
420         return false;
421     }
422 }
423
424 function iil_Close(&$conn){
425     iil_C_WriteCache($conn);
426     if (@fputs($conn->fp, "I LOGOUT\r\n")){
427         fgets($conn->fp, 1024);
428         fclose($conn->fp);
429         $conn->fp = false;
430     }
431 }
432
433 function iil_ClearCache($user, $host){
434 }
435
436
437 function iil_C_WriteCache(&$conn){
438     //echo "<!-- doing iil_C_WriteCache //-->\n";
439     if (!$conn->do_cache) return false;
440     
441     if (is_array($conn->cache)){
442         while(list($folder,$data)=each($conn->cache)){
443             if ($folder && is_array($data) && $conn->cache_dirty[$folder]){
444                 $key = $folder.".imap";
445                 $result = cache_write($conn->user, $conn->host, $key, $data, true);
446                 //echo "<!-- writing $key $data: $result //-->\n";
447             }
448         }
449     }
450 }
451
452 function iil_C_EnableCache(&$conn){
453     $conn->do_cache = true;
454 }
455
456 function iil_C_DisableCache(&$conn){
457     $conn->do_cache = false;
458 }
459
460 function iil_C_LoadCache(&$conn, $folder){
461     if (!$conn->do_cache) return false;
462     
463     $key = $folder.".imap";
464     if (!is_array($conn->cache[$folder])){
465         $conn->cache[$folder] = cache_read($conn->user, $conn->host, $key);
466         $conn->cache_dirty[$folder] = false;
467     }
468 }
469
470 function iil_C_ExpireCachedItems(&$conn, $folder, $message_set){
471     
472     if (!$conn->do_cache) return;    //caching disabled
473     if (!is_array($conn->cache[$folder])) return;    //cache not initialized|empty
474     if (count($conn->cache[$folder])==0) return;    //cache not initialized|empty
475         
476     $uids = iil_C_FetchHeaderIndex($conn, $folder, $message_set, "UID");
477     $num_removed = 0;
478     if (is_array($uids)){
479         //echo "<!-- unsetting: ".implode(",",$uids)." //-->\n";
480         while(list($n,$uid)=each($uids)){
481             unset($conn->cache[$folder][$uid]);
482             //$conn->cache[$folder][$uid] = false;
483             //$num_removed++;
484         }
485         $conn->cache_dirty[$folder] = true;
486
487         //echo '<!--'."\n";
488         //print_r($conn->cache);
489         //echo "\n".'//-->'."\n";
490     }else{
491         echo "<!-- failed to get uids: $message_set //-->\n";
492     }
493     
494     /*
495     if ($num_removed>0){
496         $new_cache;
497         reset($conn->cache[$folder]);
498         while(list($uid,$item)=each($conn->cache[$folder])){
499             if ($item) $new_cache[$uid] = $conn->cache[$folder][$uid];
500         }
501         $conn->cache[$folder] = $new_cache;
502     }
503     */
504 }
505
506 function iil_ExplodeQuotedString($delimiter, $string){
507     $quotes=explode("\"", $string);
508     while ( list($key, $val) = each($quotes))
509         if (($key % 2) == 1) 
510             $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
511     $string=implode("\"", $quotes);
512     
513     $result=explode($delimiter, $string);
514     while ( list($key, $val) = each($result) )
515         $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
516     
517     return $result;
518 }
519
520 function iil_CheckForRecent($host, $user, $password, $mailbox){
521     if (empty($mailbox)) $mailbox="INBOX";
522     
523     $conn=iil_Connect($host, $user, $password, "plain");
524     $fp = $conn->fp;
525     if ($fp){
526         fputs($fp, "a002 EXAMINE \"$mailbox\"\r\n");
527         do{
528             $line=chop(iil_ReadLine($fp, 300));
529             $a=explode(" ", $line);
530             if (($a[0]=="*") && (strcasecmp($a[2], "RECENT")==0))  $result=(int)$a[1];
531         }while (!iil_StartsWith($a[0],"a002"));
532
533         fputs($fp, "a003 LOGOUT\r\n");
534         fclose($fp);
535     }else $result=-2;
536     
537     return $result;
538 }
539
540 function iil_C_Select(&$conn, $mailbox){
541     $fp = $conn->fp;
542     
543     if (empty($mailbox)) return false;
544     if (strcmp($conn->selected, $mailbox)==0) return true;
545     
546     iil_C_LoadCache($conn, $mailbox);
547     
548     if (fputs($fp, "sel1 SELECT \"$mailbox\"\r\n")){
549         do{
550             $line=chop(iil_ReadLine($fp, 300));
551             $a=explode(" ", $line);
552             if (count($a) == 3){
553                 if (strcasecmp($a[2], "EXISTS")==0) $conn->exists=(int)$a[1];
554                 if (strcasecmp($a[2], "RECENT")==0) $conn->recent=(int)$a[1];
555             }
556         }while (!iil_StartsWith($line, "sel1"));
557
558         $a=explode(" ", $line);
559
560         if (strcasecmp($a[1],"OK")==0){
561             $conn->selected = $mailbox;
562             return true;
563         }else return false;
564     }else{
565         return false;
566     }
567 }
568
569 function iil_C_CheckForRecent(&$conn, $mailbox){
570     if (empty($mailbox)) $mailbox="INBOX";
571     
572     iil_C_Select($conn, $mailbox);
573     if ($conn->selected==$mailbox) return $conn->recent;
574     else return false;
575 }
576
577 function iil_C_CountMessages(&$conn, $mailbox, $refresh=false){
578     if ($refresh) $conn->selected="";
579     iil_C_Select($conn, $mailbox);
580     if ($conn->selected==$mailbox) return $conn->exists;
581     else return false;
582 }
583
584 function iil_SplitHeaderLine($string){
585     $pos=strpos($string, ":");
586     if ($pos>0){
587         $res[0]=substr($string, 0, $pos);
588         $res[1]=trim(substr($string, $pos+1));
589         return $res;
590     }else{
591         return $string;
592     }
593 }
594
595 function iil_StrToTime($str){
596     global $IMAP_MONTHS,$IMAP_SERVER_TZ;
597         
598     if ($str) $time1 = strtotime($str);
599     if ($time1 && $time1!=-1) return $time1-$IMAP_SERVER_TZ;
600     
601     //echo '<!--'.$str.'//-->';
602     
603     //replace double spaces with single space
604     $str = trim($str);
605     $str = str_replace("  ", " ", $str);
606     
607     //strip off day of week
608     $pos=strpos($str, " ");
609     if (!is_numeric(substr($str, 0, $pos))) $str = substr($str, $pos+1);
610
611     //explode, take good parts
612     $a=explode(" ",$str);
613     //$month_a=array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12);
614     $month_str=$a[1];
615     $month=$IMAP_MONTHS[$month_str];
a4bafb 616     $day=(int)$a[0];
4e17e6 617     $year=$a[2];
T 618     $time=$a[3];
619     $tz_str = $a[4];
620     $tz = substr($tz_str, 0, 3);
621     $ta=explode(":",$time);
622     $hour=(int)$ta[0]-(int)$tz;
623     $minute=$ta[1];
624     $second=$ta[2];
625     
626     //make UNIX timestamp
627     $time2 = mktime($hour, $minute, $second, $month, $day, $year);
628     //echo '<!--'.$time1.' '.$time2.' //-->'."\n";
629     return $time2;
630 }
631
e6f360 632 function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE, $encoding='US-ASCII'){
4e17e6 633     /*  Do "SELECT" command */
T 634     if (!iil_C_Select($conn, $mailbox)) return false;
635     
636     $field = strtoupper($field);
637     if ($field=='INTERNALDATE') $field='ARRIVAL';
638     $fields = array('ARRIVAL'=>1,'CC'=>1,'DATE'=>1,'FROM'=>1,'SIZE'=>1,'SUBJECT'=>1,'TO'=>1);
639     
e6f360 640     if (!$fields[$field])
T 641       return false;
4e17e6 642     
e6f360 643     $is_uid = $is_uid ? 'UID ' : '';
T 644     
645     if (!empty($add))
646       $add = " $add";
647
4e17e6 648     $fp = $conn->fp;
e6f360 649     $command = 's '. $is_uid .'SORT ('.$field.') '.$encoding.' ALL'."$add\r\n";
4e17e6 650     $line = $data = '';
T 651     
652     if (!fputs($fp, $command)) return false;
653     do{
654         $line = chop(iil_ReadLine($fp, 1024));
655         if (iil_StartsWith($line, '* SORT')) $data.=($data?' ':'').substr($line,7);
656     }while($line[0]!='s');
657     
658     if (empty($data)){
659         $conn->error = $line;
660         return false;
661     }
662     
663     $out = explode(' ',$data);
664     return $out;
665 }
666
e6f360 667 function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field, $normalize=true){
4e17e6 668     global $IMAP_USE_INTERNAL_DATE;
T 669     
670     $c=0;
671     $result=array();
672     $fp = $conn->fp;
673         
674     if (empty($index_field)) $index_field="DATE";
675     $index_field = strtoupper($index_field);
676     
677     if (empty($message_set)) return array();
678     
679     //$fields_a["DATE"] = ($IMAP_USE_INTERNAL_DATE?6:1);
680     $fields_a['DATE'] = 1;
681     $fields_a['INTERNALDATE'] = 6;
682     $fields_a['FROM'] = 1;
683     $fields_a['REPLY-TO'] = 1;
684     $fields_a['SENDER'] = 1;
685     $fields_a['TO'] = 1;
686     $fields_a['SUBJECT'] = 1;
687     $fields_a['UID'] = 2;
688     $fields_a['SIZE'] = 2;
689     $fields_a['SEEN'] = 3;
690     $fields_a['RECENT'] = 4;
691     $fields_a['DELETED'] = 5;
692     
693     $mode=$fields_a[$index_field];
694     if (!($mode > 0)) return false;
695     
696     /*  Do "SELECT" command */
697     if (!iil_C_Select($conn, $mailbox)) return false;
698         
699     /* FETCH date,from,subject headers */
700     if ($mode==1){
701         $key="fhi".($c++);
702         $request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)])\r\n";
703         if (!fputs($fp, $request)) return false;
704         do{
705             
706             $line=chop(iil_ReadLine($fp, 200));
707             $a=explode(" ", $line);
708             if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
709                 $id=$a[1];
710
711                 $str=$line=chop(iil_ReadLine($fp, 300));
712
713                 while($line[0]!=")"){                    //caution, this line works only in this particular case
714                     $line=chop(iil_ReadLine($fp, 300));
715                     if ($line[0]!=")"){
716                         if (ord($line[0]) <= 32){            //continuation from previous header line
717                             $str.=" ".trim($line);
718                         }
719                         if ((ord($line[0]) > 32) || (strlen($line[0]) == 0)){
720                             list($field, $string) = iil_SplitHeaderLine($str);
721                             if (strcasecmp($field, "date")==0){
722                                 $result[$id]=iil_StrToTime($string);
723                             }else{
724                                 $result[$id] = str_replace("\"", "", $string);
725                                 if ($normalize) $result[$id]=strtoupper($result[$id]);
726                             }
727                             $str=$line;
728                         }
729                     }
730                 }
731             }
732             /*
733             $end_pos = strlen($line)-1;
734             if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[$end_pos]=="}")){
735                 $id = $a[1];
736                 $pos = strrpos($line, "{")+1;
737                 $bytes = (int)substr($line, $pos, $end_pos-$pos);
738                 $received = 0;
739                 do{
740                     $line = iil_ReadLine($fp, 0);
741                     $received+=strlen($line);
742                     $line = chop($line);
743                     
744                     if ($received>$bytes) break;
745                     else if (!$line) continue;
746                     
747                     list($field,$string)=explode(": ", $line);
748                     
749                     if (strcasecmp($field, "date")==0)
750                         $result[$id] = iil_StrToTime($string);
751                     else if ($index_field!="DATE")
752                         $result[$id]=strtoupper(str_replace("\"", "", $string));
753                 }while($line[0]!=")");
754             }else{
755                 //one line response, not expected so ignore                
756             }
757             */
758         }while(!iil_StartsWith($line, $key));
759     }else if ($mode==6){
760         $key="fhi".($c++);
761         $request = $key." FETCH $message_set (INTERNALDATE)\r\n";
762         if (!fputs($fp, $request)) return false;
763         do{
764             $line=chop(iil_ReadLine($fp, 200));
765             if ($line[0]=="*"){
766                 //original: "* 10 FETCH (INTERNALDATE "31-Jul-2002 09:18:02 -0500")"
767                 $paren_pos = strpos($line, "(");
768                 $foo = substr($line, 0, $paren_pos);
769                 $a = explode(" ", $foo);
770                 $id = $a[1];
771                 
772                 $open_pos = strpos($line, "\"") + 1;
773                 $close_pos = strrpos($line, "\"");
774                 if ($open_pos && $close_pos){
775                     $len = $close_pos - $open_pos;
776                     $time_str = substr($line, $open_pos, $len);
777                     $result[$id] = strtotime($time_str);
778                 }
779             }else{
780                 $a = explode(" ", $line);
781             }
782         }while(!iil_StartsWith($a[0], $key));
783     }else{
784         if ($mode >= 3) $field_name="FLAGS";
785         else if ($index_field=="SIZE") $field_name="RFC822.SIZE";
786         else $field_name=$index_field;
787
788         /*             FETCH uid, size, flags        */
789         $key="fhi".($c++);
790         $request=$key." FETCH $message_set ($field_name)\r\n";
791
792         if (!fputs($fp, $request)) return false;
793         do{
794             $line=chop(iil_ReadLine($fp, 200));
795             $a = explode(" ", $line);
796             if (($line[0]=="*") && ($a[2]=="FETCH")){
797                 $line=str_replace("(", "", $line);
798                 $line=str_replace(")", "", $line);
799                 $a=explode(" ", $line);
800                 
801                 $id=$a[1];
802
803                 if (isset($result[$id])) continue; //if we already got the data, skip forward
804                 if ($a[3]!=$field_name) continue;  //make sure it's returning what we requested
805             
806                 /*  Caution, bad assumptions, next several lines */
807                 if ($mode==2) $result[$id]=$a[4];
808                 else{
809                     $haystack=strtoupper($line);
810                     $result[$id]=(strpos($haystack, $index_field) > 0 ? "F" : "N");
811                 }
812             }
813         }while(!iil_StartsWith($line, $key));
814     }
815
816     //check number of elements...
817     list($start_mid,$end_mid)=explode(':',$message_set);
818     if (is_numeric($start_mid) && is_numeric($end_mid)){
819         //count how many we should have
820         $should_have = $end_mid - $start_mid +1;
821         
822         //if we have less, try and fill in the "gaps"
823         if (count($result)<$should_have){
824             for($i=$start_mid;$i<=$end_mid;$i++) if (!isset($result[$i])) $result[$i] = '';
825         }
826     }
827     
828     return $result;    
829
830 }
831
832 function iil_CompressMessageSet($message_set){
833     //given a comma delimited list of independent mid's, 
834     //compresses by grouping sequences together
835     
836     //if less than 255 bytes long, let's not bother
837     if (strlen($message_set)<255) return $message_set;
838     
839     //see if it's already been compress
840     if (strpos($message_set,':')!==false) return $message_set;
841     
842     //separate, then sort
843     $ids = explode(',',$message_set);
844     sort($ids);
845     
846     $result = array();
847     $start = $prev = $ids[0];
848     foreach($ids as $id){
849         $incr = $id - $prev;
850         if ($incr>1){            //found a gap
851             if ($start==$prev) $result[] = $prev;    //push single id
852             else $result[] = $start.':'.$prev;        //push sequence as start_id:end_id
853             $start = $id;                            //start of new sequence
854         }
855         $prev = $id;
856     }
857     //handle the last sequence/id
858     if ($start==$prev) $result[] = $prev;
859     else $result[] = $start.':'.$prev;
860
861     //return as comma separated string
862     return implode(',',$result);
863 }
864
865 function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids){
866     if (!is_array($uids) || count($uids)==0) return array();
867     return iil_C_Search($conn, $mailbox, "UID ".implode(",", $uids));
868 }
869
870 function iil_C_UIDToMID(&$conn, $mailbox, $uid){
871     $result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
872     if (count($result)==1) return $result[0];
873     else return false;
874 }
875
876 function iil_C_FetchUIDs(&$conn,$mailbox){
877     global $clock;
878     
30233b 879     $num = iil_C_CountMessages($conn, $mailbox);
4e17e6 880     if ($num==0) return array();
T 881     $message_set = '1'.($num>1?':'.$num:'');
882     
883     //if cache not enabled, just call iil_C_FetchHeaderIndex on 'UID' field
884     if (!$conn->do_cache)
885         return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
886
887     //otherwise, let's check cache first
888     $key = $mailbox.'.uids';
889     $cache_good = true;
890     if ($conn->uid_cache) $data = $conn->uid_cache;
891     else $data = cache_read($conn->user, $conn->host, $key);
892     
893     //was anything cached at all?
894     if ($data===false) $cache_good = -1;
895     
896     //make sure number of messages were the same
897     if ($cache_good>0 && $data['n']!=$num) $cache_good = -2;
898     
899     //if everything's okay so far...
900     if ($cache_good>0){
901         //check UIDs of highest mid with current and cached
902         $temp = iil_C_Search($conn, $mailbox, 'UID '.$data['d'][$num]);
903         if (!$temp || !is_array($temp) || $temp[0]!=$num) $cache_good=-3;
904     }
905
906     //if cached data's good, return it
907     if ($cache_good>0){
908         return $data['d'];
909     }
910
911     //otherwise, we need to fetch it
912     $data = array('n'=>$num,'d'=>array());
913     $data['d'] = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
914     cache_write($conn->user, $conn->host, $key, $data);
915     $conn->uid_cache = $data;
916     return $data['d'];
917 }
918
919 function iil_SortThreadHeaders($headers, $index_a, $uids){
920     asort($index_a);
921     $result = array();
922     foreach($index_a as $mid=>$foobar){
923         $uid = $uids[$mid];
924         $result[$uid] = $headers[$uid];
925     }
926     return $result;
927 }
928
929 function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set){
930     global $clock;
931     global $index_a;
932     
933     if (empty($message_set)) return false;
934
935     $result = array();
936     $uids = iil_C_FetchUIDs($conn, $mailbox);
937     $debug = false;
938     
939     /* Get cached records where possible */
940     if ($conn->do_cache){
941         $cached = cache_read($conn->user, $conn->host, $mailbox.'.thhd');
942         if ($cached && is_array($uids) && count($uids)>0){
943             $needed_set = "";
944             foreach($uids as $id=>$uid){
945                 if ($cached[$uid]){
946                     $result[$uid] = $cached[$uid];
947                     $result[$uid]->id = $id;
948                 }else $needed_set.=($needed_set?",":"").$id;
949             }
950             if ($needed_set) $message_set = $needed_set;
951             else $message_set = '';
952         }
953     }
954     $message_set = iil_CompressMessageSet($message_set);
955     if ($debug) echo "Still need: ".$message_set;
956     
957     /* if we're missing any, get them */
958     if ($message_set){
959         /* FETCH date,from,subject headers */
960         $key="fh";
961         $fp = $conn->fp;
962         $request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])\r\n";
963         $mid_to_id = array();
964         if (!fputs($fp, $request)) return false;
965         do{
966             $line = chop(iil_ReadLine($fp, 1024));
967             if ($debug) echo $line."\n";
968             if (ereg('\{[0-9]+\}$', $line)){
969                 $a = explode(" ", $line);
970                 $new = array();
971
972                 $new_thhd = new iilThreadHeader;
973                 $new_thhd->id = $a[1];
974                 do{
975                     $line=chop(iil_ReadLine($fp, 1024),"\r\n");
976                     if (iil_StartsWithI($line,'Message-ID:') || (iil_StartsWithI($line,'In-Reply-To:')) || (iil_StartsWithI($line,'SUBJECT:'))){
977                         $pos = strpos($line, ":");
978                         $field_name = substr($line, 0, $pos);
979                         $field_val = substr($line, $pos+1);
980                         $new[strtoupper($field_name)] = trim($field_val);
981                     }else if (ereg('^[[:space:]]', $line)){
982                         $new[strtoupper($field_name)].= trim($line);
983                     }
984                 }while($line[0]!=')');
985                 $new_thhd->sbj = $new['SUBJECT'];
986                 $new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
987                 $new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
988                 
989                 $result[$uids[$new_thhd->id]] = $new_thhd;
990             }
991         }while(!iil_StartsWith($line, "fh"));
992     }
993     
994     /* sort headers */
995     if (is_array($index_a)){
996         $result = iil_SortThreadHeaders($result, $index_a, $uids);    
997     }
998     
999     /* write new set to cache */
1000     if ($conn->do_cache){
1001         if (count($result)!=count($cached))
1002             cache_write($conn->user, $conn->host, $mailbox.'.thhd', $result);        
1003     }
1004     
1005     //echo 'iil_FetchThreadHeaders:'."\n";
1006     //print_r($result);
1007     
1008     return $result;
1009 }
1010
1011 function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock){
1012     global $index_a;
1013
1014     if (empty($message_set)) return false;
1015     
1016     $result=array();
1017     $roots=array();
1018     $root_mids = array();
1019     $sub_mids = array();
1020     $strays = array();
1021     $messages = array();
1022     $fp = $conn->fp;
1023     $debug = false;
1024     
1025     $sbj_filter_pat = '[a-zA-Z]{2,3}(\[[0-9]*\])?:([[:space:]]*)';
1026     
1027     /*  Do "SELECT" command */
1028     if (!iil_C_Select($conn, $mailbox)) return false;
1029
1030     /* FETCH date,from,subject headers */
1031     $mid_to_id = array();
1032     $messages = array();
1033     $headers = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
1034     if ($clock) $clock->register('fetched headers');
1035     
1036     if ($debug) print_r($headers);
1037     
1038     /* go through header records */
1039     foreach($headers as $header){
1040         //$id = $header['i'];
1041         //$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'], 
1042         //            'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
1043         $id = $header->id;
1044         $new = array('id'=>$id, 'MESSAGE-ID'=>$header->mid, 
1045                     'IN-REPLY-TO'=>$header->irt, 'SUBJECT'=>$header->sbj);
1046
1047         /* add to message-id -> mid lookup table */
1048         $mid_to_id[$new['MESSAGE-ID']] = $id;
1049         
1050         /* if no subject, use message-id */
1051         if (empty($new['SUBJECT'])) $new['SUBJECT'] = $new['MESSAGE-ID'];
1052         
1053         /* if subject contains 'RE:' or has in-reply-to header, it's a reply */
1054         $sbj_pre ='';
1055         $has_re = false;
1056         if (eregi($sbj_filter_pat, $new['SUBJECT'])) $has_re = true;
1057         if ($has_re||$new['IN-REPLY-TO']) $sbj_pre = 'RE:';
1058         
1059         /* strip out 're:', 'fw:' etc */
1060         if ($has_re) $sbj = ereg_replace($sbj_filter_pat,'', $new['SUBJECT']);
1061         else $sbj = $new['SUBJECT'];
1062         $new['SUBJECT'] = $sbj_pre.$sbj;
1063         
1064         
1065         /* if subject not a known thread-root, add to list */
1066         if ($debug) echo $id.' '.$new['SUBJECT']."\t".$new['MESSAGE-ID']."\n";
1067         $root_id = $roots[$sbj];
1068         
1069         if ($root_id && ($has_re || !$root_in_root[$root_id])){
1070             if ($debug) echo "\tfound root: $root_id\n";
1071             $sub_mids[$new['MESSAGE-ID']] = $root_id;
1072             $result[$root_id][] = $id;
1073         }else if (!isset($roots[$sbj])||(!$has_re&&$root_in_root[$root_id])){
1074             /* try to use In-Reply-To header to find root 
1075                 unless subject contains 'Re:' */
1076             if ($has_re&&$new['IN-REPLY-TO']){
1077                 if ($debug) echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
1078                 
1079                 //reply to known message?
1080                 $temp = $sub_mids[$new['IN-REPLY-TO']];
1081                 
1082                 if ($temp){
1083                     //found it, root:=parent's root
1084                     if ($debug) echo "\tfound parent: ".$new['SUBJECT']."\n";
1085                     $result[$temp][] = $id;
1086                     $sub_mids[$new['MESSAGE-ID']] = $temp;
1087                     $sbj = '';
1088                 }else{
1089                     //if we can't find referenced parent, it's a "stray"
1090                     $strays[$id] = $new['IN-REPLY-TO'];
1091                 }
1092             }
1093             
1094             //add subject as root
1095             if ($sbj){
1096                 if ($debug) echo "\t added to root\n";
1097                 $roots[$sbj] = $id;
1098                 $root_in_root[$id] = !$has_re;
1099                 $sub_mids[$new['MESSAGE-ID']] = $id;
1100                 $result[$id] = array($id);
1101             }
1102             if ($debug) echo $new['MESSAGE-ID']."\t".$sbj."\n";
1103         }
1104             
1105     }
1106     
1107     //now that we've gone through all the messages,
1108     //go back and try and link up the stray threads
1109     if (count($strays)>0){
1110         foreach($strays as $id=>$irt){
1111             $root_id = $sub_mids[$irt];
1112             if (!$root_id || $root_id==$id) continue;
1113             $result[$root_id] = array_merge($result[$root_id],$result[$id]);
1114             unset($result[$id]);
1115         }
1116     }
1117     
1118     if ($clock) $clock->register('data prepped');
1119     
1120     if ($debug) print_r($roots);
1121     //print_r($result);
1122     return $result;
1123 }
1124
1125
1126 function iil_SortThreads(&$tree, $index, $sort_order='ASC'){
1127     if (!is_array($tree) || !is_array($index)) return false;
1128
1129     //create an id to position lookup table
1130     $i = 0;
1131     foreach($index as $id=>$val){
1132         $i++;
1133         $index[$id] = $i;
1134     }
1135     $max = $i+1;
1136     
1137     //for each tree, set array key to position
1138     $itree = array();
1139     foreach($tree as $id=>$node){
1140         if (count($tree[$id])<=1){
1141             //for "threads" with only one message, key is position of that message
1142             $n = $index[$id];
1143             $itree[$n] = array($n=>$id);
1144         }else{
1145             //for "threads" with multiple messages, 
1146             $min = $max;
1147             $new_a = array();
1148             foreach($tree[$id] as $mid){
1149                 $new_a[$index[$mid]] = $mid;        //create new sub-array mapping position to id
1150                 $pos = $index[$mid];
1151                 if ($pos&&$pos<$min) $min = $index[$mid];    //find smallest position
1152             }
1153             $n = $min;    //smallest position of child is thread position
1154             
1155             //assign smallest position to root level key
1156             //set children array to one created above
1157             ksort($new_a);
1158             $itree[$n] = $new_a;
1159         }
1160     }
1161     
1162     
1163     //sort by key, this basically sorts all threads
1164     ksort($itree);
1165     $i=0;
1166     $out=array();
1167     foreach($itree as $k=>$node){
1168         $out[$i] = $itree[$k];
1169         $i++;
1170     }
1171     
1172     //return
1173     return $out;
1174 }
1175
1176 function iil_IndexThreads(&$tree){
1177     /* creates array mapping mid to thread id */
1178     
1179     if (!is_array($tree)) return false;
1180     
1181     $t_index = array();
1182     foreach($tree as $pos=>$kids){
1183         foreach($kids as $kid) $t_index[$kid] = $pos;
1184     }
1185     
1186     return $t_index;
1187 }
1188
1189 function iil_C_FetchHeaders(&$conn, $mailbox, $message_set){
1190     global $IMAP_USE_INTERNAL_DATE;
1191     
1192     $c=0;
1193     $result=array();
1194     $fp = $conn->fp;
1195     
1196     if (empty($message_set)) return array();
1197     
1198     /*  Do "SELECT" command */
1199     if (!iil_C_Select($conn, $mailbox)){
1200         $conn->error = "Couldn't select $mailbox";
1201         return false;
1202     }
1203         
1204     /* Get cached records where possible */
1205     if ($conn->do_cache){
1206         $uids = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, "UID");
1207         if (is_array($uids) && count($conn->cache[$mailbox]>0)){
1208             $needed_set = "";
1209             while(list($id,$uid)=each($uids)){
1210                 if ($conn->cache[$mailbox][$uid]){
1211                     $result[$id] = $conn->cache[$mailbox][$uid];
1212                     $result[$id]->id = $id;
1213                 }else $needed_set.=($needed_set?",":"").$id;
1214             }
1215             //echo "<!-- iil_C_FetchHeader\nMessage Set: $message_set\nNeeded Set:$needed_set\n//-->\n";
1216             if ($needed_set) $message_set = iil_CompressMessageSet($needed_set);
1217             else return $result;
1218         }
1219     }
1220
1221     /* FETCH date,from,subject headers */
1222     $key="fh".($c++);
f88d41 1223     $request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID REFERENCE)])\r\n";
4e17e6 1224
T 1225     if (!fputs($fp, $request)) return false;
1226     do{
1227         $line=chop(iil_ReadLine($fp, 200));
1228         $a=explode(" ", $line);
1229         if (($line[0]=="*") && ($a[2]=="FETCH")){
1230             $id=$a[1];
1231             $result[$id]=new iilBasicHeader;
1232             $result[$id]->id = $id;
1233             $result[$id]->subject = "";
1234             /*
1235                 Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1236                 So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1237                 process the previous line.  Otherwise, we'll keep adding the strings until we come
1238                 to the next valid header line.
1239             */
1240             $i = 0;
1241             $lines = array();
1242             do{
1243                 $line = chop(iil_ReadLine($fp, 300),"\r\n");
1244                 if (ord($line[0])<=32) $lines[$i].=(empty($lines[$i])?"":"\n").trim(chop($line));
1245                 else{
1246                     $i++;
1247                     $lines[$i] = trim(chop($line));
1248                 }
b076a4 1249             }while($line[0]!=")" && strncmp($line, $key, strlen($key)));  // patch from "Maksim Rubis" <siburny@hotmail.com>
4e17e6 1250             
b076a4 1251             if(strncmp($line, $key, strlen($key)))
T 1252             { 
4e17e6 1253             //process header, fill iilBasicHeader obj.
T 1254             //    initialize
1255             if (is_array($headers)){
1256                 reset($headers);
1257                 while ( list($k, $bar) = each($headers) ) $headers[$k] = "";
1258             }
1259
1260             //    create array with header field:data
1261             $headers = array();
1262             while ( list($lines_key, $str) = each($lines) ){
1263                 list($field, $string) = iil_SplitHeaderLine($str);
1264                 $field = strtolower($field);
1265                 $headers[$field] = $string;
1266             }
1267             $result[$id]->date = $headers["date"];
1268             $result[$id]->timestamp = iil_StrToTime($headers["date"]);
1269             $result[$id]->from = $headers["from"];
1270             $result[$id]->to = str_replace("\n", " ", $headers["to"]);
1271             $result[$id]->subject = str_replace("\n", "", $headers["subject"]);
1272             $result[$id]->replyto = str_replace("\n", " ", $headers["reply-to"]);
1273             $result[$id]->cc = str_replace("\n", " ", $headers["cc"]);
bde645 1274             $result[$id]->bcc = str_replace("\n", " ", $headers["bcc"]);
4e17e6 1275             $result[$id]->encoding = str_replace("\n", " ", $headers["content-transfer-encoding"]);
T 1276             $result[$id]->ctype = str_replace("\n", " ", $headers["content-type"]);
a95e0e 1277             $result[$id]->in_reply_to = ereg_replace("[\n<>]",'', $headers['in-reply-to']);
f88d41 1278             $result[$id]->reference = $headers["reference"];
a95e0e 1279             
T 1280             list($result[$id]->ctype, $ctype_add) = explode(";", $headers["content-type"]);
1281
1282             if (preg_match('/charset="?([a-z0-9\-]+)"?/i', $ctype_add, $regs))
1283                 $result[$id]->charset = $regs[1];
1284
4e17e6 1285             $messageID = $headers["message-id"];
f88d41 1286             if (!$messageID) "mid:".$id;
4e17e6 1287             $result[$id]->messageID = $messageID;
b076a4 1288             }
T 1289             else {
1290             $a=explode(" ", $line);
1291             } 
4e17e6 1292             
T 1293         }
1294     }while(strcmp($a[0], $key)!=0);
1295         
1296     /* 
1297         FETCH uid, size, flags
1298         Sample reply line: "* 3 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen \Deleted))"
1299     */
1300     $command_key="fh".($c++);
1301     $request= $command_key." FETCH $message_set (UID RFC822.SIZE FLAGS INTERNALDATE)\r\n";
1302     if (!fputs($fp, $request)) return false;
1303     do{
1304         $line=chop(iil_ReadLine($fp, 200));
1305         //$a = explode(" ", $line);
1306         //if (($line[0]=="*") && ($a[2]=="FETCH")){
1307         if ($line[0]=="*"){
1308             //echo "<!-- $line //-->\n";
1309             //get outter most parens
1310             $open_pos = strpos($line, "(") + 1;
1311             $close_pos = strrpos($line, ")");
1312             if ($open_pos && $close_pos){
1313                 //extract ID from pre-paren
1314                 $pre_str = substr($line, 0, $open_pos);
1315                 $pre_a = explode(" ", $line);
1316                 $id = $pre_a[1];
1317                 
1318                 //get data
1319                 $len = $close_pos - $open_pos;
1320                 $str = substr($line, $open_pos, $len);
1321                 
1322                 //swap parents with quotes, then explode
1323                 $str = eregi_replace("[()]", "\"", $str);
1324                 $a = iil_ExplodeQuotedString(" ", $str);
1325                 
1326                 //did we get the right number of replies?
1327                 $parts_count = count($a);
1328                 if ($parts_count>=8){
1329                     for ($i=0;$i<$parts_count;$i=$i+2){
1330                         if (strcasecmp($a[$i],"UID")==0) $result[$id]->uid=$a[$i+1];
1331                         else if (strcasecmp($a[$i],"RFC822.SIZE")==0) $result[$id]->size=$a[$i+1];
1332                         else if (strcasecmp($a[$i],"INTERNALDATE")==0) $time_str = $a[$i+1];
1333                         else if (strcasecmp($a[$i],"FLAGS")==0) $flags_str = $a[$i+1];
1334                     }
1335
1336                     // process flags
1337                     $flags_str = eregi_replace('[\\\"]', "", $flags_str);
1338                     $flags_a = explode(" ", $flags_str);
1339                     //echo "<!-- ID: $id FLAGS: ".implode(",", $flags_a)." //-->\n";
1340                     
1341                     $result[$id]->seen = false;
1342                     $result[$id]->recent = false;
1343                     $result[$id]->deleted = false;
1344                     $result[$id]->answered = false;
1345                     if (is_array($flags_a)){
1346                         reset($flags_a);
1347                         while (list($key,$val)=each($flags_a)){
1348                             if (strcasecmp($val,"Seen")==0) $result[$id]->seen = true;
1349                             else if (strcasecmp($val, "Deleted")==0) $result[$id]->deleted=true;
1350                             else if (strcasecmp($val, "Recent")==0) $result[$id]->recent = true;
1351                             else if (strcasecmp($val, "Answered")==0) $result[$id]->answered = true;
1352                         }
1353                         $result[$id]->flags=$flags_str;
1354                     }
1355             
1356                     // if time is gmt...    
1357                     $time_str = str_replace('GMT','+0000',$time_str);
1358                     
1359                     //get timezone
1360                     $time_str = substr($time_str, 0, -1);
1361                     $time_zone_str = substr($time_str, -5); //extract timezone
1362                     $time_str = substr($time_str, 1, -6); //remove quotes
1363                     $time_zone = (float)substr($time_zone_str, 1, 2); //get first two digits
1364                     if ($time_zone_str[3]!='0') $time_zone += 0.5;  //handle half hour offset
1365                     if ($time_zone_str[0]=="-") $time_zone = $time_zone * -1.0; //minus?
1366                     $result[$id]->internaldate = $time_str;
1367                     
1368                     if ($IMAP_USE_INTERNAL_DATE){
1369                         //calculate timestamp
1370                         $timestamp = strtotime($time_str); //return's server's time
1371                         $na_timestamp = $timestamp;
1372                         $timestamp -= $time_zone * 3600; //compensate for tz, get GMT
1373                         $result[$id]->timestamp = $timestamp;
1374                     }
1375                         
1376                     if ($conn->do_cache){
1377                         $uid = $result[$id]->uid;
1378                         $conn->cache[$mailbox][$uid] = $result[$id];
1379                         $conn->cache_dirty[$mailbox] = true;
1380                     }
1381                     //echo "<!-- ID: $id : $time_str -- local: $na_timestamp (".date("F j, Y, g:i a", $na_timestamp).") tz: $time_zone -- GMT: ".$timestamp." (".date("F j, Y, g:i a", $timestamp).")  //-->\n";
1382                 }else{
1383                     //echo "<!-- ERROR: $id : $str //-->\n";
1384                 }
1385             }
1386         }
1387     }while(strpos($line, $command_key)===false);
1388         
1389     return $result;
1390 }
1391
1392
1393 function iil_C_FetchHeader(&$conn, $mailbox, $id){
1394     $fp = $conn->fp;
1395     $a=iil_C_FetchHeaders($conn, $mailbox, $id);
1396     if (is_array($a)) return $a[$id];
1397     else return false;
1398 }
1399
1400
1401 function iil_SortHeaders($a, $field, $flag){
1402     if (empty($field)) $field="uid";
1403     $field=strtolower($field);
1404     if ($field=="date"||$field=='internaldate') $field="timestamp";
1405     if (empty($flag)) $flag="ASC";
1406     $flag=strtoupper($flag);
b076a4 1407     $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ',"\"") : array("\"");
4647e1 1408
4e17e6 1409     $c=count($a);
T 1410     if ($c>0){
1411         /*
1412             Strategy:
1413             First, we'll create an "index" array.
1414             Then, we'll use sort() on that array, 
1415             and use that to sort the main array.
1416         */
1417                 
3062b3 1418         // create "index" array
4e17e6 1419         $index=array();
T 1420         reset($a);
1421         while (list($key, $val)=each($a)){
4647e1 1422
0d361b 1423             if ($field=="timestamp"){
T 1424                 $data = @strtotime($val->date);
1425                 if ($data == false)
1426                     $data = $val->timestamp;
1427                 }
1428             else {
1429                 $data = $val->$field;
1430                 if (is_string($data))
1431                     $data=strtoupper(str_replace($stripArr, "", $data));
1432                 }
4647e1 1433
4e17e6 1434             $index[$key]=$data;
T 1435         }
1436         
1437         // sort index
1438         $i=0;
1439         if ($flag=="ASC") asort($index);
1440         else arsort($index);
1441         
1442         // form new array based on index 
1443         $result=array();
1444         reset($index);
1445         while (list($key, $val)=each($index)){
9fee0e 1446             $result[$key]=$a[$key];
4e17e6 1447             $i++;
T 1448         }
1449     }
1450     
1451     return $result;
1452 }
1453
1454 function iil_C_Expunge(&$conn, $mailbox){
1455     $fp = $conn->fp;
1456     if (iil_C_Select($conn, $mailbox)){
1457         $c=0;
1458         fputs($fp, "exp1 EXPUNGE\r\n");
1459         do{
1460             $line=chop(iil_ReadLine($fp, 100));
1461             if ($line[0]=="*") $c++;
1462         }while (!iil_StartsWith($line, "exp1"));
1463         
1464         if (iil_ParseResult($line) == 0){
1465             $conn->selected = ""; //state has changed, need to reselect            
1466             //$conn->exists-=$c;
1467             return $c;
1468         }else{
1469             $conn->error = $line;
1470             return -1;
1471         }
1472     }
1473     
1474     return -1;
1475 }
1476
1477 function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod){
1478     if ($mod!="+" && $mod!="-") return -1;
1479     
1480     $fp = $conn->fp;
1481     $flags=array(
1482                     "SEEN"=>"\\Seen",
1483                     "DELETED"=>"\\Deleted",
1484                     "RECENT"=>"\\Recent",
1485                     "ANSWERED"=>"\\Answered",
1486                     "DRAFT"=>"\\Draft",
1487                     "FLAGGED"=>"\\Flagged"
1488                    );
1489     $flag=strtoupper($flag);
1490     $flag=$flags[$flag];
1491     if (iil_C_Select($conn, $mailbox)){
1492         $c=0;
1493         fputs($fp, "flg STORE $messages ".$mod."FLAGS (".$flag.")\r\n");
1494         do{
1495             $line=chop(iil_ReadLine($fp, 100));
1496             if ($line[0]=="*") $c++;
1497         }while (!iil_StartsWith($line, "flg"));
520c36 1498
4e17e6 1499         if (iil_ParseResult($line) == 0){
T 1500             iil_C_ExpireCachedItems($conn, $mailbox, $messages);
1501             return $c;
1502         }else{
1503             $conn->error = $line;
1504             return -1;
1505         }
1506     }else{
1507         $conn->error = "Select failed";
1508         return -1;
1509     }
1510 }
1511
1512 function iil_C_Flag(&$conn, $mailbox, $messages, $flag){
1513     return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "+");
1514 }
1515
1516 function iil_C_Unflag(&$conn, $mailbox, $messages, $flag){
1517     return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "-");
1518 }
1519
1520 function iil_C_Delete(&$conn, $mailbox, $messages){
1521     return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "+");
1522 }
1523
1524 function iil_C_Undelete(&$conn, $mailbox, $messages){
1525     return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "-");
1526 }
1527
1528
1529 function iil_C_Unseen(&$conn, $mailbox, $messages){
1530     return iil_C_ModFlag($conn, $mailbox, $messages, "SEEN", "-");
1531 }
1532
1533
1534 function iil_C_Copy(&$conn, $messages, $from, $to){
1535     $fp = $conn->fp;
1536
1537     if (empty($from) || empty($to)) return -1;
1538
1539     if (iil_C_Select($conn, $from)){
1540         $c=0;
1541         
1542         fputs($fp, "cpy1 COPY $messages \"$to\"\r\n");
1543         $line=iil_ReadReply($fp);
1544         return iil_ParseResult($line);
1545     }else{
1546         return -1;
1547     }
1548 }
1549
1550 function iil_FormatSearchDate($month, $day, $year){
1551     $month = (int)$month;
1552     $months=array(
1553             1=>"Jan", 2=>"Feb", 3=>"Mar", 4=>"Apr", 
1554             5=>"May", 6=>"Jun", 7=>"Jul", 8=>"Aug", 
1555             9=>"Sep", 10=>"Oct", 11=>"Nov", 12=>"Dec"
1556             );
1557     return $day."-".$months[$month]."-".$year;
1558 }
1559
1560 function iil_C_CountUnseen(&$conn, $folder){
1561     $index = iil_C_Search($conn, $folder, "ALL UNSEEN");
1562     if (is_array($index)){
1563         $str = implode(",", $index);
1564         if (empty($str)) return false;
1565         else return count($index);
1566     }else return false;
1567 }
1568
1569 function iil_C_UID2ID(&$conn, $folder, $uid){
1570     if ($uid > 0){
1571         $id_a = iil_C_Search($conn, $folder, "UID $uid");
1572         if (is_array($id_a)){
1573             $count = count($id_a);
1574             if ($count > 1) return false;
1575             else return $id_a[0];
1576         }
1577     }
1578     return false;
1579 }
1580
e6f360 1581 function iil_C_ID2UID(&$conn, $folder, $id){
T 1582     $fp = $conn->fp;
1583     $result=-1;
1584     if ($id > 0) {
1585         if (iil_C_Select($conn, $folder)){
1586             $key = "FUID";
1587             if (fputs($fp, "$key FETCH $id (UID)\r\n")){
1588                 do{
1589                     $line=chop(iil_ReadLine($fp, 1024));
1590                     if (eregi("^\* $id FETCH \(UID (.*)\)", $line, $r)){
1591                         $result = $r[1];
1592                     }
1593                 } while (!preg_match("/^$key/", $line));
1594             }
1595         }
1596     }
1597     return $result;
1598 }
1599
4e17e6 1600 function iil_C_Search(&$conn, $folder, $criteria){
T 1601     $fp = $conn->fp;
1602     if (iil_C_Select($conn, $folder)){
1603         $c=0;
1604         
1605         $query = "srch1 SEARCH ".chop($criteria)."\r\n";
1606         fputs($fp, $query);
1607         do{
1608             $line=trim(chop(iil_ReadLine($fp, 10000)));
1609             if (eregi("^\* SEARCH", $line)){
1610                 $str = trim(substr($line, 8));
1611                 $messages = explode(" ", $str);
1612             }
1613         }while(!iil_StartsWith($line, "srch1"));
1614         
1615         $result_code=iil_ParseResult($line);
1616         if ($result_code==0) return $messages;
1617         else{
8c2e58 1618             $conn->error = "iil_C_Search: ".$line."\n";
4e17e6 1619             return false;
T 1620         }
1621         
1622     }else{
8c2e58 1623         $conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
4e17e6 1624         return false;
T 1625     }
1626 }
1627
1628 function iil_C_Move(&$conn, $messages, $from, $to){
1629     $fp = $conn->fp;
1630     
1631     if (!$from || !$to) return -1;
1632     
1633     $r=iil_C_Copy($conn, $messages, $from,$to);
1634     if ($r==0){
1635         return iil_C_Delete($conn, $from, $messages);
1636     }else{
1637         return $r;
1638     }
1639 }
1640
1641 function iil_C_GetHierarchyDelimiter(&$conn){
1642     if ($conn->delimiter) return $conn->delimiter;
1643     
1644     $fp = $conn->fp;
1645     $delimiter = false;
1646     
1647     //try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
1648     if (!fputs($fp, "ghd LIST \"\" \"\"\r\n")) return false;
1649     do{
1650         $line=iil_ReadLine($fp, 500);
1651         if ($line[0]=="*"){
1652             $line = rtrim($line);
1653             $a=iil_ExplodeQuotedString(" ", $line);
1654             if ($a[0]=="*") $delimiter = str_replace("\"", "", $a[count($a)-2]);
1655         }
1656     }while (!iil_StartsWith($line, "ghd"));
1657
1658     if (strlen($delimiter)>0) return $delimiter;
1659     
1660     //if that fails, try namespace extension
1661     //try to fetch namespace data
1662     fputs($conn->fp, "ns1 NAMESPACE\r\n");
1663     do{
1664         $line = iil_ReadLine($conn->fp, 1024);
1665         if (iil_StartsWith($line, "* NAMESPACE")){
1666             $i = 0;
1667             $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
1668         }
1669     }while(!iil_StartsWith($line, "ns1"));
1670         
1671     if (!is_array($data)) return false;
1672     
1673     //extract user space data (opposed to global/shared space)
1674     $user_space_data = $data[0];
1675     if (!is_array($user_space_data)) return false;
1676     
1677     //get first element
1678     $first_userspace = $user_space_data[0];
1679     if (!is_array($first_userspace)) return false;
1680
1681     //extract delimiter
1682     $delimiter = $first_userspace[1];    
1683
1684     return $delimiter;
1685 }
1686
1687 function iil_C_ListMailboxes(&$conn, $ref, $mailbox){
1688     global $IGNORE_FOLDERS;
1689     
1690     $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
1691         
1692     $fp = $conn->fp;
1693     if (empty($mailbox)) $mailbox="*";
1694     if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
1695     
1696     // send command
1697     if (!fputs($fp, "lmb LIST \"".$ref."\" \"$mailbox\"\r\n")) return false;
1698     $i=0;
1699     // get folder list
1700     do{
1701         $line=iil_ReadLine($fp, 500);
1702         $line=iil_MultLine($fp, $line);
1703
1704         $a = explode(" ", $line);
1705         if (($line[0]=="*") && ($a[1]=="LIST")){
1706             $line = rtrim($line);
1707             // split one line
1708             $a=iil_ExplodeQuotedString(" ", $line);
1709             // last string is folder name
1710             $folder = str_replace("\"", "", $a[count($a)-1]);
1711             if (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder))) $folders[$i] = $folder;
1712             // second from last is delimiter
1713             $delim = str_replace("\"", "", $a[count($a)-2]);
1714             // is it a container?
1715             $i++;
1716         }
1717     }while (!iil_StartsWith($line, "lmb"));
1718
1719     if (is_array($folders)){
1720         if (!empty($ref)){
1721             // if rootdir was specified, make sure it's the first element
1722             // some IMAP servers (i.e. Courier) won't return it
1723             if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
1724             if ($folders[0]!=$ref) array_unshift($folders, $ref);
1725         }
1726         return $folders;
1727     }else if (iil_ParseResult($line)==0){
1728         return array('INBOX');
1729     }else{
1730         $conn->error = $line;
1731         return false;
1732     }
1733 }
1734
1735
1736 function iil_C_ListSubscribed(&$conn, $ref, $mailbox){
1737     global $IGNORE_FOLDERS;
1738     
1739     $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
1740     
1741     $fp = $conn->fp;
1742     if (empty($mailbox)) $mailbox = "*";
1743     if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
1744     $folders = array();
1745
1746     // send command
1747     if (!fputs($fp, "lsb LSUB \"".$ref."\" \"".$mailbox."\"\r\n")){
1748         $conn->error = "Couldn't send LSUB command\n";
1749         return false;
1750     }
1751     $i=0;
1752     // get folder list
1753     do{
1754         $line=iil_ReadLine($fp, 500);
1755         $line=iil_MultLine($fp, $line);
1756         $a = explode(" ", $line);
1757         if (($line[0]=="*") && ($a[1]=="LSUB")){
1758             $line = rtrim($line);
1759             // split one line
1760             $a=iil_ExplodeQuotedString(" ", $line);
1761             // last string is folder name
1762             //$folder = UTF7DecodeString(str_replace("\"", "", $a[count($a)-1]));
1763             $folder = str_replace("\"", "", $a[count($a)-1]);
1764             if ((!in_array($folder, $folders)) && (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder)))) $folders[$i] = $folder;
1765             // second from last is delimiter
1766             $delim = str_replace("\"", "", $a[count($a)-2]);
1767             // is it a container?
1768             $i++;
1769         }
1770     }while (!iil_StartsWith($line, "lsb"));
1771
1772     if (is_array($folders)){
1773         if (!empty($ref)){
1774             // if rootdir was specified, make sure it's the first element
1775             // some IMAP servers (i.e. Courier) won't return it
1776             if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
1777             if ($folders[0]!=$ref) array_unshift($folders, $ref);
1778         }
1779         return $folders;
1780     }else{
1781         $conn->error = $line;
1782         return false;
1783     }
1784 }
1785
1786
1787 function iil_C_Subscribe(&$conn, $folder){
1788     $fp = $conn->fp;
1789
1790     $query = "sub1 SUBSCRIBE \"".$folder."\"\r\n";
1791     fputs($fp, $query);
1792     $line=trim(chop(iil_ReadLine($fp, 10000)));
1793     return iil_ParseResult($line);
1794 }
1795
1796
1797 function iil_C_UnSubscribe(&$conn, $folder){
1798     $fp = $conn->fp;
1799
1800     $query = "usub1 UNSUBSCRIBE \"".$folder."\"\r\n";
1801     fputs($fp, $query);
1802     $line=trim(chop(iil_ReadLine($fp, 10000)));
1803     return iil_ParseResult($line);
1804 }
1805
1806
1807 function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $part){
1808     $fp = $conn->fp;
1809     $result=false;
1810     if (($part==0)||(empty($part))) $part="HEADER";
1811     else $part.=".MIME";
1812     
1813     if (iil_C_Select($conn, $mailbox)){
1814         $key="fh".($c++);
1815         $request=$key." FETCH $id (BODY.PEEK[$part])\r\n";
1816         if (!fputs($fp, $request)) return false;
1817         do{
1818             $line=chop(iil_ReadLine($fp, 200));
1819             $a=explode(" ", $line);
1820             if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
1821                 $line=iil_ReadLine($fp, 300);
1822                 while(chop($line)!=")"){
1823                     $result.=$line;
1824                     $line=iil_ReadLine($fp, 300);
1825                 }
1826             }
1827         }while(strcmp($a[0], $key)!=0);
1828     }
1829     
1830     return $result;
1831 }
1832
1833
1834 function iil_C_HandlePartBody(&$conn, $mailbox, $id, $part, $mode){
1835     /* modes:
1836         1: return string
1837         2: print
1838         3: base64 and print
1839     */
1840     $fp = $conn->fp;
1841     $result=false;
1842     if (($part==0)||(empty($part))) $part="TEXT";
1843     
1844     if (iil_C_Select($conn, $mailbox)){
1845         $reply_key="* ".$id;
1846         // format request
1847         $key="ftch".($c++)." ";
1848         $request=$key."FETCH $id (BODY.PEEK[$part])\r\n";
1849         // send request
1850         if (!fputs($fp, $request)) return false;
1851         // receive reply line
1852         do{
1853             $line = chop(iil_ReadLine($fp, 1000));
1854             $a = explode(" ", $line);
1855         }while ($a[2]!="FETCH");
1856         $len = strlen($line);
1857         if ($line[$len-1] == ")"){
1858             //one line response, get everything between first and last quotes
1859             $from = strpos($line, "\"") + 1;
1860             $to = strrpos($line, "\"");
1861             $len = $to - $from;
1862             if ($mode==1) $result = substr($line, $from, $len);
1863             else if ($mode==2) echo substr($line, $from, $len);
1864             else if ($mode==3) echo base64_decode(substr($line, $from, $len));
1865         }else if ($line[$len-1] == "}"){
1866             //multi-line request, find sizes of content and receive that many bytes
1867             $from = strpos($line, "{") + 1;
1868             $to = strrpos($line, "}");
1869             $len = $to - $from;
1870             $sizeStr = substr($line, $from, $len);
1871             $bytes = (int)$sizeStr;
1872             $received = 0;
1873             while ($received < $bytes){
1874                 $remaining = $bytes - $received;
1875                 $line = iil_ReadLine($fp, 1024);
1876                 $len = strlen($line);
1877                 if ($len > $remaining) substr($line, 0, $remaining);
1878                 $received += strlen($line);
1879                 if ($mode==1) $result .= chop($line)."\n";
1880                 else if ($mode==2){ echo chop($line)."\n"; flush(); }
1881                 else if ($mode==3){ echo base64_decode($line); flush(); }
1882             }
1883         }
1884         // read in anything up until 'til last line
1885         do{
1886             $line = iil_ReadLine($fp, 1024);
1887         }while(!iil_StartsWith($line, $key));
1888         
1889         if ($result){
1890             $result = chop($result);
30233b 1891             return $result; // substr($result, 0, strlen($result)-1);
4e17e6 1892         }else return false;
T 1893     }else{
1894         echo "Select failed.";
1895     }
1896     
1897     if ($mode==1) return $result;
1898     else return $received;
1899 }
1900
1901 function iil_C_FetchPartBody(&$conn, $mailbox, $id, $part){
1902     return iil_C_HandlePartBody($conn, $mailbox, $id, $part, 1);
1903 }
1904
1905 function iil_C_PrintPartBody(&$conn, $mailbox, $id, $part){
1906     iil_C_HandlePartBody($conn, $mailbox, $id, $part, 2);
1907 }
1908
1909 function iil_C_PrintBase64Body(&$conn, $mailbox, $id, $part){
1910     iil_C_HandlePartBody($conn, $mailbox, $id, $part, 3);
1911 }
1912
1913 function iil_C_CreateFolder(&$conn, $folder){
1914     $fp = $conn->fp;
1915     if (fputs($fp, "c CREATE \"".$folder."\"\r\n")){
1916         do{
1917             $line=iil_ReadLine($fp, 300);
1918         }while($line[0]!="c");
1919         $conn->error = $line;
1920         return (iil_ParseResult($line)==0);
1921     }else{
1922         return false;
1923     }
1924 }
1925
1926 function iil_C_RenameFolder(&$conn, $from, $to){
1927     $fp = $conn->fp;
1928     if (fputs($fp, "r RENAME \"".$from."\" \"".$to."\"\r\n")){
1929         do{
1930             $line=iil_ReadLine($fp, 300);
1931         }while($line[0]!="r");
1932         return (iil_ParseResult($line)==0);
1933     }else{
1934         return false;
1935     }    
1936 }
1937
1938 function iil_C_DeleteFolder(&$conn, $folder){
1939     $fp = $conn->fp;
1940     if (fputs($fp, "d DELETE \"".$folder."\"\r\n")){
1941         do{
1942             $line=iil_ReadLine($fp, 300);
1943         }while($line[0]!="d");
1944         return (iil_ParseResult($line)==0);
1945     }else{
1946         $conn->error = "Couldn't send command\n";
1947         return false;
1948     }
1949 }
1950
e0ed97 1951 function iil_C_Append(&$conn, $folder, &$message){
4e17e6 1952     if (!$folder) return false;
T 1953     $fp = $conn->fp;
1954
1955     $message = str_replace("\r", "", $message);
1956     $message = str_replace("\n", "\r\n", $message);        
1957
1958     $len = strlen($message);
1959     if (!$len) return false;
1960     
1961     $request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
1962     if (fputs($fp, $request)){
0284c2 1963         $line=iil_ReadLine($fp, 100);        
4e17e6 1964         $sent = fwrite($fp, $message."\r\n");
T 1965         flush();
1966         do{
1967             $line=iil_ReadLine($fp, 1000);
1968         }while($line[0]!="A");
1969     
1970         $result = (iil_ParseResult($line)==0);
8c2e58 1971         if (!$result) $conn->error .= $line."\n";
4e17e6 1972         return $result;
T 1973     
1974     }else{
8c2e58 1975         $conn->error .= "Couldn't send command \"$request\"\n";
4e17e6 1976         return false;
T 1977     }
1978 }
1979
1980
1981 function iil_C_AppendFromFile(&$conn, $folder, $path){
1982     if (!$folder) return false;
1983     
1984     //open message file
1985     $in_fp = false;                
1986     if (file_exists(realpath($path))) $in_fp = fopen($path, "r");
1987     if (!$in_fp){ 
8c2e58 1988         $conn->error .= "Couldn't open $path for reading\n";
4e17e6 1989         return false;
T 1990     }
1991     
1992     $fp = $conn->fp;
1993     $len = filesize($path);
1994     if (!$len) return false;
1995     
1996     //send APPEND command
1997     $request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
1998     $bytes_sent = 0;
1999     if (fputs($fp, $request)){
2000         $line=iil_ReadLine($fp, 100);
2001                 
2002         //send file
2003         while(!feof($in_fp)){
2004             $buffer = fgets($in_fp, 4096);
2005             $bytes_sent += strlen($buffer);
2006             fputs($fp, $buffer);
2007         }
2008         fclose($in_fp);
2009
2010         fputs($fp, "\r\n");
2011
2012         //read response
2013         do{
2014             $line=iil_ReadLine($fp, 1000);
2015         }while($line[0]!="A");
2016             
2017         $result = (iil_ParseResult($line)==0);
8c2e58 2018         if (!$result) $conn->error .= $line."\n";
4e17e6 2019         return $result;
T 2020     
2021     }else{
8c2e58 2022         $conn->error .= "Couldn't send command \"$request\"\n";
4e17e6 2023         return false;
T 2024     }
2025 }
2026
2027
2028 function iil_C_FetchStructureString(&$conn, $folder, $id){
2029     $fp = $conn->fp;
2030     $result=false;
2031     if (iil_C_Select($conn, $folder)){
2032         $key = "F1247";
2033         if (fputs($fp, "$key FETCH $id (BODYSTRUCTURE)\r\n")){
2034             do{
2035                 $line=chop(iil_ReadLine($fp, 5000));
2036                 if ($line[0]=="*"){
2037                     if (ereg("\}$", $line)){
2038                         preg_match('/(.+)\{([0-9]+)\}/', $line, $match);  
2039                         $result = $match[1];
2040                         do{
2041                             $line = chop(iil_ReadLine($fp, 100));
2042                             if (!preg_match("/^$key/", $line)) $result .= $line;
2043                             else $done = true;
2044                         }while(!$done);
2045                     }else{
2046                         $result = $line;
2047                     }
2048                     list($pre, $post) = explode("BODYSTRUCTURE ", $result);
2049                     $result = substr($post, 0, strlen($post)-1);        //truncate last ')' and return
2050                 }
2051             }while (!preg_match("/^$key/",$line));
2052         }
2053     }
2054     return $result;
2055 }
2056
2057 function iil_C_PrintSource(&$conn, $folder, $id, $part){
2058     $header = iil_C_FetchPartHeader($conn, $folder, $id, $part);
2059     //echo str_replace("\r", "", $header);
2060     echo $header;
2061     echo iil_C_PrintPartBody($conn, $folder, $id, $part);
2062 }
2063
2064 function iil_C_GetQuota(&$conn){
2065 /*
2066 b GETQUOTAROOT "INBOX"
2067 * QUOTAROOT INBOX user/rchijiiwa1
2068 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2069 b OK Completed
2070 */
2071     $fp = $conn->fp;
2072     $result=false;
2073     $quota_line = "";
2074     
2075     //get line containing quota info
2076     if (fputs($fp, "QUOT1 GETQUOTAROOT \"INBOX\"\r\n")){
2077         do{
2078             $line=chop(iil_ReadLine($fp, 5000));
2079             if (iil_StartsWith($line, "* QUOTA ")) $quota_line = $line;
2080         }while(!iil_StartsWith($line, "QUOT1"));
2081     }
2082     
2083     //return false if not found, parse if found
2084     if (!empty($quota_line)){
2085         $quota_line = eregi_replace("[()]", "", $quota_line);
2086         $parts = explode(" ", $quota_line);
2087         $storage_part = array_search("STORAGE", $parts);
2088         if ($storage_part>0){
2089             $result = array();
2090             $used = $parts[$storage_part+1];
2091             $total = $parts[$storage_part+2];
2092             $result["used"] = $used;
2093             $result["total"] = (empty($total)?"??":$total);
2094             $result["percent"] = (empty($total)?"??":round(($used/$total)*100));
2095             $result["free"] = 100 - $result["percent"];
2096         }
2097     }
2098     
2099     return $result;
2100 }
2101
2102
2103 function iil_C_ClearFolder(&$conn, $folder){
2104     $num_in_trash = iil_C_CountMessages($conn, $folder);
2105     if ($num_in_trash > 0) iil_C_Delete($conn, $folder, "1:".$num_in_trash);
2106     return (iil_C_Expunge($conn, $folder) >= 0);
2107 }
2108
2109 ?>