4a97406fa62cf00b7cf70c288323d160820157e9
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This implements all functions that do general imap functions.
10 *
11 * $Id$
12 */
13
14 require_once(SM_PATH . 'functions/page_header.php');
15 require_once(SM_PATH . 'functions/auth.php');
16
17
18 global $sqimap_session_id;
19 $sqimap_session_id = 1;
20
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;
24 if (!$unique_id) {
25 return( sprintf("A%03d", $sqimap_session_id++) );
26 } else {
27 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
28 }
29 }
30
31 /*
32 * Both send a command and accept the result from the command.
33 * This is to allow proper session number handling.
34 */
35 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
36 if ($imap_stream) {
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 );
40 return $read;
41 } else {
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.") .
47 "</b></font>\n";
48 error_box($string,$color);
49 return false;
50 }
51
52 }
53
54 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
55 if ($imap_stream) {
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);
59 return $read;
60 } else {
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.") .
66 "</b></font>\n";
67 error_box($string,$color);
68 return false;
69 }
70
71 }
72
73
74 /*
75 * custom fgets function. gets a line from IMAP
76 * no matter how big it may be
77 */
78
79 function sqimap_fgets($imap_stream) {
80 $read = '';
81 $buffer = 4096;
82 $results = '';
83 $offset = 0;
84 while (strpos($results, "\r\n", $offset) === false) {
85 if (!($read = fgets($imap_stream, $buffer))) {
86 break;
87 }
88 if ( $results != '' ) {
89 $offset = strlen($results) - 1;
90 }
91 $results .= $read;
92 }
93 return $results;
94 }
95
96 /*
97 * Reads the output from the IMAP stream. If handle_errors is set to true,
98 * this will also handle all errors that are received. If it is not set,
99 * the errors will be sent back through $response and $message
100 */
101
102 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
103 global $color, $squirrelmail_language;
104 $read = '';
105 $pre_a = explode(' ',trim($pre));
106 $pre = $pre_a[0];
107 $resultlist = array();
108 $data = array();
109 $read = sqimap_fgets($imap_stream);
110 while (1) {
111 switch (true) {
112 case preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs):
113 case preg_match('/^\* (BYE \[ALERT\])(.*)$/', $read, $regs):
114 $response = $regs[1];
115 $message = trim($regs[2]);
116 break 2;
117 case preg_match("/^\* (OK \[PARSE\])(.*)$/", $read):
118 $read = sqimap_fgets($imap_stream);
119 break 1;
120 case preg_match('/^\* ([0-9]+) FETCH.*/', $read, $regs):
121 $fetch_data = array();
122 $fetch_data[] = $read;
123 $read = sqimap_fgets($imap_stream);
124 while (!preg_match('/^\* [0-9]+ FETCH.*/', $read) &&
125 !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read)) {
126 $fetch_data[] = $read;
127 $last = $read;
128 $read = sqimap_fgets($imap_stream);
129 }
130 if (isset($last) && preg_match('/^\)/', $last)) {
131 array_pop($fetch_data);
132 }
133 $resultlist[] = $fetch_data;
134 break 1;
135 default:
136 $data[] = $read;
137 $read = sqimap_fgets($imap_stream);
138 break 1;
139 }
140 }
141 if (!empty($data)) {
142 $resultlist[] = $data;
143 }
144 elseif (empty($resultlist)) {
145 $resultlist[] = array();
146 }
147 if ($handle_errors == false) {
148 return( $resultlist );
149 }
150 elseif ($response == 'NO') {
151 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
152 if (strstr($message, 'command resulted in') === false) {
153 set_up_language($squirrelmail_language);
154 require_once(SM_PATH . 'functions/display_messages.php');
155 $string = "<b><font color=$color[2]>\n" .
156 _("ERROR : Could not complete request.") .
157 "</b><br>\n" .
158 _("Query:") . ' ' .
159 htmlspecialchars($query) . '<br>' .
160 _("Reason Given: ") .
161 htmlspecialchars($message) . "</font><br>\n";
162 error_box($string,$color);
163 exit;
164 }
165 }
166 elseif ($response == 'BAD') {
167 set_up_language($squirrelmail_language);
168 require_once(SM_PATH . 'functions/display_messages.php');
169 $string = "<b><font color=$color[2]>\n" .
170 _("ERROR : Bad or malformed request.") .
171 "</b><br>\n" .
172 _("Query:") . ' '.
173 htmlspecialchars($query) . '<br>' .
174 _("Server responded: ") .
175 htmlspecialchars($message) . "</font><br>\n";
176 error_box($string,$color);
177 exit;
178 }
179 else {
180 return $resultlist;
181 }
182 }
183
184 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
185 $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
186
187 /* sqimap_read_data should be called for one response
188 but since it just calls sqimap_read_data_list which
189 handles multiple responses we need to check for that
190 and merge the $res array IF they are seperated and
191 IF it was a FETCH response. */
192
193 if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
194 && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
195 $result = array();
196 foreach($res as $index=>$value) {
197 $result = array_merge($result, $res["$index"]);
198 }
199 }
200 if (isset($result)) {
201 return $result;
202 }
203 else {
204 return $res[0];
205 }
206
207 }
208
209 /*
210 * Logs the user into the imap server. If $hide is set, no error messages
211 * will be displayed. This function returns the imap connection handle.
212 */
213 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
214 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
215
216 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
217 $host=$imap_server_address;
218
219 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
220 /* Use TLS by prefixing "tls://" to the hostname */
221 $imap_server_address = 'tls://' . $imap_server_address;
222 }
223
224 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
225
226 /* Do some error correction */
227 if (!$imap_stream) {
228 if (!$hide) {
229 set_up_language($squirrelmail_language, true);
230 require_once(SM_PATH . 'functions/display_messages.php');
231 $string = sprintf (_("Error connecting to IMAP server: %s.") .
232 "<br>\r\n", $imap_server_address) .
233 "$error_number : $error_string<br>\r\n";
234 logout_error($string,$color);
235 }
236 exit;
237 }
238
239 $server_info = fgets ($imap_stream, 1024);
240
241 /* Decrypt the password */
242 $password = OneTimePadDecrypt($password, $onetimepad);
243
244 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
245 // We're using some sort of authentication OTHER than plain or login
246 $tag=sqimap_session_id(false);
247 if ($imap_auth_mech == 'digest-md5') {
248 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
249 } elseif ($imap_auth_mech == 'cram-md5') {
250 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
251 }
252 fputs($imap_stream,$query);
253 $answer=sqimap_fgets($imap_stream);
254 // Trim the "+ " off the front
255 $response=explode(" ",$answer,3);
256 if ($response[0] == '+') {
257 // Got a challenge back
258 $challenge=$response[1];
259 if ($imap_auth_mech == 'digest-md5') {
260 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
261 } elseif ($imap_auth_mech == 'cram-md5') {
262 $reply = cram_md5_response($username,$password,$challenge);
263 }
264 fputs($imap_stream,$reply);
265 $read=sqimap_fgets($imap_stream);
266 if ($imap_auth_mech == 'digest-md5') {
267 // DIGEST-MD5 has an extra step..
268 if (substr($read,0,1) == '+') { // OK so far..
269 fputs($imap_stream,"\r\n");
270 $read=sqimap_fgets($imap_stream);
271 }
272 }
273 $results=explode(" ",$read,3);
274 $response=$results[1];
275 $message=$results[2];
276 } else {
277 // Fake the response, so the error trap at the bottom will work
278 $response="BAD";
279 $message='IMAP server does not appear to support the authentication method selected.';
280 $message .= ' Please contact your system administrator.';
281 }
282 } elseif ($imap_auth_mech == 'login') {
283 // Original IMAP login code
284 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
285 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
286 } elseif ($imap_auth_mech == 'plain') {
287 /* Replace this with SASL PLAIN if it ever gets implemented */
288 $response="BAD";
289 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
290 } else {
291 $response="BAD";
292 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
293 }
294
295 /* If the connection was not successful, lets see why */
296 if ($response != 'OK') {
297 if (!$hide) {
298 if ($response != 'NO') {
299 /* "BAD" and anything else gets reported here. */
300 $message = htmlspecialchars($message);
301 set_up_language($squirrelmail_language, true);
302 require_once(SM_PATH . 'functions/display_messages.php');
303 if ($response == 'BAD') {
304 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
305 } else {
306 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
307 }
308 if (isset($read) && is_array($read)) {
309 $string .= '<br>' . _("Read data:") . "<br>\n";
310 foreach ($read as $line) {
311 $string .= htmlspecialchars($line) . "<br>\n";
312 }
313 }
314 error_box($string,$color);
315 exit;
316 } else {
317 /*
318 * If the user does not log in with the correct
319 * username and password it is not possible to get the
320 * correct locale from the user's preferences.
321 * Therefore, apply the same hack as on the login
322 * screen.
323 *
324 * $squirrelmail_language is set by a cookie when
325 * the user selects language and logs out
326 */
327
328 set_up_language($squirrelmail_language, true);
329 include_once(SM_PATH . 'functions/display_messages.php' );
330 sqsession_destroy();
331 logout_error( _("Unknown user or password incorrect.") );
332 exit;
333 }
334 } else {
335 exit;
336 }
337 }
338 return $imap_stream;
339 }
340
341 /* Simply logs out the IMAP session */
342 function sqimap_logout ($imap_stream) {
343 /* Logout is not valid until the server returns 'BYE'
344 * If we don't have an imap_ stream we're already logged out */
345 if(isset($imap_stream) && $imap_stream)
346 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
347 }
348
349 function sqimap_capability($imap_stream, $capability='') {
350 global $sqimap_capabilities;
351 if (!is_array($sqimap_capabilities)) {
352 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
353
354 $c = explode(' ', $read[0]);
355 for ($i=2; $i < count($c); $i++) {
356 $cap_list = explode('=', $c[$i]);
357 if (isset($cap_list[1])) {
358 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
359 } else {
360 $sqimap_capabilities[$cap_list[0]] = TRUE;
361 }
362 }
363 }
364 if ($capability) {
365 if (isset($sqimap_capabilities[$capability])) {
366 return $sqimap_capabilities[$capability];
367 } else {
368 return false;
369 }
370 }
371 return $sqimap_capabilities;
372 }
373
374 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
375 function sqimap_get_delimiter ($imap_stream = false) {
376 global $sqimap_delimiter, $optional_delimiter;
377
378 /* Use configured delimiter if set */
379 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
380 return $optional_delimiter;
381 }
382
383 /* Do some caching here */
384 if (!$sqimap_delimiter) {
385 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
386 /*
387 * According to something that I can't find, this is supposed to work on all systems
388 * OS: This won't work in Courier IMAP.
389 * OS: According to rfc2342 response from NAMESPACE command is:
390 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
391 * OS: We want to lookup all personal NAMESPACES...
392 */
393 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
394 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
395 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
396 $pn = $data2[1];
397 }
398 $pna = explode(')(', $pn);
399 while (list($k, $v) = each($pna)) {
400 $lst = explode('"', $v);
401 if (isset($lst[3])) {
402 $pn[$lst[1]] = $lst[3];
403 } else {
404 $pn[$lst[1]] = '';
405 }
406 }
407 }
408 $sqimap_delimiter = $pn[0];
409 } else {
410 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
411 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
412 $quote_position = strpos ($read[0], '"');
413 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
414 }
415 }
416 return $sqimap_delimiter;
417 }
418
419
420 /* Gets the number of messages in the current mailbox. */
421 function sqimap_get_num_messages ($imap_stream, $mailbox) {
422 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
423 for ($i = 0; $i < count($read_ary); $i++) {
424 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
425 return $regs[1];
426 }
427 }
428 return false; //"BUG! Couldn't get number of messages in $mailbox!";
429 }
430
431
432 /* Returns a displayable email address.
433 * Luke Ehresman <lehresma@css.tayloru.edu>
434 * "Luke Ehresman" <lehresma@css.tayloru.edu>
435 * <lehresma@css.tayloru.edu>
436 * lehresma@css.tayloru.edu (Luke Ehresman)
437 * lehresma@css.tayloru.edu
438 * becomes: lehresma@css.tayloru.edu
439 */
440 function sqimap_find_email ($string) {
441 if (ereg("<([^>]+)>", $string, $regs)) {
442 $string = $regs[1];
443 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
444 $string = $regs[1];
445 }
446 return trim($string);
447 }
448
449
450 /*
451 * Takes the From: field and creates a displayable name.
452 * Luke Ehresman <lkehresman@yahoo.com>
453 * "Luke Ehresman" <lkehresman@yahoo.com>
454 * lkehresman@yahoo.com (Luke Ehresman)
455 * becomes: Luke Ehresman
456 * <lkehresman@yahoo.com>
457 * becomes: lkehresman@yahoo.com
458 */
459 function sqimap_find_displayable_name ($string) {
460 $string = trim($string);
461
462 if ( ereg('^(.+)<.*>', $string, $regs) ) {
463 $orig_string = $string;
464 $string = str_replace ('"', '', $regs[1] );
465 if (trim($string) == '') {
466 $string = sqimap_find_email($orig_string);
467 }
468 if( $string == '' || $string == ' ' ){
469 $string = '&nbsp;';
470 }
471 }
472 elseif ( ereg('\((.*)\)', $string, $regs) ) {
473 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
474 if ( ereg('^(.+) \(', $string, $regs) ) {
475 $string = ereg_replace( ' \(\)$', '', $string );
476 } else {
477 $string = '&nbsp;';
478 }
479 } else {
480 $string = $regs[1];
481 }
482 }
483 else {
484 $string = str_replace ('"', '', sqimap_find_email($string));
485 }
486
487 return trim($string);
488 }
489
490 /*
491 * Returns the number of unseen messages in this folder
492 */
493 function sqimap_unseen_messages ($imap_stream, $mailbox) {
494 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
495 $i = 0;
496 $regs = array(false, false);
497 while (isset($read_ary[$i])) {
498 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
499 break;
500 }
501 $i++;
502 }
503 return $regs[1];
504 }
505
506 /*
507 * Returns the number of unseen/total messages in this folder
508 */
509 function sqimap_status_messages ($imap_stream, $mailbox) {
510 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
511 $i = 0;
512 $messages = $unseen = false;
513 $regs = array(false,false);
514 while (isset($read_ary[$i])) {
515 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
516 $unseen = $regs[1];
517 }
518 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
519 $messages = $regs[1];
520 }
521 $i++;
522 }
523 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
524 }
525
526
527 /*
528 * Saves a message to a given folder -- used for saving sent messages
529 */
530 function sqimap_append ($imap_stream, $sent_folder, $length) {
531 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
532 $tmp = fgets ($imap_stream, 1024);
533 }
534
535 function sqimap_append_done ($imap_stream, $folder='') {
536 global $squirrelmail_language, $color;
537 fputs ($imap_stream, "\r\n");
538 $tmp = fgets ($imap_stream, 1024);
539 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
540 set_up_language($squirrelmail_language);
541 require_once(SM_PATH . 'functions/display_messages.php');
542 $reason = $regs[3];
543 if ($regs[2] == 'NO') {
544 $string = "<b><font color=$color[2]>\n" .
545 _("ERROR : Could not append message to") ." $folder." .
546 "</b><br>\n" .
547 _("Server responded: ") .
548 $reason . "<br>\n";
549 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
550 $string .= _("Solution: ") .
551 _("Remove unneccessary messages from your folder and start with your Trash folder.")
552 ."<br>\n";
553 }
554 $string .= "</font>\n";
555 error_box($string,$color);
556 } else {
557 $string = "<b><font color=$color[2]>\n" .
558 _("ERROR : Bad or malformed request.") .
559 "</b><br>\n" .
560 _("Server responded: ") .
561 $tmp . "</font><br>\n";
562 error_box($string,$color);
563 exit;
564 }
565 }
566 }
567
568 function sqimap_get_user_server ($imap_server, $username) {
569 if (substr($imap_server, 0, 4) != "map:") {
570 return $imap_server;
571 }
572 $function = substr($imap_server, 4);
573 return $function($username);
574 }
575
576 /* This is an example that gets imapservers from yellowpages (NIS).
577 * you can simple put map:map_yp_alias in your $imap_server_address
578 * in config.php use your own function instead map_yp_alias to map your
579 * LDAP whatever way to find the users imapserver. */
580
581 function map_yp_alias($username) {
582 $yp = `ypmatch $username aliases`;
583 return chop(substr($yp, strlen($username)+1));
584 }
585
586 ?>