Language fix
[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
16 global $sqimap_session_id;
17 $sqimap_session_id = 1;
18
19 /* Sets an unique session id in order to avoid simultanous sessions crash. */
20 function sqimap_session_id($unique_id = false) {
21 global $data_dir, $username, $sqimap_session_id;
22 if (!$unique_id) {
23 return( sprintf("A%03d", $sqimap_session_id++) );
24 } else {
25 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
26 }
27 }
28
29 /*
30 * Both send a command and accept the result from the command.
31 * This is to allow proper session number handling.
32 */
33 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
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
50 }
51
52 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
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
69 }
70
71
72 /*
73 * custom fgets function. gets a line from IMAP
74 * no matter how big it may be
75 */
76
77 function 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
90 /*
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
94 */
95
96 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
97 global $color, $squirrelmail_language;
98 $read = '';
99 $pre_a = explode(' ',trim($pre));
100 $pre = $pre_a[0];
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;
114 case preg_match('/^\* ([0-9]+) FETCH.*/', $read, $regs):
115 $fetch_data = array();
116 $fetch_data[] = $read;
117 $read = sqimap_fgets($imap_stream);
118 while (!preg_match('/^\* [0-9]+ FETCH.*/', $read) &&
119 !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read)) {
120 $fetch_data[] = $read;
121 $last = $read;
122 $read = sqimap_fgets($imap_stream);
123 }
124 if (isset($last) && preg_match('/^\)/', $last)) {
125 array_pop($fetch_data);
126 }
127 $resultlist[] = $fetch_data;
128 break 1;
129 default:
130 $data[] = $read;
131 $read = sqimap_fgets($imap_stream);
132 break 1;
133 }
134 }
135 if (!empty($data)) {
136 $resultlist[] = $data;
137 }
138 elseif (empty($resultlist)) {
139 $resultlist[] = array();
140 }
141 if ($handle_errors == false) {
142 return( $resultlist );
143 }
144 elseif ($response == 'NO') {
145 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
146 if (strstr($message, 'command resulted in') === false) {
147 set_up_language($squirrelmail_language);
148 require_once(SM_PATH . 'functions/display_messages.php');
149 $string = "<b><font color=$color[2]>\n" .
150 _("ERROR : Could not complete request.") .
151 "</b><br>\n" .
152 _("Query:") .
153 $query . '<br>' .
154 _("Reason Given: ") .
155 $message . "</font><br>\n";
156 error_box($string,$color);
157 exit;
158 }
159 }
160 elseif ($response == 'BAD') {
161 set_up_language($squirrelmail_language);
162 require_once(SM_PATH . 'functions/display_messages.php');
163 $string = "<b><font color=$color[2]>\n" .
164 _("ERROR : Bad or malformed request.") .
165 "</b><br>\n" .
166 _("Query:") .
167 $query . '<br>' .
168 _("Server responded: ") .
169 $message . "</font><br>\n";
170 error_box($string,$color);
171 exit;
172 }
173 else {
174 return $resultlist;
175 }
176 }
177
178 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
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"]);
192 }
193 }
194 if (isset($result)) {
195 return $result;
196 }
197 else {
198 return $res[0];
199 }
200
201 }
202
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 */
207 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
208 global $color, $squirrelmail_language, $onetimepad;
209
210 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
211
212 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
213 if ( !$imap_stream ) {
214 return false;
215 }
216 $server_info = fgets ($imap_stream, 1024);
217
218 /* Decrypt the password */
219 $password = OneTimePadDecrypt($password, $onetimepad);
220
221 /* Do some error correction */
222 if (!$imap_stream) {
223 if (!$hide) {
224 set_up_language($squirrelmail_language, true);
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);
230 }
231 exit;
232 }
233
234 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
235 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
236
237 /* If the connection was not successful, lets see why */
238 if ($response != 'OK') {
239 if (!$hide) {
240 if ($response != 'NO') {
241 /* "BAD" and anything else gets reported here. */
242 set_up_language($squirrelmail_language, true);
243 require_once(SM_PATH . 'functions/display_messages.php');
244 if ($response == 'BAD') {
245 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
246 } else {
247 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
248 }
249 $string .= '<br>' . _("Read data:") . "<br>\n";
250 if (is_array($read)) {
251 foreach ($read as $line) {
252 $string .= htmlspecialchars($line) . "<br>\n";
253 }
254 }
255 error_box($string,$color);
256 exit;
257 } else {
258 /*
259 * If the user does not log in with the correct
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.
264 *
265 * $squirrelmail_language is set by a cookie when
266 * the user selects language and logs out
267 */
268
269 set_up_language($squirrelmail_language, true);
270 include_once(SM_PATH . 'functions/display_messages.php' );
271 sqsession_destroy();
272 logout_error( _("Unknown user or password incorrect.") );
273 exit;
274 }
275 } else {
276 exit;
277 }
278 }
279 return $imap_stream;
280 }
281
282 /* Simply logs out the IMAP session */
283 function sqimap_logout ($imap_stream) {
284 /* Logout is not valid until the server returns 'BYE'
285 * If we don't have an imap_ stream we're already logged out */
286 if(isset($imap_stream) && $imap_stream)
287 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
288 }
289
290 function sqimap_capability($imap_stream, $capability='') {
291 global $sqimap_capabilities;
292 if (!is_array($sqimap_capabilities)) {
293 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
294
295 $c = explode(' ', $read[0]);
296 for ($i=2; $i < count($c); $i++) {
297 $cap_list = explode('=', $c[$i]);
298 if (isset($cap_list[1])) {
299 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
300 } else {
301 $sqimap_capabilities[$cap_list[0]] = TRUE;
302 }
303 }
304 }
305 if ($capability) {
306 if (isset($sqimap_capabilities[$capability])) {
307 return $sqimap_capabilities[$capability];
308 } else {
309 return false;
310 }
311 }
312 return $sqimap_capabilities;
313 }
314
315 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
316 function sqimap_get_delimiter ($imap_stream = false) {
317 global $sqimap_delimiter, $optional_delimiter;
318
319 /* Use configured delimiter if set */
320 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
321 return $optional_delimiter;
322 }
323
324 /* Do some caching here */
325 if (!$sqimap_delimiter) {
326 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
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 */
334 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
335 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
336 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
337 $pn = $data2[1];
338 }
339 $pna = explode(')(', $pn);
340 while (list($k, $v) = each($pna)) {
341 $lst = explode('"', $v);
342 if (isset($lst[3])) {
343 $pn[$lst[1]] = $lst[3];
344 } else {
345 $pn[$lst[1]] = '';
346 }
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;
358 }
359
360
361 /* Gets the number of messages in the current mailbox. */
362 function sqimap_get_num_messages ($imap_stream, $mailbox) {
363 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
364 for ($i = 0; $i < count($read_ary); $i++) {
365 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
366 return $regs[1];
367 }
368 }
369 return false; //"BUG! Couldn't get number of messages in $mailbox!";
370 }
371
372
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 */
381 function sqimap_find_email ($string) {
382 if (ereg("<([^>]+)>", $string, $regs)) {
383 $string = $regs[1];
384 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
385 $string = $regs[1];
386 }
387 return trim($string);
388 }
389
390
391 /*
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
399 */
400 function sqimap_find_displayable_name ($string) {
401 $string = trim($string);
402
403 if ( ereg('^(.+)<.*>', $string, $regs) ) {
404 $orig_string = $string;
405 $string = str_replace ('"', '', $regs[1] );
406 if (trim($string) == '') {
407 $string = sqimap_find_email($orig_string);
408 }
409 if( $string == '' || $string == ' ' ){
410 $string = '&nbsp';
411 }
412 }
413 elseif ( ereg('\((.*)\)', $string, $regs) ) {
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 }
423 }
424 else {
425 $string = str_replace ('"', '', sqimap_find_email($string));
426 }
427
428 return trim($string);
429 }
430
431 /*
432 * Returns the number of unseen messages in this folder
433 */
434 function sqimap_unseen_messages ($imap_stream, $mailbox) {
435 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
436 $i = 0;
437 $regs = array(false, false);
438 while (isset($read_ary[$i])) {
439 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
440 break;
441 }
442 $i++;
443 }
444 return $regs[1];
445 }
446
447 /*
448 * Returns the number of unseen/total messages in this folder
449 */
450 function 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
467
468 /*
469 * Saves a message to a given folder -- used for saving sent messages
470 */
471 function sqimap_append ($imap_stream, $sent_folder, $length) {
472 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
473 $tmp = fgets ($imap_stream, 1024);
474 }
475
476 function sqimap_append_done ($imap_stream, $folder='') {
477 global $squirrelmail_language, $color;
478 fputs ($imap_stream, "\r\n");
479 $tmp = fgets ($imap_stream, 1024);
480 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
481 set_up_language($squirrelmail_language);
482 require_once(SM_PATH . 'functions/display_messages.php');
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)) {
491 $string .= _("Solution: ") .
492 _("Remove unneccessary messages from your folder and start with your Trash folder.")
493 ."<br>\n";
494 }
495 $string .= "</font>\n";
496 error_box($string,$color);
497 } else {
498 $string = "<b><font color=$color[2]>\n" .
499 _("ERROR : Bad or malformed request.") .
500 "</b><br>\n" .
501 _("Server responded: ") .
502 $tmp . "</font><br>\n";
503 error_box($string,$color);
504 exit;
505 }
506 }
507 }
508
509 function sqimap_get_user_server ($imap_server, $username) {
510 if (substr($imap_server, 0, 4) != "map:") {
511 return $imap_server;
512 }
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
522 function map_yp_alias($username) {
523 $yp = `ypmatch $username aliases`;
524 return chop(substr($yp, strlen($username)+1));
525 }
526
527 ?>