Another sneaky folder list (or two)
[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 * If we don't have an imap_ stream we're already logged out */
262 if(isset($imap_stream) && $imap_stream)
263 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
264 }
265
266 function sqimap_capability($imap_stream, $capability='') {
267 global $sqimap_capabilities;
268 if (!is_array($sqimap_capabilities)) {
269 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
270
271 $c = explode(' ', $read[0]);
272 for ($i=2; $i < count($c); $i++) {
273 $cap_list = explode('=', $c[$i]);
274 if (isset($cap_list[1])) {
275 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
276 } else {
277 $sqimap_capabilities[$cap_list[0]] = TRUE;
278 }
279 }
280 }
281 if ($capability) {
282 if (isset($sqimap_capabilities[$capability])) {
283 return $sqimap_capabilities[$capability];
284 } else {
285 return false;
286 }
287 }
288 return $sqimap_capabilities;
289 }
290
291 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
292 function sqimap_get_delimiter ($imap_stream = false) {
293 global $sqimap_delimiter, $optional_delimiter;
294
295 /* Use configured delimiter if set */
296 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
297 return $optional_delimiter;
298 }
299
300 /* Do some caching here */
301 if (!$sqimap_delimiter) {
302 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
303 /*
304 * According to something that I can't find, this is supposed to work on all systems
305 * OS: This won't work in Courier IMAP.
306 * OS: According to rfc2342 response from NAMESPACE command is:
307 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
308 * OS: We want to lookup all personal NAMESPACES...
309 */
310 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
311 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
312 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
313 $pn = $data2[1];
314 }
315 $pna = explode(')(', $pn);
316 while (list($k, $v) = each($pna)) {
317 $lst = explode('"', $v);
318 if (isset($lst[3])) {
319 $pn[$lst[1]] = $lst[3];
320 } else {
321 $pn[$lst[1]] = '';
322 }
323 }
324 }
325 $sqimap_delimiter = $pn[0];
326 } else {
327 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
328 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
329 $quote_position = strpos ($read[0], '"');
330 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
331 }
332 }
333 return $sqimap_delimiter;
334 }
335
336
337 /* Gets the number of messages in the current mailbox. */
338 function sqimap_get_num_messages ($imap_stream, $mailbox) {
339 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
340 for ($i = 0; $i < count($read_ary); $i++) {
341 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
342 return $regs[1];
343 }
344 }
345 return false; //"BUG! Couldn't get number of messages in $mailbox!";
346 }
347
348
349 /* Returns a displayable email address.
350 * Luke Ehresman <lehresma@css.tayloru.edu>
351 * "Luke Ehresman" <lehresma@css.tayloru.edu>
352 * <lehresma@css.tayloru.edu>
353 * lehresma@css.tayloru.edu (Luke Ehresman)
354 * lehresma@css.tayloru.edu
355 * becomes: lehresma@css.tayloru.edu
356 */
357 function sqimap_find_email ($string) {
358 if (ereg("<([^>]+)>", $string, $regs)) {
359 $string = $regs[1];
360 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
361 $string = $regs[1];
362 }
363 return trim($string);
364 }
365
366
367 /*
368 * Takes the From: field and creates a displayable name.
369 * Luke Ehresman <lkehresman@yahoo.com>
370 * "Luke Ehresman" <lkehresman@yahoo.com>
371 * lkehresman@yahoo.com (Luke Ehresman)
372 * becomes: Luke Ehresman
373 * <lkehresman@yahoo.com>
374 * becomes: lkehresman@yahoo.com
375 */
376 function sqimap_find_displayable_name ($string) {
377 $string = trim($string);
378
379 if ( ereg('^(.+)<.*>', $string, $regs) ) {
380 $orig_string = $string;
381 $string = str_replace ('"', '', $regs[1] );
382 if (trim($string) == '') {
383 $string = sqimap_find_email($orig_string);
384 }
385 if( $string == '' || $string == ' ' ){
386 $string = '&nbsp';
387 }
388 }
389 elseif ( ereg('\((.*)\)', $string, $regs) ) {
390 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
391 if ( ereg('^(.+) \(', $string, $regs) ) {
392 $string = ereg_replace( ' \(\)$', '', $string );
393 } else {
394 $string = '&nbsp';
395 }
396 } else {
397 $string = $regs[1];
398 }
399 }
400 else {
401 $string = str_replace ('"', '', sqimap_find_email($string));
402 }
403
404 return trim($string);
405 }
406
407 /*
408 * Returns the number of unseen messages in this folder
409 */
410 function sqimap_unseen_messages ($imap_stream, $mailbox) {
411 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
412 $i = 0;
413 $regs = array(false, false);
414 while (isset($read_ary[$i])) {
415 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
416 break;
417 }
418 $i++;
419 }
420 return $regs[1];
421 }
422
423 /*
424 * Returns the number of unseen/total messages in this folder
425 */
426 function sqimap_status_messages ($imap_stream, $mailbox) {
427 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
428 $i = 0;
429 $messages = $unseen = false;
430 $regs = array(false,false);
431 while (isset($read_ary[$i])) {
432 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
433 $unseen = $regs[1];
434 }
435 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
436 $messages = $regs[1];
437 }
438 $i++;
439 }
440 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
441 }
442
443
444 /*
445 * Saves a message to a given folder -- used for saving sent messages
446 */
447 function sqimap_append ($imap_stream, $sent_folder, $length) {
448 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
449 $tmp = fgets ($imap_stream, 1024);
450 }
451
452 function sqimap_append_done ($imap_stream) {
453 global $squirrelmail_language, $color;
454 fputs ($imap_stream, "\r\n");
455 $tmp = fgets ($imap_stream, 1024);
456 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
457 set_up_language($squirrelmail_language);
458 require_once(SM_PATH . 'functions/display_messages.php');
459 $string = "<b><font color=$color[2]>\n" .
460 _("ERROR : Bad or malformed request.") .
461 "</b><br>\n" .
462 _("Server responded: ") .
463 $tmp . "</font><br>\n";
464 error_box($string,$color);
465 exit;
466 }
467 }
468
469 function sqimap_get_user_server ($imap_server, $username) {
470 if (substr($imap_server, 0, 4) != "map:") {
471 return $imap_server;
472 }
473 $function = substr($imap_server, 4);
474 return $function($username);
475 }
476
477 /* This is an example that gets imapservers from yellowpages (NIS).
478 * you can simple put map:map_yp_alias in your $imap_server_address
479 * in config.php use your own function instead map_yp_alias to map your
480 * LDAP whatever way to find the users imapserver. */
481
482 function map_yp_alias($username) {
483 $yp = `ypmatch $username aliases`;
484 return chop(substr($yp, strlen($username)+1));
485 }
486
487 ?>