8e1e1254fc7ff1ef3c7605933b7c30a9129d98ef
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This implements all functions that do general imap functions.
14 require_once(SM_PATH
. 'functions/page_header.php');
15 require_once(SM_PATH
. 'functions/auth.php');
18 global $sqimap_session_id;
19 $sqimap_session_id = 1;
21 /* Sets an unique session id in order to avoid simultanous sessions crash. */
22 function sqimap_session_id($unique_id = false) {
23 global $data_dir, $username, $sqimap_session_id;
25 return( sprintf("A%03d", $sqimap_session_id++
) );
27 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
32 * Both send a command and accept the result from the command.
33 * This is to allow proper session number handling.
35 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
37 $sid = sqimap_session_id($unique_id);
38 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
39 $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
42 global $squirrelmail_language, $color;
43 set_up_language($squirrelmail_language);
44 require_once(SM_PATH
. 'functions/display_messages.php');
45 $string = "<b><font color=$color[2]>\n" .
46 _("ERROR : No available imapstream.") .
48 error_box($string,$color);
54 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
56 $sid = sqimap_session_id($unique_id);
57 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
58 $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
61 global $squirrelmail_language, $color;
62 set_up_language($squirrelmail_language);
63 require_once(SM_PATH
. 'functions/display_messages.php');
64 $string = "<b><font color=$color[2]>\n" .
65 _("ERROR : No available imapstream.") .
67 error_box($string,$color);
75 * custom fgets function. gets a line from IMAP
76 * no matter how big it may be
79 function sqimap_fgets($imap_stream) {
85 while (strpos($results, "\r\n", $offset) === false) {
86 if (!($read = fgets($imap_stream, $buffer))) {
87 /* this happens in case of an error */
88 /* reset $results because it's useless */
92 if ( $results != '' ) {
93 $offset = strlen($results) - 1;
101 * Reads the output from the IMAP stream. If handle_errors is set to true,
102 * this will also handle all errors that are received. If it is not set,
103 * the errors will be sent back through $response and $message
106 function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
107 global $color, $squirrelmail_language;
109 $tag_uid_a = explode(' ',trim($tag_uid));
110 $tag = $tag_uid_a[0];
111 $resultlist = array();
113 $read = sqimap_fgets($imap_stream);
121 $read = sqimap_fgets($imap_stream);
126 /* get the command */
129 $s = substr($read,$i);
130 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
131 $arg = substr($s,0,$j);
133 $found_tag = substr($read,0,$i-1);
134 if ($arg && $found_tag==$tag) {
143 $message = trim(substr($read,$i+
strlen($arg)));
144 break 3; /* switch switch while */
146 /* this shouldn't happen */
148 $message = trim(substr($read,$i+
strlen($arg)));
149 break 3; /* switch switch while */
151 } elseif($found_tag !== $tag) {
152 /* reset data array because we do not need this reponse */
154 $read = sqimap_fgets($imap_stream);
157 } // end case $tag{0}
161 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
162 /* check for literal */
163 $s = substr($read,-3);
164 $fetch_data = array();
165 do { /* outer loop, continue until next untagged fetch
167 do { /* innerloop for fetching literals. with this loop
168 we prohibid that literal responses appear in the
169 outer loop so we can trust the untagged and
170 tagged info provided by $read */
171 if ($s === "}\r\n") {
172 $j = strrpos($read,'{');
173 $iLit = substr($read,$j+
1,-3);
174 $fetch_data[] = $read;
175 $sLiteral = fread($imap_stream,$iLit);
176 if ($sLiteral === false) { /* error */
177 break 4; /* while while switch while */
179 /* backwards compattibility */
180 $aLiteral = explode("\n", $sLiteral);
181 /* release not neaded data */
183 foreach ($aLiteral as $line) {
184 $fetch_data[] = $line ."\n";
186 /* release not neaded data */
188 /* next fgets belongs to this fetch because
189 we just got the exact literalsize and there
190 must follow data to complete the response */
191 $read = sqimap_fgets($imap_stream);
192 if ($read === false) { /* error */
193 break 4; /* while while switch while */
195 $fetch_data[] = $read;
197 $fetch_data[] = $read;
199 /* retrieve next line and check in the while
200 statements if it belongs to this fetch response */
201 $read = sqimap_fgets($imap_stream);
202 if ($read === false) { /* error */
203 break 4; /* while while switch while */
205 /* check for next untagged reponse and break */
206 if ($read{0} == '*') break 2;
207 $s = substr($read,-3);
208 } while ($s === "}\r\n");
209 $s = substr($read,-3);
210 } while ($read{0} !== '*' &&
211 substr($read,0,strlen($tag)) !== $tag);
212 $resultlist[] = $fetch_data;
213 /* release not neaded data */
216 $s = substr($read,-3);
218 if ($s === "}\r\n") {
219 $j = strrpos($read,'{');
220 $iLit = substr($read,$j+
1,-3);
222 $sLiteral = fread($imap_stream,$iLit);
223 if ($sLiteral === false) { /* error */
225 break 3; /* while switch while */
228 $fetch_data[] = sqimap_fgets($imap_stream);
232 $read = sqimap_fgets($imap_stream);
233 if ($read && $read{0} == '*') break;
234 $s = substr($read,-3);
235 } while ($s === "}\r\n");
243 /* error processing in case $read is false */
244 if ($read === false) {
246 set_up_language($squirrelmail_language);
247 require_once(SM_PATH
. 'functions/display_messages.php');
248 $string = "<b><font color=$color[2]>\n" .
249 _("ERROR : Connection dropped by imap-server.") .
252 htmlspecialchars($query) . '<br>' . "</font><br>\n";
253 error_box($string,$color);
257 /* Set $resultlist array */
259 $resultlist[] = $data;
261 elseif (empty($resultlist)) {
262 $resultlist[] = array();
265 /* Return result or handle errors */
266 if ($handle_errors == false) {
267 return( $resultlist );
269 elseif ($response == 'NO') {
270 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
271 if (strstr($message, 'command resulted in') === false) {
272 set_up_language($squirrelmail_language);
273 require_once(SM_PATH
. 'functions/display_messages.php');
274 $string = "<b><font color=$color[2]>\n" .
275 _("ERROR : Could not complete request.") .
278 htmlspecialchars($query) . '<br>' .
279 _("Reason Given: ") .
280 htmlspecialchars($message) . "</font><br>\n";
281 error_box($string,$color);
285 elseif ($response == 'BAD') {
286 set_up_language($squirrelmail_language);
287 require_once(SM_PATH
. 'functions/display_messages.php');
288 $string = "<b><font color=$color[2]>\n" .
289 _("ERROR : Bad or malformed request.") .
292 htmlspecialchars($query) . '<br>' .
293 _("Server responded: ") .
294 htmlspecialchars($message) . "</font><br>\n";
295 error_box($string,$color);
303 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
304 $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors, $response, $message, $query);
306 /* sqimap_read_data should be called for one response
307 but since it just calls sqimap_read_data_list which
308 handles multiple responses we need to check for that
309 and merge the $res array IF they are seperated and
310 IF it was a FETCH response. */
312 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
313 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
314 // $result = array();
315 // foreach($res as $index=>$value) {
316 // $result = array_merge($result, $res["$index"]);
319 if (isset($result)) {
329 * Logs the user into the imap server. If $hide is set, no error messages
330 * will be displayed. This function returns the imap connection handle.
332 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
333 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
335 if (!isset($onetimepad) ||
empty($onetimepad)) {
336 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
338 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
339 $host=$imap_server_address;
341 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
342 /* Use TLS by prefixing "tls://" to the hostname */
343 $imap_server_address = 'tls://' . $imap_server_address;
346 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
348 /* Do some error correction */
351 set_up_language($squirrelmail_language, true);
352 require_once(SM_PATH
. 'functions/display_messages.php');
353 $string = sprintf (_("Error connecting to IMAP server: %s.") .
354 "<br>\r\n", $imap_server_address) .
355 "$error_number : $error_string<br>\r\n";
356 logout_error($string,$color);
361 $server_info = fgets ($imap_stream, 1024);
363 /* Decrypt the password */
364 $password = OneTimePadDecrypt($password, $onetimepad);
366 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
367 // We're using some sort of authentication OTHER than plain or login
368 $tag=sqimap_session_id(false);
369 if ($imap_auth_mech == 'digest-md5') {
370 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
371 } elseif ($imap_auth_mech == 'cram-md5') {
372 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
374 fputs($imap_stream,$query);
375 $answer=sqimap_fgets($imap_stream);
376 // Trim the "+ " off the front
377 $response=explode(" ",$answer,3);
378 if ($response[0] == '+') {
379 // Got a challenge back
380 $challenge=$response[1];
381 if ($imap_auth_mech == 'digest-md5') {
382 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
383 } elseif ($imap_auth_mech == 'cram-md5') {
384 $reply = cram_md5_response($username,$password,$challenge);
386 fputs($imap_stream,$reply);
387 $read=sqimap_fgets($imap_stream);
388 if ($imap_auth_mech == 'digest-md5') {
389 // DIGEST-MD5 has an extra step..
390 if (substr($read,0,1) == '+') { // OK so far..
391 fputs($imap_stream,"\r\n");
392 $read=sqimap_fgets($imap_stream);
395 $results=explode(" ",$read,3);
396 $response=$results[1];
397 $message=$results[2];
399 // Fake the response, so the error trap at the bottom will work
401 $message='IMAP server does not appear to support the authentication method selected.';
402 $message .= ' Please contact your system administrator.';
404 } elseif ($imap_auth_mech == 'login') {
405 // Original IMAP login code
406 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
407 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
408 } elseif ($imap_auth_mech == 'plain') {
409 /* Replace this with SASL PLAIN if it ever gets implemented */
411 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
414 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
417 /* If the connection was not successful, lets see why */
418 if ($response != 'OK') {
420 if ($response != 'NO') {
421 /* "BAD" and anything else gets reported here. */
422 $message = htmlspecialchars($message);
423 set_up_language($squirrelmail_language, true);
424 require_once(SM_PATH
. 'functions/display_messages.php');
425 if ($response == 'BAD') {
426 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
428 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
430 if (isset($read) && is_array($read)) {
431 $string .= '<br>' . _("Read data:") . "<br>\n";
432 foreach ($read as $line) {
433 $string .= htmlspecialchars($line) . "<br>\n";
436 error_box($string,$color);
440 * If the user does not log in with the correct
441 * username and password it is not possible to get the
442 * correct locale from the user's preferences.
443 * Therefore, apply the same hack as on the login
446 * $squirrelmail_language is set by a cookie when
447 * the user selects language and logs out
450 set_up_language($squirrelmail_language, true);
451 include_once(SM_PATH
. 'functions/display_messages.php' );
453 logout_error( _("Unknown user or password incorrect.") );
463 /* Simply logs out the IMAP session */
464 function sqimap_logout ($imap_stream) {
465 /* Logout is not valid until the server returns 'BYE'
466 * If we don't have an imap_ stream we're already logged out */
467 if(isset($imap_stream) && $imap_stream)
468 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
471 function sqimap_capability($imap_stream, $capability='') {
472 global $sqimap_capabilities;
473 if (!is_array($sqimap_capabilities)) {
474 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
476 $c = explode(' ', $read[0]);
477 for ($i=2; $i < count($c); $i++
) {
478 $cap_list = explode('=', $c[$i]);
479 if (isset($cap_list[1])) {
480 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
482 $sqimap_capabilities[$cap_list[0]] = TRUE;
487 if (isset($sqimap_capabilities[$capability])) {
488 return $sqimap_capabilities[$capability];
493 return $sqimap_capabilities;
496 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
497 function sqimap_get_delimiter ($imap_stream = false) {
498 global $sqimap_delimiter, $optional_delimiter;
500 /* Use configured delimiter if set */
501 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
502 return $optional_delimiter;
505 /* Do some caching here */
506 if (!$sqimap_delimiter) {
507 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
509 * According to something that I can't find, this is supposed to work on all systems
510 * OS: This won't work in Courier IMAP.
511 * OS: According to rfc2342 response from NAMESPACE command is:
512 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
513 * OS: We want to lookup all personal NAMESPACES...
515 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
516 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
517 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
520 $pna = explode(')(', $pn);
521 while (list($k, $v) = each($pna)) {
522 $lst = explode('"', $v);
523 if (isset($lst[3])) {
524 $pn[$lst[1]] = $lst[3];
530 $sqimap_delimiter = $pn[0];
532 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
533 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
534 $quote_position = strpos ($read[0], '"');
535 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
538 return $sqimap_delimiter;
542 /* Gets the number of messages in the current mailbox. */
543 function sqimap_get_num_messages ($imap_stream, $mailbox) {
544 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
545 for ($i = 0; $i < count($read_ary); $i++
) {
546 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
550 return false; //"BUG! Couldn't get number of messages in $mailbox!";
554 function parseAddress($address, $max=0, $addr_ar = array(), $group = '', $host='', $limit=0) {
556 $j = strlen($address);
560 if ($max && $max == count($addr_ar)) {
564 if ($max && $max == count($addr_ar)) {
567 $char = $address{$pos};
570 /* check if it is an encoded string */
571 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',substr($address,$pos),$reg)) {
572 /* add stringpart before the encoded string to the personal var */
574 $personal = substr($address,0,$pos);
576 $personal .= $reg[1];
577 $pos +
= strlen($reg[1]);
582 case '"': /* get the personal name */
584 if ($address{$pos} == '"') {
587 $personal_start = $personal_end = $pos;
589 $personal_end = strpos($address,'"',$pos);
590 if (($personal_end-2)>0 && (substr($address,$personal_end-2,2) === '\\"' ||
591 substr($address,$personal_end-2,2) === '\\\\')) {
592 $pos = $personal_end+
1;
594 $personal = substr($address,$personal_start,$personal_end-$personal_start);
598 if ($personal_end) { /* prohibit endless loops due to very wrong addresses */
599 $pos = $personal_end+
1;
605 case '<': /* get email address */
607 $addr_end = strpos($address,'>',$addr_start);
608 if($addr_end === FALSE) {
609 // in case the address doesn't end, prevent loop
612 $addr = substr($address,$addr_start+
1,$addr_end-$addr_start-1);
616 case '(': /* rip off comments */
618 $pos = strpos($address,')');
619 if ($pos !== false) {
620 $comment = substr($address, $addr_start+
1,($pos-$addr_start-1));
621 $address_start = substr($address, 0, $addr_start);
622 $address_end = substr($address, $pos +
1);
623 $address = $address_start . $address_end;
625 $j = strlen($address);
626 $pos = $addr_start +
1;
628 case ';': /* we reached a non rfc2822 compliant delimiter */
630 $address = substr($address, 0, $pos - 1);
634 case ',': /* we reached a delimiter */
636 $addr = substr($address, 0, $pos);
637 } else if ($personal == '') {
638 $personal = trim(substr($address, 0, $addr_start));
640 if (!$personal && $comment) $personal = $comment;
641 if ($personal) $personal = decodeHeader($personal);
642 $addr_ar[] = array($addr,$personal);
643 $address = trim(substr($address, $pos+
1));
644 $j = strlen($address);
649 case ':': /* process the group addresses */
651 $group = substr($address, 0, $pos);
652 $address = substr($address, $pos+
1);
653 $result = parseAddress($address, $max, $addr_ar, $group);
654 $addr_ar = $result[0];
656 $address = substr($address, $pos++
);
657 $j = strlen($address);
666 $addr = substr($address, 0, $pos);
667 } else if ($personal == '') {
668 $personal = trim(substr($address, 0, $addr_start));
670 if (!$personal && $comment) $personal = $comment;
672 if ($group && $addr == '') { /* no addresses found in group */
674 $addr_ar[] = array('',$personal);
675 return (array($addr_ar,$pos+
1 ));
677 $addr_ar[] = array($addr,$personal);
678 return (array($addr_ar,$pos+
1 ));
680 if ($personal ||
$addr) {
681 $addr_ar[] = array($addr, $personal);
688 * Returns the number of unseen messages in this folder
690 function sqimap_unseen_messages ($imap_stream, $mailbox) {
691 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
693 $regs = array(false, false);
694 while (isset($read_ary[$i])) {
695 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
704 * Returns the number of unseen/total messages in this folder
706 function sqimap_status_messages ($imap_stream, $mailbox) {
707 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
709 $messages = $unseen = $recent = false;
710 $regs = array(false,false);
711 while (isset($read_ary[$i])) {
712 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
715 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
716 $messages = $regs[1];
718 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
723 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
728 * Saves a message to a given folder -- used for saving sent messages
730 function sqimap_append ($imap_stream, $sent_folder, $length) {
731 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
732 $tmp = fgets ($imap_stream, 1024);
735 function sqimap_append_done ($imap_stream, $folder='') {
736 global $squirrelmail_language, $color;
737 fputs ($imap_stream, "\r\n");
738 $tmp = fgets ($imap_stream, 1024);
739 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
740 set_up_language($squirrelmail_language);
741 require_once(SM_PATH
. 'functions/display_messages.php');
743 if ($regs[2] == 'NO') {
744 $string = "<b><font color=$color[2]>\n" .
745 _("ERROR : Could not append message to") ." $folder." .
747 _("Server responded: ") .
749 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
750 $string .= _("Solution: ") .
751 _("Remove unneccessary messages from your folder and start with your Trash folder.")
754 $string .= "</font>\n";
755 error_box($string,$color);
757 $string = "<b><font color=$color[2]>\n" .
758 _("ERROR : Bad or malformed request.") .
760 _("Server responded: ") .
761 $tmp . "</font><br>\n";
762 error_box($string,$color);
768 function sqimap_get_user_server ($imap_server, $username) {
769 if (substr($imap_server, 0, 4) != "map:") {
772 $function = substr($imap_server, 4);
773 return $function($username);
776 /* This is an example that gets imapservers from yellowpages (NIS).
777 * you can simple put map:map_yp_alias in your $imap_server_address
778 * in config.php use your own function instead map_yp_alias to map your
779 * LDAP whatever way to find the users imapserver. */
781 function map_yp_alias($username) {
782 $yp = `ypmatch
$username aliases`
;
783 return chop(substr($yp, strlen($username)+
1));