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