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