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) {
83 while (strpos($read, "\n") === false) {
84 if (!($read = fgets($imap_stream, $buffer))) {
93 * Reads the output from the IMAP stream. If handle_errors is set to true,
94 * this will also handle all errors that are received. If it is not set,
95 * the errors will be sent back through $response and $message
98 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
99 global $color, $squirrelmail_language;
101 $pre_a = explode(' ',trim($pre));
103 $resultlist = array();
105 $read = sqimap_fgets($imap_stream);
108 case preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs):
109 case preg_match('/^\* (BYE \[ALERT\])(.*)$/', $read, $regs):
110 $response = $regs[1];
111 $message = trim($regs[2]);
113 case preg_match("/^\* (OK \[PARSE\])(.*)$/", $read):
114 $read = sqimap_fgets($imap_stream);
116 case preg_match('/^\* ([0-9]+) FETCH.*/', $read, $regs):
117 $fetch_data = array();
118 $fetch_data[] = $read;
119 $read = sqimap_fgets($imap_stream);
120 while (!preg_match('/^\* [0-9]+ FETCH.*/', $read) &&
121 !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read)) {
122 $fetch_data[] = $read;
124 $read = sqimap_fgets($imap_stream);
126 if (isset($last) && preg_match('/^\)/', $last)) {
127 array_pop($fetch_data);
129 $resultlist[] = $fetch_data;
133 $read = sqimap_fgets($imap_stream);
138 $resultlist[] = $data;
140 elseif (empty($resultlist)) {
141 $resultlist[] = array();
143 if ($handle_errors == false) {
144 return( $resultlist );
146 elseif ($response == 'NO') {
147 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
148 if (strstr($message, 'command resulted in') === false) {
149 set_up_language($squirrelmail_language);
150 require_once(SM_PATH
. 'functions/display_messages.php');
151 $string = "<b><font color=$color[2]>\n" .
152 _("ERROR : Could not complete request.") .
155 htmlspecialchars($query) . '<br>' .
156 _("Reason Given: ") .
157 htmlspecialchars($message) . "</font><br>\n";
158 error_box($string,$color);
162 elseif ($response == 'BAD') {
163 set_up_language($squirrelmail_language);
164 require_once(SM_PATH
. 'functions/display_messages.php');
165 $string = "<b><font color=$color[2]>\n" .
166 _("ERROR : Bad or malformed request.") .
169 htmlspecialchars($query) . '<br>' .
170 _("Server responded: ") .
171 htmlspecialchars($message) . "</font><br>\n";
172 error_box($string,$color);
180 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
181 $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
183 /* sqimap_read_data should be called for one response
184 but since it just calls sqimap_read_data_list which
185 handles multiple responses we need to check for that
186 and merge the $res array IF they are seperated and
187 IF it was a FETCH response. */
189 if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
190 && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
192 foreach($res as $index=>$value) {
193 $result = array_merge($result, $res["$index"]);
196 if (isset($result)) {
206 * Logs the user into the imap server. If $hide is set, no error messages
207 * will be displayed. This function returns the imap connection handle.
209 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
210 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
212 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
213 $host=$imap_server_address;
215 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
216 /* Use TLS by prefixing "tls://" to the hostname */
217 $imap_server_address = 'tls://' . $imap_server_address;
220 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
222 /* Do some error correction */
225 set_up_language($squirrelmail_language, true);
226 require_once(SM_PATH
. 'functions/display_messages.php');
227 $string = sprintf (_("Error connecting to IMAP server: %s.") .
228 "<br>\r\n", $imap_server_address) .
229 "$error_number : $error_string<br>\r\n";
230 logout_error($string,$color);
235 $server_info = fgets ($imap_stream, 1024);
237 /* Decrypt the password */
238 $password = OneTimePadDecrypt($password, $onetimepad);
240 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
241 // We're using some sort of authentication OTHER than plain or login
242 $tag=sqimap_session_id(false);
243 if ($imap_auth_mech == 'digest-md5') {
244 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
245 } elseif ($imap_auth_mech == 'cram-md5') {
246 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
248 fputs($imap_stream,$query);
249 $answer=sqimap_fgets($imap_stream);
250 // Trim the "+ " off the front
251 $response=explode(" ",$answer,3);
252 if ($response[0] == '+') {
253 // Got a challenge back
254 $challenge=$response[1];
255 if ($imap_auth_mech == 'digest-md5') {
256 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
257 } elseif ($imap_auth_mech == 'cram-md5') {
258 $reply = cram_md5_response($username,$password,$challenge);
260 fputs($imap_stream,$reply);
261 $read=sqimap_fgets($imap_stream);
262 if ($imap_auth_mech == 'digest-md5') {
263 // DIGEST-MD5 has an extra step..
264 if (substr($read,0,1) == '+') { // OK so far..
265 fputs($imap_stream,"\r\n");
266 $read=sqimap_fgets($imap_stream);
269 $results=explode(" ",$read,3);
270 $response=$results[1];
271 $message=$results[2];
273 // Fake the response, so the error trap at the bottom will work
275 $message='IMAP server does not appear to support the authentication method selected.';
276 $message .= ' Please contact your system administrator.';
278 } elseif ($imap_auth_mech == 'login') {
279 // Original IMAP login code
280 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
281 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
282 } elseif ($imap_auth_mech == 'plain') {
283 /* Replace this with SASL PLAIN if it ever gets implemented */
285 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
288 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
291 /* If the connection was not successful, lets see why */
292 if ($response != 'OK') {
294 if ($response != 'NO') {
295 /* "BAD" and anything else gets reported here. */
296 $message = htmlspecialchars($message);
297 set_up_language($squirrelmail_language, true);
298 require_once(SM_PATH
. 'functions/display_messages.php');
299 if ($response == 'BAD') {
300 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
302 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
304 if (isset($read) && is_array($read)) {
305 $string .= '<br>' . _("Read data:") . "<br>\n";
306 foreach ($read as $line) {
307 $string .= htmlspecialchars($line) . "<br>\n";
310 error_box($string,$color);
314 * If the user does not log in with the correct
315 * username and password it is not possible to get the
316 * correct locale from the user's preferences.
317 * Therefore, apply the same hack as on the login
320 * $squirrelmail_language is set by a cookie when
321 * the user selects language and logs out
324 set_up_language($squirrelmail_language, true);
325 include_once(SM_PATH
. 'functions/display_messages.php' );
327 logout_error( _("Unknown user or password incorrect.") );
337 /* Simply logs out the IMAP session */
338 function sqimap_logout ($imap_stream) {
339 /* Logout is not valid until the server returns 'BYE'
340 * If we don't have an imap_ stream we're already logged out */
341 if(isset($imap_stream) && $imap_stream)
342 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
345 function sqimap_capability($imap_stream, $capability='') {
346 global $sqimap_capabilities;
347 if (!is_array($sqimap_capabilities)) {
348 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
350 $c = explode(' ', $read[0]);
351 for ($i=2; $i < count($c); $i++
) {
352 $cap_list = explode('=', $c[$i]);
353 if (isset($cap_list[1])) {
354 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
356 $sqimap_capabilities[$cap_list[0]] = TRUE;
361 if (isset($sqimap_capabilities[$capability])) {
362 return $sqimap_capabilities[$capability];
367 return $sqimap_capabilities;
370 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
371 function sqimap_get_delimiter ($imap_stream = false) {
372 global $sqimap_delimiter, $optional_delimiter;
374 /* Use configured delimiter if set */
375 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
376 return $optional_delimiter;
379 /* Do some caching here */
380 if (!$sqimap_delimiter) {
381 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
383 * According to something that I can't find, this is supposed to work on all systems
384 * OS: This won't work in Courier IMAP.
385 * OS: According to rfc2342 response from NAMESPACE command is:
386 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
387 * OS: We want to lookup all personal NAMESPACES...
389 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
390 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
391 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
394 $pna = explode(')(', $pn);
395 while (list($k, $v) = each($pna)) {
396 $lst = explode('"', $v);
397 if (isset($lst[3])) {
398 $pn[$lst[1]] = $lst[3];
404 $sqimap_delimiter = $pn[0];
406 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
407 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
408 $quote_position = strpos ($read[0], '"');
409 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
412 return $sqimap_delimiter;
416 /* Gets the number of messages in the current mailbox. */
417 function sqimap_get_num_messages ($imap_stream, $mailbox) {
418 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
419 for ($i = 0; $i < count($read_ary); $i++
) {
420 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
424 return false; //"BUG! Couldn't get number of messages in $mailbox!";
428 /* Returns a displayable email address.
429 * Luke Ehresman <lehresma@css.tayloru.edu>
430 * "Luke Ehresman" <lehresma@css.tayloru.edu>
431 * <lehresma@css.tayloru.edu>
432 * lehresma@css.tayloru.edu (Luke Ehresman)
433 * lehresma@css.tayloru.edu
434 * becomes: lehresma@css.tayloru.edu
436 function sqimap_find_email ($string) {
437 if (ereg("<([^>]+)>", $string, $regs)) {
439 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
442 return trim($string);
447 * Takes the From: field and creates a displayable name.
448 * Luke Ehresman <lkehresman@yahoo.com>
449 * "Luke Ehresman" <lkehresman@yahoo.com>
450 * lkehresman@yahoo.com (Luke Ehresman)
451 * becomes: Luke Ehresman
452 * <lkehresman@yahoo.com>
453 * becomes: lkehresman@yahoo.com
455 function sqimap_find_displayable_name ($string) {
456 $string = trim($string);
458 if ( ereg('^(.+)<.*>', $string, $regs) ) {
459 $orig_string = $string;
460 $string = str_replace ('"', '', $regs[1] );
461 if (trim($string) == '') {
462 $string = sqimap_find_email($orig_string);
464 if( $string == '' ||
$string == ' ' ){
468 elseif ( ereg('\((.*)\)', $string, $regs) ) {
469 if( ( $regs[1] == '' ) ||
( $regs[1] == ' ' ) ){
470 if ( ereg('^(.+) \(', $string, $regs) ) {
471 $string = ereg_replace( ' \(\)$', '', $string );
480 $string = str_replace ('"', '', sqimap_find_email($string));
483 return trim($string);
487 * Returns the number of unseen messages in this folder
489 function sqimap_unseen_messages ($imap_stream, $mailbox) {
490 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
492 $regs = array(false, false);
493 while (isset($read_ary[$i])) {
494 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
503 * Returns the number of unseen/total messages in this folder
505 function sqimap_status_messages ($imap_stream, $mailbox) {
506 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
508 $messages = $unseen = false;
509 $regs = array(false,false);
510 while (isset($read_ary[$i])) {
511 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
514 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
515 $messages = $regs[1];
519 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
524 * Saves a message to a given folder -- used for saving sent messages
526 function sqimap_append ($imap_stream, $sent_folder, $length) {
527 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
528 $tmp = fgets ($imap_stream, 1024);
531 function sqimap_append_done ($imap_stream, $folder='') {
532 global $squirrelmail_language, $color;
533 fputs ($imap_stream, "\r\n");
534 $tmp = fgets ($imap_stream, 1024);
535 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
536 set_up_language($squirrelmail_language);
537 require_once(SM_PATH
. 'functions/display_messages.php');
539 if ($regs[2] == 'NO') {
540 $string = "<b><font color=$color[2]>\n" .
541 _("ERROR : Could not append message to") ." $folder." .
543 _("Server responded: ") .
545 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
546 $string .= _("Solution: ") .
547 _("Remove unneccessary messages from your folder and start with your Trash folder.")
550 $string .= "</font>\n";
551 error_box($string,$color);
553 $string = "<b><font color=$color[2]>\n" .
554 _("ERROR : Bad or malformed request.") .
556 _("Server responded: ") .
557 $tmp . "</font><br>\n";
558 error_box($string,$color);
564 function sqimap_get_user_server ($imap_server, $username) {
565 if (substr($imap_server, 0, 4) != "map:") {
568 $function = substr($imap_server, 4);
569 return $function($username);
572 /* This is an example that gets imapservers from yellowpages (NIS).
573 * you can simple put map:map_yp_alias in your $imap_server_address
574 * in config.php use your own function instead map_yp_alias to map your
575 * LDAP whatever way to find the users imapserver. */
577 function map_yp_alias($username) {
578 $yp = `ypmatch
$username aliases`
;
579 return chop(substr($yp, strlen($username)+
1));