6 * Copyright (c) 1999-2004 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');
21 * Generates a new session ID by incrementing the last one used;
22 * this ensures that each command has a unique ID.
23 * @param bool unique_id
24 * @return string IMAP session id of the form 'A000'.
26 function sqimap_session_id($unique_id = FALSE) {
27 static $sqimap_session_id = 1;
30 return( sprintf("A%03d", $sqimap_session_id++
) );
32 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
37 * Both send a command and accept the result from the command.
38 * This is to allow proper session number handling.
40 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
42 $sid = sqimap_session_id($unique_id);
43 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
44 $tag_uid_a = explode(' ',trim($sid));
46 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
47 /* get the response and the message */
48 $message = $message[$tag];
49 $response = $response[$tag];
52 global $squirrelmail_language, $color;
53 set_up_language($squirrelmail_language);
54 require_once(SM_PATH
. 'functions/display_messages.php');
55 $string = "<b><font color=$color[2]>\n" .
56 _("ERROR : No available imapstream.") .
58 error_box($string,$color);
63 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
64 &$message, $unique_id = false,$filter=false,
65 $outputstream=false,$no_return=false) {
67 $sid = sqimap_session_id($unique_id);
68 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
69 $tag_uid_a = explode(' ',trim($sid));
72 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
73 $message, $query,$filter,$outputstream,$no_return);
74 if (empty($read)) { //Imap server dropped its connection
79 /* retrieve the response and the message */
80 $response = $response[$tag];
81 $message = $message[$tag];
83 if (!empty($read[$tag])) {
84 return $read[$tag][0];
89 global $squirrelmail_language, $color;
90 set_up_language($squirrelmail_language);
91 require_once(SM_PATH
. 'functions/display_messages.php');
92 $string = "<b><font color=$color[2]>\n" .
93 _("ERROR : No available imapstream.") .
95 error_box($string,$color);
100 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
101 $sid = sqimap_session_id($unique_id);
102 $tag_uid_a = explode(' ',trim($sid));
103 $tag = $tag_uid_a[0];
104 $query = $sid . ' '.$new_query."\r\n";
105 $aQuery[$tag] = $query;
108 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
109 &$aServerResponse, &$aServerMessage, $unique_id = false,
110 $filter=false,$outputstream=false,$no_return=false) {
114 Do not fire all calls at once to the imap-server but split the calls up
115 in portions of $iChunkSize. If we do not do that I think we misbehave as
116 IMAP client or should handle BYE calls if the IMAP-server drops the
117 connection because the number of queries is to large. This isn't tested
118 but a wild guess how it could work in the field.
120 After testing it on Exchange 2000 we discovered that a chunksize of 32
121 was quicker then when we raised it to 128.
123 $iQueryCount = count($aQueryList);
125 // array_chunk would also do the job but it's supported from php > 4.2
126 $aQueryChunks = array();
127 $iLoops = floor($iQueryCount / $iChunkSize);
129 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
131 if (!function_exists('array_chunk')) { // arraychunk replacement
133 for($i=0;$i<$iLoops;++
$i) {
134 for($j=0;$j<$iChunkSize;++
$j) {
135 $key = key($aQueryList);
136 $aTmp[$key] = $aQueryList[$key];
137 if (next($aQueryList) === false) break;
139 $aQueryChunks[] = $aTmp;
142 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
145 for ($i=0;$i<$iLoops;++
$i) {
146 $aQuery = $aQueryChunks[$i];
147 foreach($aQuery as $tag => $query) {
148 fputs($imap_stream,$query);
149 $aResults[$tag] = false;
151 foreach($aQuery as $tag => $query) {
152 if ($aResults[$tag] == false) {
153 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
154 $handle_errors, $response, $message, $query,
155 $filter,$outputstream,$no_return);
156 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
157 if (!empty($aResponse)) {
158 $aResults[$returned_tag] = $aResponse[0];
160 $aResults[$returned_tag] = $aResponse;
162 $aServerResponse[$returned_tag] = $response[$returned_tag];
163 $aServerMessage[$returned_tag] = $message[$returned_tag];
172 * Custom fgets function: gets a line from the IMAP-server,
173 * no matter how big it may be.
174 * @param stream imap_stream the stream to read from
175 * @return string a line
177 function sqimap_fgets($imap_stream) {
182 while (strpos($results, "\r\n", $offset) === false) {
183 if (!($read = fgets($imap_stream, $buffer))) {
184 /* this happens in case of an error */
185 /* reset $results because it's useless */
189 if ( $results != '' ) {
190 $offset = strlen($results) - 1;
197 function sqimap_fread($imap_stream,$iSize,$filter=false,
198 $outputstream=false, $no_return=false) {
199 if (!$filter ||
!$outputstream) {
200 $iBufferSize = $iSize;
202 // see php bug 24033. They changed fread behaviour %$^&$%
203 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
205 if ($iSize < $iBufferSize) {
206 $iBufferSize = $iSize;
210 $sRead = $sReadRem = '';
211 // NB: fread can also stop at end of a packet on sockets.
212 while ($iRetrieved < $iSize) {
213 $sRead = fread($imap_stream,$iBufferSize);
214 $iLength = strlen($sRead);
215 $iRetrieved +
= $iLength ;
216 $iRemaining = $iSize - $iRetrieved;
217 if ($iRemaining < $iBufferSize) {
218 $iBufferSize = $iRemaining;
225 $sRead = $sReadRem . $sRead;
228 if (substr($sRead,-1) !== "\n") {
229 $i = strrpos($sRead,"\n");
230 if ($i !== false && $iRetrieved<$iSize) {
232 $sReadRem = substr($sRead,$i);
233 $sRead = substr($sRead,0,$i);
234 } else if ($iLength && $iRetrieved<$iSize) { // linelength > received buffer
239 if ($filter && $sRead) {
242 if ($outputstream && $sRead) {
243 if (is_resource($outputstream)) {
244 fwrite($outputstream,$sRead);
245 } else if ($outputstream == 'php://stdout') {
259 * Obsolete function, inform plugins that use it
260 * @deprecated use sqimap_run_command or sqimap_run_command_list instead
262 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
263 &$response, &$message, $query = '') {
264 global $color, $squirrelmail_language;
265 set_up_language($squirrelmail_language);
266 require_once(SM_PATH
. 'functions/display_messages.php');
267 $string = "<b><font color=$color[2]>\n" .
268 _("ERROR : Bad function call.") .
271 'There is a plugin installed which make use of the <br>' .
272 'SquirrelMail internal function sqimap_read_data_list.<br>'.
273 'Please adapt the installed plugin and let it use<br>'.
274 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
275 'The following query was issued:<br>'.
276 htmlspecialchars($query) . '<br>' . "</font><br>\n";
277 error_box($string,$color);
278 echo '</body></html>';
283 * Function to display an error related to an IMAP-query.
284 * @param string title the caption of the error box
285 * @param string query the query that went wrong
286 * @param string message_title optional message title
287 * @param string message optional error message
288 * @param string $link an optional link to try again
291 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
293 global $color, $squirrelmail_language;
295 set_up_language($squirrelmail_language);
296 require_once(SM_PATH
. 'functions/display_messages.php');
297 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
298 $cmd = explode(' ',$query);
299 $cmd= strtolower($cmd[0]);
301 if ($query != '' && $cmd != 'login')
302 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
303 if ($message_title != '')
304 $string .= $message_title;
306 $string .= htmlspecialchars($message);
307 $string .= "</font><br>\n";
310 error_box($string,$color);
314 * Reads the output from the IMAP stream. If handle_errors is set to true,
315 * this will also handle all errors that are received. If it is not set,
316 * the errors will be sent back through $response and $message.
318 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
319 &$response, &$message, $query = '',
320 $filter = false, $outputstream = false, $no_return = false) {
321 global $color, $squirrelmail_language;
323 if (!is_array($message)) $message = array();
324 if (!is_array($response)) $response = array();
326 $resultlist = array();
328 $read = sqimap_fgets($imap_stream);
336 $read = sqimap_fgets($imap_stream);
341 /* get the command */
344 $s = substr($read,$i);
345 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
346 $arg = substr($s,0,$j);
348 $found_tag = substr($read,0,$i-1);
357 $response[$found_tag] = $arg;
358 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
360 $resultlist[] = $data;
362 $aResponse[$found_tag] = $resultlist;
363 $data = $resultlist = array();
364 if ($found_tag == $tag) {
365 break 3; /* switch switch while */
369 /* this shouldn't happen */
370 $response[$found_tag] = $arg;
371 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
373 $resultlist[] = $data;
375 $aResponse[$found_tag] = $resultlist;
376 $data = $resultlist = array();
377 if ($found_tag == $tag) {
378 break 3; /* switch switch while */
382 $read = sqimap_fgets($imap_stream);
383 if ($read === false) { /* error */
384 break 3; /* switch switch while */
387 } // end case $tag{0}
391 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
392 /* check for literal */
393 $s = substr($read,-3);
394 $fetch_data = array();
395 do { /* outer loop, continue until next untagged fetch
397 do { /* innerloop for fetching literals. with this loop
398 we prohibid that literal responses appear in the
399 outer loop so we can trust the untagged and
400 tagged info provided by $read */
401 if ($s === "}\r\n") {
402 $j = strrpos($read,'{');
403 $iLit = substr($read,$j+
1,-3);
404 $fetch_data[] = $read;
405 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
406 if ($sLiteral === false) { /* error */
407 break 4; /* while while switch while */
409 /* backwards compattibility */
410 $aLiteral = explode("\n", $sLiteral);
411 /* release not neaded data */
413 foreach ($aLiteral as $line) {
414 $fetch_data[] = $line ."\n";
416 /* release not neaded data */
418 /* next fgets belongs to this fetch because
419 we just got the exact literalsize and there
420 must follow data to complete the response */
421 $read = sqimap_fgets($imap_stream);
422 if ($read === false) { /* error */
423 break 4; /* while while switch while */
425 $fetch_data[] = $read;
427 $fetch_data[] = $read;
429 /* retrieve next line and check in the while
430 statements if it belongs to this fetch response */
431 $read = sqimap_fgets($imap_stream);
432 if ($read === false) { /* error */
433 break 4; /* while while switch while */
435 /* check for next untagged reponse and break */
436 if ($read{0} == '*') break 2;
437 $s = substr($read,-3);
438 } while ($s === "}\r\n");
439 $s = substr($read,-3);
440 } while ($read{0} !== '*' &&
441 substr($read,0,strlen($tag)) !== $tag);
442 $resultlist[] = $fetch_data;
443 /* release not neaded data */
446 $s = substr($read,-3);
448 if ($s === "}\r\n") {
449 $j = strrpos($read,'{');
450 $iLit = substr($read,$j+
1,-3);
452 $sLiteral = fread($imap_stream,$iLit);
453 if ($sLiteral === false) { /* error */
455 break 3; /* while switch while */
458 $data[] = sqimap_fgets($imap_stream);
462 $read = sqimap_fgets($imap_stream);
463 if ($read === false) {
464 break 3; /* while switch while */
465 } else if ($read{0} == '*') {
468 $s = substr($read,-3);
469 } while ($s === "}\r\n");
477 /* error processing in case $read is false */
478 if ($read === false) {
480 if ($handle_errors) {
481 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
486 /* Set $resultlist array */
488 //$resultlist[] = $data;
490 elseif (empty($resultlist)) {
491 $resultlist[] = array();
494 /* Return result or handle errors */
495 if ($handle_errors == false) {
498 switch ($response[$tag]) {
503 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
504 if (strstr($message[$tag], 'command resulted in') === false) {
505 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
506 echo '</body></html>';
511 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
512 echo '</body></html>';
515 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
516 echo '</body></html>';
519 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
520 /* the error is displayed but because we don't know the reponse we
521 return the result anyway */
527 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
528 &$response, &$message, $query = '',
529 $filter=false,$outputstream=false,$no_return=false) {
531 $tag_uid_a = explode(' ',trim($tag_uid));
532 $tag = $tag_uid_a[0];
534 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
535 $response, $message, $query,$filter,$outputstream,$no_return);
536 /* sqimap_read_data should be called for one response
537 but since it just calls sqimap_retrieve_imap_response which
538 handles multiple responses we need to check for that
539 and merge the $res array IF they are seperated and
540 IF it was a FETCH response. */
542 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
543 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
544 // $result = array();
545 // foreach($res as $index=>$value) {
546 // $result = array_merge($result, $res["$index"]);
549 if (isset($result)) {
550 return $result[$tag];
558 * Connects to the IMAP server and returns a resource identifier for use with
559 * the other SquirrelMail IMAP functions. Does NOT login!
560 * @param string server hostname of IMAP server
561 * @param int port port number to connect to
562 * @param bool tls whether to use TLS when connecting.
563 * @return imap-stream resource identifier
565 function sqimap_create_stream($server,$port,$tls=false) {
566 global $username, $use_imap_tls;
569 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
570 /* Use TLS by prefixing "tls://" to the hostname */
571 $server = 'tls://' . $server;
573 require_once(SM_PATH
. 'functions/display_messages.php');
574 $string = "Unable to connect to IMAP server!<br>TLS is enabled, but this " .
575 "version of PHP does not support TLS sockets, or is missing the openssl " .
576 "extension.<br><br>Please contact your system administrator.";
577 logout_error($string,$color);
581 $imap_stream = fsockopen($server, $port, $error_number, $error_string, 15);
583 /* Do some error correction */
585 set_up_language($squirrelmail_language, true);
586 require_once(SM_PATH
. 'functions/display_messages.php');
587 $string = sprintf (_("Error connecting to IMAP server: %s.") .
588 "<br>\r\n", $server) .
589 "$error_number : $error_string<br>\r\n";
590 logout_error($string,$color);
593 $server_info = fgets ($imap_stream, 1024);
598 * Logs the user into the imap server. If $hide is set, no error messages
599 * will be displayed. This function returns the imap connection handle.
601 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
602 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
603 $imap_auth_mech, $sqimap_capabilities;
605 if (!isset($onetimepad) ||
empty($onetimepad)) {
606 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
608 if (!isset($sqimap_capabilities)) {
609 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
612 $host = $imap_server_address;
613 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
615 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
617 /* Decrypt the password */
618 $password = OneTimePadDecrypt($password, $onetimepad);
620 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
621 // We're using some sort of authentication OTHER than plain or login
622 $tag=sqimap_session_id(false);
623 if ($imap_auth_mech == 'digest-md5') {
624 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
625 } elseif ($imap_auth_mech == 'cram-md5') {
626 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
628 fputs($imap_stream,$query);
629 $answer=sqimap_fgets($imap_stream);
630 // Trim the "+ " off the front
631 $response=explode(" ",$answer,3);
632 if ($response[0] == '+') {
633 // Got a challenge back
634 $challenge=$response[1];
635 if ($imap_auth_mech == 'digest-md5') {
636 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
637 } elseif ($imap_auth_mech == 'cram-md5') {
638 $reply = cram_md5_response($username,$password,$challenge);
640 fputs($imap_stream,$reply);
641 $read=sqimap_fgets($imap_stream);
642 if ($imap_auth_mech == 'digest-md5') {
643 // DIGEST-MD5 has an extra step..
644 if (substr($read,0,1) == '+') { // OK so far..
645 fputs($imap_stream,"\r\n");
646 $read=sqimap_fgets($imap_stream);
649 $results=explode(" ",$read,3);
650 $response=$results[1];
651 $message=$results[2];
653 // Fake the response, so the error trap at the bottom will work
655 $message='IMAP server does not appear to support the authentication method selected.';
656 $message .= ' Please contact your system administrator.';
658 } elseif ($imap_auth_mech == 'login') {
659 // Original IMAP login code
660 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
661 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
662 } elseif ($imap_auth_mech == 'plain') {
668 * The mechanism consists of a single message from the client to the
669 * server. The client sends the authorization identity (identity to
670 * login as), followed by a US-ASCII NUL character, followed by the
671 * authentication identity (identity whose password will be used),
672 * followed by a US-ASCII NUL character, followed by the clear-text
673 * password. The client may leave the authorization identity empty to
674 * indicate that it is the same as the authentication identity.
677 $tag=sqimap_session_id(false);
678 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ?
true : false;
679 $auth = base64_encode("$username\0$username\0$password");
681 // IMAP Extension for SASL Initial Client Response
682 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
683 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
684 fputs($imap_stream, $query);
685 $read = sqimap_fgets($imap_stream);
687 $query = $tag . " AUTHENTICATE PLAIN\r\n";
688 fputs($imap_stream, $query);
689 $read=sqimap_fgets($imap_stream);
690 if (substr($read,0,1) == '+') { // OK so far..
691 fputs($imap_stream, "$auth\r\n");
692 $read = sqimap_fgets($imap_stream);
695 $results=explode(" ",$read,3);
696 $response=$results[1];
697 $message=$results[2];
700 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
703 /* If the connection was not successful, lets see why */
704 if ($response != 'OK') {
706 if ($response != 'NO') {
707 /* "BAD" and anything else gets reported here. */
708 $message = htmlspecialchars($message);
709 set_up_language($squirrelmail_language, true);
710 require_once(SM_PATH
. 'functions/display_messages.php');
711 if ($response == 'BAD') {
712 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
714 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
716 if (isset($read) && is_array($read)) {
717 $string .= '<br>' . _("Read data:") . "<br>\n";
718 foreach ($read as $line) {
719 $string .= htmlspecialchars($line) . "<br>\n";
722 error_box($string,$color);
726 * If the user does not log in with the correct
727 * username and password it is not possible to get the
728 * correct locale from the user's preferences.
729 * Therefore, apply the same hack as on the login
732 * $squirrelmail_language is set by a cookie when
733 * the user selects language and logs out
736 set_up_language($squirrelmail_language, true);
737 include_once(SM_PATH
. 'functions/display_messages.php' );
739 logout_error( _("Unknown user or password incorrect.") );
750 * Simply logs out the IMAP session
751 * @param stream imap_stream the IMAP connection to log out.
754 function sqimap_logout ($imap_stream) {
755 /* Logout is not valid until the server returns 'BYE'
756 * If we don't have an imap_ stream we're already logged out */
757 if(isset($imap_stream) && $imap_stream)
758 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
762 * Retreive the CAPABILITY string from the IMAP server.
763 * If capability is set, returns only that specific capability,
764 * else returns array of all capabilities.
766 function sqimap_capability($imap_stream, $capability='') {
767 global $sqimap_capabilities;
768 if (!is_array($sqimap_capabilities)) {
769 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
771 $c = explode(' ', $read[0]);
772 for ($i=2; $i < count($c); $i++
) {
773 $cap_list = explode('=', $c[$i]);
774 if (isset($cap_list[1])) {
775 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
777 $sqimap_capabilities[$cap_list[0]] = TRUE;
782 if (isset($sqimap_capabilities[$capability])) {
783 return $sqimap_capabilities[$capability];
788 return $sqimap_capabilities;
792 * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
794 function sqimap_get_delimiter ($imap_stream = false) {
795 global $sqimap_delimiter, $optional_delimiter;
797 /* Use configured delimiter if set */
798 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
799 return $optional_delimiter;
802 /* Do some caching here */
803 if (!$sqimap_delimiter) {
804 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
806 * According to something that I can't find, this is supposed to work on all systems
807 * OS: This won't work in Courier IMAP.
808 * OS: According to rfc2342 response from NAMESPACE command is:
809 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
810 * OS: We want to lookup all personal NAMESPACES...
812 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
813 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
814 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
817 $pna = explode(')(', $pn);
818 while (list($k, $v) = each($pna)) {
819 $lst = explode('"', $v);
820 if (isset($lst[3])) {
821 $pn[$lst[1]] = $lst[3];
827 $sqimap_delimiter = $pn[0];
829 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
830 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
831 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
832 $quote_position = strpos ($read[0], '"');
833 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
836 return $sqimap_delimiter;
840 * This encodes a mailbox name for use in IMAP commands.
841 * @param string what the mailbox to encode
842 * @return string the encoded mailbox string
844 function sqimap_encode_mailbox_name($what)
846 if (ereg("[\"\\\r\n]", $what))
847 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
848 return '"' . $what . '"'; /* 4.3 quoted string form */
853 * Gets the number of messages in the current mailbox.
855 function sqimap_get_num_messages ($imap_stream, $mailbox) {
856 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
857 for ($i = 0; $i < count($read_ary); $i++
) {
858 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
862 return false; //"BUG! Couldn't get number of messages in $mailbox!";
865 function parseAddress($address, $max=0) {
868 $iCnt = strlen($address);
869 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
870 $aReplace = array(' (',' <',' ,',' ;',' :');
871 $address = str_replace($aSpecials,$aReplace,$address);
872 $i = $iAddrFound = $bGroup = 0;
874 $cChar = $address{$i};
878 $iEnd = strpos($address,'>',$i+
1);
880 $sToken = substr($address,$i);
883 $sToken = substr($address,$i,$iEnd - $i +
1);
886 $sToken = str_replace($aReplace, $aSpecials,$sToken);
887 $aTokens[] = $sToken;
890 $iEnd = strpos($address,$cChar,$i+
1);
892 // skip escaped quotes
893 $prev_char = $address{$iEnd-1};
894 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
895 $iEnd = strpos($address,$cChar,$iEnd+
1);
897 $prev_char = $address{$iEnd-1};
904 $sToken = substr($address,$i);
907 // also remove the surrounding quotes
908 $sToken = substr($address,$i+
1,$iEnd - $i -1);
911 $sToken = str_replace($aReplace, $aSpecials,$sToken);
912 if ($sToken) $aTokens[] = $sToken;
915 $iEnd = strpos($address,')',$i);
917 $sToken = substr($address,$i);
920 $sToken = substr($address,$i,$iEnd - $i +
1);
923 $sToken = str_replace($aReplace, $aSpecials,$sToken);
924 $aTokens[] = $sToken;
934 if ($max && $max == $iAddrFound) {
946 $iEnd = strpos($address,' ',$i+
1);
948 $sToken = trim(substr($address,$i,$iEnd - $i));
951 $sToken = trim(substr($address,$i));
954 if ($sToken) $aTokens[] = $sToken;
958 $sPersonal = $sEmail = $sComment = $sGroup = '';
959 $aStack = $aComment = array();
960 foreach ($aTokens as $sToken) {
961 if ($max && $max == count($aAddress)) {
973 $aComment[] = substr($sToken,1,-1);
977 $sEmail = trim(implode(' ',$aStack));
978 $aAddress[] = array($sGroup,$sEmail);
979 $aStack = $aComment = array();
985 while (count($aStack) && !$sEmail) {
986 $sEmail = trim(array_pop($aStack));
989 if (count($aStack)) {
990 $sPersonal = trim(implode('',$aStack));
994 if (!$sPersonal && count($aComment)) {
995 $sComment = implode(' ',$aComment);
996 $sPersonal .= $sComment;
998 $aAddress[] = array($sEmail,$sPersonal);
999 $sPersonal = $sComment = $sEmail = '';
1000 $aStack = $aComment = array();
1003 $sGroup = implode(' ',$aStack); break;
1007 $sEmail = trim(substr($sToken,1,-1));
1012 default: $aStack[] = $sToken; break;
1015 /* now do the action again for the last address */
1017 while (count($aStack) && !$sEmail) {
1018 $sEmail = trim(array_pop($aStack));
1021 if (count($aStack)) {
1022 $sPersonal = trim(implode('',$aStack));
1026 if (!$sPersonal && count($aComment)) {
1027 $sComment = implode(' ',$aComment);
1028 $sPersonal .= $sComment;
1030 $aAddress[] = array($sEmail,$sPersonal);
1036 * Returns the number of unseen messages in this folder.
1038 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1039 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
1041 $regs = array(false, false);
1042 while (isset($read_ary[$i])) {
1043 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
1052 * Returns the number of total/unseen/recent messages in this folder
1054 function sqimap_status_messages ($imap_stream, $mailbox) {
1055 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1057 $messages = $unseen = $recent = false;
1058 $regs = array(false,false);
1059 while (isset($read_ary[$i])) {
1060 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1063 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1064 $messages = $regs[1];
1066 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1071 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1076 * Saves a message to a given folder -- used for saving sent messages
1078 function sqimap_append ($imap_stream, $sent_folder, $length) {
1079 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1080 $tmp = fgets ($imap_stream, 1024);
1083 function sqimap_append_done ($imap_stream, $folder='') {
1084 global $squirrelmail_language, $color;
1085 fputs ($imap_stream, "\r\n");
1086 $tmp = fgets ($imap_stream, 1024);
1087 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1088 set_up_language($squirrelmail_language);
1089 require_once(SM_PATH
. 'functions/display_messages.php');
1091 if ($regs[2] == 'NO') {
1092 $string = "<b><font color=$color[2]>\n" .
1093 _("ERROR : Could not append message to") ." $folder." .
1095 _("Server responded: ") .
1097 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1098 $string .= _("Solution: ") .
1099 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1102 $string .= "</font>\n";
1103 error_box($string,$color);
1105 $string = "<b><font color=$color[2]>\n" .
1106 _("ERROR : Bad or malformed request.") .
1108 _("Server responded: ") .
1109 $tmp . "</font><br>\n";
1110 error_box($string,$color);
1116 function sqimap_get_user_server ($imap_server, $username) {
1117 if (substr($imap_server, 0, 4) != "map:") {
1118 return $imap_server;
1120 $function = substr($imap_server, 4);
1121 return $function($username);
1125 * This is an example that gets imapservers from yellowpages (NIS).
1126 * you can simple put map:map_yp_alias in your $imap_server_address
1127 * in config.php use your own function instead map_yp_alias to map your
1128 * LDAP whatever way to find the users imapserver.
1130 function map_yp_alias($username) {
1131 $yp = `ypmatch
$username aliases`
;
1132 return chop(substr($yp, strlen($username)+
1));