c3ef35da2b40d0c6b061e98b12d27d519dcc981e
6 * Copyright (c) 1999-2005 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
17 require_once(SM_PATH
. 'functions/page_header.php');
18 require_once(SM_PATH
. 'functions/auth.php');
22 * Generates a new session ID by incrementing the last one used;
23 * this ensures that each command has a unique ID.
24 * @param bool unique_id
25 * @return string IMAP session id of the form 'A000'.
27 function sqimap_session_id($unique_id = FALSE) {
28 static $sqimap_session_id = 1;
31 return( sprintf("A%03d", $sqimap_session_id++
) );
33 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
38 * Both send a command and accept the result from the command.
39 * This is to allow proper session number handling.
41 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
43 $sid = sqimap_session_id($unique_id);
44 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
45 $tag_uid_a = explode(' ',trim($sid));
47 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
48 /* get the response and the message */
49 $message = $message[$tag];
50 $response = $response[$tag];
53 global $squirrelmail_language, $color;
54 set_up_language($squirrelmail_language);
55 require_once(SM_PATH
. 'functions/display_messages.php');
56 $string = "<b><font color=\"$color[2]\">\n" .
57 _("ERROR : No available imapstream.") .
59 error_box($string,$color);
64 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
65 &$message, $unique_id = false,$filter=false,
66 $outputstream=false,$no_return=false) {
68 $sid = sqimap_session_id($unique_id);
69 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
70 $tag_uid_a = explode(' ',trim($sid));
73 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
74 $message, $query,$filter,$outputstream,$no_return);
75 if (empty($read)) { //Imap server dropped its connection
80 /* retrieve the response and the message */
81 $response = $response[$tag];
82 $message = $message[$tag];
84 if (!empty($read[$tag])) {
85 return $read[$tag][0];
90 global $squirrelmail_language, $color;
91 set_up_language($squirrelmail_language);
92 require_once(SM_PATH
. 'functions/display_messages.php');
93 $string = "<b><font color=\"$color[2]\">\n" .
94 _("ERROR : No available imapstream.") .
96 error_box($string,$color);
101 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
102 $sid = sqimap_session_id($unique_id);
103 $tag_uid_a = explode(' ',trim($sid));
104 $tag = $tag_uid_a[0];
105 $query = $sid . ' '.$new_query."\r\n";
106 $aQuery[$tag] = $query;
109 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
110 &$aServerResponse, &$aServerMessage, $unique_id = false,
111 $filter=false,$outputstream=false,$no_return=false) {
115 Do not fire all calls at once to the imap-server but split the calls up
116 in portions of $iChunkSize. If we do not do that I think we misbehave as
117 IMAP client or should handle BYE calls if the IMAP-server drops the
118 connection because the number of queries is to large. This isn't tested
119 but a wild guess how it could work in the field.
121 After testing it on Exchange 2000 we discovered that a chunksize of 32
122 was quicker then when we raised it to 128.
124 $iQueryCount = count($aQueryList);
126 // array_chunk would also do the job but it's supported from php > 4.2
127 $aQueryChunks = array();
128 $iLoops = floor($iQueryCount / $iChunkSize);
130 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
132 if (!function_exists('array_chunk')) { // arraychunk replacement
134 for($i=0;$i<$iLoops;++
$i) {
135 for($j=0;$j<$iChunkSize;++
$j) {
136 $key = key($aQueryList);
137 $aTmp[$key] = $aQueryList[$key];
138 if (next($aQueryList) === false) break;
140 $aQueryChunks[] = $aTmp;
143 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
146 for ($i=0;$i<$iLoops;++
$i) {
147 $aQuery = $aQueryChunks[$i];
148 foreach($aQuery as $tag => $query) {
149 fputs($imap_stream,$query);
150 $aResults[$tag] = false;
152 foreach($aQuery as $tag => $query) {
153 if ($aResults[$tag] == false) {
154 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
155 $handle_errors, $response, $message, $query,
156 $filter,$outputstream,$no_return);
157 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
158 if (!empty($aResponse)) {
159 $aResults[$returned_tag] = $aResponse[0];
161 $aResults[$returned_tag] = $aResponse;
163 $aServerResponse[$returned_tag] = $response[$returned_tag];
164 $aServerMessage[$returned_tag] = $message[$returned_tag];
173 * Custom fgets function: gets a line from the IMAP-server,
174 * no matter how big it may be.
175 * @param stream imap_stream the stream to read from
176 * @return string a line
178 function sqimap_fgets($imap_stream) {
183 while (strpos($results, "\r\n", $offset) === false) {
184 if (!($read = fgets($imap_stream, $buffer))) {
185 /* this happens in case of an error */
186 /* reset $results because it's useless */
190 if ( $results != '' ) {
191 $offset = strlen($results) - 1;
198 function sqimap_fread($imap_stream,$iSize,$filter=false,
199 $outputstream=false, $no_return=false) {
200 if (!$filter ||
!$outputstream) {
201 $iBufferSize = $iSize;
203 // see php bug 24033. They changed fread behaviour %$^&$%
204 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
206 if ($iSize < $iBufferSize) {
207 $iBufferSize = $iSize;
212 $sRead = $sReadRem = '';
213 // NB: fread can also stop at end of a packet on sockets.
214 while ($iRetrieved < $iSize) {
215 $sRead = fread($imap_stream,$iBufferSize);
216 $iLength = strlen($sRead);
217 $iRetrieved +
= $iLength ;
218 $iRemaining = $iSize - $iRetrieved;
219 if ($iRemaining < $iBufferSize) {
220 $iBufferSize = $iRemaining;
226 if ($sReadRem != '') {
227 $sRead = $sReadRem . $sRead;
231 if ($filter && $sRead != '') {
232 // in case the filter is base64 decoding we return a remainder
233 $sReadRem = $filter($sRead);
235 if ($outputstream && $sRead != '') {
236 if (is_resource($outputstream)) {
237 fwrite($outputstream,$sRead);
238 } else if ($outputstream == 'php://stdout') {
253 * Obsolete function, inform plugins that use it
254 * @deprecated use sqimap_run_command or sqimap_run_command_list instead
256 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
257 &$response, &$message, $query = '') {
258 global $color, $squirrelmail_language;
259 set_up_language($squirrelmail_language);
260 require_once(SM_PATH
. 'functions/display_messages.php');
261 $string = "<b><font color=\"$color[2]\">\n" .
262 _("ERROR : Bad function call.") .
265 'There is a plugin installed which make use of the <br />' .
266 'SquirrelMail internal function sqimap_read_data_list.<br />'.
267 'Please adapt the installed plugin and let it use<br />'.
268 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
269 'The following query was issued:<br />'.
270 htmlspecialchars($query) . '<br />' . "</font><br />\n";
271 error_box($string,$color);
272 echo '</body></html>';
277 * Function to display an error related to an IMAP-query.
278 * @param string title the caption of the error box
279 * @param string query the query that went wrong
280 * @param string message_title optional message title
281 * @param string message optional error message
282 * @param string $link an optional link to try again
285 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
287 global $color, $squirrelmail_language;
289 set_up_language($squirrelmail_language);
290 require_once(SM_PATH
. 'functions/display_messages.php');
291 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
292 $cmd = explode(' ',$query);
293 $cmd= strtolower($cmd[0]);
295 if ($query != '' && $cmd != 'login')
296 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
297 if ($message_title != '')
298 $string .= $message_title;
300 $string .= htmlspecialchars($message);
301 $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();
320 $resultlist = array();
322 $read = sqimap_fgets($imap_stream);
330 $read = sqimap_fgets($imap_stream);
335 /* get the command */
338 $s = substr($read,$i);
339 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
340 $arg = substr($s,0,$j);
342 $found_tag = substr($read,0,$i-1);
351 $response[$found_tag] = $arg;
352 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
354 $resultlist[] = $data;
356 $aResponse[$found_tag] = $resultlist;
357 $data = $resultlist = array();
358 if ($found_tag == $tag) {
359 break 3; /* switch switch while */
363 /* this shouldn't happen */
364 $response[$found_tag] = $arg;
365 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
367 $resultlist[] = $data;
369 $aResponse[$found_tag] = $resultlist;
370 $data = $resultlist = array();
371 if ($found_tag == $tag) {
372 break 3; /* switch switch while */
376 $read = sqimap_fgets($imap_stream);
377 if ($read === false) { /* error */
378 break 2; /* switch while */
381 } // end case $tag{0}
385 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
386 /* check for literal */
387 $s = substr($read,-3);
388 $fetch_data = array();
389 do { /* outer loop, continue until next untagged fetch
391 do { /* innerloop for fetching literals. with this loop
392 we prohibid that literal responses appear in the
393 outer loop so we can trust the untagged and
394 tagged info provided by $read */
395 if ($s === "}\r\n") {
396 $j = strrpos($read,'{');
397 $iLit = substr($read,$j+
1,-3);
398 $fetch_data[] = $read;
399 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
400 if ($sLiteral === false) { /* error */
401 break 4; /* while while switch while */
403 /* backwards compattibility */
404 $aLiteral = explode("\n", $sLiteral);
405 /* release not neaded data */
407 foreach ($aLiteral as $line) {
408 $fetch_data[] = $line ."\n";
410 /* release not neaded data */
412 /* next fgets belongs to this fetch because
413 we just got the exact literalsize and there
414 must follow data to complete the response */
415 $read = sqimap_fgets($imap_stream);
416 if ($read === false) { /* error */
417 break 4; /* while while switch while */
419 $fetch_data[] = $read;
421 $fetch_data[] = $read;
423 /* retrieve next line and check in the while
424 statements if it belongs to this fetch response */
425 $read = sqimap_fgets($imap_stream);
426 if ($read === false) { /* error */
427 break 4; /* while while switch while */
429 /* check for next untagged reponse and break */
430 if ($read{0} == '*') break 2;
431 $s = substr($read,-3);
432 } while ($s === "}\r\n");
433 $s = substr($read,-3);
434 } while ($read{0} !== '*' &&
435 substr($read,0,strlen($tag)) !== $tag);
436 $resultlist[] = $fetch_data;
437 /* release not neaded data */
440 $s = substr($read,-3);
442 if ($s === "}\r\n") {
443 $j = strrpos($read,'{');
444 $iLit = substr($read,$j+
1,-3);
446 $sLiteral = fread($imap_stream,$iLit);
447 if ($sLiteral === false) { /* error */
449 break 3; /* while switch while */
452 $data[] = sqimap_fgets($imap_stream);
456 $read = sqimap_fgets($imap_stream);
457 if ($read === false) {
458 break 3; /* while switch while */
459 } else if ($read{0} == '*') {
462 $s = substr($read,-3);
463 } while ($s === "}\r\n");
471 /* error processing in case $read is false */
472 if ($read === false) {
473 // try to retrieve an untagged bye respons from the results
474 $sResponse = array_pop($data);
475 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
476 if (!$handle_errors) {
479 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded:"),$sResponse);
480 echo '</body></html>';
482 } else if ($handle_errors) {
484 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
489 /* Set $resultlist array */
491 //$resultlist[] = $data;
493 elseif (empty($resultlist)) {
494 $resultlist[] = array();
497 /* Return result or handle errors */
498 if ($handle_errors == false) {
501 switch ($response[$tag]) {
506 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
507 if (strstr($message[$tag], 'command resulted in') === false) {
508 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
509 echo '</body></html>';
514 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
515 echo '</body></html>';
518 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
519 echo '</body></html>';
522 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
523 /* the error is displayed but because we don't know the reponse we
524 return the result anyway */
530 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
531 &$response, &$message, $query = '',
532 $filter=false,$outputstream=false,$no_return=false) {
534 $tag_uid_a = explode(' ',trim($tag_uid));
535 $tag = $tag_uid_a[0];
537 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
538 $response, $message, $query,$filter,$outputstream,$no_return);
543 * Connects to the IMAP server and returns a resource identifier for use with
544 * the other SquirrelMail IMAP functions. Does NOT login!
545 * @param string server hostname of IMAP server
546 * @param int port port number to connect to
547 * @param bool tls whether to use TLS when connecting.
548 * @return imap-stream resource identifier
550 function sqimap_create_stream($server,$port,$tls=false) {
551 global $squirrelmail_language;
554 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
555 /* Use TLS by prefixing "tls://" to the hostname */
556 $server = 'tls://' . $server;
558 require_once(SM_PATH
. 'functions/display_messages.php');
559 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
561 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
563 _("Please contact your system administrator and report this error.") );
567 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
569 /* Do some error correction */
571 set_up_language($squirrelmail_language, true);
572 require_once(SM_PATH
. 'functions/display_messages.php');
573 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
574 "<br />\r\n$error_number : $error_string<br />\r\n" );
577 $server_info = fgets ($imap_stream, 1024);
582 * Logs the user into the imap server. If $hide is set, no error messages
583 * will be displayed. This function returns the imap connection handle.
585 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
586 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
587 $imap_auth_mech, $sqimap_capabilities;
589 if (!isset($onetimepad) ||
empty($onetimepad)) {
590 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
592 if (!isset($sqimap_capabilities)) {
593 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
596 $host = $imap_server_address;
597 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
599 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
601 /* Decrypt the password */
602 $password = OneTimePadDecrypt($password, $onetimepad);
604 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
605 // We're using some sort of authentication OTHER than plain or login
606 $tag=sqimap_session_id(false);
607 if ($imap_auth_mech == 'digest-md5') {
608 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
609 } elseif ($imap_auth_mech == 'cram-md5') {
610 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
612 fputs($imap_stream,$query);
613 $answer=sqimap_fgets($imap_stream);
614 // Trim the "+ " off the front
615 $response=explode(" ",$answer,3);
616 if ($response[0] == '+') {
617 // Got a challenge back
618 $challenge=$response[1];
619 if ($imap_auth_mech == 'digest-md5') {
620 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
621 } elseif ($imap_auth_mech == 'cram-md5') {
622 $reply = cram_md5_response($username,$password,$challenge);
624 fputs($imap_stream,$reply);
625 $read=sqimap_fgets($imap_stream);
626 if ($imap_auth_mech == 'digest-md5') {
627 // DIGEST-MD5 has an extra step..
628 if (substr($read,0,1) == '+') { // OK so far..
629 fputs($imap_stream,"\r\n");
630 $read=sqimap_fgets($imap_stream);
633 $results=explode(" ",$read,3);
634 $response=$results[1];
635 $message=$results[2];
637 // Fake the response, so the error trap at the bottom will work
639 $message='IMAP server does not appear to support the authentication method selected.';
640 $message .= ' Please contact your system administrator.';
642 } elseif ($imap_auth_mech == 'login') {
643 // Original IMAP login code
644 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
645 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
646 } elseif ($imap_auth_mech == 'plain') {
652 * The mechanism consists of a single message from the client to the
653 * server. The client sends the authorization identity (identity to
654 * login as), followed by a US-ASCII NUL character, followed by the
655 * authentication identity (identity whose password will be used),
656 * followed by a US-ASCII NUL character, followed by the clear-text
657 * password. The client may leave the authorization identity empty to
658 * indicate that it is the same as the authentication identity.
661 $tag=sqimap_session_id(false);
662 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ?
true : false;
663 $auth = base64_encode("$username\0$username\0$password");
665 // IMAP Extension for SASL Initial Client Response
666 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
667 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
668 fputs($imap_stream, $query);
669 $read = sqimap_fgets($imap_stream);
671 $query = $tag . " AUTHENTICATE PLAIN\r\n";
672 fputs($imap_stream, $query);
673 $read=sqimap_fgets($imap_stream);
674 if (substr($read,0,1) == '+') { // OK so far..
675 fputs($imap_stream, "$auth\r\n");
676 $read = sqimap_fgets($imap_stream);
679 $results=explode(" ",$read,3);
680 $response=$results[1];
681 $message=$results[2];
684 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
687 /* If the connection was not successful, lets see why */
688 if ($response != 'OK') {
690 if ($response != 'NO') {
691 /* "BAD" and anything else gets reported here. */
692 $message = htmlspecialchars($message);
693 set_up_language($squirrelmail_language, true);
694 require_once(SM_PATH
. 'functions/display_messages.php');
695 if ($response == 'BAD') {
696 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
698 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
700 if (isset($read) && is_array($read)) {
701 $string .= '<br />' . _("Read data:") . "<br />\n";
702 foreach ($read as $line) {
703 $string .= htmlspecialchars($line) . "<br />\n";
706 error_box($string,$color);
710 * If the user does not log in with the correct
711 * username and password it is not possible to get the
712 * correct locale from the user's preferences.
713 * Therefore, apply the same hack as on the login
716 * $squirrelmail_language is set by a cookie when
717 * the user selects language and logs out
720 set_up_language($squirrelmail_language, true);
721 include_once(SM_PATH
. 'functions/display_messages.php' );
723 /* terminate the session nicely */
724 sqimap_logout($imap_stream);
725 logout_error( _("Unknown user or password incorrect.") );
736 * Simply logs out the IMAP session
737 * @param stream imap_stream the IMAP connection to log out.
740 function sqimap_logout ($imap_stream) {
741 /* Logout is not valid until the server returns 'BYE'
742 * If we don't have an imap_ stream we're already logged out */
743 if(isset($imap_stream) && $imap_stream)
744 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
748 * Retreive the CAPABILITY string from the IMAP server.
749 * If capability is set, returns only that specific capability,
750 * else returns array of all capabilities.
752 function sqimap_capability($imap_stream, $capability='') {
753 global $sqimap_capabilities;
754 if (!is_array($sqimap_capabilities)) {
755 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
757 $c = explode(' ', $read[0]);
758 for ($i=2; $i < count($c); $i++
) {
759 $cap_list = explode('=', $c[$i]);
760 if (isset($cap_list[1])) {
761 // FIX ME. capabilities can occure multiple times.
762 // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
763 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
765 $sqimap_capabilities[$cap_list[0]] = TRUE;
770 if (isset($sqimap_capabilities[$capability])) {
771 return $sqimap_capabilities[$capability];
776 return $sqimap_capabilities;
780 * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
782 function sqimap_get_delimiter ($imap_stream = false) {
783 global $sqimap_delimiter, $optional_delimiter;
785 /* Use configured delimiter if set */
786 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
787 return $optional_delimiter;
790 /* Do some caching here */
791 if (!$sqimap_delimiter) {
792 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
794 * According to something that I can't find, this is supposed to work on all systems
795 * OS: This won't work in Courier IMAP.
796 * OS: According to rfc2342 response from NAMESPACE command is:
797 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
798 * OS: We want to lookup all personal NAMESPACES...
800 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
801 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
802 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
805 $pna = explode(')(', $pn);
806 while (list($k, $v) = each($pna)) {
807 $lst = explode('"', $v);
808 if (isset($lst[3])) {
809 $pn[$lst[1]] = $lst[3];
815 $sqimap_delimiter = $pn[0];
817 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
818 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
819 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
820 $quote_position = strpos ($read[0], '"');
821 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
824 return $sqimap_delimiter;
828 * This encodes a mailbox name for use in IMAP commands.
829 * @param string what the mailbox to encode
830 * @return string the encoded mailbox string
832 function sqimap_encode_mailbox_name($what)
834 if (ereg("[\"\\\r\n]", $what))
835 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
836 return '"' . $what . '"'; /* 4.3 quoted string form */
840 * Gets the number of messages in the current mailbox.
842 * OBSOLETE use sqimap_status_messages instead.
844 function sqimap_get_num_messages ($imap_stream, $mailbox) {
845 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
846 for ($i = 0; $i < count($read_ary); $i++
) {
847 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
851 return false; //"BUG! Couldn't get number of messages in $mailbox!";
853 include_once(SM_PATH
. 'functions/rfc822address.php');
856 * OBSOLETE FUNCTION should be removed after mailbox_display,
857 * printMessage function is adapted
859 function parseAddress($address, $max=0) {
860 $aAddress = parseRFC822Address($address,array('limit'=> $max));
862 * Because the expected format of the array element is changed we adapt it now.
863 * This also implies that this function is obsolete and should be removed after the
864 * rest of the source is adapted. See Rfc822Address.php for the new function.
866 array_walk($aAddress, '_adaptAddress');
871 * OBSOLETE FUNCTION should be removed after mailbox_display,
872 * printMessage function is adapted
874 function _adaptAddress(&$aAddr,$k) {
875 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
876 $aAddr[SQM_ADDR_PERSONAL
] : '';
877 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
878 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
879 $aAddr[SQM_ADDR_MAILBOX
];
880 $aAddr = array($sEmail,$sPersonal);
884 * Returns the number of unseen messages in this folder.
885 * obsoleted by sqimap_status_messages !
887 function sqimap_unseen_messages ($imap_stream, $mailbox) {
888 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
889 return $aStatus['UNSEEN'];
893 * Returns the status items of a mailbox.
894 * Default it returns MESSAGES,UNSEEN and RECENT
895 * Supported status items are MESSAGES, UNSEEN, RECENT, UIDNEXT and UIDVALIDITY
897 function sqimap_status_messages ($imap_stream, $mailbox,
898 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
900 $aStatusItems = implode(' ',$aStatusItems);
901 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
902 " ($aStatusItems)", false, $result, $message);
904 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
905 $regs = array(false,false);
906 while (isset($read_ary[$i])) {
907 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
910 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
911 $messages = $regs[1];
913 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
916 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
919 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
920 $uidvalidity = $regs[1];
924 return array('MESSAGES' => $messages,
927 'UIDNEXT' => $uidnext,
928 'UIDVALIDITY' => $uidvalidity);
933 * Saves a message to a given folder -- used for saving sent messages
935 function sqimap_append ($imap_stream, $sent_folder, $length) {
936 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
937 $tmp = fgets ($imap_stream, 1024);
940 function sqimap_append_done ($imap_stream, $folder='') {
941 global $squirrelmail_language, $color;
942 fputs ($imap_stream, "\r\n");
943 $tmp = fgets ($imap_stream, 1024);
944 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
945 set_up_language($squirrelmail_language);
946 require_once(SM_PATH
. 'functions/display_messages.php');
948 if ($regs[2] == 'NO') {
949 $string = "<b><font color=\"$color[2]\">\n" .
950 _("ERROR : Could not append message to") ." $folder." .
952 _("Server responded: ") .
953 $reason . "<br />\n";
954 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
955 $string .= _("Solution: ") .
956 _("Remove unneccessary messages from your folder and start with your Trash folder.")
959 $string .= "</font>\n";
960 error_box($string,$color);
962 $string = "<b><font color=\"$color[2]\">\n" .
963 _("ERROR : Bad or malformed request.") .
965 _("Server responded: ") .
966 $tmp . "</font><br />\n";
967 error_box($string,$color);
973 function sqimap_get_user_server ($imap_server, $username) {
974 if (substr($imap_server, 0, 4) != "map:") {
977 $function = substr($imap_server, 4);
978 return $function($username);
982 * This is an example that gets imapservers from yellowpages (NIS).
983 * you can simple put map:map_yp_alias in your $imap_server_address
984 * in config.php use your own function instead map_yp_alias to map your
985 * LDAP whatever way to find the users imapserver.
987 function map_yp_alias($username) {
988 $yp = `ypmatch
$username aliases`
;
989 return chop(substr($yp, strlen($username)+
1));