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