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