UID support
[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('../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 * Reads the output from the IMAP stream. If handle_errors is set to true,
50 * this will also handle all errors that are received. If it is not set,
51 * the errors will be sent back through $response and $message
52 */
53 function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
54 global $color, $squirrelmail_language;
55
56 $read = '';
57 $bufsize = 9096;
58 $resultlist = array();
59 $pre_a = explode(' ',trim($pre));
60 $pre = $pre_a[0];
61 $more_msgs = true;
62 while ($more_msgs) {
63 $data = array();
64 $total_size = 0;
65
66 while (strpos($read, "\n") === false) {
67 if(!($read .= fgets($imap_stream, $bufsize))) {
68 break;
69 }
70 }
71 if (preg_match('/^\* [0-9]+ FETCH.*\{([0-9]+)\}/', $read, $regs)) {
72 $size = $regs[1];
73 } else if (preg_match('/^\* [0-9]+ FETCH/', $read, $regs)) {
74 /* Sizeless response, probably single-line */
75 $size = -1;
76 $data[] = $read;
77 $read = fgets($imap_stream, $bufsize);
78 } else {
79 $size = -1;
80 }
81 while (1) {
82 while (strpos($read, "\n") === false) {
83 if(!($read .= fgets($imap_stream, $bufsize))) {
84 break;
85 }
86 }
87 /* If we know the size, no need to look at the end parameters */
88 /* In case of a totalsize > size we do have to look at the end
89 parameters because there can exists literals inside bodystructures.
90 */
91 if ($size > 0) {
92 if ($total_size == $size) {
93 /* We've reached the end of this 'message', switch to the next one. */
94 $data[] = $read;
95 break;
96 } else if ($total_size > $size) {
97 $size = -1; /* switch to end parameters in case of literals inside a bodystructure */
98 $difference = $total_size - $size;
99 $total_size = $total_size - strlen($read);
100 $data[] = substr ($read, 0, strlen($read)-$difference);
101 $read = substr ($read, strlen($read)-$difference, strlen($read));
102 } else {
103 $data[] = $read;
104 $read = fgets($imap_stream, $bufsize);
105 while (strpos($read, "\n") === false) {
106 $read .= fgets($imap_stream, $bufsize);
107 }
108 }
109 $total_size += strlen($read);
110 } else {
111 if (preg_match("/^$pre (OK|BAD|NO)(.*)/", $read, $regs) ||
112 (($size == -1) && preg_match('/^\* [0-9]+ FETCH.*/', $read, $regs))) {
113 break;
114 } else if ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
115 /*
116 * This block has been added in order to avoid the problem
117 * caused by the * OK [PARSE] Missing parameter answer
118 * Please, replace it with a better parsing if you know how.
119 * This block has been updated by
120 * Seth E. Randall <sethr@missoulafcu.org>. Once we see
121 * one OK [PARSE line, we just go through and keep
122 * tossing them out until we get something different.
123 */
124 while ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
125 $read = fgets($imap_stream, $bufsize);
126 }
127 $data[] = $read;
128 $read = fgets ($imap_stream, $bufsize);
129 } else if (preg_match('/^\* BYE \[ALERT\](.*)/', $read, $regs)) {
130 /*
131 * It seems that the IMAP server has coughed up a lung
132 * and hung up the connection. Print any info we have
133 * and abort.
134 */
135 echo _("Please contact your system administrator and report the following error:") . "<br>\n";
136 echo $regs[1];
137 exit;
138 } else {
139 $data[] = $read;
140 $read = fgets ($imap_stream, $bufsize);
141 }
142 }
143 }
144
145 while (($more_msgs = !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs)) &&
146 !preg_match("/^\* [0-9]+ FETCH.*/", $read, $regs)) {
147 $read = fgets($imap_stream, $bufsize);
148 }
149 $resultlist[] = $data;
150 }
151
152 $response = $regs[1];
153 $message = trim($regs[2]);
154
155 if ($handle_errors == false) {
156 return( $resultlist );
157 } else if ($response == 'NO') {
158 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
159 if (strstr($message, 'command resulted in') === false) {
160 set_up_language($squirrelmail_language);
161 echo "<br><b><font color=$color[2]>\n" .
162 _("ERROR : Could not complete request.") .
163 "</b><br>\n" .
164 _("Query:") .
165 $query . '<br>' .
166 _("Reason Given: ") .
167 $message . "</font><br>\n";
168 exit;
169 }
170 } else if ($response == 'BAD') {
171 set_up_language($squirrelmail_language);
172 echo "<br><b><font color=$color[2]>\n" .
173 _("ERROR : Bad or malformed request.") .
174 "</b><br>\n" .
175 _("Query:") .
176 $query . '<br>' .
177 _("Server responded: ") .
178 $message . "</font><br>\n";
179 exit;
180 } else {
181 return $resultlist;
182 }
183 }
184
185 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
186 $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
187 return $res[0];
188 }
189
190 /*
191 * Logs the user into the imap server. If $hide is set, no error messages
192 * will be displayed. This function returns the imap connection handle.
193 */
194 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
195 global $color, $squirrelmail_language, $HTTP_ACCEPT_LANGUAGE, $onetimepad;
196
197 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
198 if ( !$imap_stream ) {
199 return false;
200 }
201 $server_info = fgets ($imap_stream, 1024);
202
203 /* Decrypt the password */
204 $password = OneTimePadDecrypt($password, $onetimepad);
205
206 /* Do some error correction */
207 if (!$imap_stream) {
208 if (!$hide) {
209 set_up_language($squirrelmail_language, true);
210 printf (_("Error connecting to IMAP server: %s.")."<br>\r\n", $imap_server_address);
211 echo "$error_number : $error_string<br>\r\n";
212 }
213 exit;
214 }
215
216 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
217 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
218
219 /* If the connection was not successful, lets see why */
220 if ($response != 'OK') {
221 if (!$hide) {
222 if ($response != 'NO') {
223 /* "BAD" and anything else gets reported here. */
224 set_up_language($squirrelmail_language, true);
225 if ($response == 'BAD') {
226 printf (_("Bad request: %s")."<br>\r\n", $message);
227 } else {
228 printf (_("Unknown error: %s") . "<br>\n", $message);
229 }
230 echo '<br>' . _("Read data:") . "<br>\n";
231 if (is_array($read)) {
232 foreach ($read as $line) {
233 echo htmlspecialchars($line) . "<br>\n";
234 }
235 }
236 exit;
237 } else {
238 /*
239 * If the user does not log in with the correct
240 * username and password it is not possible to get the
241 * correct locale from the user's preferences.
242 * Therefore, apply the same hack as on the login
243 * screen.
244 *
245 * $squirrelmail_language is set by a cookie when
246 * the user selects language and logs out
247 */
248
249 set_up_language($squirrelmail_language, true);
250 include_once( '../functions/display_messages.php' );
251 logout_error( _("Unknown user or password incorrect.") );
252 session_destroy();
253 exit;
254 }
255 } else {
256 exit;
257 }
258 }
259 return $imap_stream;
260 }
261
262 /* Simply logs out the IMAP session */
263 function sqimap_logout ($imap_stream) {
264 /* Logout is not valid until the server returns 'BYE' */
265 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
266 }
267
268 function sqimap_capability($imap_stream, $capability='') {
269 global $sqimap_capabilities;
270 if (!is_array($sqimap_capabilities)) {
271 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
272
273 $c = explode(' ', $read[0]);
274 for ($i=2; $i < count($c); $i++) {
275 $cap_list = explode('=', $c[$i]);
276 if (isset($cap_list[1])) {
277 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
278 } else {
279 $sqimap_capabilities[$cap_list[0]] = TRUE;
280 }
281 }
282 }
283 if ($capability) {
284 if (isset($sqimap_capabilities[$capability])) {
285 return $sqimap_capabilities[$capability];
286 } else {
287 return false;
288 }
289 }
290 return $sqimap_capabilities;
291 }
292
293 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
294 function sqimap_get_delimiter ($imap_stream = false) {
295 global $sqimap_delimiter, $optional_delimiter;
296
297 /* Use configured delimiter if set */
298 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
299 return $optional_delimiter;
300 }
301
302 /* Do some caching here */
303 if (!$sqimap_delimiter) {
304 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
305 /*
306 * According to something that I can't find, this is supposed to work on all systems
307 * OS: This won't work in Courier IMAP.
308 * OS: According to rfc2342 response from NAMESPACE command is:
309 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
310 * OS: We want to lookup all personal NAMESPACES...
311 */
312 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
313 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
314 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
315 $pn = $data2[1];
316 }
317 $pna = explode(')(', $pn);
318 while (list($k, $v) = each($pna)) {
319 $lst = explode('"', $v);
320 if (isset($lst[3])) {
321 $pn[$lst[1]] = $lst[3];
322 } else {
323 $pn[$lst[1]] = '';
324 }
325 }
326 }
327 $sqimap_delimiter = $pn[0];
328 } else {
329 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
330 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
331 $quote_position = strpos ($read[0], '"');
332 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
333 }
334 }
335 return $sqimap_delimiter;
336 }
337
338
339 /* Gets the number of messages in the current mailbox. */
340 function sqimap_get_num_messages ($imap_stream, $mailbox) {
341 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", true, $result, $message);
342 for ($i = 0; $i < count($read_ary); $i++) {
343 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
344 return $regs[1];
345 }
346 }
347 return "BUG! Couldn't get number of messages in $mailbox!";
348 }
349
350
351 /* Returns a displayable email address.
352 * Luke Ehresman <lehresma@css.tayloru.edu>
353 * "Luke Ehresman" <lehresma@css.tayloru.edu>
354 * <lehresma@css.tayloru.edu>
355 * lehresma@css.tayloru.edu (Luke Ehresman)
356 * lehresma@css.tayloru.edu
357 * becomes: lehresma@css.tayloru.edu
358 */
359 function sqimap_find_email ($string) {
360 if (ereg("<([^>]+)>", $string, $regs)) {
361 $string = $regs[1];
362 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
363 $string = $regs[1];
364 }
365 return trim($string);
366 }
367
368
369 /*
370 * Takes the From: field and creates a displayable name.
371 * Luke Ehresman <lkehresman@yahoo.com>
372 * "Luke Ehresman" <lkehresman@yahoo.com>
373 * lkehresman@yahoo.com (Luke Ehresman)
374 * becomes: Luke Ehresman
375 * <lkehresman@yahoo.com>
376 * becomes: lkehresman@yahoo.com
377 */
378 function sqimap_find_displayable_name ($string) {
379 $string = trim($string);
380
381 if ( ereg('^(.+)<.*>', $string, $regs) ) {
382 $orig_string = $string;
383 $string = str_replace ('"', '', $regs[1] );
384 if (trim($string) == '') {
385 $string = sqimap_find_email($orig_string);
386 }
387 if( $string == '' || $string == ' ' ){
388 $string = '&nbsp';
389 }
390 }
391 elseif ( ereg('\((.*)\)', $string, $regs) ) {
392 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
393 if ( ereg('^(.+) \(', $string, $regs) ) {
394 $string = ereg_replace( ' \(\)$', '', $string );
395 } else {
396 $string = '&nbsp';
397 }
398 } else {
399 $string = $regs[1];
400 }
401 }
402 else {
403 $string = str_replace ('"', '', sqimap_find_email($string));
404 }
405
406 return trim($string);
407 }
408
409 /*
410 * Returns the number of unseen messages in this folder
411 */
412 function sqimap_unseen_messages ($imap_stream, $mailbox) {
413 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", true, $result, $message);
414 $i = 0;
415 while (isset($read_ary[$i])) {
416 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
417 break;
418 }
419 $i++;
420 }
421 return $regs[1];
422 }
423
424
425 /*
426 * Saves a message to a given folder -- used for saving sent messages
427 */
428 function sqimap_append ($imap_stream, $sent_folder, $length) {
429 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
430 $tmp = fgets ($imap_stream, 1024);
431 }
432
433 function sqimap_append_done ($imap_stream) {
434 fputs ($imap_stream, "\r\n");
435 $tmp = fgets ($imap_stream, 1024);
436 }
437
438 ?>