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 - Abort do-loop on socket errors (fgets returns false)
52 - $ICL_SSL is not boolean anymore but contains the connection schema (ssl or tls)
53 - Removed some debuggers (echo ...)
54 File altered by Aleksander Machniak <alec@alec.pl>
55 - trim(chop()) replaced by trim()
56 - added iil_Escape()/iil_UnEscape() with support for " and \ in folder names
57 - support \ character in username in iil_C_Login()
58 - fixed iil_MultLine(): use iil_ReadBytes() instead of iil_ReadLine()
59 - fixed iil_C_FetchStructureString() to handle many literal strings in response
60 - removed hardcoded data size in iil_ReadLine()
61 - added iil_PutLine() wrapper for fputs()
62 - code cleanup and identation fixes
63 - removed flush() calls in iil_C_HandlePartBody() to prevent from memory leak (#1485187)
64 - don't return "??" from iil_C_GetQuota()
65 - RFC3501 [7.1] don't call CAPABILITY if was returned in server
66 optional resposne in iil_Connect(), added iil_C_GetCapability()
67 - remove 'undisclosed-recipients' string from 'To' header
68 - iil_C_HandlePartBody(): added 6th argument and fixed endless loop
69 - added iil_PutLineC()
70 - fixed iil_C_Sort() to support very long and/or divided responses
71 - added BYE/BAD response simple support for endless loop prevention
72 - added 3rd argument in iil_StartsWith* functions
73 - fix iil_C_FetchPartHeader() in some cases by use of iil_C_HandlePartBody()
74 - allow iil_C_HandlePartBody() to fetch whole message
75 - optimize iil_C_FetchHeaders() to use only one FETCH command
76 - added 4th argument to iil_Connect()
77 - allow setting rootdir and delimiter before connect
78 - support multiquota result
79 - include BODYSTRUCTURE in iil_C_FetchHeaders()
80 - added iil_C_FetchMIMEHeaders() function
81 - added \* flag support
82 - use PREG instead of EREG
83 - removed caching functions
84 - handling connection startup response
85 - added UID EXPUNGE support
86 - fixed problem with double quotes and spaces in folder names in LIST and LSUB
87 - rewritten iil_C_FetchHeaderIndex()
89 ********************************************************/
92 * @todo Possibly clean up more CS.
93 * @todo Try to replace most double-quotes with single-quotes.
94 * @todo Split this file into smaller files.
95 * @todo Refactor code.
96 * @todo Replace echo-debugging (make it adhere to config setting and log)
100 if (!isset($IMAP_USE_HEADER_DATE) || !$IMAP_USE_HEADER_DATE) {
101 $IMAP_USE_INTERNAL_DATE = true;
104 $GLOBALS['IMAP_FLAGS'] = array(
106 'DELETED' => '\\Deleted',
107 'RECENT' => '\\Recent',
108 'ANSWERED' => '\\Answered',
109 'DRAFT' => '\\Draft',
110 'FLAGGED' => '\\Flagged',
111 'FORWARDED' => '$Forwarded',
112 'MDNSENT' => '$MDNSent',
121 * @todo Change class vars to public/private
135 var $capability = array();
136 var $permanentflags = array();
137 var $capability_readed = false;
141 * @todo Change class vars to public/private
167 var $mdn_sent = false;
168 var $is_draft = false;
170 var $deleted = false;
172 var $answered = false;
173 var $forwarded = false;
175 var $flagged = false;
176 var $others = array();
180 * @todo Change class vars to public/private
182 class iilThreadHeader
190 function iil_xor($string, $string2) {
192 $size = strlen($string);
193 for ($i=0; $i<$size; $i++) {
194 $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
199 function iil_PutLine($fp, $string, $endln=true) {
202 if (!empty($my_prefs['debug_mode']))
203 write_log('imap', 'C: '. rtrim($string));
205 return fputs($fp, $string . ($endln ? "\r\n" : ''));
208 // iil_PutLine replacement with Command Continuation Requests (RFC3501 7.5) support
209 function iil_PutLineC($fp, $string, $endln=true) {
214 if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
215 for($i=0, $cnt=count($parts); $i<$cnt; $i++) {
216 if(preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
217 $res += iil_PutLine($fp, $parts[$i].$parts[$i+1], false);
218 $line = iil_ReadLine($fp, 1000);
219 // handle error in command
225 $res += iil_PutLine($fp, $parts[$i], false);
231 function iil_ReadLine($fp, $size=1024) {
245 $buffer = fgets($fp, $size);
247 if ($buffer === false) {
250 if (!empty($my_prefs['debug_mode']))
251 write_log('imap', 'S: '. chop($buffer));
253 } while ($buffer[strlen($buffer)-1] != "\n");
258 function iil_MultLine($fp, $line, $escape=false) {
260 if (preg_match('/\{[0-9]+\}$/', $line)) {
263 preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
265 while (strlen($out) < $bytes) {
266 $line = iil_ReadBytes($fp, $bytes);
270 $line = $a[1][0] . '"' . ($escape ? iil_Escape($out) : $out) . '"';
275 function iil_ReadBytes($fp, $bytes) {
280 $d = fread($fp, $bytes-$len);
281 if (!empty($my_prefs['debug_mode']))
282 write_log('imap', 'S: '. $d);
284 $data_len = strlen($data);
285 if ($len == $data_len) {
286 break; //nothing was read -> exit to avoid apache lockups
289 } while ($len < $bytes);
294 // don't use it in loops, until you exactly know what you're doing
295 function iil_ReadReply($fp) {
297 $line = trim(iil_ReadLine($fp, 1024));
298 } while ($line[0] == '*');
303 function iil_ParseResult($string) {
304 $a = explode(' ', trim($string));
305 if (count($a) >= 2) {
306 if (strcasecmp($a[1], 'OK') == 0) {
308 } else if (strcasecmp($a[1], 'NO') == 0) {
310 } else if (strcasecmp($a[1], 'BAD') == 0) {
312 } else if (strcasecmp($a[1], 'BYE') == 0) {
319 // check if $string starts with $match (or * BYE/BAD)
320 function iil_StartsWith($string, $match, $error=false) {
321 $len = strlen($match);
325 if (strncmp($string, $match, $len) == 0) {
328 if ($error && preg_match('/^\* (BYE|BAD) /i', $string)) {
334 function iil_StartsWithI($string, $match, $error=false) {
335 $len = strlen($match);
339 if (strncasecmp($string, $match, $len) == 0) {
342 if ($error && preg_match('/^\* (BYE|BAD) /i', $string)) {
349 function iil_Escape($string)
351 return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
354 function iil_UnEscape($string)
356 return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
359 function iil_C_GetCapability(&$conn, $name)
361 if (in_array($name, $conn->capability)) {
364 else if ($conn->capability_readed) {
368 // get capabilities (only once) because initial
369 // optional CAPABILITY response may differ
370 $conn->capability = array();
372 iil_PutLine($conn->fp, "cp01 CAPABILITY");
374 $line = trim(iil_ReadLine($conn->fp, 1024));
375 $a = explode(' ', $line);
376 if ($line[0] == '*') {
377 while (list($k, $w) = each($a)) {
378 if ($w != '*' && $w != 'CAPABILITY')
379 $conn->capability[] = strtoupper($w);
382 } while ($a[0] != 'cp01');
384 $conn->capability_readed = true;
386 if (in_array($name, $conn->capability)) {
393 function iil_C_ClearCapability(&$conn)
395 $conn->capability = array();
396 $conn->capability_readed = false;
399 function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge) {
404 // initialize ipad, opad
405 for ($i=0;$i<64;$i++) {
410 // pad $pass so it's 64 bytes
411 $padLen = 64 - strlen($pass);
412 for ($i=0;$i<$padLen;$i++) {
417 $hash = md5(iil_xor($pass,$opad) . pack("H*", md5(iil_xor($pass, $ipad) . base64_decode($encChallenge))));
420 $reply = base64_encode($user . ' ' . $hash);
422 // send result, get reply
423 iil_PutLine($conn->fp, $reply);
424 $line = iil_ReadLine($conn->fp, 1024);
427 $result = iil_ParseResult($line);
434 if ($result == -3) fclose($conn->fp); // BYE response
436 $conn->error .= 'Authentication for ' . $user . ' failed (AUTH): "';
437 $conn->error .= htmlspecialchars($line) . '"';
438 $conn->errorNum = $result;
443 function iil_C_Login(&$conn, $user, $password) {
445 iil_PutLine($conn->fp, 'a001 LOGIN "'.iil_Escape($user).'" "'.iil_Escape($password).'"');
447 $line = iil_ReadReply($conn->fp);
450 $result = iil_ParseResult($line);
460 $conn->error .= 'Authentication for ' . $user . ' failed (LOGIN): "';
461 $conn->error .= htmlspecialchars($line)."\"";
462 $conn->errorNum = $result;
467 function iil_ParseNamespace2($str, &$i, $len=0, $l) {
469 $str = str_replace('NIL', '()', $str);
477 for ($i;$i<$len;$i++) {
478 $c = (string)$str[$i];
479 if ($c == '(' && !$in_quotes) {
481 $data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
483 } else if ($c == ')' && !$in_quotes) {
485 } else if ($c == '\\') {
488 $data[$elem] .= $c.$str[$i];
490 } else if ($c == '"') {
491 $in_quotes = !$in_quotes;
495 } else if ($in_quotes) {
502 function iil_C_NameSpace(&$conn) {
505 if (isset($my_prefs['rootdir']) && is_string($my_prefs['rootdir'])) {
506 $conn->rootdir = $my_prefs['rootdir'];
510 if (!iil_C_GetCapability($conn, 'NAMESPACE')) {
514 iil_PutLine($conn->fp, "ns1 NAMESPACE");
516 $line = iil_ReadLine($conn->fp, 1024);
517 if (iil_StartsWith($line, '* NAMESPACE')) {
519 $line = iil_UnEscape($line);
520 $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
522 } while (!iil_StartsWith($line, 'ns1', true));
524 if (!is_array($data)) {
528 $user_space_data = $data[0];
529 if (!is_array($user_space_data)) {
533 $first_userspace = $user_space_data[0];
534 if (count($first_userspace)!=2) {
538 $conn->rootdir = $first_userspace[0];
539 $conn->delimiter = $first_userspace[1];
540 $my_prefs['rootdir'] = substr($conn->rootdir, 0, -1);
541 $my_prefs['delimiter'] = $conn->delimiter;
546 function iil_Connect($host, $user, $password, $options=null) {
547 global $iil_error, $iil_errornum;
548 global $ICL_SSL, $ICL_PORT;
549 global $my_prefs, $IMAP_USE_INTERNAL_DATE;
554 // set some imap options
555 if (is_array($options)) {
556 foreach($options as $optkey => $optval) {
557 if ($optkey == 'imap') {
558 $auth_method = $optval;
559 } else if ($optkey == 'rootdir') {
560 $my_prefs['rootdir'] = $optval;
561 } else if ($optkey == 'delimiter') {
562 $my_prefs['delimiter'] = $optval;
563 } else if ($optkey == 'debug_mode') {
564 $my_prefs['debug_mode'] = $optval;
569 if (empty($auth_method))
570 $auth_method = 'check';
572 $message = "INITIAL: $auth_method\n";
576 // initialize connection
577 $conn = new iilConnection;
580 $conn->selected = '';
584 if ($my_prefs['sort_field'] == 'INTERNALDATE') {
585 $IMAP_USE_INTERNAL_DATE = true;
586 } else if ($my_prefs['sort_field'] == 'DATE') {
587 $IMAP_USE_INTERNAL_DATE = false;
592 $iil_error = "Empty host";
597 $iil_error = "Empty user";
601 if (empty($password)) {
602 $iil_error = "Empty password";
611 if ($ICL_SSL && $ICL_SSL != 'tls') {
612 $host = $ICL_SSL . '://' . $host;
615 $conn->fp = fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
617 $iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
622 stream_set_timeout($conn->fp, 10);
623 $line = stream_get_line($conn->fp, 8192, "\r\n");
625 if ($my_prefs['debug_mode'] && $line)
626 write_log('imap', 'S: '. $line);
628 // Connected to wrong port or connection error?
629 if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
631 $iil_error = "Wrong startup greeting ($host:$ICL_PORT): $line";
633 $iil_error = "Empty startup greeting ($host:$ICL_PORT)";
638 // RFC3501 [7.1] optional CAPABILITY response
639 if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
640 $conn->capability = explode(' ', strtoupper($matches[1]));
643 $conn->message .= $line;
646 if ($ICL_SSL == 'tls' && iil_C_GetCapability($conn, 'STARTTLS')) {
647 if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
648 iil_PutLine($conn->fp, 'stls000 STARTTLS');
650 $line = iil_ReadLine($conn->fp, 4096);
651 if (!iil_StartsWith($line, 'stls000 OK')) {
652 $iil_error = "Server responded to STARTTLS with: $line";
657 if (!stream_socket_enable_crypto($conn->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
658 $iil_error = "Unable to negotiate TLS";
663 // Now we're authenticated, capabilities need to be reread
664 iil_C_ClearCapability($conn);
668 if (strcasecmp($auth_method, "check") == 0) {
669 //check for supported auth methods
670 if (iil_C_GetCapability($conn, 'AUTH=CRAM-MD5') || iil_C_GetCapability($conn, 'AUTH=CRAM_MD5')) {
671 $auth_method = 'auth';
674 //default to plain text auth
675 $auth_method = 'plain';
679 if (strcasecmp($auth_method, 'auth') == 0) {
680 $conn->message .= "Trying CRAM-MD5\n";
682 //do CRAM-MD5 authentication
683 iil_PutLine($conn->fp, "a000 AUTHENTICATE CRAM-MD5");
684 $line = trim(iil_ReadLine($conn->fp, 1024));
686 $conn->message .= "$line\n";
688 if ($line[0] == '+') {
689 $conn->message .= 'Got challenge: ' . htmlspecialchars($line) . "\n";
691 //got a challenge string, try CRAM-5
692 $result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
694 // stop if server sent BYE response
696 $iil_error = $conn->error;
697 $iil_errornum = $conn->errorNum;
700 $conn->message .= "Tried CRAM-MD5: $result \n";
702 $conn->message .='No challenge ('.htmlspecialchars($line)."), try plain\n";
707 if ((!$result)||(strcasecmp($auth, "plain") == 0)) {
709 $result = iil_C_Login($conn, $user, $password);
710 $conn->message .= "Tried PLAIN: $result \n";
713 $conn->message .= $auth;
715 if (!is_int($result)) {
716 iil_C_Namespace($conn);
719 $iil_error = $conn->error;
720 $iil_errornum = $conn->errorNum;
725 function iil_Close(&$conn) {
726 if (iil_PutLine($conn->fp, "I LOGOUT")) {
727 fgets($conn->fp, 1024);
733 function iil_ExplodeQuotedString($delimiter, $string) {
735 $strlen = strlen($string);
737 for ($q=$p=$i=0; $i < $strlen; $i++) {
738 if ($string[$i] == "\"" && $string[$i-1] != "\\") {
739 $q = $q ? false : true;
741 else if (!$q && preg_match("/$delimiter/", $string[$i])) {
742 $result[] = substr($string, $p, $i - $p);
747 $result[] = substr($string, $p);
751 function iil_CheckForRecent($host, $user, $password, $mailbox) {
752 if (empty($mailbox)) {
756 $conn = iil_Connect($host, $user, $password, 'plain');
759 iil_PutLine($fp, "a002 EXAMINE \"".iil_Escape($mailbox)."\"");
761 $line=chop(iil_ReadLine($fp, 300));
762 $a=explode(' ', $line);
763 if (($a[0] == '*') && (strcasecmp($a[2], 'RECENT') == 0)) {
764 $result = (int) $a[1];
766 } while (!iil_StartsWith($a[0], 'a002', true));
768 iil_PutLine($fp, "a003 LOGOUT");
777 function iil_C_Select(&$conn, $mailbox) {
779 if (empty($mailbox)) {
782 if (strcmp($conn->selected, $mailbox) == 0) {
786 if (iil_PutLine($conn->fp, "sel1 SELECT \"".iil_Escape($mailbox).'"')) {
788 $line = chop(iil_ReadLine($conn->fp, 300));
789 $a = explode(' ', $line);
790 if (count($a) == 3) {
791 if (strcasecmp($a[2], 'EXISTS') == 0) {
792 $conn->exists = (int) $a[1];
794 else if (strcasecmp($a[2], 'RECENT') == 0) {
795 $conn->recent = (int) $a[1];
798 else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
799 $conn->permanentflags = explode(' ', $match[1]);
801 } while (!iil_StartsWith($line, 'sel1', true));
803 $a = explode(' ', $line);
805 if (strcasecmp($a[1], 'OK') == 0) {
806 $conn->selected = $mailbox;
813 function iil_C_CheckForRecent(&$conn, $mailbox) {
814 if (empty($mailbox)) {
818 iil_C_Select($conn, $mailbox);
819 if ($conn->selected == $mailbox) {
820 return $conn->recent;
825 function iil_C_CountMessages(&$conn, $mailbox, $refresh = false) {
827 $conn->selected = '';
830 iil_C_Select($conn, $mailbox);
831 if ($conn->selected == $mailbox) {
832 return $conn->exists;
837 function iil_SplitHeaderLine($string) {
838 $pos=strpos($string, ':');
840 $res[0] = substr($string, 0, $pos);
841 $res[1] = trim(substr($string, $pos+1));
847 function iil_StrToTime($date) {
849 // support non-standard "GMTXXXX" literal
850 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
851 // if date parsing fails, we have a date in non-rfc format.
852 // remove token from the end and try again
853 while ((($ts = @strtotime($date))===false) || ($ts < 0))
855 $d = explode(' ', $date);
858 $date = implode(' ', $d);
863 return $ts < 0 ? 0 : $ts;
866 function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE,
867 $encoding = 'US-ASCII') {
869 $field = strtoupper($field);
870 if ($field == 'INTERNALDATE') {
874 $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
875 'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
877 if (!$fields[$field]) {
881 /* Do "SELECT" command */
882 if (!iil_C_Select($conn, $mailbox)) {
886 $is_uid = $is_uid ? 'UID ' : '';
892 $command = 's ' . $is_uid . 'SORT (' . $field . ') ';
893 $command .= $encoding . ' ALL' . $add;
896 if (!iil_PutLineC($conn->fp, $command)) {
900 $line = chop(iil_ReadLine($conn->fp));
901 if (iil_StartsWith($line, '* SORT')) {
902 $data .= substr($line, 7);
903 } else if (preg_match('/^[0-9 ]+$/', $line)) {
906 } while (!iil_StartsWith($line, 's ', true));
908 $result_code = iil_ParseResult($line);
910 if ($result_code != 0) {
911 $conn->error = 'iil_C_Sort: ' . $line . "\n";
915 return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
918 function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field='', $skip_deleted=true) {
920 list($from_idx, $to_idx) = explode(':', $message_set);
921 if (empty($message_set) ||
922 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
926 $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
928 $fields_a['DATE'] = 1;
929 $fields_a['INTERNALDATE'] = 4;
930 $fields_a['FROM'] = 1;
931 $fields_a['REPLY-TO'] = 1;
932 $fields_a['SENDER'] = 1;
934 $fields_a['SUBJECT'] = 1;
935 $fields_a['UID'] = 2;
936 $fields_a['SIZE'] = 2;
937 $fields_a['SEEN'] = 3;
938 $fields_a['RECENT'] = 3;
939 $fields_a['DELETED'] = 3;
941 if (!($mode = $fields_a[$index_field])) {
945 /* Do "SELECT" command */
946 if (!iil_C_Select($conn, $mailbox)) {
950 // build FETCH command string
952 $deleted = $skip_deleted ? ' FLAGS' : '';
955 $request = " FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
956 else if ($mode == 2) {
957 if ($index_field == 'SIZE')
958 $request = " FETCH $message_set (RFC822.SIZE$deleted)";
960 $request = " FETCH $message_set ($index_field$deleted)";
961 } else if ($mode == 3)
962 $request = " FETCH $message_set (FLAGS)";
964 $request = " FETCH $message_set (INTERNALDATE$deleted)";
966 $request = $key . $request;
968 if (!iil_PutLine($conn->fp, $request))
974 $line = chop(iil_ReadLine($conn->fp, 200));
975 $line = iil_MultLine($conn->fp, $line);
977 if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
982 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
983 $flags = explode(' ', strtoupper($matches[1]));
984 if (in_array('\\DELETED', $flags)) {
991 if (preg_match('/BODY\[HEADER\.FIELDS \("?(DATE|FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
992 $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
993 $value = trim($value);
994 if ($index_field == 'DATE') {
995 $result[$id] = iil_StrToTime($value);
997 $result[$id] = $value;
1002 } else if ($mode == 2) {
1003 if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
1004 $result[$id] = trim($matches[2]);
1008 } else if ($mode == 3) {
1009 if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
1010 $flags = explode(' ', $matches[1]);
1012 $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
1013 } else if ($mode == 4) {
1014 if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
1015 $result[$id] = iil_StrToTime($matches[1]);
1021 } while (!iil_StartsWith($line, $key, true));
1024 //check number of elements...
1025 if (is_numeric($from_idx) && is_numeric($to_idx)) {
1026 //count how many we should have
1027 $should_have = $to_idx - $from_idx + 1;
1029 //if we have less, try and fill in the "gaps"
1030 if (count($result) < $should_have) {
1031 for ($i=$from_idx; $i<=$to_idx; $i++) {
1032 if (!isset($result[$i])) {
1042 function iil_CompressMessageSet($message_set) {
1043 //given a comma delimited list of independent mid's,
1044 //compresses by grouping sequences together
1046 //if less than 255 bytes long, let's not bother
1047 if (strlen($message_set)<255) {
1048 return $message_set;
1051 //see if it's already been compress
1052 if (strpos($message_set, ':') !== false) {
1053 return $message_set;
1056 //separate, then sort
1057 $ids = explode(',', $message_set);
1061 $start = $prev = $ids[0];
1063 foreach ($ids as $id) {
1064 $incr = $id - $prev;
1065 if ($incr > 1) { //found a gap
1066 if ($start == $prev) {
1067 $result[] = $prev; //push single id
1069 $result[] = $start . ':' . $prev; //push sequence as start_id:end_id
1071 $start = $id; //start of new sequence
1076 //handle the last sequence/id
1077 if ($start==$prev) {
1080 $result[] = $start.':'.$prev;
1083 //return as comma separated string
1084 return implode(',', $result);
1087 function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids) {
1088 if (!is_array($uids) || count($uids) == 0) {
1091 return iil_C_Search($conn, $mailbox, 'UID ' . implode(',', $uids));
1094 function iil_C_UIDToMID(&$conn, $mailbox, $uid) {
1095 $result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
1096 if (count($result) == 1) {
1102 function iil_C_FetchUIDs(&$conn,$mailbox) {
1105 $num = iil_C_CountMessages($conn, $mailbox);
1109 $message_set = '1' . ($num>1?':' . $num:'');
1111 return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
1114 function iil_SortThreadHeaders($headers, $index_a, $uids) {
1117 foreach ($index_a as $mid=>$foobar) {
1119 $result[$uid] = $headers[$uid];
1124 function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set) {
1128 list($from_idx, $to_idx) = explode(':', $message_set);
1129 if (empty($message_set) || (isset($to_idx)
1130 && (int)$from_idx > (int)$to_idx)) {
1135 $uids = iil_C_FetchUIDs($conn, $mailbox);
1138 $message_set = iil_CompressMessageSet($message_set);
1140 /* if we're missing any, get them */
1142 /* FETCH date,from,subject headers */
1145 $request = $key . " FETCH $message_set ";
1146 $request .= "(BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])";
1147 $mid_to_id = array();
1148 if (!iil_PutLine($fp, $request)) {
1152 $line = chop(iil_ReadLine($fp, 1024));
1156 if (preg_match('/\{[0-9]+\}$/', $line)) {
1157 $a = explode(' ', $line);
1160 $new_thhd = new iilThreadHeader;
1161 $new_thhd->id = $a[1];
1163 $line = chop(iil_ReadLine($fp, 1024), "\r\n");
1164 if (iil_StartsWithI($line, 'Message-ID:')
1165 || (iil_StartsWithI($line,'In-Reply-To:'))
1166 || (iil_StartsWithI($line,'SUBJECT:'))) {
1168 $pos = strpos($line, ':');
1169 $field_name = substr($line, 0, $pos);
1170 $field_val = substr($line, $pos+1);
1172 $new[strtoupper($field_name)] = trim($field_val);
1174 } else if (preg_match('/^\s+/', $line)) {
1175 $new[strtoupper($field_name)] .= trim($line);
1177 } while ($line[0] != ')');
1179 $new_thhd->sbj = $new['SUBJECT'];
1180 $new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
1181 $new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
1183 $result[$uids[$new_thhd->id]] = $new_thhd;
1185 } while (!iil_StartsWith($line, 'fh'));
1189 if (is_array($index_a)) {
1190 $result = iil_SortThreadHeaders($result, $index_a, $uids);
1193 //echo 'iil_FetchThreadHeaders:'."\n";
1199 function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock) {
1202 list($from_idx, $to_idx) = explode(':', $message_set);
1203 if (empty($message_set) || (isset($to_idx)
1204 && (int)$from_idx > (int)$to_idx)) {
1210 $root_mids = array();
1211 $sub_mids = array();
1213 $messages = array();
1217 $sbj_filter_pat = '/[a-z]{2,3}(\[[0-9]*\])?:(\s*)/i';
1219 /* Do "SELECT" command */
1220 if (!iil_C_Select($conn, $mailbox)) {
1224 /* FETCH date,from,subject headers */
1225 $mid_to_id = array();
1226 $messages = array();
1227 $headers = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
1229 $clock->register('fetched headers');
1236 /* go through header records */
1237 foreach ($headers as $header) {
1238 //$id = $header['i'];
1239 //$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'],
1240 // 'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
1242 $new = array('id' => $id, 'MESSAGE-ID' => $header->mid,
1243 'IN-REPLY-TO' => $header->irt, 'SUBJECT' => $header->sbj);
1245 /* add to message-id -> mid lookup table */
1246 $mid_to_id[$new['MESSAGE-ID']] = $id;
1248 /* if no subject, use message-id */
1249 if (empty($new['SUBJECT'])) {
1250 $new['SUBJECT'] = $new['MESSAGE-ID'];
1253 /* if subject contains 'RE:' or has in-reply-to header, it's a reply */
1256 if (preg_match($sbj_filter_pat, $new['SUBJECT'])) {
1259 if ($has_re || $new['IN-REPLY-TO']) {
1263 /* strip out 're:', 'fw:' etc */
1265 $sbj = preg_replace($sbj_filter_pat, '', $new['SUBJECT']);
1267 $sbj = $new['SUBJECT'];
1269 $new['SUBJECT'] = $sbj_pre.$sbj;
1272 /* if subject not a known thread-root, add to list */
1274 echo $id . ' ' . $new['SUBJECT'] . "\t" . $new['MESSAGE-ID'] . "\n";
1276 $root_id = $roots[$sbj];
1278 if ($root_id && ($has_re || !$root_in_root[$root_id])) {
1280 echo "\tfound root: $root_id\n";
1282 $sub_mids[$new['MESSAGE-ID']] = $root_id;
1283 $result[$root_id][] = $id;
1284 } else if (!isset($roots[$sbj]) || (!$has_re && $root_in_root[$root_id])) {
1285 /* try to use In-Reply-To header to find root
1286 unless subject contains 'Re:' */
1287 if ($has_re&&$new['IN-REPLY-TO']) {
1289 echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
1291 //reply to known message?
1292 $temp = $sub_mids[$new['IN-REPLY-TO']];
1295 //found it, root:=parent's root
1297 echo "\tfound parent: ".$new['SUBJECT']."\n";
1299 $result[$temp][] = $id;
1300 $sub_mids[$new['MESSAGE-ID']] = $temp;
1303 //if we can't find referenced parent, it's a "stray"
1304 $strays[$id] = $new['IN-REPLY-TO'];
1308 //add subject as root
1311 echo "\t added to root\n";
1314 $root_in_root[$id] = !$has_re;
1315 $sub_mids[$new['MESSAGE-ID']] = $id;
1316 $result[$id] = array($id);
1319 echo $new['MESSAGE-ID'] . "\t" . $sbj . "\n";
1324 //now that we've gone through all the messages,
1325 //go back and try and link up the stray threads
1326 if (count($strays) > 0) {
1327 foreach ($strays as $id=>$irt) {
1328 $root_id = $sub_mids[$irt];
1329 if (!$root_id || $root_id==$id) {
1332 $result[$root_id] = array_merge($result[$root_id],$result[$id]);
1333 unset($result[$id]);
1338 $clock->register('data prepped');
1348 function iil_SortThreads(&$tree, $index, $sort_order = 'ASC') {
1349 if (!is_array($tree) || !is_array($index)) {
1353 //create an id to position lookup table
1355 foreach ($index as $id=>$val) {
1361 //for each tree, set array key to position
1363 foreach ($tree as $id=>$node) {
1364 if (count($tree[$id])<=1) {
1365 //for "threads" with only one message, key is position of that message
1367 $itree[$n] = array($n=>$id);
1369 //for "threads" with multiple messages,
1372 foreach ($tree[$id] as $mid) {
1373 $new_a[$index[$mid]] = $mid; //create new sub-array mapping position to id
1374 $pos = $index[$mid];
1375 if ($pos&&$pos<$min) {
1376 $min = $index[$mid]; //find smallest position
1379 $n = $min; //smallest position of child is thread position
1381 //assign smallest position to root level key
1382 //set children array to one created above
1384 $itree[$n] = $new_a;
1388 //sort by key, this basically sorts all threads
1392 foreach ($itree as $k=>$node) {
1393 $out[$i] = $itree[$k];
1400 function iil_IndexThreads(&$tree) {
1401 /* creates array mapping mid to thread id */
1403 if (!is_array($tree)) {
1408 foreach ($tree as $pos=>$kids) {
1409 foreach ($kids as $kid) $t_index[$kid] = $pos;
1415 function iil_C_FetchHeaders(&$conn, $mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1417 global $IMAP_USE_INTERNAL_DATE;
1422 /* Do "SELECT" command */
1423 if (!iil_C_Select($conn, $mailbox)) {
1424 $conn->error = "Couldn't select $mailbox";
1428 $message_set = iil_CompressMessageSet($message_set);
1431 $add = ' '.strtoupper(trim($add));
1433 /* FETCH uid, size, flags and headers */
1435 $request = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1436 $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1438 $request .= "BODYSTRUCTURE ";
1439 $request .= "BODY.PEEK[HEADER.FIELDS ";
1440 $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
1441 $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
1442 $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY".$add.")])";
1444 if (!iil_PutLine($fp, $request)) {
1448 $line = iil_ReadLine($fp, 1024);
1449 $line = iil_MultLine($fp, $line);
1451 $a = explode(' ', $line);
1452 if (($line[0] == '*') && ($a[2] == 'FETCH')) {
1455 $result[$id] = new iilBasicHeader;
1456 $result[$id]->id = $id;
1457 $result[$id]->subject = '';
1458 $result[$id]->messageID = 'mid:' . $id;
1464 * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1465 INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1466 BODY[HEADER.FIELDS ...
1469 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1472 // swap parents with quotes, then explode
1473 $str = preg_replace('/[()]/', '"', $str);
1474 $a = iil_ExplodeQuotedString(' ', $str);
1476 // did we get the right number of replies?
1477 $parts_count = count($a);
1478 if ($parts_count>=6) {
1479 for ($i=0; $i<$parts_count; $i=$i+2) {
1480 if (strcasecmp($a[$i],'UID') == 0)
1481 $result[$id]->uid = $a[$i+1];
1482 else if (strcasecmp($a[$i],'RFC822.SIZE') == 0)
1483 $result[$id]->size = $a[$i+1];
1484 else if (strcasecmp($a[$i],'INTERNALDATE') == 0)
1485 $time_str = $a[$i+1];
1486 else if (strcasecmp($a[$i],'FLAGS') == 0)
1487 $flags_str = $a[$i+1];
1490 $time_str = str_replace('"', '', $time_str);
1492 // if time is gmt...
1493 $time_str = str_replace('GMT','+0000',$time_str);
1495 $result[$id]->internaldate = $time_str;
1496 $result[$id]->timestamp = iil_StrToTime($time_str);
1497 $result[$id]->date = $time_str;
1502 while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1503 $line2 = iil_ReadLine($fp, 1024);
1504 $line .= iil_MultLine($fp, $line2, true);
1506 $result[$id]->body_structure = $m[1];
1509 // the rest of the result
1510 preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1511 $reslines = explode("\n", trim($m[1], '"'));
1512 // re-parse (see below)
1513 foreach ($reslines as $line) {
1514 if (ord($line[0])<=32) {
1515 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1517 $lines[++$ln] = trim($line);
1523 Start parsing headers. The problem is, some header "lines" take up multiple lines.
1524 So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1525 process the previous line. Otherwise, we'll keep adding the strings until we come
1526 to the next valid header line.
1530 $line = chop(iil_ReadLine($fp, 300), "\r\n");
1532 // The preg_match below works around communigate imap, which outputs " UID <number>)".
1533 // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1534 // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
1535 // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
1536 // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1537 // An alternative might be:
1538 // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1539 // however, unsure how well this would work with all imap clients.
1540 if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1544 // handle FLAGS reply after headers (AOL, Zimbra?)
1545 if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1546 $flags_str = $matches[1];
1550 if (ord($line[0])<=32) {
1551 $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1553 $lines[++$ln] = trim($line);
1555 // patch from "Maksim Rubis" <siburny@hotmail.com>
1556 } while (trim($line[0]) != ')' && strncmp($line, $key, strlen($key)));
1558 if (strncmp($line, $key, strlen($key))) {
1559 // process header, fill iilBasicHeader obj.
1561 if (is_array($headers)) {
1563 while (list($k, $bar) = each($headers)) {
1568 // create array with header field:data
1569 while ( list($lines_key, $str) = each($lines) ) {
1570 list($field, $string) = iil_SplitHeaderLine($str);
1572 $field = strtolower($field);
1573 $string = preg_replace('/\n\s*/', ' ', $string);
1577 if (!$IMAP_USE_INTERNAL_DATE) {
1578 $result[$id]->date = $string;
1579 $result[$id]->timestamp = iil_StrToTime($string);
1583 $result[$id]->from = $string;
1586 $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1589 $result[$id]->subject = $string;
1592 $result[$id]->replyto = $string;
1595 $result[$id]->cc = $string;
1598 $result[$id]->bcc = $string;
1600 case 'content-transfer-encoding':
1601 $result[$id]->encoding = $string;
1603 case 'content-type':
1604 $ctype_parts = explode(";", $string);
1605 $result[$id]->ctype = array_shift($ctype_parts);
1606 foreach ($ctype_parts as $ctype_add) {
1607 if (preg_match('/charset="?([a-z0-9\-\.\_]+)"?/i',
1608 $ctype_add, $regs)) {
1609 $result[$id]->charset = $regs[1];
1614 $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
1617 $result[$id]->references = $string;
1619 case 'return-receipt-to':
1620 case 'disposition-notification-to':
1621 case 'x-confirm-reading-to':
1622 $result[$id]->mdn_to = $string;
1625 $result[$id]->messageID = $string;
1628 if (preg_match('/^(\d+)/', $string, $matches))
1629 $result[$id]->priority = intval($matches[1]);
1632 if (strlen($field) > 2)
1633 $result[$id]->others[$field] = $string;
1638 $a = explode(' ', $line);
1642 if (!empty($flags_str)) {
1643 $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1644 $flags_a = explode(' ', $flags_str);
1646 if (is_array($flags_a)) {
1648 while (list(,$val)=each($flags_a)) {
1649 if (strcasecmp($val,'Seen') == 0) {
1650 $result[$id]->seen = true;
1651 } else if (strcasecmp($val, 'Deleted') == 0) {
1652 $result[$id]->deleted=true;
1653 } else if (strcasecmp($val, 'Recent') == 0) {
1654 $result[$id]->recent = true;
1655 } else if (strcasecmp($val, 'Answered') == 0) {
1656 $result[$id]->answered = true;
1657 } else if (strcasecmp($val, '$Forwarded') == 0) {
1658 $result[$id]->forwarded = true;
1659 } else if (strcasecmp($val, 'Draft') == 0) {
1660 $result[$id]->is_draft = true;
1661 } else if (strcasecmp($val, '$MDNSent') == 0) {
1662 $result[$id]->mdn_sent = true;
1663 } else if (strcasecmp($val, 'Flagged') == 0) {
1664 $result[$id]->flagged = true;
1667 $result[$id]->flags = $flags_a;
1671 } while (strcmp($a[0], $key) != 0);
1676 function iil_C_FetchHeader(&$conn, $mailbox, $id, $uidfetch=false, $bodystr=false, $add='') {
1678 $a = iil_C_FetchHeaders($conn, $mailbox, $id, $uidfetch, $bodystr, $add);
1680 return array_shift($a);
1685 function iil_SortHeaders($a, $field, $flag) {
1686 if (empty($field)) {
1689 $field = strtolower($field);
1690 if ($field == 'date' || $field == 'internaldate') {
1691 $field = 'timestamp';
1697 $flag = strtoupper($flag);
1698 $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1704 First, we'll create an "index" array.
1705 Then, we'll use sort() on that array,
1706 and use that to sort the main array.
1709 // create "index" array
1712 while (list($key, $val)=each($a)) {
1714 if ($field == 'timestamp') {
1715 $data = iil_StrToTime($val->date);
1717 $data = $val->timestamp;
1720 $data = $val->$field;
1721 if (is_string($data)) {
1722 $data=strtoupper(str_replace($stripArr, '', $data));
1730 if ($flag == 'ASC') {
1736 // form new array based on index
1739 while (list($key, $val)=each($index)) {
1740 $result[$key]=$a[$key];
1748 function iil_C_Expunge(&$conn, $mailbox, $messages=NULL) {
1750 if (iil_C_Select($conn, $mailbox)) {
1752 $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
1754 iil_PutLine($conn->fp, "exp1 $command");
1756 $line=chop(iil_ReadLine($conn->fp, 100));
1757 if ($line[0] == '*') {
1760 } while (!iil_StartsWith($line, 'exp1', true));
1762 if (iil_ParseResult($line) == 0) {
1763 $conn->selected = ''; //state has changed, need to reselect
1764 //$conn->exists-=$c;
1767 $conn->error = $line;
1773 function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod) {
1774 if ($mod != '+' && $mod != '-') {
1779 $flags = $GLOBALS['IMAP_FLAGS'];
1781 $flag = strtoupper($flag);
1782 $flag = $flags[$flag];
1784 if (iil_C_Select($conn, $mailbox)) {
1786 iil_PutLine($fp, "flg UID STORE $messages " . $mod . "FLAGS (" . $flag . ")");
1788 $line=chop(iil_ReadLine($fp, 100));
1789 if ($line[0] == '*') {
1792 } while (!iil_StartsWith($line, 'flg', true));
1794 if (iil_ParseResult($line) == 0) {
1797 $conn->error = $line;
1800 $conn->error = 'Select failed';
1804 function iil_C_Flag(&$conn, $mailbox, $messages, $flag) {
1805 return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '+');
1808 function iil_C_Unflag(&$conn, $mailbox, $messages, $flag) {
1809 return iil_C_ModFlag($conn, $mailbox, $messages, $flag, '-');
1812 function iil_C_Delete(&$conn, $mailbox, $messages) {
1813 return iil_C_ModFlag($conn, $mailbox, $messages, 'DELETED', '+');
1816 function iil_C_Copy(&$conn, $messages, $from, $to) {
1819 if (empty($from) || empty($to)) {
1823 if (iil_C_Select($conn, $from)) {
1826 iil_PutLine($fp, "cpy1 UID COPY $messages \"".iil_Escape($to)."\"");
1827 $line = iil_ReadReply($fp);
1828 return iil_ParseResult($line);
1834 function iil_C_CountUnseen(&$conn, $folder) {
1835 $index = iil_C_Search($conn, $folder, 'ALL UNSEEN');
1836 if (is_array($index))
1837 return count($index);
1841 function iil_C_UID2ID(&$conn, $folder, $uid) {
1843 $id_a = iil_C_Search($conn, $folder, "UID $uid");
1844 if (is_array($id_a) && count($id_a) == 1) {
1851 function iil_C_ID2UID(&$conn, $folder, $id) {
1857 if (iil_C_Select($conn, $folder)) {
1859 if (iil_PutLine($conn->fp, "$key FETCH $id (UID)")) {
1861 $line = chop(iil_ReadLine($conn->fp, 1024));
1862 if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1865 } while (!iil_StartsWith($line, $key, true));
1871 function iil_C_Search(&$conn, $folder, $criteria) {
1873 if (iil_C_Select($conn, $folder)) {
1876 $query = 'srch1 SEARCH ' . chop($criteria);
1877 if (!iil_PutLineC($conn->fp, $query)) {
1881 $line = trim(iil_ReadLine($conn->fp));
1882 if (iil_StartsWith($line, '* SEARCH')) {
1883 $data .= substr($line, 8);
1884 } else if (preg_match('/^[0-9 ]+$/', $line)) {
1887 } while (!iil_StartsWith($line, 'srch1', true));
1889 $result_code = iil_ParseResult($line);
1890 if ($result_code == 0) {
1891 return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
1893 $conn->error = 'iil_C_Search: ' . $line . "\n";
1896 $conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
1900 function iil_C_Move(&$conn, $messages, $from, $to) {
1902 if (!$from || !$to) {
1906 $r = iil_C_Copy($conn, $messages, $from, $to);
1909 return iil_C_Delete($conn, $from, $messages);
1915 * Gets the delimiter, for example:
1920 * @return mixed A delimiter (string), or false.
1921 * @param object $conn The current connection.
1922 * @see iil_Connect()
1924 function iil_C_GetHierarchyDelimiter(&$conn) {
1928 if ($conn->delimiter) {
1929 return $conn->delimiter;
1931 if (!empty($my_prefs['delimiter'])) {
1932 return ($conn->delimiter = $my_prefs['delimiter']);
1938 //try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
1939 if (!iil_PutLine($fp, 'ghd LIST "" ""')) {
1944 $line=iil_ReadLine($fp, 500);
1945 if ($line[0] == '*') {
1946 $line = rtrim($line);
1947 $a=iil_ExplodeQuotedString(' ', iil_UnEscape($line));
1949 $delimiter = str_replace('"', '', $a[count($a)-2]);
1952 } while (!iil_StartsWith($line, 'ghd', true));
1954 if (strlen($delimiter)>0) {
1958 //if that fails, try namespace extension
1959 //try to fetch namespace data
1960 iil_PutLine($conn->fp, "ns1 NAMESPACE");
1962 $line = iil_ReadLine($conn->fp, 1024);
1963 if (iil_StartsWith($line, '* NAMESPACE')) {
1965 $line = iil_UnEscape($line);
1966 $data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
1968 } while (!iil_StartsWith($line, 'ns1', true));
1970 if (!is_array($data)) {
1974 //extract user space data (opposed to global/shared space)
1975 $user_space_data = $data[0];
1976 if (!is_array($user_space_data)) {
1981 $first_userspace = $user_space_data[0];
1982 if (!is_array($first_userspace)) {
1987 $delimiter = $first_userspace[1];
1992 function iil_C_ListMailboxes(&$conn, $ref, $mailbox) {
1993 global $IGNORE_FOLDERS;
1995 $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
1999 if (empty($mailbox)) {
2003 if (empty($ref) && $conn->rootdir) {
2004 $ref = $conn->rootdir;
2008 if (!iil_PutLine($fp, "lmb LIST \"".$ref."\" \"".iil_Escape($mailbox)."\"")) {
2015 $line = iil_ReadLine($fp, 500);
2016 $line = iil_MultLine($fp, $line, true);
2018 $a = explode(' ', $line);
2019 if (($line[0] == '*') && ($a[1] == 'LIST')) {
2020 $line = rtrim($line);
2022 $a = iil_ExplodeQuotedString(' ', $line);
2023 // last string is folder name
2024 $folder = preg_replace(array('/^"/', '/"$/'), '', iil_UnEscape($a[count($a)-1]));
2026 if (empty($ignore) || (!empty($ignore)
2027 && !preg_match('/'.preg_quote(ignore, '/').'/i', $folder))) {
2028 $folders[$i] = $folder;
2031 // second from last is delimiter
2032 $delim = trim($a[count($a)-2], '"');
2033 // is it a container?
2036 } while (!iil_StartsWith($line, 'lmb', true));
2038 if (is_array($folders)) {
2040 // if rootdir was specified, make sure it's the first element
2041 // some IMAP servers (i.e. Courier) won't return it
2042 if ($ref[strlen($ref)-1]==$delim)
2043 $ref = substr($ref, 0, strlen($ref)-1);
2044 if ($folders[0]!=$ref)
2045 array_unshift($folders, $ref);
2048 } else if (iil_ParseResult($line) == 0) {
2049 return array('INBOX');
2051 $conn->error = $line;
2056 function iil_C_ListSubscribed(&$conn, $ref, $mailbox) {
2057 global $IGNORE_FOLDERS;
2059 $ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
2062 if (empty($mailbox)) {
2065 if (empty($ref) && $conn->rootdir) {
2066 $ref = $conn->rootdir;
2071 if (!iil_PutLine($fp, 'lsb LSUB "' . $ref . '" "' . iil_Escape($mailbox).'"')) {
2072 $conn->error = "Couldn't send LSUB command\n";
2080 $line = iil_ReadLine($fp, 500);
2081 $line = iil_MultLine($fp, $line, true);
2082 $a = explode(' ', $line);
2084 if (($line[0] == '*') && ($a[1] == 'LSUB' || $a[1] == 'LIST')) {
2085 $line = rtrim($line);
2088 $a = iil_ExplodeQuotedString(' ', $line);
2089 // last string is folder name
2090 $folder = preg_replace(array('/^"/', '/"$/'), '', iil_UnEscape($a[count($a)-1]));
2092 if ((!in_array($folder, $folders)) && (empty($ignore)
2093 || (!empty($ignore) && !preg_match('/'.preg_quote(ignore, '/').'/i', $folder)))) {
2094 $folders[$i] = $folder;
2097 // second from last is delimiter
2098 $delim = trim($a[count($a)-2], '"');
2100 // is it a container?
2103 } while (!iil_StartsWith($line, 'lsb', true));
2105 if (is_array($folders)) {
2107 // if rootdir was specified, make sure it's the first element
2108 // some IMAP servers (i.e. Courier) won't return it
2109 if ($ref[strlen($ref)-1]==$delim) {
2110 $ref = substr($ref, 0, strlen($ref)-1);
2112 if ($folders[0]!=$ref) {
2113 array_unshift($folders, $ref);
2118 $conn->error = $line;
2122 function iil_C_Subscribe(&$conn, $folder) {
2125 $query = 'sub1 SUBSCRIBE "' . iil_Escape($folder). '"';
2126 iil_PutLine($fp, $query);
2128 $line = trim(iil_ReadLine($fp, 512));
2129 return (iil_ParseResult($line) == 0);
2132 function iil_C_UnSubscribe(&$conn, $folder) {
2135 $query = 'usub1 UNSUBSCRIBE "' . iil_Escape($folder) . '"';
2136 iil_PutLine($fp, $query);
2138 $line = trim(iil_ReadLine($fp, 512));
2139 return (iil_ParseResult($line) == 0);
2142 function iil_C_FetchMIMEHeaders(&$conn, $mailbox, $id, $parts) {
2146 if (!iil_C_Select($conn, $mailbox)) {
2151 $parts = (array) $parts;
2157 foreach($parts as $part)
2158 $peeks[] = "BODY.PEEK[$part.MIME]";
2160 $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
2163 if (!iil_PutLine($fp, $request)) {
2168 $line = iil_ReadLine($fp, 1000);
2169 $line = iil_MultLine($fp, $line);
2171 if (preg_match('/BODY\[([0-9\.]+)\.MIME\]/', $line, $matches)) {
2173 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.MIME\]\s+/', '', $line);
2174 $result[$idx] = trim($result[$idx], '"');
2175 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
2177 } while (!iil_StartsWith($line, $key, true));
2182 function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $is_uid=false, $part=NULL) {
2184 $part = empty($part) ? 'HEADER' : $part.'.MIME';
2186 return iil_C_HandlePartBody($conn, $mailbox, $id, $is_uid, $part);
2189 function iil_C_HandlePartBody(&$conn, $mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL) {
2194 switch ($encoding) {
2198 case 'quoted-printable':
2211 if (iil_C_Select($conn, $mailbox)) {
2212 $reply_key = '* ' . $id;
2216 $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
2218 if (!iil_PutLine($fp, $request)) {
2222 // receive reply line
2224 $line = chop(iil_ReadLine($fp, 1000));
2225 $a = explode(' ', $line);
2226 } while (!($end = iil_StartsWith($line, $key, true)) && $a[2] != 'FETCH');
2227 $len = strlen($line);
2229 // handle empty "* X FETCH ()" response
2230 if ($line[$len-1] == ')' && $line[$len-2] != '(') {
2231 // one line response, get everything between first and last quotes
2232 if (substr($line, -4, 3) == 'NIL') {
2236 $from = strpos($line, '"') + 1;
2237 $to = strrpos($line, '"');
2239 $result = substr($line, $from, $len);
2243 $result = base64_decode($result);
2244 else if ($mode == 2)
2245 $result = quoted_printable_decode($result);
2246 else if ($mode == 3)
2247 $result = convert_uudecode($result);
2249 } else if ($line[$len-1] == '}') {
2250 //multi-line request, find sizes of content and receive that many bytes
2251 $from = strpos($line, '{') + 1;
2252 $to = strrpos($line, '}');
2254 $sizeStr = substr($line, $from, $len);
2255 $bytes = (int)$sizeStr;
2258 while ($bytes > 0) {
2259 $line = iil_ReadLine($fp, 1024);
2260 $len = strlen($line);
2262 if ($len > $bytes) {
2263 $line = substr($line, 0, $bytes);
2264 $len = strlen($line);
2269 $line = rtrim($line, "\t\r\n\0\x0B");
2270 // create chunks with proper length for base64 decoding
2271 $line = $prev.$line;
2272 $length = strlen($line);
2274 $length = floor($length / 4) * 4;
2275 $prev = substr($line, $length);
2276 $line = substr($line, 0, $length);
2282 fwrite($file, base64_decode($line));
2284 echo base64_decode($line);
2286 $result .= base64_decode($line);
2287 } else if ($mode == 2) {
2288 $line = rtrim($line, "\t\r\0\x0B");
2290 fwrite($file, quoted_printable_decode($line));
2292 echo quoted_printable_decode($line);
2294 $result .= quoted_printable_decode($line);
2295 } else if ($mode == 3) {
2296 $line = rtrim($line, "\t\r\n\0\x0B");
2297 if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
2300 fwrite($file, convert_uudecode($line));
2302 echo convert_uudecode($line);
2304 $result .= convert_uudecode($line);
2306 $line = rtrim($line, "\t\r\n\0\x0B");
2308 fwrite($file, $line . "\n");
2312 $result .= $line . "\n";
2317 // read in anything up until last line
2320 $line = iil_ReadLine($fp, 1024);
2321 } while (!iil_StartsWith($line, $key, true));
2324 $result = rtrim($result, "\t\r\n\0\x0B");
2326 fwrite($file, $result);
2327 } else if ($print) {
2330 return $result; // substr($result, 0, strlen($result)-1);
2339 function iil_C_CreateFolder(&$conn, $folder) {
2341 if (iil_PutLine($fp, 'c CREATE "' . iil_Escape($folder) . '"')) {
2343 $line=iil_ReadLine($fp, 300);
2344 } while (!iil_StartsWith($line, 'c ', true));
2345 return (iil_ParseResult($line) == 0);
2350 function iil_C_RenameFolder(&$conn, $from, $to) {
2352 if (iil_PutLine($fp, 'r RENAME "' . iil_Escape($from) . '" "' . iil_Escape($to) . '"')) {
2354 $line = iil_ReadLine($fp, 300);
2355 } while (!iil_StartsWith($line, 'r ', true));
2356 return (iil_ParseResult($line) == 0);
2361 function iil_C_DeleteFolder(&$conn, $folder) {
2363 if (iil_PutLine($fp, 'd DELETE "' . iil_Escape($folder). '"')) {
2365 $line=iil_ReadLine($fp, 300);
2366 } while (!iil_StartsWith($line, 'd ', true));
2367 return (iil_ParseResult($line) == 0);
2372 function iil_C_Append(&$conn, $folder, &$message) {
2378 $message = str_replace("\r", '', $message);
2379 $message = str_replace("\n", "\r\n", $message);
2381 $len = strlen($message);
2386 $request = 'a APPEND "' . iil_Escape($folder) .'" (\\Seen) {' . $len . '}';
2388 if (iil_PutLine($fp, $request)) {
2389 $line = iil_ReadLine($fp, 512);
2391 if ($line[0] != '+') {
2392 // $errornum = iil_ParseResult($line);
2393 $conn->error .= "Cannot write to folder: $line\n";
2397 iil_PutLine($fp, $message);
2400 $line = iil_ReadLine($fp);
2401 } while (!iil_StartsWith($line, 'a ', true));
2403 $result = (iil_ParseResult($line) == 0);
2405 $conn->error .= $line . "\n";
2410 $conn->error .= "Couldn't send command \"$request\"\n";
2414 function iil_C_AppendFromFile(&$conn, $folder, $path) {
2421 if (file_exists(realpath($path))) {
2422 $in_fp = fopen($path, 'r');
2425 $conn->error .= "Couldn't open $path for reading\n";
2430 $len = filesize($path);
2435 //send APPEND command
2436 $request = 'a APPEND "' . iil_Escape($folder) . '" (\\Seen) {' . $len . '}';
2437 if (iil_PutLine($fp, $request)) {
2438 $line = iil_ReadLine($fp, 512);
2440 if ($line[0] != '+') {
2441 //$errornum = iil_ParseResult($line);
2442 $conn->error .= "Cannot write to folder: $line\n";
2447 while (!feof($in_fp)) {
2448 $buffer = fgets($in_fp, 4096);
2449 iil_PutLine($fp, $buffer, false);
2453 iil_PutLine($fp, ''); // \r\n
2457 $line = iil_ReadLine($fp);
2458 } while (!iil_StartsWith($line, 'a ', true));
2460 $result = (iil_ParseResult($line) == 0);
2462 $conn->error .= $line . "\n";
2468 $conn->error .= "Couldn't send command \"$request\"\n";
2472 function iil_C_FetchStructureString(&$conn, $folder, $id, $is_uid=false) {
2476 if (iil_C_Select($conn, $folder)) {
2479 if (iil_PutLine($fp, $key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
2481 $line = iil_ReadLine($fp, 5000);
2482 $line = iil_MultLine($fp, $line, true);
2483 if (!preg_match("/^$key/", $line))
2485 } while (!iil_StartsWith($line, $key, true));
2487 $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2493 function iil_C_GetQuota(&$conn) {
2495 * GETQUOTAROOT "INBOX"
2496 * QUOTAROOT INBOX user/rchijiiwa1
2497 * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2502 $quota_lines = array();
2504 // get line(s) containing quota info
2505 if (iil_PutLine($fp, 'QUOT1 GETQUOTAROOT "INBOX"')) {
2507 $line=chop(iil_ReadLine($fp, 5000));
2508 if (iil_StartsWith($line, '* QUOTA ')) {
2509 $quota_lines[] = $line;
2511 } while (!iil_StartsWith($line, 'QUOT1', true));
2514 // return false if not found, parse if found
2515 $min_free = PHP_INT_MAX;
2516 foreach ($quota_lines as $key => $quota_line) {
2517 $quota_line = preg_replace('/[()]/', '', $quota_line);
2518 $parts = explode(' ', $quota_line);
2519 $storage_part = array_search('STORAGE', $parts);
2521 if (!$storage_part) continue;
2523 $used = intval($parts[$storage_part+1]);
2524 $total = intval($parts[$storage_part+2]);
2525 $free = $total - $used;
2527 // return lowest available space from all quotas
2528 if ($free < $min_free) {
2530 $result['used'] = $used;
2531 $result['total'] = $total;
2532 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2533 $result['free'] = 100 - $result['percent'];
2539 function iil_C_ClearFolder(&$conn, $folder) {
2540 $num_in_trash = iil_C_CountMessages($conn, $folder);
2541 if ($num_in_trash > 0) {
2542 iil_C_Delete($conn, $folder, '1:*');
2544 return (iil_C_Expunge($conn, $folder) >= 0);