eaaddaf78e5cc09c7cd9a6fba292655e6d595338
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This implements all functions that do general imap functions.
12 * @package squirrelmail
16 require_once(SM_PATH
. 'functions/page_header.php');
17 require_once(SM_PATH
. 'functions/auth.php');
20 global $sqimap_session_id;
21 $sqimap_session_id = 1;
24 * Generates a new session ID by incrementing the last one used;
25 * this ensures that each command has a unique ID.
26 * @param bool unique_id
27 * @return string IMAP session id of the form 'A000'.
29 function sqimap_session_id($unique_id = false) {
30 global $data_dir, $username, $sqimap_session_id;
32 return( sprintf("A%03d", $sqimap_session_id++
) );
34 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
39 * Both send a command and accept the result from the command.
40 * This is to allow proper session number handling.
42 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
44 $sid = sqimap_session_id($unique_id);
45 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
46 $tag_uid_a = explode(' ',trim($sid));
48 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
49 /* get the response and the message */
50 $message = $message[$tag];
51 $response = $response[$tag];
54 global $squirrelmail_language, $color;
55 set_up_language($squirrelmail_language);
56 require_once(SM_PATH
. 'functions/display_messages.php');
57 $string = "<b><font color=$color[2]>\n" .
58 _("ERROR : No available imapstream.") .
60 error_box($string,$color);
65 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
66 &$message, $unique_id = false,$filter=false,
67 $outputstream=false,$no_return=false) {
69 $sid = sqimap_session_id($unique_id);
70 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
71 $tag_uid_a = explode(' ',trim($sid));
74 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
75 $message, $query,$filter,$outputstream,$no_return);
76 /* retrieve the response and the message */
77 $response = $response[$tag];
78 $message = $message[$tag];
80 if (!empty($read[$tag])) {
81 return $read[$tag][0];
86 global $squirrelmail_language, $color;
87 set_up_language($squirrelmail_language);
88 require_once(SM_PATH
. 'functions/display_messages.php');
89 $string = "<b><font color=$color[2]>\n" .
90 _("ERROR : No available imapstream.") .
92 error_box($string,$color);
97 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
98 $sid = sqimap_session_id($unique_id);
99 $tag_uid_a = explode(' ',trim($sid));
100 $tag = $tag_uid_a[0];
101 $query = $sid . ' '.$new_query."\r\n";
102 $aQuery[$tag] = $query;
105 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
106 &$aServerResponse, &$aServerMessage, $unique_id = false,
107 $filter=false,$outputstream=false,$no_return=false) {
111 Do not fire all calls at once to the imap-server but split the calls up
112 in portions of $iChunkSize. If we do not do that I think we misbehave as
113 IMAP client or should handle BYE calls if the IMAP-server drops the
114 connection because the number of queries is to large. This isn't tested
115 but a wild guess how it could work in the field.
117 After testing it on Exchange 2000 we discovered that a chunksize of 32
118 was quicker then when we raised it to 128.
120 $iQueryCount = count($aQueryList);
122 // array_chunk would also do the job but it's supported from php > 4.2
123 $aQueryChunks = array();
124 $iLoops = floor($iQueryCount / $iChunkSize);
126 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
128 if (!function_exists('array_chunk')) { // arraychunk replacement
130 for($i=0;$i<$iLoops;++
$i) {
131 for($j=0;$j<$iChunkSize;++
$j) {
132 $key = key($aQueryList);
133 $aTmp[$key] = $aQueryList[$key];
134 if (next($aQueryList) === false) break;
136 $aQueryChunks[] = $aTmp;
139 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
142 for ($i=0;$i<$iLoops;++
$i) {
143 $aQuery = $aQueryChunks[$i];
144 foreach($aQuery as $tag => $query) {
145 fputs($imap_stream,$query);
146 $aResults[$tag] = false;
148 foreach($aQuery as $tag => $query) {
149 if ($aResults[$tag] == false) {
150 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
151 $handle_errors, $response, $message, $query,
152 $filter,$outputstream,$no_return);
153 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
154 if (!empty($aResponse)) {
155 $aResults[$returned_tag] = $aResponse[0];
157 $aResults[$returned_tag] = $aResponse;
159 $aServerResponse[$returned_tag] = $response[$returned_tag];
160 $aServerMessage[$returned_tag] = $message[$returned_tag];
169 * Custom fgets function: gets a line from the IMAP-server,
170 * no matter how big it may be.
171 * @param stream imap_stream the stream to read from
172 * @return string a line
174 function sqimap_fgets($imap_stream) {
179 while (strpos($results, "\r\n", $offset) === false) {
180 if (!($read = fgets($imap_stream, $buffer))) {
181 /* this happens in case of an error */
182 /* reset $results because it's useless */
186 if ( $results != '' ) {
187 $offset = strlen($results) - 1;
194 function sqimap_fread($imap_stream,$iSize,$filter=false,
195 $outputstream=false, $no_return=false) {
196 if (!$filter ||
!$outputstream) {
197 $iBufferSize = $iSize;
199 // see php bug 24033. They changed fread behaviour %$^&$%
200 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
202 if ($iSize < $iBufferSize) {
203 $iBufferSize = $iSize;
207 $sRead = $sReadRem = '';
208 // NB: fread can also stop at end of a packet on sockets.
209 while ($iRetrieved < $iSize) {
210 $sRead = fread($imap_stream,$iBufferSize);
211 $iLength = strlen($sRead);
212 $iRetrieved +
= $iLength ;
213 $iRemaining = $iSize - $iRetrieved;
214 if ($iRemaining < $iBufferSize) {
215 $iBufferSize = $iRemaining;
222 $sRead = $sReadRem . $sRead;
225 if (substr($sRead,-1) !== "\n") {
226 $i = strrpos($sRead,"\n");
227 if ($i !== false && $iRetrieved<$iSize) {
229 $sReadRem = substr($sRead,$i);
230 $sRead = substr($sRead,0,$i);
231 } else if ($iLength && $iRetrieved<$iSize) { // linelength > received buffer
236 if ($filter && $sRead) {
239 if ($outputstream && $sRead) {
240 if (is_resource($outputstream)) {
241 fwrite($outputstream,$sRead);
242 } else if ($outputstream == 'php://stdout') {
256 * Obsolete function, inform plugins that use it
257 * @deprecated use sqimap_run_command or sqimap_run_command_list instead
259 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
260 &$response, &$message, $query = '') {
261 global $color, $squirrelmail_language;
262 set_up_language($squirrelmail_language);
263 require_once(SM_PATH
. 'functions/display_messages.php');
264 $string = "<b><font color=$color[2]>\n" .
265 _("ERROR : Bad function call.") .
268 'There is a plugin installed which make use of the <br>' .
269 'SquirrelMail internal function sqimap_read_data_list.<br>'.
270 'Please adapt the installed plugin and let it use<br>'.
271 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
272 'The following query was issued:<br>'.
273 htmlspecialchars($query) . '<br>' . "</font><br>\n";
274 error_box($string,$color);
275 echo '</body></html>';
280 * Function to display an error related to an IMAP-query.
281 * @param string title the caption of the error box
282 * @param string query the query that went wrong
283 * @param string message_title
284 * @param string message the error message
287 function sqimap_error_box($title, $query = '', $message_title = '', $message = '')
289 global $color, $squirrelmail_language;
291 set_up_language($squirrelmail_language);
292 require_once(SM_PATH
. 'functions/display_messages.php');
293 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
294 $cmd = explode(' ',$query);
295 $cmd= strtolower($cmd[0]);
297 if ($query != '' && $cmd != 'login')
298 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
299 if ($message_title != '')
300 $string .= $message_title;
302 $string .= htmlspecialchars($message);
303 $string .= "</font><br>\n";
304 error_box($string,$color);
308 * Reads the output from the IMAP stream. If handle_errors is set to true,
309 * this will also handle all errors that are received. If it is not set,
310 * the errors will be sent back through $response and $message.
312 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
313 &$response, &$message, $query = '',
314 $filter = false, $outputstream = false, $no_return = false) {
315 global $color, $squirrelmail_language;
317 if (!is_array($message)) $message = array();
318 if (!is_array($response)) $response = array();
319 $resultlist = array();
321 $read = sqimap_fgets($imap_stream);
329 $read = sqimap_fgets($imap_stream);
334 /* get the command */
337 $s = substr($read,$i);
338 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
339 $arg = substr($s,0,$j);
341 $found_tag = substr($read,0,$i-1);
350 $response[$found_tag] = $arg;
351 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
353 $resultlist[] = $data;
355 $aResponse[$found_tag] = $resultlist;
356 $data = $resultlist = array();
357 if ($found_tag == $tag) {
358 break 3; /* switch switch while */
362 /* this shouldn't happen */
363 $response[$found_tag] = $arg;
364 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
366 $resultlist[] = $data;
368 $aResponse[$found_tag] = $resultlist;
369 $data = $resultlist = array();
370 if ($found_tag == $tag) {
371 break 3; /* switch switch while */
375 $read = sqimap_fgets($imap_stream);
376 if ($read === false) { /* error */
377 break 3; /* switch switch while */
380 } // end case $tag{0}
384 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
385 /* check for literal */
386 $s = substr($read,-3);
387 $fetch_data = array();
388 do { /* outer loop, continue until next untagged fetch
390 do { /* innerloop for fetching literals. with this loop
391 we prohibid that literal responses appear in the
392 outer loop so we can trust the untagged and
393 tagged info provided by $read */
394 if ($s === "}\r\n") {
395 $j = strrpos($read,'{');
396 $iLit = substr($read,$j+
1,-3);
397 $fetch_data[] = $read;
398 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
399 if ($sLiteral === false) { /* error */
400 break 4; /* while while switch while */
402 /* backwards compattibility */
403 $aLiteral = explode("\n", $sLiteral);
404 /* release not neaded data */
406 foreach ($aLiteral as $line) {
407 $fetch_data[] = $line ."\n";
409 /* release not neaded data */
411 /* next fgets belongs to this fetch because
412 we just got the exact literalsize and there
413 must follow data to complete the response */
414 $read = sqimap_fgets($imap_stream);
415 if ($read === false) { /* error */
416 break 4; /* while while switch while */
418 $fetch_data[] = $read;
420 $fetch_data[] = $read;
422 /* retrieve next line and check in the while
423 statements if it belongs to this fetch response */
424 $read = sqimap_fgets($imap_stream);
425 if ($read === false) { /* error */
426 break 4; /* while while switch while */
428 /* check for next untagged reponse and break */
429 if ($read{0} == '*') break 2;
430 $s = substr($read,-3);
431 } while ($s === "}\r\n");
432 $s = substr($read,-3);
433 } while ($read{0} !== '*' &&
434 substr($read,0,strlen($tag)) !== $tag);
435 $resultlist[] = $fetch_data;
436 /* release not neaded data */
439 $s = substr($read,-3);
441 if ($s === "}\r\n") {
442 $j = strrpos($read,'{');
443 $iLit = substr($read,$j+
1,-3);
445 $sLiteral = fread($imap_stream,$iLit);
446 if ($sLiteral === false) { /* error */
448 break 3; /* while switch while */
451 $data[] = sqimap_fgets($imap_stream);
455 $read = sqimap_fgets($imap_stream);
456 if ($read === false) {
457 break 3; /* while switch while */
458 } else if ($read{0} == '*') {
461 $s = substr($read,-3);
462 } while ($s === "}\r\n");
470 /* error processing in case $read is false */
471 if ($read === false) {
473 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
477 /* Set $resultlist array */
479 //$resultlist[] = $data;
481 elseif (empty($resultlist)) {
482 $resultlist[] = array();
485 /* Return result or handle errors */
486 if ($handle_errors == false) {
488 return( $resultlist ); //?? Why this?
490 switch ($response[$tag]) {
495 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
496 if (strstr($message[$tag], 'command resulted in') === false) {
497 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
498 echo '</body></html>';
503 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
504 echo '</body></html>';
507 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
508 echo '</body></html>';
511 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
512 /* the error is displayed but because we don't know the reponse we
513 return the result anyway */
519 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
520 &$response, &$message, $query = '',
521 $filter=false,$outputstream=false,$no_return=false) {
523 $tag_uid_a = explode(' ',trim($tag_uid));
524 $tag = $tag_uid_a[0];
526 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
527 $response, $message, $query,$filter,$outputstream,$no_return);
528 /* sqimap_read_data should be called for one response
529 but since it just calls sqimap_retrieve_imap_response which
530 handles multiple responses we need to check for that
531 and merge the $res array IF they are seperated and
532 IF it was a FETCH response. */
534 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
535 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
536 // $result = array();
537 // foreach($res as $index=>$value) {
538 // $result = array_merge($result, $res["$index"]);
541 if (isset($result)) {
542 return $result[$tag];
550 * Connects to the IMAP server and returns a resource identifier for use with
551 * the other SquirrelMail IMAP functions. Does NOT login!
552 * @param string server hostname of IMAP server
553 * @param int port port number to connect to
554 * @param bool tls whether to use TLS when connecting.
555 * @return imap-stream resource identifier
557 function sqimap_create_stream($server,$port,$tls=false) {
558 global $username, $use_imap_tls;
560 if ($use_imap_tls == true) {
561 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
562 /* Use TLS by prefixing "tls://" to the hostname */
563 $server = 'tls://' . $imap_server_address;
565 require_once(SM_PATH
. 'functions/display_messages.php');
566 $string = "Unable to connect to IMAP server!<br>TLS is enabled, but this " .
567 "version of PHP does not support TLS sockets, or is missing the openssl " .
568 "extension.<br><br>Please contact your system administrator.";
569 logout_error($string,$color);
573 $imap_stream = fsockopen($server, $port, $error_number, $error_string, 15);
575 /* Do some error correction */
577 set_up_language($squirrelmail_language, true);
578 require_once(SM_PATH
. 'functions/display_messages.php');
579 $string = sprintf (_("Error connecting to IMAP server: %s.") .
580 "<br>\r\n", $server) .
581 "$error_number : $error_string<br>\r\n";
582 logout_error($string,$color);
585 $server_info = fgets ($imap_stream, 1024);
590 * Logs the user into the imap server. If $hide is set, no error messages
591 * will be displayed. This function returns the imap connection handle.
593 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
594 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
595 $imap_auth_mech, $sqimap_capabilities;
597 if (!isset($onetimepad) ||
empty($onetimepad)) {
598 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
600 if (!isset($sqimap_capabilities)) {
601 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
604 $host = $imap_server_address;
605 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
607 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
609 /* Decrypt the password */
610 $password = OneTimePadDecrypt($password, $onetimepad);
612 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
613 // We're using some sort of authentication OTHER than plain or login
614 $tag=sqimap_session_id(false);
615 if ($imap_auth_mech == 'digest-md5') {
616 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
617 } elseif ($imap_auth_mech == 'cram-md5') {
618 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
620 fputs($imap_stream,$query);
621 $answer=sqimap_fgets($imap_stream);
622 // Trim the "+ " off the front
623 $response=explode(" ",$answer,3);
624 if ($response[0] == '+') {
625 // Got a challenge back
626 $challenge=$response[1];
627 if ($imap_auth_mech == 'digest-md5') {
628 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
629 } elseif ($imap_auth_mech == 'cram-md5') {
630 $reply = cram_md5_response($username,$password,$challenge);
632 fputs($imap_stream,$reply);
633 $read=sqimap_fgets($imap_stream);
634 if ($imap_auth_mech == 'digest-md5') {
635 // DIGEST-MD5 has an extra step..
636 if (substr($read,0,1) == '+') { // OK so far..
637 fputs($imap_stream,"\r\n");
638 $read=sqimap_fgets($imap_stream);
641 $results=explode(" ",$read,3);
642 $response=$results[1];
643 $message=$results[2];
645 // Fake the response, so the error trap at the bottom will work
647 $message='IMAP server does not appear to support the authentication method selected.';
648 $message .= ' Please contact your system administrator.';
650 } elseif ($imap_auth_mech == 'login') {
651 // Original IMAP login code
652 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
653 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
654 } elseif ($imap_auth_mech == 'plain') {
660 * The mechanism consists of a single message from the client to the
661 * server. The client sends the authorization identity (identity to
662 * login as), followed by a US-ASCII NUL character, followed by the
663 * authentication identity (identity whose password will be used),
664 * followed by a US-ASCII NUL character, followed by the clear-text
665 * password. The client may leave the authorization identity empty to
666 * indicate that it is the same as the authentication identity.
669 $tag=sqimap_session_id(false);
670 $sasl = (isset($capability['SASL']) && $capability['SASL']) ?
true : false;
671 $auth = base64_encode("$username\0$username\0$password");
673 // IMAP Extension for SASL Initial Client Response
674 // <draft-siemborski-imap-sasl-initial-response-00.txt>
675 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
676 fputs($imap_stream, $query);
677 $read = sqimap_fgets($imap_stream);
679 $query = $tag . " AUTHENTICATE PLAIN\r\n";
680 fputs($imap_stream, $query);
681 $read=sqimap_fgets($imap_stream);
682 if (substr($read,0,1) == '+') { // OK so far..
683 fputs($imap_stream, "$auth\r\n");
684 $read = sqimap_fgets($imap_stream);
687 $results=explode(" ",$read,3);
688 $response=$results[1];
689 $message=$results[2];
692 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
695 /* If the connection was not successful, lets see why */
696 if ($response != 'OK') {
698 if ($response != 'NO') {
699 /* "BAD" and anything else gets reported here. */
700 $message = htmlspecialchars($message);
701 set_up_language($squirrelmail_language, true);
702 require_once(SM_PATH
. 'functions/display_messages.php');
703 if ($response == 'BAD') {
704 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
706 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
708 if (isset($read) && is_array($read)) {
709 $string .= '<br>' . _("Read data:") . "<br>\n";
710 foreach ($read as $line) {
711 $string .= htmlspecialchars($line) . "<br>\n";
714 error_box($string,$color);
718 * If the user does not log in with the correct
719 * username and password it is not possible to get the
720 * correct locale from the user's preferences.
721 * Therefore, apply the same hack as on the login
724 * $squirrelmail_language is set by a cookie when
725 * the user selects language and logs out
728 set_up_language($squirrelmail_language, true);
729 include_once(SM_PATH
. 'functions/display_messages.php' );
731 logout_error( _("Unknown user or password incorrect.") );
742 * Simply logs out the IMAP session
743 * @param stream imap_stream the IMAP connection to log out.
746 function sqimap_logout ($imap_stream) {
747 /* Logout is not valid until the server returns 'BYE'
748 * If we don't have an imap_ stream we're already logged out */
749 if(isset($imap_stream) && $imap_stream)
750 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
754 * Retreive the CAPABILITY string from the IMAP server.
755 * If capability is set, returns only that specific capability,
756 * else returns array of all capabilities.
758 function sqimap_capability($imap_stream, $capability='') {
759 global $sqimap_capabilities;
760 if (!is_array($sqimap_capabilities)) {
761 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
763 $c = explode(' ', $read[0]);
764 for ($i=2; $i < count($c); $i++
) {
765 $cap_list = explode('=', $c[$i]);
766 if (isset($cap_list[1])) {
767 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
769 $sqimap_capabilities[$cap_list[0]] = TRUE;
774 if (isset($sqimap_capabilities[$capability])) {
775 return $sqimap_capabilities[$capability];
780 return $sqimap_capabilities;
784 * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
786 function sqimap_get_delimiter ($imap_stream = false) {
787 global $sqimap_delimiter, $optional_delimiter;
789 /* Use configured delimiter if set */
790 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
791 return $optional_delimiter;
794 /* Do some caching here */
795 if (!$sqimap_delimiter) {
796 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
798 * According to something that I can't find, this is supposed to work on all systems
799 * OS: This won't work in Courier IMAP.
800 * OS: According to rfc2342 response from NAMESPACE command is:
801 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
802 * OS: We want to lookup all personal NAMESPACES...
804 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
805 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
806 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
809 $pna = explode(')(', $pn);
810 while (list($k, $v) = each($pna)) {
811 $lst = explode('"', $v);
812 if (isset($lst[3])) {
813 $pn[$lst[1]] = $lst[3];
819 $sqimap_delimiter = $pn[0];
821 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
822 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
823 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
824 $quote_position = strpos ($read[0], '"');
825 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
828 return $sqimap_delimiter;
832 * This encodes a mailbox name for use in IMAP commands.
833 * @param string what the mailbox to encode
834 * @return string the encoded mailbox string
836 function sqimap_encode_mailbox_name($what)
838 if (ereg("[\"\\\r\n]", $what))
839 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
840 return '"' . $what . '"'; /* 4.3 quoted string form */
845 * Gets the number of messages in the current mailbox.
847 function sqimap_get_num_messages ($imap_stream, $mailbox) {
848 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
849 for ($i = 0; $i < count($read_ary); $i++
) {
850 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
854 return false; //"BUG! Couldn't get number of messages in $mailbox!";
857 function parseAddress($address, $max=0) {
860 $iCnt = strlen($address);
861 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
862 $aReplace = array(' (',' <',' ,',' ;',' :');
863 $address = str_replace($aSpecials,$aReplace,$address);
864 $i = $iAddrFound = $bGroup = 0;
866 $cChar = $address{$i};
870 $iEnd = strpos($address,'>',$i+
1);
872 $sToken = substr($address,$i);
875 $sToken = substr($address,$i,$iEnd - $i +
1);
878 $sToken = str_replace($aReplace, $aSpecials,$sToken);
879 $aTokens[] = $sToken;
882 $iEnd = strpos($address,$cChar,$i+
1);
884 // skip escaped quotes
885 $prev_char = $address{$iEnd-1};
886 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
887 $iEnd = strpos($address,$cChar,$iEnd+
1);
889 $prev_char = $address{$iEnd-1};
896 $sToken = substr($address,$i);
899 // also remove the surrounding quotes
900 $sToken = substr($address,$i+
1,$iEnd - $i -1);
903 $sToken = str_replace($aReplace, $aSpecials,$sToken);
904 if ($sToken) $aTokens[] = $sToken;
907 $iEnd = strpos($address,')',$i);
909 $sToken = substr($address,$i);
912 $sToken = substr($address,$i,$iEnd - $i +
1);
915 $sToken = str_replace($aReplace, $aSpecials,$sToken);
916 $aTokens[] = $sToken;
926 if ($max && $max == $iAddrFound) {
938 $iEnd = strpos($address,' ',$i+
1);
940 $sToken = trim(substr($address,$i,$iEnd - $i));
943 $sToken = trim(substr($address,$i));
946 if ($sToken) $aTokens[] = $sToken;
950 $sPersonal = $sEmail = $sComment = $sGroup = '';
951 $aStack = $aComment = array();
952 foreach ($aTokens as $sToken) {
953 if ($max && $max == count($aAddress)) {
965 $aComment[] = substr($sToken,1,-1);
969 $sEmail = trim(implode(' ',$aStack));
970 $aAddress[] = array($sGroup,$sEmail);
971 $aStack = $aComment = array();
977 while (count($aStack) && !$sEmail) {
978 $sEmail = trim(array_pop($aStack));
981 if (count($aStack)) {
982 $sPersonal = trim(implode('',$aStack));
986 if (!$sPersonal && count($aComment)) {
987 $sComment = implode(' ',$aComment);
988 $sPersonal .= $sComment;
990 $aAddress[] = array($sEmail,$sPersonal);
991 $sPersonal = $sComment = $sEmail = '';
992 $aStack = $aComment = array();
995 $sGroup = implode(' ',$aStack); break;
999 $sEmail = trim(substr($sToken,1,-1));
1004 default: $aStack[] = $sToken; break;
1007 /* now do the action again for the last address */
1009 while (count($aStack) && !$sEmail) {
1010 $sEmail = trim(array_pop($aStack));
1013 if (count($aStack)) {
1014 $sPersonal = trim(implode('',$aStack));
1018 if (!$sPersonal && count($aComment)) {
1019 $sComment = implode(' ',$aComment);
1020 $sPersonal .= $sComment;
1022 $aAddress[] = array($sEmail,$sPersonal);
1028 * Returns the number of unseen messages in this folder.
1030 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1031 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
1033 $regs = array(false, false);
1034 while (isset($read_ary[$i])) {
1035 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
1044 * Returns the number of total/unseen/recent messages in this folder
1046 function sqimap_status_messages ($imap_stream, $mailbox) {
1047 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1049 $messages = $unseen = $recent = false;
1050 $regs = array(false,false);
1051 while (isset($read_ary[$i])) {
1052 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1055 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1056 $messages = $regs[1];
1058 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1063 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1068 * Saves a message to a given folder -- used for saving sent messages
1070 function sqimap_append ($imap_stream, $sent_folder, $length) {
1071 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1072 $tmp = fgets ($imap_stream, 1024);
1075 function sqimap_append_done ($imap_stream, $folder='') {
1076 global $squirrelmail_language, $color;
1077 fputs ($imap_stream, "\r\n");
1078 $tmp = fgets ($imap_stream, 1024);
1079 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1080 set_up_language($squirrelmail_language);
1081 require_once(SM_PATH
. 'functions/display_messages.php');
1083 if ($regs[2] == 'NO') {
1084 $string = "<b><font color=$color[2]>\n" .
1085 _("ERROR : Could not append message to") ." $folder." .
1087 _("Server responded: ") .
1089 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1090 $string .= _("Solution: ") .
1091 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1094 $string .= "</font>\n";
1095 error_box($string,$color);
1097 $string = "<b><font color=$color[2]>\n" .
1098 _("ERROR : Bad or malformed request.") .
1100 _("Server responded: ") .
1101 $tmp . "</font><br>\n";
1102 error_box($string,$color);
1108 function sqimap_get_user_server ($imap_server, $username) {
1109 if (substr($imap_server, 0, 4) != "map:") {
1110 return $imap_server;
1112 $function = substr($imap_server, 4);
1113 return $function($username);
1117 * This is an example that gets imapservers from yellowpages (NIS).
1118 * you can simple put map:map_yp_alias in your $imap_server_address
1119 * in config.php use your own function instead map_yp_alias to map your
1120 * LDAP whatever way to find the users imapserver.
1122 function map_yp_alias($username) {
1123 $yp = `ypmatch
$username aliases`
;
1124 return chop(substr($yp, strlen($username)+
1));