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);
117 /* get the command */
120 $s = substr($read,$i);
121 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
122 $arg = substr($s,0,$j);
124 $found_tag = substr($read,0,$i-1);
125 if ($arg && $found_tag==$tag) {
134 $message = trim(substr($read,$i+
strlen($arg)));
137 /* this shouldn't happen */
139 $message = trim(substr($read,$i+
strlen($arg)));
142 } elseif($found_tag !== $tag) {
143 /* reset data array because we do not need this reponse */
145 $read = sqimap_fgets($imap_stream);
149 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
150 /* check for literal */
151 $s = substr($read,-3);
152 $fetch_data = array();
153 do { /* outer loop, continue until next untagged fetch
155 do { /* innerloop for fetching literals. with this loop
156 we prohibid that literal responses appear in the
157 outer loop so we can trust the untagged and
158 tagged info provided by $read */
159 if ($s === "}\r\n") {
160 $j = strrpos($read,'{');
161 $iLit = substr($read,$j+
1,-3);
162 $fetch_data[] = $read;
163 $sLiteral = fread($imap_stream,$iLit);
164 /* backwards compattibility */
165 $aLiteral = explode("\n", $sLiteral);
166 /* release not neaded data */
168 foreach ($aLiteral as $line) {
169 $fetch_data[] = $line ."\n";
171 /* release not neaded data */
173 /* next fgets belongs to this fetch because
174 we just got the exact literalsize and there
175 must follow data to complete the response */
176 $fetch_data[] = sqimap_fgets($imap_stream);
178 $fetch_data[] = $read;
180 /* retrieve next line and check in the while
181 statements if it belongs to this fetch response */
182 $read = sqimap_fgets($imap_stream);
183 /* check for next untagged reponse and break */
184 if ($read{0} == '*') break 2;
185 $s = substr($read,-3);
186 } while ($s === "}\r\n");
187 $s = substr($read,-3);
188 } while ($read{0} !== '*' &&
189 substr($read,0,strlen($tag)) !== $tag);
190 $resultlist[] = $fetch_data;
191 /* release not neaded data */
194 $s = substr($read,-3);
196 if ($s === "}\r\n") {
197 $j = strrpos($read,'{');
198 $iLit = substr($read,$j+
1,-3);
200 $data[] = fread($imap_stream,$iLit);
201 $fetch_data[] = sqimap_fgets($imap_stream);
205 $read = sqimap_fgets($imap_stream);
206 if ($read{0} == '*') break;
207 $s = substr($read,-3);
208 } while ($s === "}\r\n");
213 $read = sqimap_fgets($imap_stream);
216 $read = sqimap_fgets($imap_stream);
221 $resultlist[] = $data;
223 elseif (empty($resultlist)) {
224 $resultlist[] = array();
226 if ($handle_errors == false) {
227 return( $resultlist );
229 elseif ($response == 'NO') {
230 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
231 if (strstr($message, 'command resulted in') === false) {
232 set_up_language($squirrelmail_language);
233 require_once(SM_PATH
. 'functions/display_messages.php');
234 $string = "<b><font color=$color[2]>\n" .
235 _("ERROR : Could not complete request.") .
238 htmlspecialchars($query) . '<br>' .
239 _("Reason Given: ") .
240 htmlspecialchars($message) . "</font><br>\n";
241 error_box($string,$color);
245 elseif ($response == 'BAD') {
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 : Bad or malformed request.") .
252 htmlspecialchars($query) . '<br>' .
253 _("Server responded: ") .
254 htmlspecialchars($message) . "</font><br>\n";
255 error_box($string,$color);
263 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
264 $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors, $response, $message, $query);
266 /* sqimap_read_data should be called for one response
267 but since it just calls sqimap_read_data_list which
268 handles multiple responses we need to check for that
269 and merge the $res array IF they are seperated and
270 IF it was a FETCH response. */
272 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
273 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
274 // $result = array();
275 // foreach($res as $index=>$value) {
276 // $result = array_merge($result, $res["$index"]);
279 if (isset($result)) {
289 * Logs the user into the imap server. If $hide is set, no error messages
290 * will be displayed. This function returns the imap connection handle.
292 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
293 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
295 if (!isset($onetimepad) ||
empty($onetimepad)) {
296 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
298 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
299 $host=$imap_server_address;
301 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
302 /* Use TLS by prefixing "tls://" to the hostname */
303 $imap_server_address = 'tls://' . $imap_server_address;
306 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
308 /* Do some error correction */
311 set_up_language($squirrelmail_language, true);
312 require_once(SM_PATH
. 'functions/display_messages.php');
313 $string = sprintf (_("Error connecting to IMAP server: %s.") .
314 "<br>\r\n", $imap_server_address) .
315 "$error_number : $error_string<br>\r\n";
316 logout_error($string,$color);
321 $server_info = fgets ($imap_stream, 1024);
323 /* Decrypt the password */
324 $password = OneTimePadDecrypt($password, $onetimepad);
326 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
327 // We're using some sort of authentication OTHER than plain or login
328 $tag=sqimap_session_id(false);
329 if ($imap_auth_mech == 'digest-md5') {
330 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
331 } elseif ($imap_auth_mech == 'cram-md5') {
332 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
334 fputs($imap_stream,$query);
335 $answer=sqimap_fgets($imap_stream);
336 // Trim the "+ " off the front
337 $response=explode(" ",$answer,3);
338 if ($response[0] == '+') {
339 // Got a challenge back
340 $challenge=$response[1];
341 if ($imap_auth_mech == 'digest-md5') {
342 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
343 } elseif ($imap_auth_mech == 'cram-md5') {
344 $reply = cram_md5_response($username,$password,$challenge);
346 fputs($imap_stream,$reply);
347 $read=sqimap_fgets($imap_stream);
348 if ($imap_auth_mech == 'digest-md5') {
349 // DIGEST-MD5 has an extra step..
350 if (substr($read,0,1) == '+') { // OK so far..
351 fputs($imap_stream,"\r\n");
352 $read=sqimap_fgets($imap_stream);
355 $results=explode(" ",$read,3);
356 $response=$results[1];
357 $message=$results[2];
359 // Fake the response, so the error trap at the bottom will work
361 $message='IMAP server does not appear to support the authentication method selected.';
362 $message .= ' Please contact your system administrator.';
364 } elseif ($imap_auth_mech == 'login') {
365 // Original IMAP login code
366 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
367 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
368 } elseif ($imap_auth_mech == 'plain') {
369 /* Replace this with SASL PLAIN if it ever gets implemented */
371 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
374 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
377 /* If the connection was not successful, lets see why */
378 if ($response != 'OK') {
380 if ($response != 'NO') {
381 /* "BAD" and anything else gets reported here. */
382 $message = htmlspecialchars($message);
383 set_up_language($squirrelmail_language, true);
384 require_once(SM_PATH
. 'functions/display_messages.php');
385 if ($response == 'BAD') {
386 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
388 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
390 if (isset($read) && is_array($read)) {
391 $string .= '<br>' . _("Read data:") . "<br>\n";
392 foreach ($read as $line) {
393 $string .= htmlspecialchars($line) . "<br>\n";
396 error_box($string,$color);
400 * If the user does not log in with the correct
401 * username and password it is not possible to get the
402 * correct locale from the user's preferences.
403 * Therefore, apply the same hack as on the login
406 * $squirrelmail_language is set by a cookie when
407 * the user selects language and logs out
410 set_up_language($squirrelmail_language, true);
411 include_once(SM_PATH
. 'functions/display_messages.php' );
413 logout_error( _("Unknown user or password incorrect.") );
423 /* Simply logs out the IMAP session */
424 function sqimap_logout ($imap_stream) {
425 /* Logout is not valid until the server returns 'BYE'
426 * If we don't have an imap_ stream we're already logged out */
427 if(isset($imap_stream) && $imap_stream)
428 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
431 function sqimap_capability($imap_stream, $capability='') {
432 global $sqimap_capabilities;
433 if (!is_array($sqimap_capabilities)) {
434 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
436 $c = explode(' ', $read[0]);
437 for ($i=2; $i < count($c); $i++
) {
438 $cap_list = explode('=', $c[$i]);
439 if (isset($cap_list[1])) {
440 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
442 $sqimap_capabilities[$cap_list[0]] = TRUE;
447 if (isset($sqimap_capabilities[$capability])) {
448 return $sqimap_capabilities[$capability];
453 return $sqimap_capabilities;
456 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
457 function sqimap_get_delimiter ($imap_stream = false) {
458 global $sqimap_delimiter, $optional_delimiter;
460 /* Use configured delimiter if set */
461 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
462 return $optional_delimiter;
465 /* Do some caching here */
466 if (!$sqimap_delimiter) {
467 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
469 * According to something that I can't find, this is supposed to work on all systems
470 * OS: This won't work in Courier IMAP.
471 * OS: According to rfc2342 response from NAMESPACE command is:
472 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
473 * OS: We want to lookup all personal NAMESPACES...
475 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
476 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
477 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
480 $pna = explode(')(', $pn);
481 while (list($k, $v) = each($pna)) {
482 $lst = explode('"', $v);
483 if (isset($lst[3])) {
484 $pn[$lst[1]] = $lst[3];
490 $sqimap_delimiter = $pn[0];
492 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
493 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
494 $quote_position = strpos ($read[0], '"');
495 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
498 return $sqimap_delimiter;
502 /* Gets the number of messages in the current mailbox. */
503 function sqimap_get_num_messages ($imap_stream, $mailbox) {
504 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
505 for ($i = 0; $i < count($read_ary); $i++
) {
506 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
510 return false; //"BUG! Couldn't get number of messages in $mailbox!";
514 function parseAddress($address, $max=0, $addr_ar = array(), $group = '', $host='', $limit=0) {
516 $j = strlen($address);
520 if ($max && $max == count($addr_ar)) {
524 if ($max && $max == count($addr_ar)) {
527 $char = $address{$pos};
530 /* check if it is an encoded string */
531 if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',substr($address,$pos),$reg)) {
532 /* add stringpart before the encoded string to the personal var */
534 $personal = substr($address,0,$pos);
536 $personal .= $reg[1];
537 $pos +
= strlen($reg[1]);
542 case '"': /* get the personal name */
544 if ($address{$pos} == '"') {
547 $personal_start = $personal_end = $pos;
549 $personal_end = strpos($address,'"',$pos);
550 if (($personal_end-2)>0 && (substr($address,$personal_end-2,2) === '\\"' ||
551 substr($address,$personal_end-2,2) === '\\\\')) {
552 $pos = $personal_end+
1;
554 $personal = substr($address,$personal_start,$personal_end-$personal_start);
558 if ($personal_end) { /* prohibit endless loops due to very wrong addresses */
559 $pos = $personal_end+
1;
565 case '<': /* get email address */
567 $addr_end = strpos($address,'>',$addr_start);
568 if($addr_end === FALSE) {
569 // in case the address doesn't end, prevent loop
572 $addr = substr($address,$addr_start+
1,$addr_end-$addr_start-1);
576 case '(': /* rip off comments */
578 $pos = strpos($address,')');
579 if ($pos !== false) {
580 $comment = substr($address, $addr_start+
1,($pos-$addr_start-1));
581 $address_start = substr($address, 0, $addr_start);
582 $address_end = substr($address, $pos +
1);
583 $address = $address_start . $address_end;
585 $j = strlen($address);
586 $pos = $addr_start +
1;
588 case ';': /* we reached a non rfc2822 compliant delimiter */
590 $address = substr($address, 0, $pos - 1);
594 case ',': /* we reached a delimiter */
596 $addr = substr($address, 0, $pos);
597 } else if ($personal == '') {
598 $personal = trim(substr($address, 0, $addr_start));
600 if (!$personal && $comment) $personal = $comment;
601 if ($personal) $personal = decodeHeader($personal);
602 $addr_ar[] = array($addr,$personal);
603 $address = trim(substr($address, $pos+
1));
604 $j = strlen($address);
609 case ':': /* process the group addresses */
611 $group = substr($address, 0, $pos);
612 $address = substr($address, $pos+
1);
613 $result = parseAddress($address, $max, $addr_ar, $group);
614 $addr_ar = $result[0];
616 $address = substr($address, $pos++
);
617 $j = strlen($address);
626 $addr = substr($address, 0, $pos);
627 } else if ($personal == '') {
628 $personal = trim(substr($address, 0, $addr_start));
630 if (!$personal && $comment) $personal = $comment;
632 if ($group && $addr == '') { /* no addresses found in group */
634 $addr_ar[] = array('',$personal);
635 return (array($addr_ar,$pos+
1 ));
637 $addr_ar[] = array($addr,$personal);
638 return (array($addr_ar,$pos+
1 ));
640 if ($personal ||
$addr) {
641 $addr_ar[] = array($addr, $personal);
648 * Returns the number of unseen messages in this folder
650 function sqimap_unseen_messages ($imap_stream, $mailbox) {
651 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
653 $regs = array(false, false);
654 while (isset($read_ary[$i])) {
655 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
664 * Returns the number of unseen/total messages in this folder
666 function sqimap_status_messages ($imap_stream, $mailbox) {
667 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
669 $messages = $unseen = $recent = false;
670 $regs = array(false,false);
671 while (isset($read_ary[$i])) {
672 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
675 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
676 $messages = $regs[1];
678 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
683 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
688 * Saves a message to a given folder -- used for saving sent messages
690 function sqimap_append ($imap_stream, $sent_folder, $length) {
691 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
692 $tmp = fgets ($imap_stream, 1024);
695 function sqimap_append_done ($imap_stream, $folder='') {
696 global $squirrelmail_language, $color;
697 fputs ($imap_stream, "\r\n");
698 $tmp = fgets ($imap_stream, 1024);
699 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
700 set_up_language($squirrelmail_language);
701 require_once(SM_PATH
. 'functions/display_messages.php');
703 if ($regs[2] == 'NO') {
704 $string = "<b><font color=$color[2]>\n" .
705 _("ERROR : Could not append message to") ." $folder." .
707 _("Server responded: ") .
709 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
710 $string .= _("Solution: ") .
711 _("Remove unneccessary messages from your folder and start with your Trash folder.")
714 $string .= "</font>\n";
715 error_box($string,$color);
717 $string = "<b><font color=$color[2]>\n" .
718 _("ERROR : Bad or malformed request.") .
720 _("Server responded: ") .
721 $tmp . "</font><br>\n";
722 error_box($string,$color);
728 function sqimap_get_user_server ($imap_server, $username) {
729 if (substr($imap_server, 0, 4) != "map:") {
732 $function = substr($imap_server, 4);
733 return $function($username);
736 /* This is an example that gets imapservers from yellowpages (NIS).
737 * you can simple put map:map_yp_alias in your $imap_server_address
738 * in config.php use your own function instead map_yp_alias to map your
739 * LDAP whatever way to find the users imapserver. */
741 function map_yp_alias($username) {
742 $yp = `ypmatch
$username aliases`
;
743 return chop(substr($yp, strlen($username)+
1));