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 (since 1.3.0) controls use of unique
25 * identifiers/message sequence numbers in IMAP commands. See IMAP
26 * rfc 'UID command' chapter.
27 * @return string IMAP session id of the form 'A000'.
30 function sqimap_session_id($unique_id = FALSE) {
31 static $sqimap_session_id = 1;
34 return( sprintf("A%03d", $sqimap_session_id++
) );
36 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
41 * Both send a command and accept the result from the command.
42 * This is to allow proper session number handling.
43 * @param stream $imap_stream imap connection resource
44 * @param string $query imap command
45 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
46 * @param array $response
47 * @param array $message
48 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
49 * @return mixed returns false on imap error. displays error message
50 * if imap stream is not available.
53 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
55 $sid = sqimap_session_id($unique_id);
56 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
57 $tag_uid_a = explode(' ',trim($sid));
59 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
60 /* get the response and the message */
61 $message = $message[$tag];
62 $response = $response[$tag];
65 global $squirrelmail_language, $color;
66 set_up_language($squirrelmail_language);
67 require_once(SM_PATH
. 'functions/display_messages.php');
68 $string = "<b><font color=\"$color[2]\">\n" .
69 _("ERROR : No available imapstream.") .
71 error_box($string,$color);
77 * @param stream $imap_stream imap connection resource
78 * @param string $query imap command
79 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
80 * @param array $response empty string, if return = false
81 * @param array $message empty string, if return = false
82 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
83 * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
84 * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
85 * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
86 * @return mixed returns false on imap error. displays error message
87 * if imap stream is not available.
90 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
91 &$message, $unique_id = false,$filter=false,
92 $outputstream=false,$no_return=false) {
94 $sid = sqimap_session_id($unique_id);
95 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
96 $tag_uid_a = explode(' ',trim($sid));
99 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
100 $message, $query,$filter,$outputstream,$no_return);
101 if (empty($read)) { //Imap server dropped its connection
106 /* retrieve the response and the message */
107 $response = $response[$tag];
108 $message = $message[$tag];
110 if (!empty($read[$tag])) {
111 return $read[$tag][0];
116 global $squirrelmail_language, $color;
117 set_up_language($squirrelmail_language);
118 require_once(SM_PATH
. 'functions/display_messages.php');
119 $string = "<b><font color=\"$color[2]\">\n" .
120 _("ERROR : No available imapstream.") .
122 error_box($string,$color);
128 * @param mixed $new_query
130 * @param array $aQuery
131 * @param boolean $unique_id see sqimap_session_id()
134 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
135 $sid = sqimap_session_id($unique_id);
136 $tag_uid_a = explode(' ',trim($sid));
137 $tag = $tag_uid_a[0];
138 $query = $sid . ' '.$new_query."\r\n";
139 $aQuery[$tag] = $query;
143 * @param stream $imap_stream imap stream
144 * @param array $aQueryList
145 * @param boolean $handle_errors
146 * @param array $aServerResponse
147 * @param array $aServerMessage
148 * @param boolean $unique_id see sqimap_session_id()
149 * @param boolean $filter see sqimap_fread()
150 * @param mixed $outputstream see sqimap_fread()
151 * @param boolean $no_return see sqimap_fread()
154 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
155 &$aServerResponse, &$aServerMessage, $unique_id = false,
156 $filter=false,$outputstream=false,$no_return=false) {
160 Do not fire all calls at once to the imap-server but split the calls up
161 in portions of $iChunkSize. If we do not do that I think we misbehave as
162 IMAP client or should handle BYE calls if the IMAP-server drops the
163 connection because the number of queries is to large. This isn't tested
164 but a wild guess how it could work in the field.
166 After testing it on Exchange 2000 we discovered that a chunksize of 32
167 was quicker then when we raised it to 128.
169 $iQueryCount = count($aQueryList);
171 // array_chunk would also do the job but it's supported from php > 4.2
172 $aQueryChunks = array();
173 $iLoops = floor($iQueryCount / $iChunkSize);
175 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
177 if (!function_exists('array_chunk')) { // arraychunk replacement
179 for($i=0;$i<$iLoops;++
$i) {
180 for($j=0;$j<$iChunkSize;++
$j) {
181 $key = key($aQueryList);
182 $aTmp[$key] = $aQueryList[$key];
183 if (next($aQueryList) === false) break;
185 $aQueryChunks[] = $aTmp;
188 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
191 for ($i=0;$i<$iLoops;++
$i) {
192 $aQuery = $aQueryChunks[$i];
193 foreach($aQuery as $tag => $query) {
194 fputs($imap_stream,$query);
195 $aResults[$tag] = false;
197 foreach($aQuery as $tag => $query) {
198 if ($aResults[$tag] == false) {
199 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
200 $handle_errors, $response, $message, $query,
201 $filter,$outputstream,$no_return);
202 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
203 if (!empty($aResponse)) {
204 $aResults[$returned_tag] = $aResponse[0];
206 $aResults[$returned_tag] = $aResponse;
208 $aServerResponse[$returned_tag] = $response[$returned_tag];
209 $aServerMessage[$returned_tag] = $message[$returned_tag];
218 * Custom fgets function: gets a line from the IMAP-server,
219 * no matter how big it may be.
220 * @param stream $imap_stream the stream to read from
221 * @return string a line
224 function sqimap_fgets($imap_stream) {
229 while (strpos($results, "\r\n", $offset) === false) {
230 if (!($read = fgets($imap_stream, $buffer))) {
231 /* this happens in case of an error */
232 /* reset $results because it's useless */
236 if ( $results != '' ) {
237 $offset = strlen($results) - 1;
245 * @param stream $imap_stream
246 * @param integer $iSize
247 * @param boolean $filter
248 * @param mixed $outputstream stream or 'php://stdout' string
249 * @param boolean $no_return controls data returned by function
253 function sqimap_fread($imap_stream,$iSize,$filter=false,
254 $outputstream=false, $no_return=false) {
255 if (!$filter ||
!$outputstream) {
256 $iBufferSize = $iSize;
258 // see php bug 24033. They changed fread behaviour %$^&$%
259 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
261 if ($iSize < $iBufferSize) {
262 $iBufferSize = $iSize;
267 $sRead = $sReadRem = '';
268 // NB: fread can also stop at end of a packet on sockets.
269 while ($iRetrieved < $iSize) {
270 $sRead = fread($imap_stream,$iBufferSize);
271 $iLength = strlen($sRead);
272 $iRetrieved +
= $iLength ;
273 $iRemaining = $iSize - $iRetrieved;
274 if ($iRemaining < $iBufferSize) {
275 $iBufferSize = $iRemaining;
281 if ($sReadRem != '') {
282 $sRead = $sReadRem . $sRead;
286 if ($filter && $sRead != '') {
287 // in case the filter is base64 decoding we return a remainder
288 $sReadRem = $filter($sRead);
290 if ($outputstream && $sRead != '') {
291 if (is_resource($outputstream)) {
292 fwrite($outputstream,$sRead);
293 } else if ($outputstream == 'php://stdout') {
308 * Obsolete function, inform plugins that use it
309 * @param stream $imap_stream
311 * @param boolean $handle_errors
312 * @param array $response
313 * @param array $message
314 * @param string $query
316 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
318 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
319 &$response, &$message, $query = '') {
320 global $color, $squirrelmail_language;
321 set_up_language($squirrelmail_language);
322 require_once(SM_PATH
. 'functions/display_messages.php');
323 $string = "<b><font color=\"$color[2]\">\n" .
324 _("ERROR : Bad function call.") .
327 'There is a plugin installed which make use of the <br />' .
328 'SquirrelMail internal function sqimap_read_data_list.<br />'.
329 'Please adapt the installed plugin and let it use<br />'.
330 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
331 'The following query was issued:<br />'.
332 htmlspecialchars($query) . '<br />' . "</font><br />\n";
333 error_box($string,$color);
334 echo '</body></html>';
339 * Function to display an error related to an IMAP-query.
340 * @param string title the caption of the error box
341 * @param string query the query that went wrong
342 * @param string message_title optional message title
343 * @param string message optional error message
344 * @param string $link an optional link to try again
348 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
350 global $color, $squirrelmail_language;
352 set_up_language($squirrelmail_language);
353 require_once(SM_PATH
. 'functions/display_messages.php');
354 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
355 $cmd = explode(' ',$query);
356 $cmd= strtolower($cmd[0]);
358 if ($query != '' && $cmd != 'login')
359 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
360 if ($message_title != '')
361 $string .= $message_title;
363 $string .= htmlspecialchars($message);
364 $string .= "</font><br />\n";
367 error_box($string,$color);
371 * Reads the output from the IMAP stream. If handle_errors is set to true,
372 * this will also handle all errors that are received. If it is not set,
373 * the errors will be sent back through $response and $message.
374 * @param stream $imap_stream imap stream
376 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
377 * @param array $response
378 * @param array $message
379 * @param string $query command that can be printed if something fails
380 * @param boolean $filter see sqimap_fread()
381 * @param mixed $outputstream see sqimap_fread()
382 * @param boolean $no_return see sqimap_fread()
385 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
386 &$response, &$message, $query = '',
387 $filter = false, $outputstream = false, $no_return = false) {
388 global $color, $squirrelmail_language;
390 if (!is_array($message)) $message = array();
391 if (!is_array($response)) $response = array();
393 $resultlist = array();
395 $read = sqimap_fgets($imap_stream);
403 $read = sqimap_fgets($imap_stream);
408 /* get the command */
411 $s = substr($read,$i);
412 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
413 $arg = substr($s,0,$j);
415 $found_tag = substr($read,0,$i-1);
424 $response[$found_tag] = $arg;
425 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
427 $resultlist[] = $data;
429 $aResponse[$found_tag] = $resultlist;
430 $data = $resultlist = array();
431 if ($found_tag == $tag) {
432 break 3; /* switch switch while */
436 /* this shouldn't happen */
437 $response[$found_tag] = $arg;
438 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
440 $resultlist[] = $data;
442 $aResponse[$found_tag] = $resultlist;
443 $data = $resultlist = array();
444 if ($found_tag == $tag) {
445 break 3; /* switch switch while */
449 $read = sqimap_fgets($imap_stream);
450 if ($read === false) { /* error */
451 break 2; /* switch while */
454 } // end case $tag{0}
458 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
459 /* check for literal */
460 $s = substr($read,-3);
461 $fetch_data = array();
462 do { /* outer loop, continue until next untagged fetch
464 do { /* innerloop for fetching literals. with this loop
465 we prohibid that literal responses appear in the
466 outer loop so we can trust the untagged and
467 tagged info provided by $read */
468 if ($s === "}\r\n") {
469 $j = strrpos($read,'{');
470 $iLit = substr($read,$j+
1,-3);
471 $fetch_data[] = $read;
472 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
473 if ($sLiteral === false) { /* error */
474 break 4; /* while while switch while */
476 /* backwards compattibility */
477 $aLiteral = explode("\n", $sLiteral);
478 /* release not neaded data */
480 foreach ($aLiteral as $line) {
481 $fetch_data[] = $line ."\n";
483 /* release not neaded data */
485 /* next fgets belongs to this fetch because
486 we just got the exact literalsize and there
487 must follow data to complete the response */
488 $read = sqimap_fgets($imap_stream);
489 if ($read === false) { /* error */
490 break 4; /* while while switch while */
492 $fetch_data[] = $read;
494 $fetch_data[] = $read;
496 /* retrieve next line and check in the while
497 statements if it belongs to this fetch response */
498 $read = sqimap_fgets($imap_stream);
499 if ($read === false) { /* error */
500 break 4; /* while while switch while */
502 /* check for next untagged reponse and break */
503 if ($read{0} == '*') break 2;
504 $s = substr($read,-3);
505 } while ($s === "}\r\n");
506 $s = substr($read,-3);
507 } while ($read{0} !== '*' &&
508 substr($read,0,strlen($tag)) !== $tag);
509 $resultlist[] = $fetch_data;
510 /* release not neaded data */
513 $s = substr($read,-3);
515 if ($s === "}\r\n") {
516 $j = strrpos($read,'{');
517 $iLit = substr($read,$j+
1,-3);
519 $sLiteral = fread($imap_stream,$iLit);
520 if ($sLiteral === false) { /* error */
522 break 3; /* while switch while */
525 $data[] = sqimap_fgets($imap_stream);
529 $read = sqimap_fgets($imap_stream);
530 if ($read === false) {
531 break 3; /* while switch while */
532 } else if ($read{0} == '*') {
535 $s = substr($read,-3);
536 } while ($s === "}\r\n");
544 /* error processing in case $read is false */
545 if ($read === false) {
546 // try to retrieve an untagged bye respons from the results
547 $sResponse = array_pop($data);
548 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
549 if (!$handle_errors) {
552 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded:"),$sResponse);
553 echo '</body></html>';
555 } else if ($handle_errors) {
557 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
562 /* Set $resultlist array */
564 //$resultlist[] = $data;
566 elseif (empty($resultlist)) {
567 $resultlist[] = array();
570 /* Return result or handle errors */
571 if ($handle_errors == false) {
574 switch ($response[$tag]) {
579 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
580 if (strstr($message[$tag], 'command resulted in') === false) {
581 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
582 echo '</body></html>';
587 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
588 echo '</body></html>';
591 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
592 echo '</body></html>';
595 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
596 /* the error is displayed but because we don't know the reponse we
597 return the result anyway */
604 * @param stream $imap_stream imap string
605 * @param string $tag_uid
606 * @param boolean $handle_errors
607 * @param array $response
608 * @param array $message
609 * @param string $query (since 1.2.5)
610 * @param boolean $filter (since 1.4.1) see sqimap_fread()
611 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
612 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
614 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
615 &$response, &$message, $query = '',
616 $filter=false,$outputstream=false,$no_return=false) {
618 $tag_uid_a = explode(' ',trim($tag_uid));
619 $tag = $tag_uid_a[0];
621 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
622 $response, $message, $query,$filter,$outputstream,$no_return);
627 * Connects to the IMAP server and returns a resource identifier for use with
628 * the other SquirrelMail IMAP functions. Does NOT login!
629 * @param string server hostname of IMAP server
630 * @param int port port number to connect to
631 * @param bool tls whether to use TLS when connecting.
632 * @return imap-stream resource identifier
633 * @since 1.5.0 (usable only in 1.5.1 or later)
635 function sqimap_create_stream($server,$port,$tls=false) {
636 global $squirrelmail_language;
639 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
640 /* Use TLS by prefixing "tls://" to the hostname */
641 $server = 'tls://' . $server;
643 require_once(SM_PATH
. 'functions/display_messages.php');
644 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
646 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
648 _("Please contact your system administrator and report this error.") );
652 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
654 /* Do some error correction */
656 set_up_language($squirrelmail_language, true);
657 require_once(SM_PATH
. 'functions/display_messages.php');
658 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
659 "<br />\r\n$error_number : $error_string<br />\r\n" );
662 $server_info = fgets ($imap_stream, 1024);
667 * Logs the user into the imap server. If $hide is set, no error messages
668 * will be displayed. This function returns the imap connection handle.
669 * @param string $username user name
670 * @param string $password encrypted password
671 * @param string $imap_server_address address of imap server
672 * @param integer $imap_port port of imap server
673 * @param boolean $hide controls display connection errors
676 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
677 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
678 $imap_auth_mech, $sqimap_capabilities;
680 if (!isset($onetimepad) ||
empty($onetimepad)) {
681 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
683 if (!isset($sqimap_capabilities)) {
684 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
687 $host = $imap_server_address;
688 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
690 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
692 /* Decrypt the password */
693 $password = OneTimePadDecrypt($password, $onetimepad);
695 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
696 // We're using some sort of authentication OTHER than plain or login
697 $tag=sqimap_session_id(false);
698 if ($imap_auth_mech == 'digest-md5') {
699 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
700 } elseif ($imap_auth_mech == 'cram-md5') {
701 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
703 fputs($imap_stream,$query);
704 $answer=sqimap_fgets($imap_stream);
705 // Trim the "+ " off the front
706 $response=explode(" ",$answer,3);
707 if ($response[0] == '+') {
708 // Got a challenge back
709 $challenge=$response[1];
710 if ($imap_auth_mech == 'digest-md5') {
711 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
712 } elseif ($imap_auth_mech == 'cram-md5') {
713 $reply = cram_md5_response($username,$password,$challenge);
715 fputs($imap_stream,$reply);
716 $read=sqimap_fgets($imap_stream);
717 if ($imap_auth_mech == 'digest-md5') {
718 // DIGEST-MD5 has an extra step..
719 if (substr($read,0,1) == '+') { // OK so far..
720 fputs($imap_stream,"\r\n");
721 $read=sqimap_fgets($imap_stream);
724 $results=explode(" ",$read,3);
725 $response=$results[1];
726 $message=$results[2];
728 // Fake the response, so the error trap at the bottom will work
730 $message='IMAP server does not appear to support the authentication method selected.';
731 $message .= ' Please contact your system administrator.';
733 } elseif ($imap_auth_mech == 'login') {
734 // Original IMAP login code
735 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
736 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
737 } elseif ($imap_auth_mech == 'plain') {
743 * The mechanism consists of a single message from the client to the
744 * server. The client sends the authorization identity (identity to
745 * login as), followed by a US-ASCII NUL character, followed by the
746 * authentication identity (identity whose password will be used),
747 * followed by a US-ASCII NUL character, followed by the clear-text
748 * password. The client may leave the authorization identity empty to
749 * indicate that it is the same as the authentication identity.
752 $tag=sqimap_session_id(false);
753 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ?
true : false;
754 $auth = base64_encode("$username\0$username\0$password");
756 // IMAP Extension for SASL Initial Client Response
757 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
758 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
759 fputs($imap_stream, $query);
760 $read = sqimap_fgets($imap_stream);
762 $query = $tag . " AUTHENTICATE PLAIN\r\n";
763 fputs($imap_stream, $query);
764 $read=sqimap_fgets($imap_stream);
765 if (substr($read,0,1) == '+') { // OK so far..
766 fputs($imap_stream, "$auth\r\n");
767 $read = sqimap_fgets($imap_stream);
770 $results=explode(" ",$read,3);
771 $response=$results[1];
772 $message=$results[2];
775 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
778 /* If the connection was not successful, lets see why */
779 if ($response != 'OK') {
781 if ($response != 'NO') {
782 /* "BAD" and anything else gets reported here. */
783 $message = htmlspecialchars($message);
784 set_up_language($squirrelmail_language, true);
785 require_once(SM_PATH
. 'functions/display_messages.php');
786 if ($response == 'BAD') {
787 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
789 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
791 if (isset($read) && is_array($read)) {
792 $string .= '<br />' . _("Read data:") . "<br />\n";
793 foreach ($read as $line) {
794 $string .= htmlspecialchars($line) . "<br />\n";
797 error_box($string,$color);
801 * If the user does not log in with the correct
802 * username and password it is not possible to get the
803 * correct locale from the user's preferences.
804 * Therefore, apply the same hack as on the login
807 * $squirrelmail_language is set by a cookie when
808 * the user selects language and logs out
811 set_up_language($squirrelmail_language, true);
812 include_once(SM_PATH
. 'functions/display_messages.php' );
814 /* terminate the session nicely */
815 sqimap_logout($imap_stream);
816 logout_error( _("Unknown user or password incorrect.") );
824 /* Special error case:
825 * Login referrals. The server returns:
826 * ? OK [REFERRAL <imap url>]
827 * Check RFC 2221 for details. Since we do not support login referrals yet
828 * we log the user out.
830 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
831 sqimap_logout($imap_stream);
832 set_up_language($squirrelmail_language, true);
833 include_once(SM_PATH
. 'functions/display_messages.php' );
835 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
843 * Simply logs out the IMAP session
844 * @param stream $imap_stream the IMAP connection to log out.
847 function sqimap_logout ($imap_stream) {
848 /* Logout is not valid until the server returns 'BYE'
849 * If we don't have an imap_ stream we're already logged out */
850 if(isset($imap_stream) && $imap_stream)
851 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
855 * Retrieve the CAPABILITY string from the IMAP server.
856 * If capability is set, returns only that specific capability,
857 * else returns array of all capabilities.
858 * @param stream $imap_stream
859 * @param string $capability (optional since 1.3.0)
860 * @return mixed (string if $capability is set and found,
861 * false, if $capability is set and not found,
862 * array if $capability not set)
864 function sqimap_capability($imap_stream, $capability='') {
865 global $sqimap_capabilities;
866 if (!is_array($sqimap_capabilities)) {
867 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
869 $c = explode(' ', $read[0]);
870 for ($i=2; $i < count($c); $i++
) {
871 $cap_list = explode('=', $c[$i]);
872 if (isset($cap_list[1])) {
873 // FIX ME. capabilities can occure multiple times.
874 // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
875 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
877 $sqimap_capabilities[$cap_list[0]] = TRUE;
882 if (isset($sqimap_capabilities[$capability])) {
883 return $sqimap_capabilities[$capability];
888 return $sqimap_capabilities;
892 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
893 * @param stream $imap_stream
896 function sqimap_get_delimiter ($imap_stream = false) {
897 global $sqimap_delimiter, $optional_delimiter;
899 /* Use configured delimiter if set */
900 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
901 return $optional_delimiter;
904 /* Do some caching here */
905 if (!$sqimap_delimiter) {
906 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
908 * According to something that I can't find, this is supposed to work on all systems
909 * OS: This won't work in Courier IMAP.
910 * OS: According to rfc2342 response from NAMESPACE command is:
911 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
912 * OS: We want to lookup all personal NAMESPACES...
914 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
915 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
916 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
919 $pna = explode(')(', $pn);
920 while (list($k, $v) = each($pna)) {
921 $lst = explode('"', $v);
922 if (isset($lst[3])) {
923 $pn[$lst[1]] = $lst[3];
929 $sqimap_delimiter = $pn[0];
931 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
932 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
933 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
934 $quote_position = strpos ($read[0], '"');
935 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
938 return $sqimap_delimiter;
942 * This encodes a mailbox name for use in IMAP commands.
943 * @param string $what the mailbox to encode
944 * @return string the encoded mailbox string
947 function sqimap_encode_mailbox_name($what)
949 if (ereg("[\"\\\r\n]", $what))
950 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
951 return '"' . $what . '"'; /* 4.3 quoted string form */
955 * Gets the number of messages in the current mailbox.
957 * OBSOLETE use sqimap_status_messages instead.
958 * @param stream $imap_stream imap stream
959 * @param string $mailbox
962 function sqimap_get_num_messages ($imap_stream, $mailbox) {
963 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
964 for ($i = 0; $i < count($read_ary); $i++
) {
965 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
969 return false; //"BUG! Couldn't get number of messages in $mailbox!";
972 /** FIXME: include is inserted in the middle of the code */
973 include_once(SM_PATH
. 'functions/rfc822address.php');
976 * OBSOLETE FUNCTION should be removed after mailbox_display,
977 * printMessage function is adapted
978 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
979 * @param string $address
980 * @param integer $max
982 * @deprecated See Rfc822Address.php
984 function parseAddress($address, $max=0) {
985 $aAddress = parseRFC822Address($address,array('limit'=> $max));
987 * Because the expected format of the array element is changed we adapt it now.
988 * This also implies that this function is obsolete and should be removed after the
989 * rest of the source is adapted. See Rfc822Address.php for the new function.
991 array_walk($aAddress, '_adaptAddress');
996 * OBSOLETE FUNCTION should be removed after mailbox_display,
997 * printMessage function is adapted
999 * callback function used for formating of addresses array in
1000 * parseAddress() function
1001 * @param array $aAddr
1002 * @param integer $k array key
1006 function _adaptAddress(&$aAddr,$k) {
1007 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
1008 $aAddr[SQM_ADDR_PERSONAL
] : '';
1009 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
1010 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
1011 $aAddr[SQM_ADDR_MAILBOX
];
1012 $aAddr = array($sEmail,$sPersonal);
1016 * Returns the number of unseen messages in this folder.
1017 * obsoleted by sqimap_status_messages !
1018 * Arguments differ in 1.0.x
1019 * @param stream $imap_stream
1020 * @param string $mailbox
1024 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1025 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1026 return $aStatus['UNSEEN'];
1030 * Returns the status items of a mailbox.
1031 * Default it returns MESSAGES,UNSEEN and RECENT
1032 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1033 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1034 * @param stream $imap_stream imap stream
1035 * @param string $mailbox mail folder
1036 * @param array $aStatusItems status items
1040 function sqimap_status_messages ($imap_stream, $mailbox,
1041 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1043 $aStatusItems = implode(' ',$aStatusItems);
1044 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1045 " ($aStatusItems)", false, $result, $message);
1047 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1048 $regs = array(false,false);
1049 while (isset($read_ary[$i])) {
1050 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1053 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1054 $messages = $regs[1];
1056 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1059 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1060 $uidnext = $regs[1];
1062 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1063 $uidvalidity = $regs[1];
1067 return array('MESSAGES' => $messages,
1069 'RECENT' => $recent,
1070 'UIDNEXT' => $uidnext,
1071 'UIDVALIDITY' => $uidvalidity);
1076 * Saves a message to a given folder -- used for saving sent messages
1077 * @param stream $imap_stream
1078 * @param string $sent_folder
1081 function sqimap_append ($imap_stream, $sent_folder, $length) {
1082 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1083 $tmp = fgets ($imap_stream, 1024);
1084 sqimap_append_checkresponse($tmp, $sent_folder);
1088 * @param stream imap_stream
1089 * @param string $folder (since 1.3.2)
1091 function sqimap_append_done ($imap_stream, $folder='') {
1092 fputs ($imap_stream, "\r\n");
1093 $tmp = fgets ($imap_stream, 1024);
1094 sqimap_append_checkresponse($tmp, $folder);
1098 * Displays error messages, if there are errors in responses to
1099 * commands issues by sqimap_append() and sqimap_append_done() functions.
1100 * @param string $response
1101 * @param string $folder
1104 function sqimap_append_checkresponse($response, $folder) {
1106 if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
1107 global $squirrelmail_language, $color;
1108 set_up_language($squirrelmail_language);
1109 require_once(SM_PATH
. 'functions/display_messages.php');
1112 if ($regs[2] == 'NO') {
1113 $string = "<b><font color=\"$color[2]\">\n" .
1114 _("ERROR : Could not append message to") ." $folder." .
1116 _("Server responded: ") .
1117 $reason . "<br />\n";
1118 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1119 $string .= _("Solution: ") .
1120 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1123 $string .= "</font>\n";
1124 error_box($string,$color);
1126 $string = "<b><font color=\"$color[2]\">\n" .
1127 _("ERROR : Bad or malformed request.") .
1129 _("Server responded: ") .
1130 $reason . "</font><br />\n";
1131 error_box($string,$color);
1138 * Allows mapping of imap server address with custom function
1139 * see map_yp_alias()
1140 * @param string $imap_server imap server address or mapping
1141 * @param string $username
1145 function sqimap_get_user_server ($imap_server, $username) {
1146 if (substr($imap_server, 0, 4) != "map:") {
1147 return $imap_server;
1149 $function = substr($imap_server, 4);
1150 return $function($username);
1154 * This is an example that gets imapservers from yellowpages (NIS).
1155 * you can simple put map:map_yp_alias in your $imap_server_address
1156 * in config.php use your own function instead map_yp_alias to map your
1157 * LDAP whatever way to find the users imapserver.
1159 * Requires access to external ypmatch program
1160 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1161 * @param string $username
1165 function map_yp_alias($username) {
1166 $yp = `ypmatch
$username aliases`
;
1167 return chop(substr($yp, strlen($username)+
1));