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))) {
89 if ( $results != '' ) {
90 $offset = strlen($results) - 1;
98 * Reads the output from the IMAP stream. If handle_errors is set to true,
99 * this will also handle all errors that are received. If it is not set,
100 * the errors will be sent back through $response and $message
103 function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
104 global $color, $squirrelmail_language;
106 $tag_uid_a = explode(' ',trim($tag_uid));
107 $tag = $tag_uid_a[0];
108 $resultlist = array();
110 $read = sqimap_fgets($imap_stream);
118 $read = sqimap_fgets($imap_stream);
123 /* get the command */
126 $s = substr($read,$i);
127 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
128 $arg = substr($s,0,$j);
130 $found_tag = substr($read,0,$i-1);
131 if ($arg && $found_tag==$tag) {
140 $message = trim(substr($read,$i+
strlen($arg)));
143 /* this shouldn't happen */
145 $message = trim(substr($read,$i+
strlen($arg)));
148 } elseif($found_tag !== $tag) {
149 /* reset data array because we do not need this reponse */
151 $read = sqimap_fgets($imap_stream);
154 } // end case $tag{0}
158 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
159 /* check for literal */
160 $s = substr($read,-3);
161 $fetch_data = array();
162 do { /* outer loop, continue until next untagged fetch
164 do { /* innerloop for fetching literals. with this loop
165 we prohibid that literal responses appear in the
166 outer loop so we can trust the untagged and
167 tagged info provided by $read */
168 if ($s === "}\r\n") {
169 $j = strrpos($read,'{');
170 $iLit = substr($read,$j+
1,-3);
171 $fetch_data[] = $read;
172 $sLiteral = fread($imap_stream,$iLit);
173 /* backwards compattibility */
174 $aLiteral = explode("\n", $sLiteral);
175 /* release not neaded data */
177 foreach ($aLiteral as $line) {
178 $fetch_data[] = $line ."\n";
180 /* release not neaded data */
182 /* next fgets belongs to this fetch because
183 we just got the exact literalsize and there
184 must follow data to complete the response */
185 $fetch_data[] = sqimap_fgets($imap_stream);
187 $fetch_data[] = $read;
189 /* retrieve next line and check in the while
190 statements if it belongs to this fetch response */
191 $read = sqimap_fgets($imap_stream);
192 /* check for next untagged reponse and break */
193 if ($read{0} == '*') break 2;
194 $s = substr($read,-3);
195 } while ($s === "}\r\n");
196 $s = substr($read,-3);
197 } while ($read{0} !== '*' &&
198 substr($read,0,strlen($tag)) !== $tag);
199 $resultlist[] = $fetch_data;
200 /* release not neaded data */
203 $s = substr($read,-3);
205 if ($s === "}\r\n") {
206 $j = strrpos($read,'{');
207 $iLit = substr($read,$j+
1,-3);
209 $data[] = fread($imap_stream,$iLit);
210 $fetch_data[] = sqimap_fgets($imap_stream);
214 $read = sqimap_fgets($imap_stream);
215 if ($read{0} == '*') break;
216 $s = substr($read,-3);
217 } while ($s === "}\r\n");
225 /* Set $resultlist array */
227 $resultlist[] = $data;
229 elseif (empty($resultlist)) {
230 $resultlist[] = array();
233 /* Return result or handle errors */
234 if ($handle_errors == false) {
235 return( $resultlist );
237 elseif ($response == 'NO') {
238 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
239 if (strstr($message, 'command resulted in') === false) {
240 set_up_language($squirrelmail_language);
241 require_once(SM_PATH
. 'functions/display_messages.php');
242 $string = "<b><font color=$color[2]>\n" .
243 _("ERROR : Could not complete request.") .
246 htmlspecialchars($query) . '<br>' .
247 _("Reason Given: ") .
248 htmlspecialchars($message) . "</font><br>\n";
249 error_box($string,$color);
253 elseif ($response == 'BAD') {
254 set_up_language($squirrelmail_language);
255 require_once(SM_PATH
. 'functions/display_messages.php');
256 $string = "<b><font color=$color[2]>\n" .
257 _("ERROR : Bad or malformed request.") .
260 htmlspecialchars($query) . '<br>' .
261 _("Server responded: ") .
262 htmlspecialchars($message) . "</font><br>\n";
263 error_box($string,$color);
271 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
272 $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors, $response, $message, $query);
274 /* sqimap_read_data should be called for one response
275 but since it just calls sqimap_read_data_list which
276 handles multiple responses we need to check for that
277 and merge the $res array IF they are seperated and
278 IF it was a FETCH response. */
280 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
281 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
282 // $result = array();
283 // foreach($res as $index=>$value) {
284 // $result = array_merge($result, $res["$index"]);
287 if (isset($result)) {
297 * Logs the user into the imap server. If $hide is set, no error messages
298 * will be displayed. This function returns the imap connection handle.
300 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
301 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
303 if (!isset($onetimepad) ||
empty($onetimepad)) {
304 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
306 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
307 $host=$imap_server_address;
309 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
310 /* Use TLS by prefixing "tls://" to the hostname */
311 $imap_server_address = 'tls://' . $imap_server_address;
314 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
316 /* Do some error correction */
319 set_up_language($squirrelmail_language, true);
320 require_once(SM_PATH
. 'functions/display_messages.php');
321 $string = sprintf (_("Error connecting to IMAP server: %s.") .
322 "<br>\r\n", $imap_server_address) .
323 "$error_number : $error_string<br>\r\n";
324 logout_error($string,$color);
329 $server_info = fgets ($imap_stream, 1024);
331 /* Decrypt the password */
332 $password = OneTimePadDecrypt($password, $onetimepad);
334 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
335 // We're using some sort of authentication OTHER than plain or login
336 $tag=sqimap_session_id(false);
337 if ($imap_auth_mech == 'digest-md5') {
338 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
339 } elseif ($imap_auth_mech == 'cram-md5') {
340 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
342 fputs($imap_stream,$query);
343 $answer=sqimap_fgets($imap_stream);
344 // Trim the "+ " off the front
345 $response=explode(" ",$answer,3);
346 if ($response[0] == '+') {
347 // Got a challenge back
348 $challenge=$response[1];
349 if ($imap_auth_mech == 'digest-md5') {
350 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
351 } elseif ($imap_auth_mech == 'cram-md5') {
352 $reply = cram_md5_response($username,$password,$challenge);
354 fputs($imap_stream,$reply);
355 $read=sqimap_fgets($imap_stream);
356 if ($imap_auth_mech == 'digest-md5') {
357 // DIGEST-MD5 has an extra step..
358 if (substr($read,0,1) == '+') { // OK so far..
359 fputs($imap_stream,"\r\n");
360 $read=sqimap_fgets($imap_stream);
363 $results=explode(" ",$read,3);
364 $response=$results[1];
365 $message=$results[2];
367 // Fake the response, so the error trap at the bottom will work
369 $message='IMAP server does not appear to support the authentication method selected.';
370 $message .= ' Please contact your system administrator.';
372 } elseif ($imap_auth_mech == 'login') {
373 // Original IMAP login code
374 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
375 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
376 } elseif ($imap_auth_mech == 'plain') {
377 /* Replace this with SASL PLAIN if it ever gets implemented */
379 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
382 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
385 /* If the connection was not successful, lets see why */
386 if ($response != 'OK') {
388 if ($response != 'NO') {
389 /* "BAD" and anything else gets reported here. */
390 $message = htmlspecialchars($message);
391 set_up_language($squirrelmail_language, true);
392 require_once(SM_PATH
. 'functions/display_messages.php');
393 if ($response == 'BAD') {
394 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
396 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
398 if (isset($read) && is_array($read)) {
399 $string .= '<br>' . _("Read data:") . "<br>\n";
400 foreach ($read as $line) {
401 $string .= htmlspecialchars($line) . "<br>\n";
404 error_box($string,$color);
408 * If the user does not log in with the correct
409 * username and password it is not possible to get the
410 * correct locale from the user's preferences.
411 * Therefore, apply the same hack as on the login
414 * $squirrelmail_language is set by a cookie when
415 * the user selects language and logs out
418 set_up_language($squirrelmail_language, true);
419 include_once(SM_PATH
. 'functions/display_messages.php' );
421 logout_error( _("Unknown user or password incorrect.") );
431 /* Simply logs out the IMAP session */
432 function sqimap_logout ($imap_stream) {
433 /* Logout is not valid until the server returns 'BYE'
434 * If we don't have an imap_ stream we're already logged out */
435 if(isset($imap_stream) && $imap_stream)
436 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
439 function sqimap_capability($imap_stream, $capability='') {
440 global $sqimap_capabilities;
441 if (!is_array($sqimap_capabilities)) {
442 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
444 $c = explode(' ', $read[0]);
445 for ($i=2; $i < count($c); $i++
) {
446 $cap_list = explode('=', $c[$i]);
447 if (isset($cap_list[1])) {
448 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
450 $sqimap_capabilities[$cap_list[0]] = TRUE;
455 if (isset($sqimap_capabilities[$capability])) {
456 return $sqimap_capabilities[$capability];
461 return $sqimap_capabilities;
464 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
465 function sqimap_get_delimiter ($imap_stream = false) {
466 global $sqimap_delimiter, $optional_delimiter;
468 /* Use configured delimiter if set */
469 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
470 return $optional_delimiter;
473 /* Do some caching here */
474 if (!$sqimap_delimiter) {
475 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
477 * According to something that I can't find, this is supposed to work on all systems
478 * OS: This won't work in Courier IMAP.
479 * OS: According to rfc2342 response from NAMESPACE command is:
480 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
481 * OS: We want to lookup all personal NAMESPACES...
483 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
484 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
485 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
488 $pna = explode(')(', $pn);
489 while (list($k, $v) = each($pna)) {
490 $lst = explode('"', $v);
491 if (isset($lst[3])) {
492 $pn[$lst[1]] = $lst[3];
498 $sqimap_delimiter = $pn[0];
500 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
501 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
502 $quote_position = strpos ($read[0], '"');
503 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
506 return $sqimap_delimiter;
510 /* Gets the number of messages in the current mailbox. */
511 function sqimap_get_num_messages ($imap_stream, $mailbox) {
512 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
513 for ($i = 0; $i < count($read_ary); $i++
) {
514 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
518 return false; //"BUG! Couldn't get number of messages in $mailbox!";
522 function parseAddress($address, $max=0, $addr_ar = array(), $group = '', $host='', $limit=0) {
524 $j = strlen($address);
528 if ($max && $max == count($addr_ar)) {
532 if ($max && $max == count($addr_ar)) {
535 $char = $address{$pos};
538 /* check if it is an encoded string */
539 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',substr($address,$pos),$reg)) {
540 /* add stringpart before the encoded string to the personal var */
542 $personal = substr($address,0,$pos);
544 $personal .= $reg[1];
545 $pos +
= strlen($reg[1]);
550 case '"': /* get the personal name */
552 if ($address{$pos} == '"') {
555 $personal_start = $personal_end = $pos;
557 $personal_end = strpos($address,'"',$pos);
558 if (($personal_end-2)>0 && (substr($address,$personal_end-2,2) === '\\"' ||
559 substr($address,$personal_end-2,2) === '\\\\')) {
560 $pos = $personal_end+
1;
562 $personal = substr($address,$personal_start,$personal_end-$personal_start);
566 if ($personal_end) { /* prohibit endless loops due to very wrong addresses */
567 $pos = $personal_end+
1;
573 case '<': /* get email address */
575 $addr_end = strpos($address,'>',$addr_start);
576 if($addr_end === FALSE) {
577 // in case the address doesn't end, prevent loop
580 $addr = substr($address,$addr_start+
1,$addr_end-$addr_start-1);
584 case '(': /* rip off comments */
586 $pos = strpos($address,')');
587 if ($pos !== false) {
588 $comment = substr($address, $addr_start+
1,($pos-$addr_start-1));
589 $address_start = substr($address, 0, $addr_start);
590 $address_end = substr($address, $pos +
1);
591 $address = $address_start . $address_end;
593 $j = strlen($address);
594 $pos = $addr_start +
1;
596 case ';': /* we reached a non rfc2822 compliant delimiter */
598 $address = substr($address, 0, $pos - 1);
602 case ',': /* we reached a delimiter */
604 $addr = substr($address, 0, $pos);
605 } else if ($personal == '') {
606 $personal = trim(substr($address, 0, $addr_start));
608 if (!$personal && $comment) $personal = $comment;
609 if ($personal) $personal = decodeHeader($personal);
610 $addr_ar[] = array($addr,$personal);
611 $address = trim(substr($address, $pos+
1));
612 $j = strlen($address);
617 case ':': /* process the group addresses */
619 $group = substr($address, 0, $pos);
620 $address = substr($address, $pos+
1);
621 $result = parseAddress($address, $max, $addr_ar, $group);
622 $addr_ar = $result[0];
624 $address = substr($address, $pos++
);
625 $j = strlen($address);
634 $addr = substr($address, 0, $pos);
635 } else if ($personal == '') {
636 $personal = trim(substr($address, 0, $addr_start));
638 if (!$personal && $comment) $personal = $comment;
640 if ($group && $addr == '') { /* no addresses found in group */
642 $addr_ar[] = array('',$personal);
643 return (array($addr_ar,$pos+
1 ));
645 $addr_ar[] = array($addr,$personal);
646 return (array($addr_ar,$pos+
1 ));
648 if ($personal ||
$addr) {
649 $addr_ar[] = array($addr, $personal);
656 * Returns the number of unseen messages in this folder
658 function sqimap_unseen_messages ($imap_stream, $mailbox) {
659 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
661 $regs = array(false, false);
662 while (isset($read_ary[$i])) {
663 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
672 * Returns the number of unseen/total messages in this folder
674 function sqimap_status_messages ($imap_stream, $mailbox) {
675 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
677 $messages = $unseen = $recent = false;
678 $regs = array(false,false);
679 while (isset($read_ary[$i])) {
680 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
683 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
684 $messages = $regs[1];
686 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
691 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
696 * Saves a message to a given folder -- used for saving sent messages
698 function sqimap_append ($imap_stream, $sent_folder, $length) {
699 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
700 $tmp = fgets ($imap_stream, 1024);
703 function sqimap_append_done ($imap_stream, $folder='') {
704 global $squirrelmail_language, $color;
705 fputs ($imap_stream, "\r\n");
706 $tmp = fgets ($imap_stream, 1024);
707 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
708 set_up_language($squirrelmail_language);
709 require_once(SM_PATH
. 'functions/display_messages.php');
711 if ($regs[2] == 'NO') {
712 $string = "<b><font color=$color[2]>\n" .
713 _("ERROR : Could not append message to") ." $folder." .
715 _("Server responded: ") .
717 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
718 $string .= _("Solution: ") .
719 _("Remove unneccessary messages from your folder and start with your Trash folder.")
722 $string .= "</font>\n";
723 error_box($string,$color);
725 $string = "<b><font color=$color[2]>\n" .
726 _("ERROR : Bad or malformed request.") .
728 _("Server responded: ") .
729 $tmp . "</font><br>\n";
730 error_box($string,$color);
736 function sqimap_get_user_server ($imap_server, $username) {
737 if (substr($imap_server, 0, 4) != "map:") {
740 $function = substr($imap_server, 4);
741 return $function($username);
744 /* This is an example that gets imapservers from yellowpages (NIS).
745 * you can simple put map:map_yp_alias in your $imap_server_address
746 * in config.php use your own function instead map_yp_alias to map your
747 * LDAP whatever way to find the users imapserver. */
749 function map_yp_alias($username) {
750 $yp = `ypmatch
$username aliases`
;
751 return chop(substr($yp, strlen($username)+
1));