b53a2104e84b728b2986f34b8fa95d9a8f7392a6
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2003 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 require_once(SM_PATH . 'functions/auth.php');
16
17
18 global $sqimap_session_id;
19 $sqimap_session_id = 1;
20
21 /* Sets an unique session id in order to avoid simultanous sessions crash. */
22 function sqimap_session_id($unique_id = false) {
23 global $data_dir, $username, $sqimap_session_id;
24 if (!$unique_id) {
25 return( sprintf("A%03d", $sqimap_session_id++) );
26 } else {
27 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
28 }
29 }
30
31 /*
32 * Both send a command and accept the result from the command.
33 * This is to allow proper session number handling.
34 */
35 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
36 if ($imap_stream) {
37 $sid = sqimap_session_id($unique_id);
38 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
39 $tag_uid_a = explode(' ',trim($sid));
40 $tag = $tag_uid_a[0];
41 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
42 /* get the response and the message */
43 $message = $message[$tag];
44 $response = $response[$tag];
45 return $read[$tag];
46 } else {
47 global $squirrelmail_language, $color;
48 set_up_language($squirrelmail_language);
49 require_once(SM_PATH . 'functions/display_messages.php');
50 $string = "<b><font color=$color[2]>\n" .
51 _("ERROR : No available imapstream.") .
52 "</b></font>\n";
53 error_box($string,$color);
54 return false;
55 }
56 }
57
58 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
59 &$message, $unique_id = false,$filter=false,
60 $outputstream=false,$no_return=false) {
61 if ($imap_stream) {
62 $sid = sqimap_session_id($unique_id);
63 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
64 $tag_uid_a = explode(' ',trim($sid));
65 $tag = $tag_uid_a[0];
66
67 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
68 $message, $query,$filter,$outputstream,$no_return);
69 /* retrieve the response and the message */
70 $response = $response[$tag];
71 $message = $message[$tag];
72
73 if (!empty($read[$tag])) {
74 return $read[$tag][0];
75 } else {
76 return $read[$tag];
77 }
78 } else {
79 global $squirrelmail_language, $color;
80 set_up_language($squirrelmail_language);
81 require_once(SM_PATH . 'functions/display_messages.php');
82 $string = "<b><font color=$color[2]>\n" .
83 _("ERROR : No available imapstream.") .
84 "</b></font>\n";
85 error_box($string,$color);
86 return false;
87 }
88 }
89 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
90 $sid = sqimap_session_id($unique_id);
91 $tag_uid_a = explode(' ',trim($sid));
92 $tag = $tag_uid_a[0];
93 $query = $sid . ' '.$new_query."\r\n";
94 $aQuery[$tag] = $query;
95 }
96
97 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
98 &$aServerResponse, &$aServerMessage, $unique_id = false,
99 $filter=false,$outputstream=false,$no_return=false) {
100 $aResponse = false;
101
102 /*
103 Do not fire all calls at once to the imap-server but split the calls up
104 in portions of $iChunkSize. If we do not do that I think we misbehave as
105 IMAP client or should handle BYE calls if the IMAP-server drops the
106 connection because the number of queries is to large. This isn't tested
107 but a wild guess how it could work in the field.
108
109 After testing it on Exchange 2000 we discovered that a chunksize of 32
110 was quicker then when we raised it to 128.
111 */
112 $iQueryCount = count($aQueryList);
113 $iChunkSize = 32;
114 // array_chunk would also do the job but it's supported from php > 4.2
115 $aQueryChunks = array();
116 $iLoops = floor($iQueryCount / $iChunkSize);
117
118 if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
119
120 if (!function_exists('array_chunk')) { // arraychunk replacement
121 reset($aQueryList);
122 for($i=0;$i<$iLoops;++$i) {
123 for($j=0;$j<$iChunkSize;++$j) {
124 $key = key($aQueryList);
125 $aTmp[$key] = $aQueryList[$key];
126 if (next($aQueryList) === false) break;
127 }
128 $aQueryChunks[] = $aTmp;
129 }
130 } else {
131 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
132 }
133
134 for ($i=0;$i<$iLoops;++$i) {
135 $aQuery = $aQueryChunks[$i];
136 foreach($aQuery as $tag => $query) {
137 fputs($imap_stream,$query);
138 $aResults[$tag] = false;
139 }
140 foreach($aQuery as $tag => $query) {
141 if ($aResults[$tag] == false) {
142 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
143 $handle_errors, $response, $message, $query,
144 $filter,$outputstream,$no_return);
145 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
146 if (!empty($aResponse)) {
147 $aResults[$returned_tag] = $aResponse[0];
148 } else {
149 $aResults[$returned_tag] = $aResponse;
150 }
151 $aServerResponse[$returned_tag] = $response[$returned_tag];
152 $aServerMessage[$returned_tag] = $message[$returned_tag];
153 }
154 }
155 }
156 }
157 return $aResults;
158 }
159
160 /*
161 * custom fgets function. gets a line from IMAP
162 * no matter how big it may be
163 */
164
165 function sqimap_fgets($imap_stream) {
166 $read = '';
167 $buffer = 4096;
168 $results = '';
169 $offset = 0;
170 while (strpos($results, "\r\n", $offset) === false) {
171 if (!($read = fgets($imap_stream, $buffer))) {
172 /* this happens in case of an error */
173 /* reset $results because it's useless */
174 $results = false;
175 break;
176 }
177 if ( $results != '' ) {
178 $offset = strlen($results) - 1;
179 }
180 $results .= $read;
181 }
182 return $results;
183 }
184
185 function sqimap_fread($imap_stream,$iSize,$filter=false,
186 $outputstream=false, $no_return=false) {
187 if (!$filter || !$outputstream) {
188 $iBufferSize = $iSize;
189 } else {
190 // see php bug 24033. They changed fread behaviour %$^&$%
191 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
192 }
193 if ($iSize < $iBufferSize) {
194 $iBufferSize = $iSize;
195 }
196 $iRetrieved = 0;
197 $results = '';
198 $sRead = $sReadRem = '';
199 // NB: fread can also stop at end of a packet on sockets.
200 while ($iRetrieved < $iSize) {
201 $sRead = fread($imap_stream,$iBufferSize);
202 $iLength = strlen($sRead);
203 $iRetrieved += $iLength ;
204 $iRemaining = $iSize - $iRetrieved;
205 if ($iRemaining < $iBufferSize) {
206 $iBufferSize = $iRemaining;
207 }
208 if (!$sRead) {
209 $results = false;
210 break;
211 }
212 if ($sReadRem) {
213 $sRead = $sReadRem . $sRead;
214 $sReadRem = '';
215 }
216 if (substr($sRead,-1) !== "\n") {
217 $i = strrpos($sRead,"\n");
218 if ($i !== false && $iRetrieved<$iSize) {
219 ++$i;
220 $sReadRem = substr($sRead,$i);
221 $sRead = substr($sRead,0,$i);
222 } else if ($iLength && $iRetrieved<$iSize) { // linelength > received buffer
223 $sReadRem = $sRead;
224 $sRead = '';
225 }
226 }
227 if ($filter && $sRead) {
228 $filter($sRead);
229 }
230 if ($outputstream && $sRead) {
231 if (is_resource($outputstream)) {
232 fwrite($outputstream,$sRead);
233 } else if ($outputstream == 'php://stdout') {
234 echo $sRead;
235 }
236 }
237 if ($no_return) {
238 $sRead = '';
239 } else {
240 $results .= $sRead;
241 }
242 }
243 return $results;
244 }
245
246 /* obsolete function, inform plugins that use it */
247 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
248 &$response, &$message, $query = '') {
249 global $color, $squirrelmail_language;
250 set_up_language($squirrelmail_language);
251 require_once(SM_PATH . 'functions/display_messages.php');
252 $string = "<b><font color=$color[2]>\n" .
253 _("ERROR : Bad function call.") .
254 "</b><br>\n" .
255 _("Reason:") . ' '.
256 'There is a plugin installed which make use of the <br>' .
257 'SquirrelMail internal function sqimap_read_data_list.<br>'.
258 'Please adapt the installed plugin and let it use<br>'.
259 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
260 'The following query was issued:<br>'.
261 htmlspecialchars($query) . '<br>' . "</font><br>\n";
262 error_box($string,$color);
263 echo '</body></html>';
264 exit;
265 }
266
267 function sqimap_error_box($title, $query = '', $message_title = '', $message = '')
268 {
269 global $color, $squirrelmail_language;
270
271 set_up_language($squirrelmail_language);
272 require_once(SM_PATH . 'functions/display_messages.php');
273 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
274 $cmd = explode(' ',$query);
275 $cmd= strtolower($cmd[0]);
276
277 if ($query != '' && $cmd != 'login')
278 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
279 if ($message_title != '')
280 $string .= $message_title;
281 if ($message != '')
282 $string .= htmlspecialchars($message);
283 $string .= "</font><br>\n";
284 error_box($string,$color);
285 }
286
287 /*
288 * Reads the output from the IMAP stream. If handle_errors is set to true,
289 * this will also handle all errors that are received. If it is not set,
290 * the errors will be sent back through $response and $message
291 */
292
293 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
294 &$response, &$message, $query = '',
295 $filter = false, $outputstream = false, $no_return = false) {
296 global $color, $squirrelmail_language;
297 $read = '';
298 if (!is_array($message)) $message = array();
299 if (!is_array($response)) $response = array();
300 $resultlist = array();
301 $data = array();
302 $read = sqimap_fgets($imap_stream);
303 $i = $k = 0;
304 while ($read) {
305 $char = $read{0};
306 switch ($char)
307 {
308 case '+':
309 default:
310 $read = sqimap_fgets($imap_stream);
311 break;
312
313 case $tag{0}:
314 {
315 /* get the command */
316 $arg = '';
317 $i = strlen($tag)+1;
318 $s = substr($read,$i);
319 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
320 $arg = substr($s,0,$j);
321 }
322 $found_tag = substr($read,0,$i-1);
323 if ($found_tag) {
324 switch ($arg)
325 {
326 case 'OK':
327 case 'BAD':
328 case 'NO':
329 case 'BYE':
330 case 'PREAUTH':
331 $response[$found_tag] = $arg;
332 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
333 if (!empty($data)) {
334 $resultlist[] = $data;
335 }
336 $aResponse[$found_tag] = $resultlist;
337 $data = $resultlist = array();
338 if ($found_tag == $tag) {
339 break 3; /* switch switch while */
340 }
341 break;
342 default:
343 /* this shouldn't happen */
344 $response[$found_tag] = $arg;
345 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
346 if (!empty($data)) {
347 $resultlist[] = $data;
348 }
349 $aResponse[$found_tag] = $resultlist;
350 $data = $resultlist = array();
351 if ($found_tag == $tag) {
352 break 3; /* switch switch while */
353 }
354 }
355 }
356 $read = sqimap_fgets($imap_stream);
357 if ($read === false) { /* error */
358 break 3; /* switch switch while */
359 }
360 break;
361 } // end case $tag{0}
362
363 case '*':
364 {
365 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
366 /* check for literal */
367 $s = substr($read,-3);
368 $fetch_data = array();
369 do { /* outer loop, continue until next untagged fetch
370 or tagged reponse */
371 do { /* innerloop for fetching literals. with this loop
372 we prohibid that literal responses appear in the
373 outer loop so we can trust the untagged and
374 tagged info provided by $read */
375 if ($s === "}\r\n") {
376 $j = strrpos($read,'{');
377 $iLit = substr($read,$j+1,-3);
378 $fetch_data[] = $read;
379 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
380 if ($sLiteral === false) { /* error */
381 break 4; /* while while switch while */
382 }
383 /* backwards compattibility */
384 $aLiteral = explode("\n", $sLiteral);
385 /* release not neaded data */
386 unset($sLiteral);
387 foreach ($aLiteral as $line) {
388 $fetch_data[] = $line ."\n";
389 }
390 /* release not neaded data */
391 unset($aLiteral);
392 /* next fgets belongs to this fetch because
393 we just got the exact literalsize and there
394 must follow data to complete the response */
395 $read = sqimap_fgets($imap_stream);
396 if ($read === false) { /* error */
397 break 4; /* while while switch while */
398 }
399 $fetch_data[] = $read;
400 } else {
401 $fetch_data[] = $read;
402 }
403 /* retrieve next line and check in the while
404 statements if it belongs to this fetch response */
405 $read = sqimap_fgets($imap_stream);
406 if ($read === false) { /* error */
407 break 4; /* while while switch while */
408 }
409 /* check for next untagged reponse and break */
410 if ($read{0} == '*') break 2;
411 $s = substr($read,-3);
412 } while ($s === "}\r\n");
413 $s = substr($read,-3);
414 } while ($read{0} !== '*' &&
415 substr($read,0,strlen($tag)) !== $tag);
416 $resultlist[] = $fetch_data;
417 /* release not neaded data */
418 unset ($fetch_data);
419 } else {
420 $s = substr($read,-3);
421 do {
422 if ($s === "}\r\n") {
423 $j = strrpos($read,'{');
424 $iLit = substr($read,$j+1,-3);
425 $data[] = $read;
426 $sLiteral = fread($imap_stream,$iLit);
427 if ($sLiteral === false) { /* error */
428 $read = false;
429 break 3; /* while switch while */
430 }
431 $data[] = $sLiteral;
432 $data[] = sqimap_fgets($imap_stream);
433 } else {
434 $data[] = $read;
435 }
436 $read = sqimap_fgets($imap_stream);
437 if ($read === false) {
438 break 3; /* while switch while */
439 } else if ($read{0} == '*') {
440 break;
441 }
442 $s = substr($read,-3);
443 } while ($s === "}\r\n");
444 break 1;
445 }
446 break;
447 } // end case '*'
448 } // end switch
449 } // end while
450
451 /* error processing in case $read is false */
452 if ($read === false) {
453 unset($data);
454 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
455 exit;
456 }
457
458 /* Set $resultlist array */
459 if (!empty($data)) {
460 //$resultlist[] = $data;
461 }
462 elseif (empty($resultlist)) {
463 $resultlist[] = array();
464 }
465
466 /* Return result or handle errors */
467 if ($handle_errors == false) {
468 return $aResponse;
469 return( $resultlist ); //?? Why this?
470 }
471 switch ($response[$tag]) {
472 case 'OK':
473 return $aResponse;
474 break;
475 case 'NO':
476 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
477 if (strstr($message[$tag], 'command resulted in') === false) {
478 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
479 echo '</body></html>';
480 exit;
481 }
482 break;
483 case 'BAD':
484 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
485 echo '</body></html>';
486 exit;
487 case 'BYE':
488 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
489 echo '</body></html>';
490 exit;
491 default:
492 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
493 /* the error is displayed but because we don't know the reponse we
494 return the result anyway */
495 return $aResponse;
496 break;
497 }
498 }
499
500 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
501 &$response, &$message, $query = '',
502 $filter=false,$outputstream=false,$no_return=false) {
503
504 $tag_uid_a = explode(' ',trim($tag_uid));
505 $tag = $tag_uid_a[0];
506
507 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
508 $response, $message, $query,$filter,$outputstream,$no_return);
509 /* sqimap_read_data should be called for one response
510 but since it just calls sqimap_retrieve_imap_response which
511 handles multiple responses we need to check for that
512 and merge the $res array IF they are seperated and
513 IF it was a FETCH response. */
514
515 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
516 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
517 // $result = array();
518 // foreach($res as $index=>$value) {
519 // $result = array_merge($result, $res["$index"]);
520 // }
521 // }
522 if (isset($result)) {
523 return $result[$tag];
524 }
525 else {
526 return $res;
527 }
528 }
529
530 /*
531 * Logs the user into the imap server. If $hide is set, no error messages
532 * will be displayed. This function returns the imap connection handle.
533 */
534 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
535 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
536
537 if (!isset($onetimepad) || empty($onetimepad)) {
538 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
539 }
540 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
541 $host=$imap_server_address;
542
543 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
544 /* Use TLS by prefixing "tls://" to the hostname */
545 $imap_server_address = 'tls://' . $imap_server_address;
546 }
547
548 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
549
550 /* Do some error correction */
551 if (!$imap_stream) {
552 if (!$hide) {
553 set_up_language($squirrelmail_language, true);
554 require_once(SM_PATH . 'functions/display_messages.php');
555 $string = sprintf (_("Error connecting to IMAP server: %s.") .
556 "<br>\r\n", $imap_server_address) .
557 "$error_number : $error_string<br>\r\n";
558 logout_error($string,$color);
559 }
560 exit;
561 }
562
563 $server_info = fgets ($imap_stream, 1024);
564
565 /* Decrypt the password */
566 $password = OneTimePadDecrypt($password, $onetimepad);
567
568 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
569 // We're using some sort of authentication OTHER than plain or login
570 $tag=sqimap_session_id(false);
571 if ($imap_auth_mech == 'digest-md5') {
572 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
573 } elseif ($imap_auth_mech == 'cram-md5') {
574 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
575 }
576 fputs($imap_stream,$query);
577 $answer=sqimap_fgets($imap_stream);
578 // Trim the "+ " off the front
579 $response=explode(" ",$answer,3);
580 if ($response[0] == '+') {
581 // Got a challenge back
582 $challenge=$response[1];
583 if ($imap_auth_mech == 'digest-md5') {
584 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
585 } elseif ($imap_auth_mech == 'cram-md5') {
586 $reply = cram_md5_response($username,$password,$challenge);
587 }
588 fputs($imap_stream,$reply);
589 $read=sqimap_fgets($imap_stream);
590 if ($imap_auth_mech == 'digest-md5') {
591 // DIGEST-MD5 has an extra step..
592 if (substr($read,0,1) == '+') { // OK so far..
593 fputs($imap_stream,"\r\n");
594 $read=sqimap_fgets($imap_stream);
595 }
596 }
597 $results=explode(" ",$read,3);
598 $response=$results[1];
599 $message=$results[2];
600 } else {
601 // Fake the response, so the error trap at the bottom will work
602 $response="BAD";
603 $message='IMAP server does not appear to support the authentication method selected.';
604 $message .= ' Please contact your system administrator.';
605 }
606 } elseif ($imap_auth_mech == 'login') {
607 // Original IMAP login code
608 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
609 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
610 } elseif ($imap_auth_mech == 'plain') {
611 /* SASL PLAIN */
612 $tag=sqimap_session_id(false);
613 $auth = base64_encode("$username\0$username\0$password");
614
615 $query = $tag . " AUTHENTICATE PLAIN\r\n";
616 fputs($imap_stream, $query);
617 $read=sqimap_fgets($imap_stream);
618
619 if (substr($read,0,1) == '+') { // OK so far..
620 fputs($imap_stream, "$auth\r\n");
621 $read = sqimap_fgets($imap_stream);
622 }
623
624 $results=explode(" ",$read,3);
625 $response=$results[1];
626 $message=$results[2];
627 } else {
628 $response="BAD";
629 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
630 }
631
632 /* If the connection was not successful, lets see why */
633 if ($response != 'OK') {
634 if (!$hide) {
635 if ($response != 'NO') {
636 /* "BAD" and anything else gets reported here. */
637 $message = htmlspecialchars($message);
638 set_up_language($squirrelmail_language, true);
639 require_once(SM_PATH . 'functions/display_messages.php');
640 if ($response == 'BAD') {
641 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
642 } else {
643 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
644 }
645 if (isset($read) && is_array($read)) {
646 $string .= '<br>' . _("Read data:") . "<br>\n";
647 foreach ($read as $line) {
648 $string .= htmlspecialchars($line) . "<br>\n";
649 }
650 }
651 error_box($string,$color);
652 exit;
653 } else {
654 /*
655 * If the user does not log in with the correct
656 * username and password it is not possible to get the
657 * correct locale from the user's preferences.
658 * Therefore, apply the same hack as on the login
659 * screen.
660 *
661 * $squirrelmail_language is set by a cookie when
662 * the user selects language and logs out
663 */
664
665 set_up_language($squirrelmail_language, true);
666 include_once(SM_PATH . 'functions/display_messages.php' );
667 sqsession_destroy();
668 logout_error( _("Unknown user or password incorrect.") );
669 exit;
670 }
671 } else {
672 exit;
673 }
674 }
675 return $imap_stream;
676 }
677
678 /* Simply logs out the IMAP session */
679 function sqimap_logout ($imap_stream) {
680 /* Logout is not valid until the server returns 'BYE'
681 * If we don't have an imap_ stream we're already logged out */
682 if(isset($imap_stream) && $imap_stream)
683 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
684 }
685
686 function sqimap_capability($imap_stream, $capability='') {
687 global $sqimap_capabilities;
688 if (!is_array($sqimap_capabilities)) {
689 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
690
691 $c = explode(' ', $read[0]);
692 for ($i=2; $i < count($c); $i++) {
693 $cap_list = explode('=', $c[$i]);
694 if (isset($cap_list[1])) {
695 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
696 } else {
697 $sqimap_capabilities[$cap_list[0]] = TRUE;
698 }
699 }
700 }
701 if ($capability) {
702 if (isset($sqimap_capabilities[$capability])) {
703 return $sqimap_capabilities[$capability];
704 } else {
705 return false;
706 }
707 }
708 return $sqimap_capabilities;
709 }
710
711 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
712 function sqimap_get_delimiter ($imap_stream = false) {
713 global $sqimap_delimiter, $optional_delimiter;
714
715 /* Use configured delimiter if set */
716 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
717 return $optional_delimiter;
718 }
719
720 /* Do some caching here */
721 if (!$sqimap_delimiter) {
722 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
723 /*
724 * According to something that I can't find, this is supposed to work on all systems
725 * OS: This won't work in Courier IMAP.
726 * OS: According to rfc2342 response from NAMESPACE command is:
727 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
728 * OS: We want to lookup all personal NAMESPACES...
729 */
730 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
731 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
732 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
733 $pn = $data2[1];
734 }
735 $pna = explode(')(', $pn);
736 while (list($k, $v) = each($pna)) {
737 $lst = explode('"', $v);
738 if (isset($lst[3])) {
739 $pn[$lst[1]] = $lst[3];
740 } else {
741 $pn[$lst[1]] = '';
742 }
743 }
744 }
745 $sqimap_delimiter = $pn[0];
746 } else {
747 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
748 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
749 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
750 $quote_position = strpos ($read[0], '"');
751 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
752 }
753 }
754 return $sqimap_delimiter;
755 }
756
757
758 function sqimap_encode_mailbox_name($what)
759 {
760 if (ereg("[\"\\\r\n]", $what))
761 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
762 return '"' . $what . '"'; /* 4.3 quoted string form */
763 }
764
765
766 /* Gets the number of messages in the current mailbox. */
767 function sqimap_get_num_messages ($imap_stream, $mailbox) {
768 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
769 for ($i = 0; $i < count($read_ary); $i++) {
770 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
771 return $regs[1];
772 }
773 }
774 return false; //"BUG! Couldn't get number of messages in $mailbox!";
775 }
776
777
778 function parseAddress($address, $max=0) {
779 $aTokens = array();
780 $aAddress = array();
781 $iCnt = strlen($address);
782 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
783 $aReplace = array(' (',' <',' ,',' ;',' :');
784 $address = str_replace($aSpecials,$aReplace,$address);
785 $i = $iAddrFound = $bGroup = 0;
786 while ($i < $iCnt) {
787 $cChar = $address{$i};
788 switch($cChar)
789 {
790 case '<':
791 $iEnd = strpos($address,'>',$i+1);
792 if (!$iEnd) {
793 $sToken = substr($address,$i);
794 $i = $iCnt;
795 } else {
796 $sToken = substr($address,$i,$iEnd - $i +1);
797 $i = $iEnd;
798 }
799 $sToken = str_replace($aReplace, $aSpecials,$sToken);
800 $aTokens[] = $sToken;
801 break;
802 case '"':
803 $iEnd = strpos($address,$cChar,$i+1);
804 if ($iEnd) {
805 // skip escaped quotes
806 $prev_char = $address{$iEnd-1};
807 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
808 $iEnd = strpos($address,$cChar,$iEnd+1);
809 if ($iEnd) {
810 $prev_char = $address{$iEnd-1};
811 } else {
812 $prev_char = false;
813 }
814 }
815 }
816 if (!$iEnd) {
817 $sToken = substr($address,$i);
818 $i = $iCnt;
819 } else {
820 // also remove the surrounding quotes
821 $sToken = substr($address,$i+1,$iEnd - $i -1);
822 $i = $iEnd;
823 }
824 $sToken = str_replace($aReplace, $aSpecials,$sToken);
825 if ($sToken) $aTokens[] = $sToken;
826 break;
827 case '(':
828 $iEnd = strpos($address,')',$i);
829 if (!$iEnd) {
830 $sToken = substr($address,$i);
831 $i = $iCnt;
832 } else {
833 $sToken = substr($address,$i,$iEnd - $i + 1);
834 $i = $iEnd;
835 }
836 $sToken = str_replace($aReplace, $aSpecials,$sToken);
837 $aTokens[] = $sToken;
838 break;
839 case ',':
840 ++$iAddrFound;
841 case ';':
842 if (!$bGroup) {
843 ++$iAddrFound;
844 } else {
845 $bGroup = false;
846 }
847 if ($max && $max == $iAddrFound) {
848 break 2;
849 } else {
850 $aTokens[] = $cChar;
851 break;
852 }
853 case ':':
854 $bGroup = true;
855 case ' ':
856 $aTokens[] = $cChar;
857 break;
858 default:
859 $iEnd = strpos($address,' ',$i+1);
860 if ($iEnd) {
861 $sToken = trim(substr($address,$i,$iEnd - $i));
862 $i = $iEnd-1;
863 } else {
864 $sToken = trim(substr($address,$i));
865 $i = $iCnt;
866 }
867 if ($sToken) $aTokens[] = $sToken;
868 }
869 ++$i;
870 }
871 $sPersonal = $sEmail = $sComment = $sGroup = '';
872 $aStack = $aComment = array();
873 foreach ($aTokens as $sToken) {
874 if ($max && $max == count($aAddress)) {
875 return $aAddress;
876 }
877 $cChar = $sToken{0};
878 switch ($cChar)
879 {
880 case '=':
881 case '"':
882 case ' ':
883 $aStack[] = $sToken;
884 break;
885 case '(':
886 $aComment[] = substr($sToken,1,-1);
887 break;
888 case ';':
889 if ($sGroup) {
890 $sEmail = trim(implode(' ',$aStack));
891 $aAddress[] = array($sGroup,$sEmail);
892 $aStack = $aComment = array();
893 $sGroup = '';
894 break;
895 }
896 case ',':
897 if (!$sEmail) {
898 while (count($aStack) && !$sEmail) {
899 $sEmail = trim(array_pop($aStack));
900 }
901 }
902 if (count($aStack)) {
903 $sPersonal = trim(implode('',$aStack));
904 } else {
905 $sPersonal = '';
906 }
907 if (!$sPersonal && count($aComment)) {
908 $sComment = implode(' ',$aComment);
909 $sPersonal .= $sComment;
910 }
911 $aAddress[] = array($sEmail,$sPersonal);
912 $sPersonal = $sComment = $sEmail = '';
913 $aStack = $aComment = array();
914 break;
915 case ':':
916 $sGroup = implode(' ',$aStack); break;
917 $aStack = array();
918 break;
919 case '<':
920 $sEmail = trim(substr($sToken,1,-1));
921 break;
922 case '>':
923 /* skip */
924 break;
925 default: $aStack[] = $sToken; break;
926 }
927 }
928 /* now do the action again for the last address */
929 if (!$sEmail) {
930 while (count($aStack) && !$sEmail) {
931 $sEmail = trim(array_pop($aStack));
932 }
933 }
934 if (count($aStack)) {
935 $sPersonal = trim(implode('',$aStack));
936 } else {
937 $sPersonal = '';
938 }
939 if (!$sPersonal && count($aComment)) {
940 $sComment = implode(' ',$aComment);
941 $sPersonal .= $sComment;
942 }
943 $aAddress[] = array($sEmail,$sPersonal);
944 return $aAddress;
945 }
946
947
948
949 /*
950 * Returns the number of unseen messages in this folder
951 */
952 function sqimap_unseen_messages ($imap_stream, $mailbox) {
953 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
954 $i = 0;
955 $regs = array(false, false);
956 while (isset($read_ary[$i])) {
957 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
958 break;
959 }
960 $i++;
961 }
962 return $regs[1];
963 }
964
965 /*
966 * Returns the number of total/unseen/recent messages in this folder
967 */
968 function sqimap_status_messages ($imap_stream, $mailbox) {
969 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
970 $i = 0;
971 $messages = $unseen = $recent = false;
972 $regs = array(false,false);
973 while (isset($read_ary[$i])) {
974 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
975 $unseen = $regs[1];
976 }
977 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
978 $messages = $regs[1];
979 }
980 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
981 $recent = $regs[1];
982 }
983 $i++;
984 }
985 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
986 }
987
988
989 /*
990 * Saves a message to a given folder -- used for saving sent messages
991 */
992 function sqimap_append ($imap_stream, $sent_folder, $length) {
993 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
994 $tmp = fgets ($imap_stream, 1024);
995 }
996
997 function sqimap_append_done ($imap_stream, $folder='') {
998 global $squirrelmail_language, $color;
999 fputs ($imap_stream, "\r\n");
1000 $tmp = fgets ($imap_stream, 1024);
1001 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1002 set_up_language($squirrelmail_language);
1003 require_once(SM_PATH . 'functions/display_messages.php');
1004 $reason = $regs[3];
1005 if ($regs[2] == 'NO') {
1006 $string = "<b><font color=$color[2]>\n" .
1007 _("ERROR : Could not append message to") ." $folder." .
1008 "</b><br>\n" .
1009 _("Server responded: ") .
1010 $reason . "<br>\n";
1011 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1012 $string .= _("Solution: ") .
1013 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1014 ."<br>\n";
1015 }
1016 $string .= "</font>\n";
1017 error_box($string,$color);
1018 } else {
1019 $string = "<b><font color=$color[2]>\n" .
1020 _("ERROR : Bad or malformed request.") .
1021 "</b><br>\n" .
1022 _("Server responded: ") .
1023 $tmp . "</font><br>\n";
1024 error_box($string,$color);
1025 exit;
1026 }
1027 }
1028 }
1029
1030 function sqimap_get_user_server ($imap_server, $username) {
1031 if (substr($imap_server, 0, 4) != "map:") {
1032 return $imap_server;
1033 }
1034 $function = substr($imap_server, 4);
1035 return $function($username);
1036 }
1037
1038 /* This is an example that gets imapservers from yellowpages (NIS).
1039 * you can simple put map:map_yp_alias in your $imap_server_address
1040 * in config.php use your own function instead map_yp_alias to map your
1041 * LDAP whatever way to find the users imapserver. */
1042
1043 function map_yp_alias($username) {
1044 $yp = `ypmatch $username aliases`;
1045 return chop(substr($yp, strlen($username)+1));
1046 }
1047
1048 ?>