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