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