Added what I've changed to devel CVS. (conf.pl rework, CRAM/DIGEST-MD5, config overri...
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2002 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 while (strpos($read, "\n") === false) {
84 if (!($read = fgets($imap_stream, $buffer))) {
85 break;
86 }
87 $results .= $read;
88 }
89 return $results;
90 }
91
92 /*
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
96 */
97
98 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
99 global $color, $squirrelmail_language;
100 $read = '';
101 $pre_a = explode(' ',trim($pre));
102 $pre = $pre_a[0];
103 $resultlist = array();
104 $data = array();
105 $read = sqimap_fgets($imap_stream);
106 while (1) {
107 switch (true) {
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]);
112 break 2;
113 case preg_match("/^\* (OK \[PARSE\])(.*)$/", $read):
114 $read = sqimap_fgets($imap_stream);
115 break 1;
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;
123 $last = $read;
124 $read = sqimap_fgets($imap_stream);
125 }
126 if (isset($last) && preg_match('/^\)/', $last)) {
127 array_pop($fetch_data);
128 }
129 $resultlist[] = $fetch_data;
130 break 1;
131 default:
132 $data[] = $read;
133 $read = sqimap_fgets($imap_stream);
134 break 1;
135 }
136 }
137 if (!empty($data)) {
138 $resultlist[] = $data;
139 }
140 elseif (empty($resultlist)) {
141 $resultlist[] = array();
142 }
143 if ($handle_errors == false) {
144 return( $resultlist );
145 }
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.") .
153 "</b><br>\n" .
154 _("Query:") .
155 $query . '<br>' .
156 _("Reason Given: ") .
157 $message . "</font><br>\n";
158 error_box($string,$color);
159 exit;
160 }
161 }
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.") .
167 "</b><br>\n" .
168 _("Query:") .
169 $query . '<br>' .
170 _("Server responded: ") .
171 $message . "</font><br>\n";
172 error_box($string,$color);
173 exit;
174 }
175 else {
176 return $resultlist;
177 }
178 }
179
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);
182
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. */
188
189 if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
190 && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
191 $result = array();
192 foreach($res as $index=>$value) {
193 $result = array_merge($result, $res["$index"]);
194 }
195 }
196 if (isset($result)) {
197 return $result;
198 }
199 else {
200 return $res[0];
201 }
202
203 }
204
205 /*
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.
208 */
209 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
210 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
211
212 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
213 $host=$imap_server_address;
214
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;
218 }
219
220 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
221
222 /* Do some error correction */
223 if (!$imap_stream) {
224 if (!$hide) {
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);
231 }
232 exit;
233 }
234
235 $server_info = fgets ($imap_stream, 1024);
236
237 /* Decrypt the password */
238 $password = OneTimePadDecrypt($password, $onetimepad);
239
240 if ((($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) AND (extension_loaded('mhash'))) {
241 // We're using some sort of authentication OTHER than plain
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";
247 }
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);
259 }
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);
267 }
268 }
269 $results=explode(" ",$read,3);
270 $response=$results[1];
271 $message=$results[2];
272 } else {
273 // Fake the response, so the error trap at the bottom will work
274 $response="BAD";
275 $message='IMAP server does not appear to support the authentication method selected.';
276 $message .= ' Please contact your system administrator.';
277 }
278 } else {
279 // Original PLAIN login code
280 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
281 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
282 }
283
284 /* If the connection was not successful, lets see why */
285 if ($response != 'OK') {
286 if (!$hide) {
287 if ($response != 'NO') {
288 /* "BAD" and anything else gets reported here. */
289 set_up_language($squirrelmail_language, true);
290 require_once(SM_PATH . 'functions/display_messages.php');
291 if ($response == 'BAD') {
292 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
293 } else {
294 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
295 }
296 $string .= '<br>' . _("Read data:") . "<br>\n";
297 if (is_array($read)) {
298 foreach ($read as $line) {
299 $string .= htmlspecialchars($line) . "<br>\n";
300 }
301 }
302 error_box($string,$color);
303 exit;
304 } else {
305 /*
306 * If the user does not log in with the correct
307 * username and password it is not possible to get the
308 * correct locale from the user's preferences.
309 * Therefore, apply the same hack as on the login
310 * screen.
311 *
312 * $squirrelmail_language is set by a cookie when
313 * the user selects language and logs out
314 */
315
316 set_up_language($squirrelmail_language, true);
317 include_once(SM_PATH . 'functions/display_messages.php' );
318 sqsession_destroy();
319 logout_error( _("Unknown user or password incorrect.") );
320 exit;
321 }
322 } else {
323 exit;
324 }
325 }
326 return $imap_stream;
327 }
328
329 /* Simply logs out the IMAP session */
330 function sqimap_logout ($imap_stream) {
331 /* Logout is not valid until the server returns 'BYE'
332 * If we don't have an imap_ stream we're already logged out */
333 if(isset($imap_stream) && $imap_stream)
334 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
335 }
336
337 function sqimap_capability($imap_stream, $capability='') {
338 global $sqimap_capabilities;
339 if (!is_array($sqimap_capabilities)) {
340 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
341
342 $c = explode(' ', $read[0]);
343 for ($i=2; $i < count($c); $i++) {
344 $cap_list = explode('=', $c[$i]);
345 if (isset($cap_list[1])) {
346 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
347 } else {
348 $sqimap_capabilities[$cap_list[0]] = TRUE;
349 }
350 }
351 }
352 if ($capability) {
353 if (isset($sqimap_capabilities[$capability])) {
354 return $sqimap_capabilities[$capability];
355 } else {
356 return false;
357 }
358 }
359 return $sqimap_capabilities;
360 }
361
362 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
363 function sqimap_get_delimiter ($imap_stream = false) {
364 global $sqimap_delimiter, $optional_delimiter;
365
366 /* Use configured delimiter if set */
367 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
368 return $optional_delimiter;
369 }
370
371 /* Do some caching here */
372 if (!$sqimap_delimiter) {
373 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
374 /*
375 * According to something that I can't find, this is supposed to work on all systems
376 * OS: This won't work in Courier IMAP.
377 * OS: According to rfc2342 response from NAMESPACE command is:
378 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
379 * OS: We want to lookup all personal NAMESPACES...
380 */
381 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
382 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
383 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
384 $pn = $data2[1];
385 }
386 $pna = explode(')(', $pn);
387 while (list($k, $v) = each($pna)) {
388 $lst = explode('"', $v);
389 if (isset($lst[3])) {
390 $pn[$lst[1]] = $lst[3];
391 } else {
392 $pn[$lst[1]] = '';
393 }
394 }
395 }
396 $sqimap_delimiter = $pn[0];
397 } else {
398 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
399 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
400 $quote_position = strpos ($read[0], '"');
401 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
402 }
403 }
404 return $sqimap_delimiter;
405 }
406
407
408 /* Gets the number of messages in the current mailbox. */
409 function sqimap_get_num_messages ($imap_stream, $mailbox) {
410 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
411 for ($i = 0; $i < count($read_ary); $i++) {
412 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
413 return $regs[1];
414 }
415 }
416 return false; //"BUG! Couldn't get number of messages in $mailbox!";
417 }
418
419
420 /* Returns a displayable email address.
421 * Luke Ehresman <lehresma@css.tayloru.edu>
422 * "Luke Ehresman" <lehresma@css.tayloru.edu>
423 * <lehresma@css.tayloru.edu>
424 * lehresma@css.tayloru.edu (Luke Ehresman)
425 * lehresma@css.tayloru.edu
426 * becomes: lehresma@css.tayloru.edu
427 */
428 function sqimap_find_email ($string) {
429 if (ereg("<([^>]+)>", $string, $regs)) {
430 $string = $regs[1];
431 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
432 $string = $regs[1];
433 }
434 return trim($string);
435 }
436
437
438 /*
439 * Takes the From: field and creates a displayable name.
440 * Luke Ehresman <lkehresman@yahoo.com>
441 * "Luke Ehresman" <lkehresman@yahoo.com>
442 * lkehresman@yahoo.com (Luke Ehresman)
443 * becomes: Luke Ehresman
444 * <lkehresman@yahoo.com>
445 * becomes: lkehresman@yahoo.com
446 */
447 function sqimap_find_displayable_name ($string) {
448 $string = trim($string);
449
450 if ( ereg('^(.+)<.*>', $string, $regs) ) {
451 $orig_string = $string;
452 $string = str_replace ('"', '', $regs[1] );
453 if (trim($string) == '') {
454 $string = sqimap_find_email($orig_string);
455 }
456 if( $string == '' || $string == ' ' ){
457 $string = '&nbsp';
458 }
459 }
460 elseif ( ereg('\((.*)\)', $string, $regs) ) {
461 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
462 if ( ereg('^(.+) \(', $string, $regs) ) {
463 $string = ereg_replace( ' \(\)$', '', $string );
464 } else {
465 $string = '&nbsp';
466 }
467 } else {
468 $string = $regs[1];
469 }
470 }
471 else {
472 $string = str_replace ('"', '', sqimap_find_email($string));
473 }
474
475 return trim($string);
476 }
477
478 /*
479 * Returns the number of unseen messages in this folder
480 */
481 function sqimap_unseen_messages ($imap_stream, $mailbox) {
482 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
483 $i = 0;
484 $regs = array(false, false);
485 while (isset($read_ary[$i])) {
486 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
487 break;
488 }
489 $i++;
490 }
491 return $regs[1];
492 }
493
494 /*
495 * Returns the number of unseen/total messages in this folder
496 */
497 function sqimap_status_messages ($imap_stream, $mailbox) {
498 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
499 $i = 0;
500 $messages = $unseen = false;
501 $regs = array(false,false);
502 while (isset($read_ary[$i])) {
503 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
504 $unseen = $regs[1];
505 }
506 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
507 $messages = $regs[1];
508 }
509 $i++;
510 }
511 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
512 }
513
514
515 /*
516 * Saves a message to a given folder -- used for saving sent messages
517 */
518 function sqimap_append ($imap_stream, $sent_folder, $length) {
519 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
520 $tmp = fgets ($imap_stream, 1024);
521 }
522
523 function sqimap_append_done ($imap_stream, $folder='') {
524 global $squirrelmail_language, $color;
525 fputs ($imap_stream, "\r\n");
526 $tmp = fgets ($imap_stream, 1024);
527 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
528 set_up_language($squirrelmail_language);
529 require_once(SM_PATH . 'functions/display_messages.php');
530 $reason = $regs[3];
531 if ($regs[2] == 'NO') {
532 $string = "<b><font color=$color[2]>\n" .
533 _("ERROR : Could not append message to") ." $folder." .
534 "</b><br>\n" .
535 _("Server responded: ") .
536 $reason . "<br>\n";
537 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
538 $string .= _("Solution: ") .
539 _("Remove unneccessary messages from your folder and start with your Trash folder.")
540 ."<br>\n";
541 }
542 $string .= "</font>\n";
543 error_box($string,$color);
544 } else {
545 $string = "<b><font color=$color[2]>\n" .
546 _("ERROR : Bad or malformed request.") .
547 "</b><br>\n" .
548 _("Server responded: ") .
549 $tmp . "</font><br>\n";
550 error_box($string,$color);
551 exit;
552 }
553 }
554 }
555
556 function sqimap_get_user_server ($imap_server, $username) {
557 if (substr($imap_server, 0, 4) != "map:") {
558 return $imap_server;
559 }
560 $function = substr($imap_server, 4);
561 return $function($username);
562 }
563
564 /* This is an example that gets imapservers from yellowpages (NIS).
565 * you can simple put map:map_yp_alias in your $imap_server_address
566 * in config.php use your own function instead map_yp_alias to map your
567 * LDAP whatever way to find the users imapserver. */
568
569 function map_yp_alias($username) {
570 $yp = `ypmatch $username aliases`;
571 return chop(substr($yp, strlen($username)+1));
572 }
573
574 ?>