2 /////////////////////////////////////////////////////////
4 // Iloha IMAP Library (IIL)
6 // (C)Copyright 2002 Ryo Chijiiwa <Ryo@IlohaMail.org>
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
12 /////////////////////////////////////////////////////////
14 /********************************************************
16 FILE: include/imap.inc
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
23 Function containing "_C_" in name require connection handler to be
24 passed as one of the parameters. To obtain connection handler, use
27 IlohaMail-0.9-20050415
29 File altered by Thomas Bruederli <roundcube@gmail.com>
30 to fit enhanced equirements by the RoundCube Webmail:
31 - Added list of server capabilites and check these before invoking commands
32 - Added junk flag to iilBasicHeader
33 - Enhanced error reporting on fsockopen()
34 - Additional parameter for SORT command
35 - Removed Call-time pass-by-reference because deprecated
36 - Parse charset from content-type in iil_C_FetchHeaders()
37 - Enhanced heaer sorting
38 - Pass message as reference in iil_C_Append (to save memory)
39 - Added BCC and REFERENCE to the list of headers to fetch in iil_C_FetchHeaders()
40 - Leave messageID unchanged in iil_C_FetchHeaders()
41 - Avoid stripslahes in iil_Connect()
42 - Escape quotes and backslashes in iil_C_Login()
43 - Added patch to iil_SortHeaders() by Richard Green
44 - Removed <br> from error messages (better for logging)
45 - Added patch to iil_C_Sort() enabling UID SORT commands
46 - Added function iil_C_ID2UID()
47 - Casting date parts in iil_StrToTime() to avoid mktime() warnings
48 - Also acceppt LIST responses in iil_C_ListSubscribed()
49 - Sanity check of $message_set in iil_C_FetchHeaders(), iil_C_FetchHeaderIndex(), iil_C_FetchThreadHeaders()
50 - Implemented UID FETCH in iil_C_FetchHeaders()
51 - Removed some debuggers (echo ...)
53 ********************************************************/
56 // changed path to work within roundcube webmail
57 include_once("lib/icl_commons.inc");
60 if (!$IMAP_USE_HEADER_DATE) $IMAP_USE_INTERNAL_DATE = true;
61 $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);
62 $IMAP_SERVER_TZ = date('Z');
82 var $capability = array();
112 class iilThreadHeader{
120 function iil_xor($string, $string2){
122 $size = strlen($string);
123 for ($i=0; $i<$size; $i++) $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
128 function iil_ReadLine($fp, $size){
132 $buffer = fgets($fp, 2048);
134 }while($buffer[strlen($buffer)-1]!="\n");
139 function iil_MultLine($fp, $line){
141 if (ereg('\{[0-9]+\}$', $line)){
143 preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
145 while(strlen($out)<$bytes){
146 $out.=chop(iil_ReadLine($fp, 1024));
148 $line = $a[1][0]."\"$out\"";
153 function iil_ReadBytes($fp, $bytes){
157 $data.=fread($fp, $bytes-$len);
158 $len = strlen($data);
163 function iil_ReadReply($fp){
165 $line = chop(trim(iil_ReadLine($fp, 1024)));
166 }while($line[0]=="*");
171 function iil_ParseResult($string){
172 $a=explode(" ", $string);
174 if (strcasecmp($a[1], "OK")==0) return 0;
175 else if (strcasecmp($a[1], "NO")==0) return -1;
176 else if (strcasecmp($a[1], "BAD")==0) return -2;
180 // check if $string starts with $match
181 function iil_StartsWith($string, $match){
182 $len = strlen($match);
183 if ($len==0) return false;
184 if (strncmp($string, $match, $len)==0) return true;
188 function iil_StartsWithI($string, $match){
189 $len = strlen($match);
190 if ($len==0) return false;
191 if (strncasecmp($string, $match, $len)==0) return true;
196 function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge){
198 // initialize ipad, opad
199 for ($i=0;$i<64;$i++){
203 // pad $pass so it's 64 bytes
204 $padLen = 64 - strlen($pass);
205 for ($i=0;$i<$padLen;$i++) $pass .= chr(0);
207 $hash = md5(iil_xor($pass,$opad).pack("H*",md5(iil_xor($pass, $ipad).base64_decode($encChallenge))));
209 $reply = base64_encode($user." ".$hash);
211 // send result, get reply
212 fputs($conn->fp, $reply."\r\n");
213 $line = iil_ReadLine($conn->fp, 1024);
216 if (iil_ParseResult($line)==0){
221 $conn->error .= 'Authentication for '.$user.' failed (AUTH): "'.htmlspecialchars($line)."\"";
222 $conn->errorNum = -2;
227 function iil_C_Login(&$conn, $user, $password){
229 $password = strtr($password, array('"'=>'\\"', '\\' => '\\\\'));
230 fputs($conn->fp, "a001 LOGIN $user \"$password\"\r\n");
233 $line = iil_ReadReply($conn->fp);
234 }while(!iil_StartsWith($line, "a001 "));
235 $a=explode(" ", $line);
236 if (strcmp($a[1],"OK")==0){
243 $conn->error .= 'Authentication for '.$user.' failed (LOGIN): "'.htmlspecialchars($line)."\"";
244 $conn->errorNum = -2;
249 function iil_ParseNamespace2($str, &$i, $len=0, $l){
250 if (!$l) $str = str_replace("NIL", "()", $str);
251 if (!$len) $len = strlen($str);
255 for($i;$i<$len;$i++){
256 $c = (string)$str[$i];
257 if ($c=='(' && !$in_quotes){
259 $data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
261 }else if ($c==')' && !$in_quotes) return $data;
264 if ($in_quotes) $data[$elem].=$c.$str[$i];
266 $in_quotes = !$in_quotes;
267 if (!$in_quotes) $elem++;
268 }else if ($in_quotes){
275 function iil_C_NameSpace(&$conn){
278 if (!in_array('NAMESPACE', $conn->capability))
281 if ($my_prefs["rootdir"]) return true;
283 fputs($conn->fp, "ns1 NAMESPACE\r\n");
285 $line = iil_ReadLine($conn->fp, 1024);
286 if (iil_StartsWith($line, "* NAMESPACE")){
288 $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
290 }while(!iil_StartsWith($line, "ns1"));
292 if (!is_array($data)) return false;
294 $user_space_data = $data[0];
295 if (!is_array($user_space_data)) return false;
297 $first_userspace = $user_space_data[0];
298 if (count($first_userspace)!=2) return false;
300 $conn->rootdir = $first_userspace[0];
301 $conn->delimiter = $first_userspace[1];
302 $my_prefs["rootdir"] = substr($conn->rootdir, 0, -1);
308 function iil_Connect($host, $user, $password){
309 global $iil_error, $iil_errornum;
310 global $ICL_SSL, $ICL_PORT;
311 global $IMAP_NO_CACHE;
312 global $my_prefs, $IMAP_USE_INTERNAL_DATE;
318 // $user = stripslashes($user);
319 // $password = stripslashes($password);
322 $auth_method = "plain";
323 if (func_num_args() >= 4){
324 $auth_array = func_get_arg(3);
325 if (is_array($auth_array)) $auth_method = $auth_array["imap"];
326 if (empty($auth_method)) $auth_method = "plain";
328 $message = "INITIAL: $auth_method\n";
332 //initialize connection
333 $conn = new iilConnection;
339 $conn->cache = array();
340 $conn->do_cache = (function_exists("cache_write")&&!$IMAP_NO_CACHE);
341 $conn->cache_dirty = array();
343 if ($my_prefs['sort_field']=='INTERNALDATE') $IMAP_USE_INTERNAL_DATE = true;
344 else if ($my_prefs['sort_field']=='DATE') $IMAP_USE_INTERNAL_DATE = false;
345 //echo '<!-- conn sort_field: '.$my_prefs['sort_field'].' //-->';
348 if (empty($host)) $iil_error .= "Invalid host\n";
349 if (empty($user)) $iil_error .= "Invalid user\n";
350 if (empty($password)) $iil_error .= "Invalid password\n";
351 if (!empty($iil_error)) return false;
352 if (!$ICL_PORT) $ICL_PORT = 143;
356 $host = "ssl://".$host;
359 //open socket connection
360 $conn->fp = @fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
362 $iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
367 $iil_error.="Socket connection established\r\n";
368 $line=iil_ReadLine($conn->fp, 300);
370 if (strcasecmp($auth_method, "check")==0){
371 //check for supported auth methods
373 //default to plain text auth
374 $auth_method = "plain";
377 fputs($conn->fp, "cp01 CAPABILITY\r\n");
379 $line = trim(chop(iil_ReadLine($conn->fp, 100)));
380 $conn->message.="$line\n";
381 $a = explode(" ", $line);
383 while ( list($k, $w) = each($a) ){
384 if ($w!='*' && $w!='CAPABILITY')
385 $conn->capability[] = $w;
386 if ((strcasecmp($w, "AUTH=CRAM_MD5")==0)||
387 (strcasecmp($w, "AUTH=CRAM-MD5")==0)){
388 $auth_method = "auth";
392 }while($a[0]!="cp01");
395 if (strcasecmp($auth_method, "auth")==0){
396 $conn->message.="Trying CRAM-MD5\n";
397 //do CRAM-MD5 authentication
398 fputs($conn->fp, "a000 AUTHENTICATE CRAM-MD5\r\n");
399 $line = trim(chop(iil_ReadLine($conn->fp, 1024)));
400 $conn->message.="$line\n";
402 $conn->message.='Got challenge: '.htmlspecialchars($line)."\n";
403 //got a challenge string, try CRAM-5
404 $result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
405 $conn->message.= "Tried CRAM-MD5: $result \n";
407 $conn->message.='No challenge ('.htmlspecialchars($line)."), try plain\n";
412 if ((!$result)||(strcasecmp($auth, "plain")==0)){
414 $result = iil_C_Login($conn, $user, $password);
415 $conn->message.="Tried PLAIN: $result \n";
418 $conn->message .= $auth;
421 iil_C_Namespace($conn);
424 $iil_error = $conn->error;
425 $iil_errornum = $conn->errorNum;
430 function iil_Close(&$conn){
431 iil_C_WriteCache($conn);
432 if (@fputs($conn->fp, "I LOGOUT\r\n")){
433 fgets($conn->fp, 1024);
439 function iil_ClearCache($user, $host){
443 function iil_C_WriteCache(&$conn){
444 //echo "<!-- doing iil_C_WriteCache //-->\n";
445 if (!$conn->do_cache) return false;
447 if (is_array($conn->cache)){
448 while(list($folder,$data)=each($conn->cache)){
449 if ($folder && is_array($data) && $conn->cache_dirty[$folder]){
450 $key = $folder.".imap";
451 $result = cache_write($conn->user, $conn->host, $key, $data, true);
452 //echo "<!-- writing $key $data: $result //-->\n";
458 function iil_C_EnableCache(&$conn){
459 $conn->do_cache = true;
462 function iil_C_DisableCache(&$conn){
463 $conn->do_cache = false;
466 function iil_C_LoadCache(&$conn, $folder){
467 if (!$conn->do_cache) return false;
469 $key = $folder.".imap";
470 if (!is_array($conn->cache[$folder])){
471 $conn->cache[$folder] = cache_read($conn->user, $conn->host, $key);
472 $conn->cache_dirty[$folder] = false;
476 function iil_C_ExpireCachedItems(&$conn, $folder, $message_set){
478 if (!$conn->do_cache) return; //caching disabled
479 if (!is_array($conn->cache[$folder])) return; //cache not initialized|empty
480 if (count($conn->cache[$folder])==0) return; //cache not initialized|empty
482 $uids = iil_C_FetchHeaderIndex($conn, $folder, $message_set, "UID");
484 if (is_array($uids)){
485 //echo "<!-- unsetting: ".implode(",",$uids)." //-->\n";
486 while(list($n,$uid)=each($uids)){
487 unset($conn->cache[$folder][$uid]);
488 //$conn->cache[$folder][$uid] = false;
491 $conn->cache_dirty[$folder] = true;
494 //print_r($conn->cache);
495 //echo "\n".'//-->'."\n";
497 echo "<!-- failed to get uids: $message_set //-->\n";
503 reset($conn->cache[$folder]);
504 while(list($uid,$item)=each($conn->cache[$folder])){
505 if ($item) $new_cache[$uid] = $conn->cache[$folder][$uid];
507 $conn->cache[$folder] = $new_cache;
512 function iil_ExplodeQuotedString($delimiter, $string){
513 $quotes=explode("\"", $string);
514 while ( list($key, $val) = each($quotes))
516 $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
517 $string=implode("\"", $quotes);
519 $result=explode($delimiter, $string);
520 while ( list($key, $val) = each($result) )
521 $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
526 function iil_CheckForRecent($host, $user, $password, $mailbox){
527 if (empty($mailbox)) $mailbox="INBOX";
529 $conn=iil_Connect($host, $user, $password, "plain");
532 fputs($fp, "a002 EXAMINE \"$mailbox\"\r\n");
534 $line=chop(iil_ReadLine($fp, 300));
535 $a=explode(" ", $line);
536 if (($a[0]=="*") && (strcasecmp($a[2], "RECENT")==0)) $result=(int)$a[1];
537 }while (!iil_StartsWith($a[0],"a002"));
539 fputs($fp, "a003 LOGOUT\r\n");
546 function iil_C_Select(&$conn, $mailbox){
549 if (empty($mailbox)) return false;
550 if (strcmp($conn->selected, $mailbox)==0) return true;
552 iil_C_LoadCache($conn, $mailbox);
554 if (fputs($fp, "sel1 SELECT \"$mailbox\"\r\n")){
556 $line=chop(iil_ReadLine($fp, 300));
557 $a=explode(" ", $line);
559 if (strcasecmp($a[2], "EXISTS")==0) $conn->exists=(int)$a[1];
560 if (strcasecmp($a[2], "RECENT")==0) $conn->recent=(int)$a[1];
562 }while (!iil_StartsWith($line, "sel1"));
564 $a=explode(" ", $line);
566 if (strcasecmp($a[1],"OK")==0){
567 $conn->selected = $mailbox;
575 function iil_C_CheckForRecent(&$conn, $mailbox){
576 if (empty($mailbox)) $mailbox="INBOX";
578 iil_C_Select($conn, $mailbox);
579 if ($conn->selected==$mailbox) return $conn->recent;
583 function iil_C_CountMessages(&$conn, $mailbox, $refresh=false){
584 if ($refresh) $conn->selected="";
585 iil_C_Select($conn, $mailbox);
586 if ($conn->selected==$mailbox) return $conn->exists;
590 function iil_SplitHeaderLine($string){
591 $pos=strpos($string, ":");
593 $res[0]=substr($string, 0, $pos);
594 $res[1]=trim(substr($string, $pos+1));
601 function iil_StrToTime($str){
602 global $IMAP_MONTHS,$IMAP_SERVER_TZ;
604 if ($str) $time1 = strtotime($str);
605 if ($time1 && $time1!=-1) return $time1-$IMAP_SERVER_TZ;
607 //echo '<!--'.$str.'//-->';
609 //replace double spaces with single space
611 $str = str_replace(" ", " ", $str);
613 //strip off day of week
614 $pos=strpos($str, " ");
615 if (!is_numeric(substr($str, 0, $pos))) $str = substr($str, $pos+1);
617 //explode, take good parts
618 $a=explode(" ",$str);
619 //$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);
621 $month=$IMAP_MONTHS[$month_str];
626 $tz = substr($tz_str, 0, 3);
627 $ta = explode(":",$time);
628 $hour=(int)$ta[0]-(int)$tz;
632 //make UNIX timestamp
633 $time2 = mktime($hour, $minute, $second, $month, $day, $year);
634 //echo '<!--'.$time1.' '.$time2.' //-->'."\n";
638 function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE, $encoding='US-ASCII'){
639 /* Do "SELECT" command */
640 if (!iil_C_Select($conn, $mailbox)) return false;
642 $field = strtoupper($field);
643 if ($field=='INTERNALDATE') $field='ARRIVAL';
644 $fields = array('ARRIVAL'=>1,'CC'=>1,'DATE'=>1,'FROM'=>1,'SIZE'=>1,'SUBJECT'=>1,'TO'=>1);
646 if (!$fields[$field])
649 $is_uid = $is_uid ? 'UID ' : '';
655 $command = 's '. $is_uid .'SORT ('.$field.') '.$encoding.' ALL'."$add\r\n";
658 if (!fputs($fp, $command)) return false;
660 $line = chop(iil_ReadLine($fp, 1024));
661 if (iil_StartsWith($line, '* SORT')) $data.=($data?' ':'').substr($line,7);
662 }while($line[0]!='s');
665 $conn->error = $line;
669 $out = explode(' ',$data);
673 function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field, $normalize=true){
674 global $IMAP_USE_INTERNAL_DATE;
680 if (empty($index_field)) $index_field="DATE";
681 $index_field = strtoupper($index_field);
683 list($from_idx, $to_idx) = explode(':', $message_set);
684 if (empty($message_set) || (isset($to_idx) && (int)$from_idx > (int)$to_idx))
687 //$fields_a["DATE"] = ($IMAP_USE_INTERNAL_DATE?6:1);
688 $fields_a['DATE'] = 1;
689 $fields_a['INTERNALDATE'] = 6;
690 $fields_a['FROM'] = 1;
691 $fields_a['REPLY-TO'] = 1;
692 $fields_a['SENDER'] = 1;
694 $fields_a['SUBJECT'] = 1;
695 $fields_a['UID'] = 2;
696 $fields_a['SIZE'] = 2;
697 $fields_a['SEEN'] = 3;
698 $fields_a['RECENT'] = 4;
699 $fields_a['DELETED'] = 5;
701 $mode=$fields_a[$index_field];
702 if (!($mode > 0)) return false;
704 /* Do "SELECT" command */
705 if (!iil_C_Select($conn, $mailbox)) return false;
707 /* FETCH date,from,subject headers */
710 $request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)])\r\n";
711 if (!fputs($fp, $request)) return false;
714 $line=chop(iil_ReadLine($fp, 200));
715 $a=explode(" ", $line);
716 if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
719 $str=$line=chop(iil_ReadLine($fp, 300));
721 while($line[0]!=")"){ //caution, this line works only in this particular case
722 $line=chop(iil_ReadLine($fp, 300));
724 if (ord($line[0]) <= 32){ //continuation from previous header line
725 $str.=" ".trim($line);
727 if ((ord($line[0]) > 32) || (strlen($line[0]) == 0)){
728 list($field, $string) = iil_SplitHeaderLine($str);
729 if (strcasecmp($field, "date")==0){
730 $result[$id]=iil_StrToTime($string);
732 $result[$id] = str_replace("\"", "", $string);
733 if ($normalize) $result[$id]=strtoupper($result[$id]);
741 $end_pos = strlen($line)-1;
742 if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[$end_pos]=="}")){
744 $pos = strrpos($line, "{")+1;
745 $bytes = (int)substr($line, $pos, $end_pos-$pos);
748 $line = iil_ReadLine($fp, 0);
749 $received+=strlen($line);
752 if ($received>$bytes) break;
753 else if (!$line) continue;
755 list($field,$string)=explode(": ", $line);
757 if (strcasecmp($field, "date")==0)
758 $result[$id] = iil_StrToTime($string);
759 else if ($index_field!="DATE")
760 $result[$id]=strtoupper(str_replace("\"", "", $string));
761 }while($line[0]!=")");
763 //one line response, not expected so ignore
766 }while(!iil_StartsWith($line, $key));
769 $request = $key." FETCH $message_set (INTERNALDATE)\r\n";
770 if (!fputs($fp, $request)) return false;
772 $line=chop(iil_ReadLine($fp, 200));
774 //original: "* 10 FETCH (INTERNALDATE "31-Jul-2002 09:18:02 -0500")"
775 $paren_pos = strpos($line, "(");
776 $foo = substr($line, 0, $paren_pos);
777 $a = explode(" ", $foo);
780 $open_pos = strpos($line, "\"") + 1;
781 $close_pos = strrpos($line, "\"");
782 if ($open_pos && $close_pos){
783 $len = $close_pos - $open_pos;
784 $time_str = substr($line, $open_pos, $len);
785 $result[$id] = strtotime($time_str);
788 $a = explode(" ", $line);
790 }while(!iil_StartsWith($a[0], $key));
792 if ($mode >= 3) $field_name="FLAGS";
793 else if ($index_field=="SIZE") $field_name="RFC822.SIZE";
794 else $field_name=$index_field;
796 /* FETCH uid, size, flags */
798 $request=$key." FETCH $message_set ($field_name)\r\n";
800 if (!fputs($fp, $request)) return false;
802 $line=chop(iil_ReadLine($fp, 200));
803 $a = explode(" ", $line);
804 if (($line[0]=="*") && ($a[2]=="FETCH")){
805 $line=str_replace("(", "", $line);
806 $line=str_replace(")", "", $line);
807 $a=explode(" ", $line);
811 if (isset($result[$id])) continue; //if we already got the data, skip forward
812 if ($a[3]!=$field_name) continue; //make sure it's returning what we requested
814 /* Caution, bad assumptions, next several lines */
815 if ($mode==2) $result[$id]=$a[4];
817 $haystack=strtoupper($line);
818 $result[$id]=(strpos($haystack, $index_field) > 0 ? "F" : "N");
821 }while(!iil_StartsWith($line, $key));
824 //check number of elements...
825 list($start_mid,$end_mid)=explode(':',$message_set);
826 if (is_numeric($start_mid) && is_numeric($end_mid)){
827 //count how many we should have
828 $should_have = $end_mid - $start_mid +1;
830 //if we have less, try and fill in the "gaps"
831 if (count($result)<$should_have){
832 for($i=$start_mid;$i<=$end_mid;$i++) if (!isset($result[$i])) $result[$i] = '';
840 function iil_CompressMessageSet($message_set){
841 //given a comma delimited list of independent mid's,
842 //compresses by grouping sequences together
844 //if less than 255 bytes long, let's not bother
845 if (strlen($message_set)<255) return $message_set;
847 //see if it's already been compress
848 if (strpos($message_set,':')!==false) return $message_set;
850 //separate, then sort
851 $ids = explode(',',$message_set);
855 $start = $prev = $ids[0];
856 foreach($ids as $id){
858 if ($incr>1){ //found a gap
859 if ($start==$prev) $result[] = $prev; //push single id
860 else $result[] = $start.':'.$prev; //push sequence as start_id:end_id
861 $start = $id; //start of new sequence
865 //handle the last sequence/id
866 if ($start==$prev) $result[] = $prev;
867 else $result[] = $start.':'.$prev;
869 //return as comma separated string
870 return implode(',',$result);
873 function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids){
874 if (!is_array($uids) || count($uids)==0) return array();
875 return iil_C_Search($conn, $mailbox, "UID ".implode(",", $uids));
878 function iil_C_UIDToMID(&$conn, $mailbox, $uid){
879 $result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
880 if (count($result)==1) return $result[0];
884 function iil_C_FetchUIDs(&$conn,$mailbox){
887 $num = iil_C_CountMessages($conn, $mailbox);
888 if ($num==0) return array();
889 $message_set = '1'.($num>1?':'.$num:'');
891 //if cache not enabled, just call iil_C_FetchHeaderIndex on 'UID' field
892 if (!$conn->do_cache)
893 return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
895 //otherwise, let's check cache first
896 $key = $mailbox.'.uids';
898 if ($conn->uid_cache) $data = $conn->uid_cache;
899 else $data = cache_read($conn->user, $conn->host, $key);
901 //was anything cached at all?
902 if ($data===false) $cache_good = -1;
904 //make sure number of messages were the same
905 if ($cache_good>0 && $data['n']!=$num) $cache_good = -2;
907 //if everything's okay so far...
909 //check UIDs of highest mid with current and cached
910 $temp = iil_C_Search($conn, $mailbox, 'UID '.$data['d'][$num]);
911 if (!$temp || !is_array($temp) || $temp[0]!=$num) $cache_good=-3;
914 //if cached data's good, return it
919 //otherwise, we need to fetch it
920 $data = array('n'=>$num,'d'=>array());
921 $data['d'] = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
922 cache_write($conn->user, $conn->host, $key, $data);
923 $conn->uid_cache = $data;
927 function iil_SortThreadHeaders($headers, $index_a, $uids){
930 foreach($index_a as $mid=>$foobar){
932 $result[$uid] = $headers[$uid];
937 function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set){
941 list($from_idx, $to_idx) = explode(':', $message_set);
942 if (empty($message_set) || (isset($to_idx) && (int)$from_idx > (int)$to_idx))
946 $uids = iil_C_FetchUIDs($conn, $mailbox);
949 /* Get cached records where possible */
950 if ($conn->do_cache){
951 $cached = cache_read($conn->user, $conn->host, $mailbox.'.thhd');
952 if ($cached && is_array($uids) && count($uids)>0){
954 foreach($uids as $id=>$uid){
956 $result[$uid] = $cached[$uid];
957 $result[$uid]->id = $id;
958 }else $needed_set.=($needed_set?",":"").$id;
960 if ($needed_set) $message_set = $needed_set;
961 else $message_set = '';
964 $message_set = iil_CompressMessageSet($message_set);
965 if ($debug) echo "Still need: ".$message_set;
967 /* if we're missing any, get them */
969 /* FETCH date,from,subject headers */
972 $request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])\r\n";
973 $mid_to_id = array();
974 if (!fputs($fp, $request)) return false;
976 $line = chop(iil_ReadLine($fp, 1024));
977 if ($debug) echo $line."\n";
978 if (ereg('\{[0-9]+\}$', $line)){
979 $a = explode(" ", $line);
982 $new_thhd = new iilThreadHeader;
983 $new_thhd->id = $a[1];
985 $line=chop(iil_ReadLine($fp, 1024),"\r\n");
986 if (iil_StartsWithI($line,'Message-ID:') || (iil_StartsWithI($line,'In-Reply-To:')) || (iil_StartsWithI($line,'SUBJECT:'))){
987 $pos = strpos($line, ":");
988 $field_name = substr($line, 0, $pos);
989 $field_val = substr($line, $pos+1);
990 $new[strtoupper($field_name)] = trim($field_val);
991 }else if (ereg('^[[:space:]]', $line)){
992 $new[strtoupper($field_name)].= trim($line);
994 }while($line[0]!=')');
995 $new_thhd->sbj = $new['SUBJECT'];
996 $new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
997 $new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
999 $result[$uids[$new_thhd->id]] = $new_thhd;
1001 }while(!iil_StartsWith($line, "fh"));
1005 if (is_array($index_a)){
1006 $result = iil_SortThreadHeaders($result, $index_a, $uids);
1009 /* write new set to cache */
1010 if ($conn->do_cache){
1011 if (count($result)!=count($cached))
1012 cache_write($conn->user, $conn->host, $mailbox.'.thhd', $result);
1015 //echo 'iil_FetchThreadHeaders:'."\n";
1021 function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock){
1024 list($from_idx, $to_idx) = explode(':', $message_set);
1025 if (empty($message_set) || (isset($to_idx) && (int)$from_idx > (int)$to_idx))
1030 $root_mids = array();
1031 $sub_mids = array();
1033 $messages = array();
1037 $sbj_filter_pat = '[a-zA-Z]{2,3}(\[[0-9]*\])?:([[:space:]]*)';
1039 /* Do "SELECT" command */
1040 if (!iil_C_Select($conn, $mailbox)) return false;
1042 /* FETCH date,from,subject headers */
1043 $mid_to_id = array();
1044 $messages = array();
1045 $headers = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
1046 if ($clock) $clock->register('fetched headers');
1048 if ($debug) print_r($headers);
1050 /* go through header records */
1051 foreach($headers as $header){
1052 //$id = $header['i'];
1053 //$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'],
1054 // 'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
1056 $new = array('id'=>$id, 'MESSAGE-ID'=>$header->mid,
1057 'IN-REPLY-TO'=>$header->irt, 'SUBJECT'=>$header->sbj);
1059 /* add to message-id -> mid lookup table */
1060 $mid_to_id[$new['MESSAGE-ID']] = $id;
1062 /* if no subject, use message-id */
1063 if (empty($new['SUBJECT'])) $new['SUBJECT'] = $new['MESSAGE-ID'];
1065 /* if subject contains 'RE:' or has in-reply-to header, it's a reply */
1068 if (eregi($sbj_filter_pat, $new['SUBJECT'])) $has_re = true;
1069 if ($has_re||$new['IN-REPLY-TO']) $sbj_pre = 'RE:';
1071 /* strip out 're:', 'fw:' etc */
1072 if ($has_re) $sbj = ereg_replace($sbj_filter_pat,'', $new['SUBJECT']);
1073 else $sbj = $new['SUBJECT'];
1074 $new['SUBJECT'] = $sbj_pre.$sbj;
1077 /* if subject not a known thread-root, add to list */
1078 if ($debug) echo $id.' '.$new['SUBJECT']."\t".$new['MESSAGE-ID']."\n";
1079 $root_id = $roots[$sbj];
1081 if ($root_id && ($has_re || !$root_in_root[$root_id])){
1082 if ($debug) echo "\tfound root: $root_id\n";
1083 $sub_mids[$new['MESSAGE-ID']] = $root_id;
1084 $result[$root_id][] = $id;
1085 }else if (!isset($roots[$sbj])||(!$has_re&&$root_in_root[$root_id])){
1086 /* try to use In-Reply-To header to find root
1087 unless subject contains 'Re:' */
1088 if ($has_re&&$new['IN-REPLY-TO']){
1089 if ($debug) echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
1091 //reply to known message?
1092 $temp = $sub_mids[$new['IN-REPLY-TO']];
1095 //found it, root:=parent's root
1096 if ($debug) echo "\tfound parent: ".$new['SUBJECT']."\n";
1097 $result[$temp][] = $id;
1098 $sub_mids[$new['MESSAGE-ID']] = $temp;
1101 //if we can't find referenced parent, it's a "stray"
1102 $strays[$id] = $new['IN-REPLY-TO'];
1106 //add subject as root
1108 if ($debug) echo "\t added to root\n";
1110 $root_in_root[$id] = !$has_re;
1111 $sub_mids[$new['MESSAGE-ID']] = $id;
1112 $result[$id] = array($id);
1114 if ($debug) echo $new['MESSAGE-ID']."\t".$sbj."\n";
1119 //now that we've gone through all the messages,
1120 //go back and try and link up the stray threads
1121 if (count($strays)>0){
1122 foreach($strays as $id=>$irt){
1123 $root_id = $sub_mids[$irt];
1124 if (!$root_id || $root_id==$id) continue;
1125 $result[$root_id] = array_merge($result[$root_id],$result[$id]);
1126 unset($result[$id]);
1130 if ($clock) $clock->register('data prepped');
1132 if ($debug) print_r($roots);
1138 function iil_SortThreads(&$tree, $index, $sort_order='ASC'){
1139 if (!is_array($tree) || !is_array($index)) return false;
1141 //create an id to position lookup table
1143 foreach($index as $id=>$val){
1149 //for each tree, set array key to position
1151 foreach($tree as $id=>$node){
1152 if (count($tree[$id])<=1){
1153 //for "threads" with only one message, key is position of that message
1155 $itree[$n] = array($n=>$id);
1157 //for "threads" with multiple messages,
1160 foreach($tree[$id] as $mid){
1161 $new_a[$index[$mid]] = $mid; //create new sub-array mapping position to id
1162 $pos = $index[$mid];
1163 if ($pos&&$pos<$min) $min = $index[$mid]; //find smallest position
1165 $n = $min; //smallest position of child is thread position
1167 //assign smallest position to root level key
1168 //set children array to one created above
1170 $itree[$n] = $new_a;
1175 //sort by key, this basically sorts all threads
1179 foreach($itree as $k=>$node){
1180 $out[$i] = $itree[$k];
1188 function iil_IndexThreads(&$tree){
1189 /* creates array mapping mid to thread id */
1191 if (!is_array($tree)) return false;
1194 foreach($tree as $pos=>$kids){
1195 foreach($kids as $kid) $t_index[$kid] = $pos;
1201 function iil_C_FetchHeaders(&$conn, $mailbox, $message_set, $uidfetch=false){
1202 global $IMAP_USE_INTERNAL_DATE;
1208 list($from_idx, $to_idx) = explode(':', $message_set);
1209 if (empty($message_set) || (isset($to_idx) && (int)$from_idx > (int)$to_idx))
1212 /* Do "SELECT" command */
1213 if (!iil_C_Select($conn, $mailbox)){
1214 $conn->error = "Couldn't select $mailbox";
1218 /* Get cached records where possible */
1219 if ($conn->do_cache){
1220 $uids = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, "UID");
1221 if (is_array($uids) && count($conn->cache[$mailbox]>0)){
1223 while(list($id,$uid)=each($uids)){
1224 if ($conn->cache[$mailbox][$uid]){
1225 $result[$id] = $conn->cache[$mailbox][$uid];
1226 $result[$id]->id = $id;
1227 }else $needed_set.=($needed_set?",":"").$id;
1229 //echo "<!-- iil_C_FetchHeader\nMessage Set: $message_set\nNeeded Set:$needed_set\n//-->\n";
1230 if ($needed_set) $message_set = iil_CompressMessageSet($needed_set);
1231 else return $result;
1235 /* FETCH date,from,subject headers */
1237 $prefix=$uidfetch?" UID":"";
1238 $request=$key.$prefix." 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";
1240 if (!fputs($fp, $request)) return false;
1242 $line=chop(iil_ReadLine($fp, 200));
1243 $a=explode(" ", $line);
1244 if (($line[0]=="*") && ($a[2]=="FETCH")){
1246 $result[$id]=new iilBasicHeader;
1247 $result[$id]->id = $id;
1248 $result[$id]->subject = "";
1250 Start parsing headers. The problem is, some header "lines" take up multiple lines.
1251 So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1252 process the previous line. Otherwise, we'll keep adding the strings until we come
1253 to the next valid header line.
1258 $line = chop(iil_ReadLine($fp, 300),"\r\n");
1259 if (ord($line[0])<=32) $lines[$i].=(empty($lines[$i])?"":"\n").trim(chop($line));
1262 $lines[$i] = trim(chop($line));
1264 }while($line[0]!=")" && strncmp($line, $key, strlen($key))); // patch from "Maksim Rubis" <siburny@hotmail.com>
1266 if(strncmp($line, $key, strlen($key)))
1268 //process header, fill iilBasicHeader obj.
1270 if (is_array($headers)){
1272 while ( list($k, $bar) = each($headers) ) $headers[$k] = "";
1275 // create array with header field:data
1277 while ( list($lines_key, $str) = each($lines) ){
1278 list($field, $string) = iil_SplitHeaderLine($str);
1279 $field = strtolower($field);
1280 $headers[$field] = $string;
1282 $result[$id]->date = $headers["date"];
1283 $result[$id]->timestamp = iil_StrToTime($headers["date"]);
1284 $result[$id]->from = $headers["from"];
1285 $result[$id]->to = str_replace("\n", " ", $headers["to"]);
1286 $result[$id]->subject = str_replace("\n", "", $headers["subject"]);
1287 $result[$id]->replyto = str_replace("\n", " ", $headers["reply-to"]);
1288 $result[$id]->cc = str_replace("\n", " ", $headers["cc"]);
1289 $result[$id]->bcc = str_replace("\n", " ", $headers["bcc"]);
1290 $result[$id]->encoding = str_replace("\n", " ", $headers["content-transfer-encoding"]);
1291 $result[$id]->ctype = str_replace("\n", " ", $headers["content-type"]);
1292 $result[$id]->in_reply_to = ereg_replace("[\n<>]",'', $headers['in-reply-to']);
1293 $result[$id]->reference = $headers["reference"];
1295 list($result[$id]->ctype, $ctype_add) = explode(";", $headers["content-type"]);
1297 if (preg_match('/charset="?([a-z0-9\-]+)"?/i', $ctype_add, $regs))
1298 $result[$id]->charset = $regs[1];
1300 $messageID = $headers["message-id"];
1301 if (!$messageID) "mid:".$id;
1302 $result[$id]->messageID = $messageID;
1305 $a=explode(" ", $line);
1309 }while(strcmp($a[0], $key)!=0);
1312 FETCH uid, size, flags
1313 Sample reply line: "* 3 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen \Deleted))"
1315 $command_key="fh".($c++);
1316 $request= $command_key.$prefix." FETCH $message_set (UID RFC822.SIZE FLAGS INTERNALDATE)\r\n";
1317 if (!fputs($fp, $request)) return false;
1319 $line=chop(iil_ReadLine($fp, 200));
1320 //$a = explode(" ", $line);
1321 //if (($line[0]=="*") && ($a[2]=="FETCH")){
1323 //echo "<!-- $line //-->\n";
1324 //get outter most parens
1325 $open_pos = strpos($line, "(") + 1;
1326 $close_pos = strrpos($line, ")");
1327 if ($open_pos && $close_pos){
1328 //extract ID from pre-paren
1329 $pre_str = substr($line, 0, $open_pos);
1330 $pre_a = explode(" ", $line);
1334 $len = $close_pos - $open_pos;
1335 $str = substr($line, $open_pos, $len);
1337 //swap parents with quotes, then explode
1338 $str = eregi_replace("[()]", "\"", $str);
1339 $a = iil_ExplodeQuotedString(" ", $str);
1341 //did we get the right number of replies?
1342 $parts_count = count($a);
1343 if ($parts_count>=8){
1344 for ($i=0;$i<$parts_count;$i=$i+2){
1345 if (strcasecmp($a[$i],"UID")==0) $result[$id]->uid=$a[$i+1];
1346 else if (strcasecmp($a[$i],"RFC822.SIZE")==0) $result[$id]->size=$a[$i+1];
1347 else if (strcasecmp($a[$i],"INTERNALDATE")==0) $time_str = $a[$i+1];
1348 else if (strcasecmp($a[$i],"FLAGS")==0) $flags_str = $a[$i+1];
1352 $flags_str = eregi_replace('[\\\"]', "", $flags_str);
1353 $flags_a = explode(" ", $flags_str);
1354 //echo "<!-- ID: $id FLAGS: ".implode(",", $flags_a)." //-->\n";
1356 $result[$id]->seen = false;
1357 $result[$id]->recent = false;
1358 $result[$id]->deleted = false;
1359 $result[$id]->answered = false;
1360 if (is_array($flags_a)){
1362 while (list($key,$val)=each($flags_a)){
1363 if (strcasecmp($val,"Seen")==0) $result[$id]->seen = true;
1364 else if (strcasecmp($val, "Deleted")==0) $result[$id]->deleted=true;
1365 else if (strcasecmp($val, "Recent")==0) $result[$id]->recent = true;
1366 else if (strcasecmp($val, "Answered")==0) $result[$id]->answered = true;
1368 $result[$id]->flags=$flags_str;
1371 // if time is gmt...
1372 $time_str = str_replace('GMT','+0000',$time_str);
1375 $time_str = substr($time_str, 0, -1);
1376 $time_zone_str = substr($time_str, -5); //extract timezone
1377 $time_str = substr($time_str, 1, -6); //remove quotes
1378 $time_zone = (float)substr($time_zone_str, 1, 2); //get first two digits
1379 if ($time_zone_str[3]!='0') $time_zone += 0.5; //handle half hour offset
1380 if ($time_zone_str[0]=="-") $time_zone = $time_zone * -1.0; //minus?
1381 $result[$id]->internaldate = $time_str;
1383 if ($IMAP_USE_INTERNAL_DATE){
1384 //calculate timestamp
1385 $timestamp = strtotime($time_str); //return's server's time
1386 $na_timestamp = $timestamp;
1387 $timestamp -= $time_zone * 3600; //compensate for tz, get GMT
1388 $result[$id]->timestamp = $timestamp;
1391 if ($conn->do_cache){
1392 $uid = $result[$id]->uid;
1393 $conn->cache[$mailbox][$uid] = $result[$id];
1394 $conn->cache_dirty[$mailbox] = true;
1396 //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";
1398 //echo "<!-- ERROR: $id : $str //-->\n";
1402 }while(strpos($line, $command_key)===false);
1408 function iil_C_FetchHeader(&$conn, $mailbox, $id, $uidfetch=false){
1410 $a=iil_C_FetchHeaders($conn, $mailbox, $id, $uidfetch);
1411 if (is_array($a)) return array_shift($a);
1416 function iil_SortHeaders($a, $field, $flag){
1417 if (empty($field)) $field="uid";
1418 $field=strtolower($field);
1419 if ($field=="date"||$field=='internaldate') $field="timestamp";
1420 if (empty($flag)) $flag="ASC";
1421 $flag=strtoupper($flag);
1422 $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ',"\"") : array("\"");
1428 First, we'll create an "index" array.
1429 Then, we'll use sort() on that array,
1430 and use that to sort the main array.
1433 // create "index" array
1436 while (list($key, $val)=each($a)){
1438 if ($field=="timestamp"){
1439 $data = @strtotime($val->date);
1441 $data = $val->timestamp;
1444 $data = $val->$field;
1445 if (is_string($data))
1446 $data=strtoupper(str_replace($stripArr, "", $data));
1454 if ($flag=="ASC") asort($index);
1455 else arsort($index);
1457 // form new array based on index
1460 while (list($key, $val)=each($index)){
1461 $result[$key]=$a[$key];
1469 function iil_C_Expunge(&$conn, $mailbox){
1471 if (iil_C_Select($conn, $mailbox)){
1473 fputs($fp, "exp1 EXPUNGE\r\n");
1475 $line=chop(iil_ReadLine($fp, 100));
1476 if ($line[0]=="*") $c++;
1477 }while (!iil_StartsWith($line, "exp1"));
1479 if (iil_ParseResult($line) == 0){
1480 $conn->selected = ""; //state has changed, need to reselect
1481 //$conn->exists-=$c;
1484 $conn->error = $line;
1492 function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod){
1493 if ($mod!="+" && $mod!="-") return -1;
1498 "DELETED"=>"\\Deleted",
1499 "RECENT"=>"\\Recent",
1500 "ANSWERED"=>"\\Answered",
1502 "FLAGGED"=>"\\Flagged"
1504 $flag=strtoupper($flag);
1505 $flag=$flags[$flag];
1506 if (iil_C_Select($conn, $mailbox)){
1508 fputs($fp, "flg STORE $messages ".$mod."FLAGS (".$flag.")\r\n");
1510 $line=chop(iil_ReadLine($fp, 100));
1511 if ($line[0]=="*") $c++;
1512 }while (!iil_StartsWith($line, "flg"));
1514 if (iil_ParseResult($line) == 0){
1515 iil_C_ExpireCachedItems($conn, $mailbox, $messages);
1518 $conn->error = $line;
1522 $conn->error = "Select failed";
1527 function iil_C_Flag(&$conn, $mailbox, $messages, $flag){
1528 return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "+");
1531 function iil_C_Unflag(&$conn, $mailbox, $messages, $flag){
1532 return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "-");
1535 function iil_C_Delete(&$conn, $mailbox, $messages){
1536 return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "+");
1539 function iil_C_Undelete(&$conn, $mailbox, $messages){
1540 return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "-");
1544 function iil_C_Unseen(&$conn, $mailbox, $messages){
1545 return iil_C_ModFlag($conn, $mailbox, $messages, "SEEN", "-");
1549 function iil_C_Copy(&$conn, $messages, $from, $to){
1552 if (empty($from) || empty($to)) return -1;
1554 if (iil_C_Select($conn, $from)){
1557 fputs($fp, "cpy1 COPY $messages \"$to\"\r\n");
1558 $line=iil_ReadReply($fp);
1559 return iil_ParseResult($line);
1565 function iil_FormatSearchDate($month, $day, $year){
1566 $month = (int)$month;
1568 1=>"Jan", 2=>"Feb", 3=>"Mar", 4=>"Apr",
1569 5=>"May", 6=>"Jun", 7=>"Jul", 8=>"Aug",
1570 9=>"Sep", 10=>"Oct", 11=>"Nov", 12=>"Dec"
1572 return $day."-".$months[$month]."-".$year;
1575 function iil_C_CountUnseen(&$conn, $folder){
1576 $index = iil_C_Search($conn, $folder, "ALL UNSEEN");
1577 if (is_array($index)){
1578 $str = implode(",", $index);
1579 if (empty($str)) return false;
1580 else return count($index);
1584 function iil_C_UID2ID(&$conn, $folder, $uid){
1586 $id_a = iil_C_Search($conn, $folder, "UID $uid");
1587 if (is_array($id_a)){
1588 $count = count($id_a);
1589 if ($count > 1) return false;
1590 else return $id_a[0];
1596 function iil_C_ID2UID(&$conn, $folder, $id){
1600 if (iil_C_Select($conn, $folder)){
1602 if (fputs($fp, "$key FETCH $id (UID)\r\n")){
1604 $line=chop(iil_ReadLine($fp, 1024));
1605 if (eregi("^\* $id FETCH \(UID (.*)\)", $line, $r)){
1608 } while (!preg_match("/^$key/", $line));
1615 function iil_C_Search(&$conn, $folder, $criteria){
1617 if (iil_C_Select($conn, $folder)){
1620 $query = "srch1 SEARCH ".chop($criteria)."\r\n";
1623 $line=trim(chop(iil_ReadLine($fp, 10000)));
1624 if (eregi("^\* SEARCH", $line)){
1625 $str = trim(substr($line, 8));
1626 $messages = explode(" ", $str);
1628 }while(!iil_StartsWith($line, "srch1"));
1630 $result_code=iil_ParseResult($line);
1631 if ($result_code==0) return $messages;
1633 $conn->error = "iil_C_Search: ".$line."\n";
1638 $conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
1643 function iil_C_Move(&$conn, $messages, $from, $to){
1646 if (!$from || !$to) return -1;
1648 $r=iil_C_Copy($conn, $messages, $from,$to);
1650 return iil_C_Delete($conn, $from, $messages);
1656 function iil_C_GetHierarchyDelimiter(&$conn){
1657 if ($conn->delimiter) return $conn->delimiter;
1662 //try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
1663 if (!fputs($fp, "ghd LIST \"\" \"\"\r\n")) return false;
1665 $line=iil_ReadLine($fp, 500);
1667 $line = rtrim($line);
1668 $a=iil_ExplodeQuotedString(" ", $line);
1669 if ($a[0]=="*") $delimiter = str_replace("\"", "", $a[count($a)-2]);
1671 }while (!iil_StartsWith($line, "ghd"));
1673 if (strlen($delimiter)>0) return $delimiter;
1675 //if that fails, try namespace extension
1676 //try to fetch namespace data
1677 fputs($conn->fp, "ns1 NAMESPACE\r\n");
1679 $line = iil_ReadLine($conn->fp, 1024);
1680 if (iil_StartsWith($line, "* NAMESPACE")){
1682 $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
1684 }while(!iil_StartsWith($line, "ns1"));
1686 if (!is_array($data)) return false;
1688 //extract user space data (opposed to global/shared space)
1689 $user_space_data = $data[0];
1690 if (!is_array($user_space_data)) return false;
1693 $first_userspace = $user_space_data[0];
1694 if (!is_array($first_userspace)) return false;
1697 $delimiter = $first_userspace[1];
1702 function iil_C_ListMailboxes(&$conn, $ref, $mailbox){
1703 global $IGNORE_FOLDERS;
1705 $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
1708 if (empty($mailbox)) $mailbox="*";
1709 if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
1712 if (!fputs($fp, "lmb LIST \"".$ref."\" \"$mailbox\"\r\n")) return false;
1716 $line=iil_ReadLine($fp, 500);
1717 $line=iil_MultLine($fp, $line);
1719 $a = explode(" ", $line);
1720 if (($line[0]=="*") && ($a[1]=="LIST")){
1721 $line = rtrim($line);
1723 $a=iil_ExplodeQuotedString(" ", $line);
1724 // last string is folder name
1725 $folder = str_replace("\"", "", $a[count($a)-1]);
1726 if (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder))) $folders[$i] = $folder;
1727 // second from last is delimiter
1728 $delim = str_replace("\"", "", $a[count($a)-2]);
1729 // is it a container?
1732 }while (!iil_StartsWith($line, "lmb"));
1734 if (is_array($folders)){
1736 // if rootdir was specified, make sure it's the first element
1737 // some IMAP servers (i.e. Courier) won't return it
1738 if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
1739 if ($folders[0]!=$ref) array_unshift($folders, $ref);
1742 }else if (iil_ParseResult($line)==0){
1743 return array('INBOX');
1745 $conn->error = $line;
1751 function iil_C_ListSubscribed(&$conn, $ref, $mailbox){
1752 global $IGNORE_FOLDERS;
1754 $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
1757 if (empty($mailbox)) $mailbox = "*";
1758 if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
1762 if (!fputs($fp, "lsb LSUB \"".$ref."\" \"".$mailbox."\"\r\n")){
1763 $conn->error = "Couldn't send LSUB command\n";
1769 $line=iil_ReadLine($fp, 500);
1770 $line=iil_MultLine($fp, $line);
1771 $a = explode(" ", $line);
1772 if (($line[0]=="*") && ($a[1]=="LSUB" || $a[1]=="LIST")){
1773 $line = rtrim($line);
1775 $a=iil_ExplodeQuotedString(" ", $line);
1776 // last string is folder name
1777 //$folder = UTF7DecodeString(str_replace("\"", "", $a[count($a)-1]));
1778 $folder = str_replace("\"", "", $a[count($a)-1]);
1779 if ((!in_array($folder, $folders)) && (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder)))) $folders[$i] = $folder;
1780 // second from last is delimiter
1781 $delim = str_replace("\"", "", $a[count($a)-2]);
1782 // is it a container?
1785 }while (!iil_StartsWith($line, "lsb"));
1787 if (is_array($folders)){
1789 // if rootdir was specified, make sure it's the first element
1790 // some IMAP servers (i.e. Courier) won't return it
1791 if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
1792 if ($folders[0]!=$ref) array_unshift($folders, $ref);
1796 $conn->error = $line;
1802 function iil_C_Subscribe(&$conn, $folder){
1805 $query = "sub1 SUBSCRIBE \"".$folder."\"\r\n";
1807 $line=trim(chop(iil_ReadLine($fp, 10000)));
1808 return iil_ParseResult($line);
1812 function iil_C_UnSubscribe(&$conn, $folder){
1815 $query = "usub1 UNSUBSCRIBE \"".$folder."\"\r\n";
1817 $line=trim(chop(iil_ReadLine($fp, 10000)));
1818 return iil_ParseResult($line);
1822 function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $part){
1825 if (($part==0)||(empty($part))) $part="HEADER";
1826 else $part.=".MIME";
1828 if (iil_C_Select($conn, $mailbox)){
1830 $request=$key." FETCH $id (BODY.PEEK[$part])\r\n";
1831 if (!fputs($fp, $request)) return false;
1833 $line=chop(iil_ReadLine($fp, 200));
1834 $a=explode(" ", $line);
1835 if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
1836 $line=iil_ReadLine($fp, 300);
1837 while(chop($line)!=")"){
1839 $line=iil_ReadLine($fp, 300);
1842 }while(strcmp($a[0], $key)!=0);
1849 function iil_C_HandlePartBody(&$conn, $mailbox, $id, $part, $mode){
1857 if (($part==0)||(empty($part))) $part="TEXT";
1859 if (iil_C_Select($conn, $mailbox)){
1860 $reply_key="* ".$id;
1862 $key="ftch".($c++)." ";
1863 $request=$key."FETCH $id (BODY.PEEK[$part])\r\n";
1865 if (!fputs($fp, $request)) return false;
1866 // receive reply line
1868 $line = chop(iil_ReadLine($fp, 1000));
1869 $a = explode(" ", $line);
1870 }while ($a[2]!="FETCH");
1871 $len = strlen($line);
1872 if ($line[$len-1] == ")"){
1873 //one line response, get everything between first and last quotes
1874 $from = strpos($line, "\"") + 1;
1875 $to = strrpos($line, "\"");
1877 if ($mode==1) $result = substr($line, $from, $len);
1878 else if ($mode==2) echo substr($line, $from, $len);
1879 else if ($mode==3) echo base64_decode(substr($line, $from, $len));
1880 }else if ($line[$len-1] == "}"){
1881 //multi-line request, find sizes of content and receive that many bytes
1882 $from = strpos($line, "{") + 1;
1883 $to = strrpos($line, "}");
1885 $sizeStr = substr($line, $from, $len);
1886 $bytes = (int)$sizeStr;
1888 while ($received < $bytes){
1889 $remaining = $bytes - $received;
1890 $line = iil_ReadLine($fp, 1024);
1891 $len = strlen($line);
1892 if ($len > $remaining) $line = substr($line, 0, $remaining);
1893 $received += strlen($line);
1894 if ($mode==1) $result .= chop($line)."\n";
1895 else if ($mode==2){ echo chop($line)."\n"; flush(); }
1896 else if ($mode==3){ echo base64_decode($line); flush(); }
1899 // read in anything up until 'til last line
1901 $line = iil_ReadLine($fp, 1024);
1902 }while(!iil_StartsWith($line, $key));
1905 $result = chop($result);
1906 return $result; // substr($result, 0, strlen($result)-1);
1909 echo "Select failed.";
1912 if ($mode==1) return $result;
1913 else return $received;
1916 function iil_C_FetchPartBody(&$conn, $mailbox, $id, $part){
1917 return iil_C_HandlePartBody($conn, $mailbox, $id, $part, 1);
1920 function iil_C_PrintPartBody(&$conn, $mailbox, $id, $part){
1921 iil_C_HandlePartBody($conn, $mailbox, $id, $part, 2);
1924 function iil_C_PrintBase64Body(&$conn, $mailbox, $id, $part){
1925 iil_C_HandlePartBody($conn, $mailbox, $id, $part, 3);
1928 function iil_C_CreateFolder(&$conn, $folder){
1930 if (fputs($fp, "c CREATE \"".$folder."\"\r\n")){
1932 $line=iil_ReadLine($fp, 300);
1933 }while($line[0]!="c");
1934 $conn->error = $line;
1935 return (iil_ParseResult($line)==0);
1941 function iil_C_RenameFolder(&$conn, $from, $to){
1943 if (fputs($fp, "r RENAME \"".$from."\" \"".$to."\"\r\n")){
1945 $line=iil_ReadLine($fp, 300);
1946 }while($line[0]!="r");
1947 return (iil_ParseResult($line)==0);
1953 function iil_C_DeleteFolder(&$conn, $folder){
1955 if (fputs($fp, "d DELETE \"".$folder."\"\r\n")){
1957 $line=iil_ReadLine($fp, 300);
1958 }while($line[0]!="d");
1959 return (iil_ParseResult($line)==0);
1961 $conn->error = "Couldn't send command\n";
1966 function iil_C_Append(&$conn, $folder, &$message){
1967 if (!$folder) return false;
1970 $message = str_replace("\r", "", $message);
1971 $message = str_replace("\n", "\r\n", $message);
1973 $len = strlen($message);
1974 if (!$len) return false;
1976 $request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
1977 if (fputs($fp, $request)){
1978 $line=iil_ReadLine($fp, 100);
1979 $sent = fwrite($fp, $message."\r\n");
1982 $line=iil_ReadLine($fp, 1000);
1983 }while($line[0]!="A");
1985 $result = (iil_ParseResult($line)==0);
1986 if (!$result) $conn->error .= $line."\n";
1990 $conn->error .= "Couldn't send command \"$request\"\n";
1996 function iil_C_AppendFromFile(&$conn, $folder, $path){
1997 if (!$folder) return false;
2001 if (file_exists(realpath($path))) $in_fp = fopen($path, "r");
2003 $conn->error .= "Couldn't open $path for reading\n";
2008 $len = filesize($path);
2009 if (!$len) return false;
2011 //send APPEND command
2012 $request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
2014 if (fputs($fp, $request)){
2015 $line=iil_ReadLine($fp, 100);
2018 while(!feof($in_fp)){
2019 $buffer = fgets($in_fp, 4096);
2020 $bytes_sent += strlen($buffer);
2021 fputs($fp, $buffer);
2029 $line=iil_ReadLine($fp, 1000);
2030 }while($line[0]!="A");
2032 $result = (iil_ParseResult($line)==0);
2033 if (!$result) $conn->error .= $line."\n";
2037 $conn->error .= "Couldn't send command \"$request\"\n";
2043 function iil_C_FetchStructureString(&$conn, $folder, $id){
2046 if (iil_C_Select($conn, $folder)){
2048 if (fputs($fp, "$key FETCH $id (BODYSTRUCTURE)\r\n")){
2050 $line=chop(iil_ReadLine($fp, 5000));
2052 if (ereg("\}$", $line)){
2053 preg_match('/(.+)\{([0-9]+)\}/', $line, $match);
2054 $result = $match[1];
2056 $line = chop(iil_ReadLine($fp, 100));
2057 if (!preg_match("/^$key/", $line)) $result .= $line;
2063 list($pre, $post) = explode("BODYSTRUCTURE ", $result);
2064 $result = substr($post, 0, strlen($post)-1); //truncate last ')' and return
2066 }while (!preg_match("/^$key/",$line));
2072 function iil_C_PrintSource(&$conn, $folder, $id, $part){
2073 $header = iil_C_FetchPartHeader($conn, $folder, $id, $part);
2074 //echo str_replace("\r", "", $header);
2076 echo iil_C_PrintPartBody($conn, $folder, $id, $part);
2079 function iil_C_GetQuota(&$conn){
2081 b GETQUOTAROOT "INBOX"
2082 * QUOTAROOT INBOX user/rchijiiwa1
2083 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2090 //get line containing quota info
2091 if (fputs($fp, "QUOT1 GETQUOTAROOT \"INBOX\"\r\n")){
2093 $line=chop(iil_ReadLine($fp, 5000));
2094 if (iil_StartsWith($line, "* QUOTA ")) $quota_line = $line;
2095 }while(!iil_StartsWith($line, "QUOT1"));
2098 //return false if not found, parse if found
2099 if (!empty($quota_line)){
2100 $quota_line = eregi_replace("[()]", "", $quota_line);
2101 $parts = explode(" ", $quota_line);
2102 $storage_part = array_search("STORAGE", $parts);
2103 if ($storage_part>0){
2105 $used = $parts[$storage_part+1];
2106 $total = $parts[$storage_part+2];
2107 $result["used"] = $used;
2108 $result["total"] = (empty($total)?"??":$total);
2109 $result["percent"] = (empty($total)?"??":round(($used/$total)*100));
2110 $result["free"] = 100 - $result["percent"];
2118 function iil_C_ClearFolder(&$conn, $folder){
2119 $num_in_trash = iil_C_CountMessages($conn, $folder);
2120 if ($num_in_trash > 0) iil_C_Delete($conn, $folder, "1:".$num_in_trash);
2121 return (iil_C_Expunge($conn, $folder) >= 0);