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