Fixes from Jason to sqimap_read_data.
[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 * 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 echo "<br><b><font color=$color[2]>\n" .
125 _("ERROR : Could not complete request.") .
126 "</b><br>\n" .
127 _("Query:") .
128 $query . '<br>' .
129 _("Reason Given: ") .
130 $message . "</font><br>\n";
131 exit;
132 }
133 }
134 elseif ($response == 'BAD') {
135 set_up_language($squirrelmail_language);
136 echo "<br><b><font color=$color[2]>\n" .
137 _("ERROR : Bad or malformed request.") .
138 "</b><br>\n" .
139 _("Query:") .
140 $query . '<br>' .
141 _("Server responded: ") .
142 $message . "</font><br>\n";
143 exit;
144 }
145 else {
146 return $resultlist;
147 }
148 }
149
150 function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
151 $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
152
153 /* sqimap_read_data should be called for one response
154 but since it just calls sqimap_read_data_list which
155 handles multiple responses we need to check for that
156 and merge the $res array IF they are seperated and
157 IF it was a FETCH response. */
158
159 if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
160 && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
161 $result = array();
162 foreach($res as $index=>$value) {
163 $result = array_merge($result, $res["$index"]);
164 }
165 }
166 if (isset($result)) {
167 return $result;
168 }
169 else {
170 return $res[0];
171 }
172
173 }
174
175 /*
176 * Logs the user into the imap server. If $hide is set, no error messages
177 * will be displayed. This function returns the imap connection handle.
178 */
179 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
180 global $color, $squirrelmail_language, $HTTP_ACCEPT_LANGUAGE, $onetimepad;
181
182 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
183
184 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
185 if ( !$imap_stream ) {
186 return false;
187 }
188 $server_info = fgets ($imap_stream, 1024);
189
190 /* Decrypt the password */
191 $password = OneTimePadDecrypt($password, $onetimepad);
192
193 /* Do some error correction */
194 if (!$imap_stream) {
195 if (!$hide) {
196 set_up_language($squirrelmail_language, true);
197 printf (_("Error connecting to IMAP server: %s.")."<br>\r\n", $imap_server_address);
198 echo "$error_number : $error_string<br>\r\n";
199 }
200 exit;
201 }
202
203 $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
204 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
205
206 /* If the connection was not successful, lets see why */
207 if ($response != 'OK') {
208 if (!$hide) {
209 if ($response != 'NO') {
210 /* "BAD" and anything else gets reported here. */
211 set_up_language($squirrelmail_language, true);
212 if ($response == 'BAD') {
213 printf (_("Bad request: %s")."<br>\r\n", $message);
214 } else {
215 printf (_("Unknown error: %s") . "<br>\n", $message);
216 }
217 echo '<br>' . _("Read data:") . "<br>\n";
218 if (is_array($read)) {
219 foreach ($read as $line) {
220 echo htmlspecialchars($line) . "<br>\n";
221 }
222 }
223 exit;
224 } else {
225 /*
226 * If the user does not log in with the correct
227 * username and password it is not possible to get the
228 * correct locale from the user's preferences.
229 * Therefore, apply the same hack as on the login
230 * screen.
231 *
232 * $squirrelmail_language is set by a cookie when
233 * the user selects language and logs out
234 */
235
236 set_up_language($squirrelmail_language, true);
237 include_once( '../functions/display_messages.php' );
238 logout_error( _("Unknown user or password incorrect.") );
239 session_destroy();
240 exit;
241 }
242 } else {
243 exit;
244 }
245 }
246 return $imap_stream;
247 }
248
249 /* Simply logs out the IMAP session */
250 function sqimap_logout ($imap_stream) {
251 /* Logout is not valid until the server returns 'BYE' */
252 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
253 }
254
255 function sqimap_capability($imap_stream, $capability='') {
256 global $sqimap_capabilities;
257 if (!is_array($sqimap_capabilities)) {
258 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
259
260 $c = explode(' ', $read[0]);
261 for ($i=2; $i < count($c); $i++) {
262 $cap_list = explode('=', $c[$i]);
263 if (isset($cap_list[1])) {
264 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
265 } else {
266 $sqimap_capabilities[$cap_list[0]] = TRUE;
267 }
268 }
269 }
270 if ($capability) {
271 if (isset($sqimap_capabilities[$capability])) {
272 return $sqimap_capabilities[$capability];
273 } else {
274 return false;
275 }
276 }
277 return $sqimap_capabilities;
278 }
279
280 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
281 function sqimap_get_delimiter ($imap_stream = false) {
282 global $sqimap_delimiter, $optional_delimiter;
283
284 /* Use configured delimiter if set */
285 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
286 return $optional_delimiter;
287 }
288
289 /* Do some caching here */
290 if (!$sqimap_delimiter) {
291 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
292 /*
293 * According to something that I can't find, this is supposed to work on all systems
294 * OS: This won't work in Courier IMAP.
295 * OS: According to rfc2342 response from NAMESPACE command is:
296 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
297 * OS: We want to lookup all personal NAMESPACES...
298 */
299 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
300 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
301 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
302 $pn = $data2[1];
303 }
304 $pna = explode(')(', $pn);
305 while (list($k, $v) = each($pna)) {
306 $lst = explode('"', $v);
307 if (isset($lst[3])) {
308 $pn[$lst[1]] = $lst[3];
309 } else {
310 $pn[$lst[1]] = '';
311 }
312 }
313 }
314 $sqimap_delimiter = $pn[0];
315 } else {
316 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
317 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
318 $quote_position = strpos ($read[0], '"');
319 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
320 }
321 }
322 return $sqimap_delimiter;
323 }
324
325
326 /* Gets the number of messages in the current mailbox. */
327 function sqimap_get_num_messages ($imap_stream, $mailbox) {
328 $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", true, $result, $message);
329 for ($i = 0; $i < count($read_ary); $i++) {
330 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
331 return $regs[1];
332 }
333 }
334 return "BUG! Couldn't get number of messages in $mailbox!";
335 }
336
337
338 /* Returns a displayable email address.
339 * Luke Ehresman <lehresma@css.tayloru.edu>
340 * "Luke Ehresman" <lehresma@css.tayloru.edu>
341 * <lehresma@css.tayloru.edu>
342 * lehresma@css.tayloru.edu (Luke Ehresman)
343 * lehresma@css.tayloru.edu
344 * becomes: lehresma@css.tayloru.edu
345 */
346 function sqimap_find_email ($string) {
347 if (ereg("<([^>]+)>", $string, $regs)) {
348 $string = $regs[1];
349 } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
350 $string = $regs[1];
351 }
352 return trim($string);
353 }
354
355
356 /*
357 * Takes the From: field and creates a displayable name.
358 * Luke Ehresman <lkehresman@yahoo.com>
359 * "Luke Ehresman" <lkehresman@yahoo.com>
360 * lkehresman@yahoo.com (Luke Ehresman)
361 * becomes: Luke Ehresman
362 * <lkehresman@yahoo.com>
363 * becomes: lkehresman@yahoo.com
364 */
365 function sqimap_find_displayable_name ($string) {
366 $string = trim($string);
367
368 if ( ereg('^(.+)<.*>', $string, $regs) ) {
369 $orig_string = $string;
370 $string = str_replace ('"', '', $regs[1] );
371 if (trim($string) == '') {
372 $string = sqimap_find_email($orig_string);
373 }
374 if( $string == '' || $string == ' ' ){
375 $string = '&nbsp';
376 }
377 }
378 elseif ( ereg('\((.*)\)', $string, $regs) ) {
379 if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
380 if ( ereg('^(.+) \(', $string, $regs) ) {
381 $string = ereg_replace( ' \(\)$', '', $string );
382 } else {
383 $string = '&nbsp';
384 }
385 } else {
386 $string = $regs[1];
387 }
388 }
389 else {
390 $string = str_replace ('"', '', sqimap_find_email($string));
391 }
392
393 return trim($string);
394 }
395
396 /*
397 * Returns the number of unseen messages in this folder
398 */
399 function sqimap_unseen_messages ($imap_stream, $mailbox) {
400 $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", true, $result, $message);
401 $i = 0;
402 while (isset($read_ary[$i])) {
403 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
404 break;
405 }
406 $i++;
407 }
408 return $regs[1];
409 }
410
411
412 /*
413 * Saves a message to a given folder -- used for saving sent messages
414 */
415 function sqimap_append ($imap_stream, $sent_folder, $length) {
416 fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
417 $tmp = fgets ($imap_stream, 1024);
418 }
419
420 function sqimap_append_done ($imap_stream) {
421 fputs ($imap_stream, "\r\n");
422 $tmp = fgets ($imap_stream, 1024);
423 }
424
425 function sqimap_get_user_server ($imap_server, $username) {
426
427 if (substr($imap_server, 0, 4) != "map:") {
428 return $imap_server;
429 }
430
431 $function = substr($imap_server, 4);
432 return $function($username);
433 }
434
435 /* This is an example that gets imapservers from yellowpages (NIS).
436 * you can simple put map:map_yp_alias in your $imap_server_address
437 * in config.php use your own function instead map_yp_alias to map your
438 * LDAP whatever way to find the users imapserver. */
439
440 function map_yp_alias($username) {
441 $yp = `ypmatch $username aliases`;
442 return chop(substr($yp, strlen($username)+1));
443 }
444
445 ?>