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');
19 include_once(SM_PATH
. 'functions/rfc822address.php');
23 * Generates a new session ID by incrementing the last one used;
24 * this ensures that each command has a unique ID.
25 * @param bool $unique_id (since 1.3.0) controls use of unique
26 * identifiers/message sequence numbers in IMAP commands. See IMAP
27 * rfc 'UID command' chapter.
28 * @return string IMAP session id of the form 'A000'.
31 function sqimap_session_id($unique_id = FALSE) {
32 static $sqimap_session_id = 1;
35 return( sprintf("A%03d", $sqimap_session_id++
) );
37 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
42 * Both send a command and accept the result from the command.
43 * This is to allow proper session number handling.
44 * @param stream $imap_stream imap connection resource
45 * @param string $query imap command
46 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
47 * @param array $response
48 * @param array $message
49 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
50 * @return mixed returns false on imap error. displays error message
51 * if imap stream is not available.
54 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
56 $sid = sqimap_session_id($unique_id);
57 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
58 $tag_uid_a = explode(' ',trim($sid));
60 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
61 /* get the response and the message */
62 $message = $message[$tag];
63 $response = $response[$tag];
66 global $squirrelmail_language, $color;
67 set_up_language($squirrelmail_language);
68 require_once(SM_PATH
. 'functions/display_messages.php');
69 $string = "<b><font color=\"$color[2]\">\n" .
70 _("ERROR: No available IMAP stream.") .
72 error_box($string,$color);
78 * @param stream $imap_stream imap connection resource
79 * @param string $query imap command
80 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
81 * @param array $response empty string, if return = false
82 * @param array $message empty string, if return = false
83 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
84 * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
85 * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
86 * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
87 * @return mixed returns false on imap error. displays error message
88 * if imap stream is not available.
91 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
92 &$message, $unique_id = false,$filter=false,
93 $outputstream=false,$no_return=false) {
95 $sid = sqimap_session_id($unique_id);
96 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
97 $tag_uid_a = explode(' ',trim($sid));
100 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
101 $message, $query,$filter,$outputstream,$no_return);
102 if (empty($read)) { //IMAP server dropped its connection
107 /* retrieve the response and the message */
108 $response = $response[$tag];
109 $message = $message[$tag];
111 if (!empty($read[$tag])) {
112 return $read[$tag][0];
117 global $squirrelmail_language, $color;
118 set_up_language($squirrelmail_language);
119 require_once(SM_PATH
. 'functions/display_messages.php');
120 $string = "<b><font color=\"$color[2]\">\n" .
121 _("ERROR: No available IMAP stream.") .
123 error_box($string,$color);
129 * @param mixed $new_query
131 * @param array $aQuery
132 * @param boolean $unique_id see sqimap_session_id()
135 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
136 $sid = sqimap_session_id($unique_id);
137 $tag_uid_a = explode(' ',trim($sid));
138 $tag = $tag_uid_a[0];
139 $query = $sid . ' '.$new_query."\r\n";
140 $aQuery[$tag] = $query;
144 * @param stream $imap_stream imap stream
145 * @param array $aQueryList
146 * @param boolean $handle_errors
147 * @param array $aServerResponse
148 * @param array $aServerMessage
149 * @param boolean $unique_id see sqimap_session_id()
150 * @param boolean $filter see sqimap_fread()
151 * @param mixed $outputstream see sqimap_fread()
152 * @param boolean $no_return see sqimap_fread()
155 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
156 &$aServerResponse, &$aServerMessage, $unique_id = false,
157 $filter=false,$outputstream=false,$no_return=false) {
161 Do not fire all calls at once to the IMAP server but split the calls up
162 in portions of $iChunkSize. If we do not do that I think we misbehave as
163 IMAP client or should handle BYE calls if the IMAP server drops the
164 connection because the number of queries is to large. This isn't tested
165 but a wild guess how it could work in the field.
167 After testing it on Exchange 2000 we discovered that a chunksize of 32
168 was quicker then when we raised it to 128.
170 $iQueryCount = count($aQueryList);
172 // array_chunk would also do the job but it's supported from php > 4.2
173 $aQueryChunks = array();
174 $iLoops = floor($iQueryCount / $iChunkSize);
176 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
178 if (!function_exists('array_chunk')) { // arraychunk replacement
180 for($i=0;$i<$iLoops;++
$i) {
181 for($j=0;$j<$iChunkSize;++
$j) {
182 $key = key($aQueryList);
183 $aTmp[$key] = $aQueryList[$key];
184 if (next($aQueryList) === false) break;
186 $aQueryChunks[] = $aTmp;
189 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
192 for ($i=0;$i<$iLoops;++
$i) {
193 $aQuery = $aQueryChunks[$i];
194 foreach($aQuery as $tag => $query) {
195 fputs($imap_stream,$query);
196 $aResults[$tag] = false;
198 foreach($aQuery as $tag => $query) {
199 if ($aResults[$tag] == false) {
200 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
201 $handle_errors, $response, $message, $query,
202 $filter,$outputstream,$no_return);
203 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
204 if (!empty($aResponse)) {
205 $aResults[$returned_tag] = $aResponse[0];
207 $aResults[$returned_tag] = $aResponse;
209 $aServerResponse[$returned_tag] = $response[$returned_tag];
210 $aServerMessage[$returned_tag] = $message[$returned_tag];
219 * Custom fgets function: gets a line from the IMAP server,
220 * no matter how big it may be.
221 * @param stream $imap_stream the stream to read from
222 * @return string a line
225 function sqimap_fgets($imap_stream) {
230 while (strpos($results, "\r\n", $offset) === false) {
231 if (!($read = fgets($imap_stream, $buffer))) {
232 /* this happens in case of an error */
233 /* reset $results because it's useless */
237 if ( $results != '' ) {
238 $offset = strlen($results) - 1;
246 * @param stream $imap_stream
247 * @param integer $iSize
248 * @param boolean $filter
249 * @param mixed $outputstream stream or 'php://stdout' string
250 * @param boolean $no_return controls data returned by function
254 function sqimap_fread($imap_stream,$iSize,$filter=false,
255 $outputstream=false, $no_return=false) {
256 if (!$filter ||
!$outputstream) {
257 $iBufferSize = $iSize;
259 // see php bug 24033. They changed fread behaviour %$^&$%
260 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
262 if ($iSize < $iBufferSize) {
263 $iBufferSize = $iSize;
268 $sRead = $sReadRem = '';
269 // NB: fread can also stop at end of a packet on sockets.
270 while ($iRetrieved < $iSize) {
271 $sRead = fread($imap_stream,$iBufferSize);
272 $iLength = strlen($sRead);
273 $iRetrieved +
= $iLength ;
274 $iRemaining = $iSize - $iRetrieved;
275 if ($iRemaining < $iBufferSize) {
276 $iBufferSize = $iRemaining;
282 if ($sReadRem != '') {
283 $sRead = $sReadRem . $sRead;
287 if ($filter && $sRead != '') {
288 // in case the filter is base64 decoding we return a remainder
289 $sReadRem = $filter($sRead);
291 if ($outputstream && $sRead != '') {
292 if (is_resource($outputstream)) {
293 fwrite($outputstream,$sRead);
294 } else if ($outputstream == 'php://stdout') {
309 * Obsolete function, inform plugins that use it
310 * @param stream $imap_stream
312 * @param boolean $handle_errors
313 * @param array $response
314 * @param array $message
315 * @param string $query
317 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
319 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
320 &$response, &$message, $query = '') {
321 global $color, $squirrelmail_language;
322 set_up_language($squirrelmail_language);
323 require_once(SM_PATH
. 'functions/display_messages.php');
324 $string = "<b><font color=\"$color[2]\">\n" .
325 _("ERROR: Bad function call.") .
328 'There is a plugin installed which make use of the <br />' .
329 'SquirrelMail internal function sqimap_read_data_list.<br />'.
330 'Please adapt the installed plugin and let it use<br />'.
331 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
332 'The following query was issued:<br />'.
333 htmlspecialchars($query) . '<br />' . "</font><br />\n";
334 error_box($string,$color);
335 echo '</body></html>';
340 * Function to display an error related to an IMAP query.
341 * @param string title the caption of the error box
342 * @param string query the query that went wrong
343 * @param string message_title optional message title
344 * @param string message optional error message
345 * @param string $link an optional link to try again
349 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
351 global $color, $squirrelmail_language;
353 set_up_language($squirrelmail_language);
354 require_once(SM_PATH
. 'functions/display_messages.php');
355 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
356 $cmd = explode(' ',$query);
357 $cmd= strtolower($cmd[0]);
359 if ($query != '' && $cmd != 'login')
360 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
361 if ($message_title != '')
362 $string .= $message_title;
364 $string .= htmlspecialchars($message);
365 $string .= "</font><br />\n";
368 error_box($string,$color);
372 * Reads the output from the IMAP stream. If handle_errors is set to true,
373 * this will also handle all errors that are received. If it is not set,
374 * the errors will be sent back through $response and $message.
375 * @param stream $imap_stream imap stream
377 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
378 * @param array $response
379 * @param array $message
380 * @param string $query command that can be printed if something fails
381 * @param boolean $filter see sqimap_fread()
382 * @param mixed $outputstream see sqimap_fread()
383 * @param boolean $no_return see sqimap_fread()
386 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
387 &$response, &$message, $query = '',
388 $filter = false, $outputstream = false, $no_return = false) {
389 global $color, $squirrelmail_language;
391 if (!is_array($message)) $message = array();
392 if (!is_array($response)) $response = array();
394 $resultlist = array();
396 $read = sqimap_fgets($imap_stream);
404 $read = sqimap_fgets($imap_stream);
409 /* get the command */
412 $s = substr($read,$i);
413 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
414 $arg = substr($s,0,$j);
416 $found_tag = substr($read,0,$i-1);
425 $response[$found_tag] = $arg;
426 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
428 $resultlist[] = $data;
430 $aResponse[$found_tag] = $resultlist;
431 $data = $resultlist = array();
432 if ($found_tag == $tag) {
433 break 3; /* switch switch while */
437 /* this shouldn't happen */
438 $response[$found_tag] = $arg;
439 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
441 $resultlist[] = $data;
443 $aResponse[$found_tag] = $resultlist;
444 $data = $resultlist = array();
445 if ($found_tag == $tag) {
446 break 3; /* switch switch while */
450 $read = sqimap_fgets($imap_stream);
451 if ($read === false) { /* error */
452 break 2; /* switch while */
455 } // end case $tag{0}
459 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
460 /* check for literal */
461 $s = substr($read,-3);
462 $fetch_data = array();
463 do { /* outer loop, continue until next untagged fetch
465 do { /* innerloop for fetching literals. with this loop
466 we prohibid that literal responses appear in the
467 outer loop so we can trust the untagged and
468 tagged info provided by $read */
469 if ($s === "}\r\n") {
470 $j = strrpos($read,'{');
471 $iLit = substr($read,$j+
1,-3);
472 $fetch_data[] = $read;
473 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
474 if ($sLiteral === false) { /* error */
475 break 4; /* while while switch while */
477 /* backwards compattibility */
478 $aLiteral = explode("\n", $sLiteral);
479 /* release not neaded data */
481 foreach ($aLiteral as $line) {
482 $fetch_data[] = $line ."\n";
484 /* release not neaded data */
486 /* next fgets belongs to this fetch because
487 we just got the exact literalsize and there
488 must follow data to complete the response */
489 $read = sqimap_fgets($imap_stream);
490 if ($read === false) { /* error */
491 break 4; /* while while switch while */
493 $fetch_data[] = $read;
495 $fetch_data[] = $read;
497 /* retrieve next line and check in the while
498 statements if it belongs to this fetch response */
499 $read = sqimap_fgets($imap_stream);
500 if ($read === false) { /* error */
501 break 4; /* while while switch while */
503 /* check for next untagged reponse and break */
504 if ($read{0} == '*') break 2;
505 $s = substr($read,-3);
506 } while ($s === "}\r\n");
507 $s = substr($read,-3);
508 } while ($read{0} !== '*' &&
509 substr($read,0,strlen($tag)) !== $tag);
510 $resultlist[] = $fetch_data;
511 /* release not neaded data */
514 $s = substr($read,-3);
516 if ($s === "}\r\n") {
517 $j = strrpos($read,'{');
518 $iLit = substr($read,$j+
1,-3);
520 $sLiteral = fread($imap_stream,$iLit);
521 if ($sLiteral === false) { /* error */
523 break 3; /* while switch while */
526 $data[] = sqimap_fgets($imap_stream);
530 $read = sqimap_fgets($imap_stream);
531 if ($read === false) {
532 break 3; /* while switch while */
533 } else if ($read{0} == '*') {
536 $s = substr($read,-3);
537 } while ($s === "}\r\n");
545 /* error processing in case $read is false */
546 if ($read === false) {
547 // try to retrieve an untagged bye respons from the results
548 $sResponse = array_pop($data);
549 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
550 if (!$handle_errors) {
553 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
554 echo '</body></html>';
556 } else if ($handle_errors) {
558 sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
563 /* Set $resultlist array */
565 //$resultlist[] = $data;
567 elseif (empty($resultlist)) {
568 $resultlist[] = array();
571 /* Return result or handle errors */
572 if ($handle_errors == false) {
575 switch ($response[$tag]) {
580 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
581 if (strstr($message[$tag], 'command resulted in') === false) {
582 sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
583 echo '</body></html>';
588 sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
589 echo '</body></html>';
592 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
593 echo '</body></html>';
596 sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
597 /* the error is displayed but because we don't know the reponse we
598 return the result anyway */
605 * @param stream $imap_stream imap string
606 * @param string $tag_uid
607 * @param boolean $handle_errors
608 * @param array $response
609 * @param array $message
610 * @param string $query (since 1.2.5)
611 * @param boolean $filter (since 1.4.1) see sqimap_fread()
612 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
613 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
615 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
616 &$response, &$message, $query = '',
617 $filter=false,$outputstream=false,$no_return=false) {
619 $tag_uid_a = explode(' ',trim($tag_uid));
620 $tag = $tag_uid_a[0];
622 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
623 $response, $message, $query,$filter,$outputstream,$no_return);
628 * Connects to the IMAP server and returns a resource identifier for use with
629 * the other SquirrelMail IMAP functions. Does NOT login!
630 * @param string server hostname of IMAP server
631 * @param int port port number to connect to
632 * @param bool tls whether to use TLS when connecting.
633 * @return imap-stream resource identifier
634 * @since 1.5.0 (usable only in 1.5.1 or later)
636 function sqimap_create_stream($server,$port,$tls=false) {
637 global $squirrelmail_language;
640 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
641 /* Use TLS by prefixing "tls://" to the hostname */
642 $server = 'tls://' . $server;
644 require_once(SM_PATH
. 'functions/display_messages.php');
645 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
647 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
649 _("Please contact your system administrator and report this error."),
650 sprintf(_("Error connecting to IMAP server: %s."), $server));
654 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
656 /* Do some error correction */
658 set_up_language($squirrelmail_language, true);
659 require_once(SM_PATH
. 'functions/display_messages.php');
660 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
661 "<br />\r\n$error_number : $error_string<br />\r\n",
662 sprintf(_("Error connecting to IMAP server: %s."), $server) );
665 $server_info = fgets ($imap_stream, 1024);
670 * Logs the user into the IMAP server. If $hide is set, no error messages
671 * will be displayed. This function returns the IMAP connection handle.
672 * @param string $username user name
673 * @param string $password encrypted password
674 * @param string $imap_server_address address of imap server
675 * @param integer $imap_port port of imap server
676 * @param boolean $hide controls display connection errors
679 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
680 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
681 $imap_auth_mech, $sqimap_capabilities;
683 if (!isset($onetimepad) ||
empty($onetimepad)) {
684 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
686 if (!isset($sqimap_capabilities)) {
687 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
690 $host = $imap_server_address;
691 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
693 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
695 /* Decrypt the password */
696 $password = OneTimePadDecrypt($password, $onetimepad);
698 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
699 // We're using some sort of authentication OTHER than plain or login
700 $tag=sqimap_session_id(false);
701 if ($imap_auth_mech == 'digest-md5') {
702 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
703 } elseif ($imap_auth_mech == 'cram-md5') {
704 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
706 fputs($imap_stream,$query);
707 $answer=sqimap_fgets($imap_stream);
708 // Trim the "+ " off the front
709 $response=explode(" ",$answer,3);
710 if ($response[0] == '+') {
711 // Got a challenge back
712 $challenge=$response[1];
713 if ($imap_auth_mech == 'digest-md5') {
714 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
715 } elseif ($imap_auth_mech == 'cram-md5') {
716 $reply = cram_md5_response($username,$password,$challenge);
718 fputs($imap_stream,$reply);
719 $read=sqimap_fgets($imap_stream);
720 if ($imap_auth_mech == 'digest-md5') {
721 // DIGEST-MD5 has an extra step..
722 if (substr($read,0,1) == '+') { // OK so far..
723 fputs($imap_stream,"\r\n");
724 $read=sqimap_fgets($imap_stream);
727 $results=explode(" ",$read,3);
728 $response=$results[1];
729 $message=$results[2];
731 // Fake the response, so the error trap at the bottom will work
733 $message='IMAP server does not appear to support the authentication method selected.';
734 $message .= ' Please contact your system administrator.';
736 } elseif ($imap_auth_mech == 'login') {
737 // Original IMAP login code
738 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
739 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
740 } elseif ($imap_auth_mech == 'plain') {
746 * The mechanism consists of a single message from the client to the
747 * server. The client sends the authorization identity (identity to
748 * login as), followed by a US-ASCII NUL character, followed by the
749 * authentication identity (identity whose password will be used),
750 * followed by a US-ASCII NUL character, followed by the clear-text
751 * password. The client may leave the authorization identity empty to
752 * indicate that it is the same as the authentication identity.
755 $tag=sqimap_session_id(false);
756 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ?
true : false;
757 $auth = base64_encode("$username\0$username\0$password");
759 // IMAP Extension for SASL Initial Client Response
760 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
761 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
762 fputs($imap_stream, $query);
763 $read = sqimap_fgets($imap_stream);
765 $query = $tag . " AUTHENTICATE PLAIN\r\n";
766 fputs($imap_stream, $query);
767 $read=sqimap_fgets($imap_stream);
768 if (substr($read,0,1) == '+') { // OK so far..
769 fputs($imap_stream, "$auth\r\n");
770 $read = sqimap_fgets($imap_stream);
773 $results=explode(" ",$read,3);
774 $response=$results[1];
775 $message=$results[2];
778 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
781 /* If the connection was not successful, lets see why */
782 if ($response != 'OK') {
784 if ($response != 'NO') {
785 /* "BAD" and anything else gets reported here. */
786 $message = htmlspecialchars($message);
787 set_up_language($squirrelmail_language, true);
788 require_once(SM_PATH
. 'functions/display_messages.php');
789 if ($response == 'BAD') {
790 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
792 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
794 if (isset($read) && is_array($read)) {
795 $string .= '<br />' . _("Read data:") . "<br />\n";
796 foreach ($read as $line) {
797 $string .= htmlspecialchars($line) . "<br />\n";
800 error_box($string,$color);
804 * If the user does not log in with the correct
805 * username and password it is not possible to get the
806 * correct locale from the user's preferences.
807 * Therefore, apply the same hack as on the login
810 * $squirrelmail_language is set by a cookie when
811 * the user selects language and logs out
814 set_up_language($squirrelmail_language, true);
815 include_once(SM_PATH
. 'functions/display_messages.php' );
817 /* terminate the session nicely */
818 sqimap_logout($imap_stream);
819 logout_error( _("Unknown user or password incorrect.") );
827 /* Special error case:
828 * Login referrals. The server returns:
829 * ? OK [REFERRAL <imap url>]
830 * Check RFC 2221 for details. Since we do not support login referrals yet
831 * we log the user out.
833 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
834 sqimap_logout($imap_stream);
835 set_up_language($squirrelmail_language, true);
836 include_once(SM_PATH
. 'functions/display_messages.php' );
838 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
846 * Simply logs out the IMAP session
847 * @param stream $imap_stream the IMAP connection to log out.
850 function sqimap_logout ($imap_stream) {
851 /* Logout is not valid until the server returns 'BYE'
852 * If we don't have an imap_ stream we're already logged out */
853 if(isset($imap_stream) && $imap_stream)
854 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
858 * Retrieve the CAPABILITY string from the IMAP server.
859 * If capability is set, returns only that specific capability,
860 * else returns array of all capabilities.
861 * @param stream $imap_stream
862 * @param string $capability (optional since 1.3.0)
863 * @return mixed (string if $capability is set and found,
864 * false, if $capability is set and not found,
865 * array if $capability not set)
867 function sqimap_capability($imap_stream, $capability='') {
868 sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION
);
870 if (!is_array($sqimap_capabilities)) {
871 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
873 $c = explode(' ', $read[0]);
874 for ($i=2; $i < count($c); $i++
) {
875 $cap_list = explode('=', $c[$i]);
876 if (isset($cap_list[1])) {
877 // FIX ME. capabilities can occure multiple times.
878 // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
879 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
881 $sqimap_capabilities[$cap_list[0]] = TRUE;
886 if (isset($sqimap_capabilities[$capability])) {
887 return $sqimap_capabilities[$capability];
892 return $sqimap_capabilities;
896 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
897 * @param stream $imap_stream
900 function sqimap_get_delimiter ($imap_stream = false) {
901 global $sqimap_delimiter, $optional_delimiter;
903 /* Use configured delimiter if set */
904 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
905 return $optional_delimiter;
908 /* Do some caching here */
909 if (!$sqimap_delimiter) {
910 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
912 * According to something that I can't find, this is supposed to work on all systems
913 * OS: This won't work in Courier IMAP.
914 * OS: According to rfc2342 response from NAMESPACE command is:
915 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
916 * OS: We want to lookup all personal NAMESPACES...
918 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
919 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
920 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
923 $pna = explode(')(', $pn);
924 while (list($k, $v) = each($pna)) {
925 $lst = explode('"', $v);
926 if (isset($lst[3])) {
927 $pn[$lst[1]] = $lst[3];
933 $sqimap_delimiter = $pn[0];
935 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
936 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
937 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
938 $quote_position = strpos ($read[0], '"');
939 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
942 return $sqimap_delimiter;
946 * This encodes a mailbox name for use in IMAP commands.
947 * @param string $what the mailbox to encode
948 * @return string the encoded mailbox string
951 function sqimap_encode_mailbox_name($what)
953 if (ereg("[\"\\\r\n]", $what))
954 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
955 return '"' . $what . '"'; /* 4.3 quoted string form */
959 * Gets the number of messages in the current mailbox.
961 * OBSOLETE use sqimap_status_messages instead.
962 * @param stream $imap_stream imap stream
963 * @param string $mailbox
966 function sqimap_get_num_messages ($imap_stream, $mailbox) {
967 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
968 for ($i = 0; $i < count($read_ary); $i++
) {
969 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
973 return false; //"BUG! Couldn't get number of messages in $mailbox!";
977 * OBSOLETE FUNCTION should be removed after mailbox_display,
978 * printMessage function is adapted
979 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
980 * @param string $address
981 * @param integer $max
983 * @deprecated See Rfc822Address.php
985 function parseAddress($address, $max=0) {
986 $aAddress = parseRFC822Address($address,array('limit'=> $max));
988 * Because the expected format of the array element is changed we adapt it now.
989 * This also implies that this function is obsolete and should be removed after the
990 * rest of the source is adapted. See Rfc822Address.php for the new function.
992 array_walk($aAddress, '_adaptAddress');
997 * OBSOLETE FUNCTION should be removed after mailbox_display,
998 * printMessage function is adapted
1000 * callback function used for formating of addresses array in
1001 * parseAddress() function
1002 * @param array $aAddr
1003 * @param integer $k array key
1007 function _adaptAddress(&$aAddr,$k) {
1008 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
1009 $aAddr[SQM_ADDR_PERSONAL
] : '';
1010 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
1011 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
1012 $aAddr[SQM_ADDR_MAILBOX
];
1013 $aAddr = array($sEmail,$sPersonal);
1017 * Returns the number of unseen messages in this folder.
1018 * obsoleted by sqimap_status_messages !
1019 * Arguments differ in 1.0.x
1020 * @param stream $imap_stream
1021 * @param string $mailbox
1025 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1026 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1027 return $aStatus['UNSEEN'];
1031 * Returns the status items of a mailbox.
1032 * Default it returns MESSAGES,UNSEEN and RECENT
1033 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1034 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1035 * @param stream $imap_stream imap stream
1036 * @param string $mailbox mail folder
1037 * @param array $aStatusItems status items
1041 function sqimap_status_messages ($imap_stream, $mailbox,
1042 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1044 $aStatusItems = implode(' ',$aStatusItems);
1045 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1046 " ($aStatusItems)", false, $result, $message);
1048 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1049 $regs = array(false,false);
1050 while (isset($read_ary[$i])) {
1051 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1054 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1055 $messages = $regs[1];
1057 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1060 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1061 $uidnext = $regs[1];
1063 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1064 $uidvalidity = $regs[1];
1068 return array('MESSAGES' => $messages,
1070 'RECENT' => $recent,
1071 'UIDNEXT' => $uidnext,
1072 'UIDVALIDITY' => $uidvalidity);
1077 * Saves a message to a given folder -- used for saving sent messages
1078 * @param stream $imap_stream
1079 * @param string $sent_folder
1082 function sqimap_append ($imap_stream, $sent_folder, $length) {
1083 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1084 $tmp = fgets ($imap_stream, 1024);
1085 sqimap_append_checkresponse($tmp, $sent_folder);
1089 * @param stream imap_stream
1090 * @param string $folder (since 1.3.2)
1092 function sqimap_append_done ($imap_stream, $folder='') {
1093 fputs ($imap_stream, "\r\n");
1094 $tmp = fgets ($imap_stream, 1024);
1095 sqimap_append_checkresponse($tmp, $folder);
1099 * Displays error messages, if there are errors in responses to
1100 * commands issues by sqimap_append() and sqimap_append_done() functions.
1101 * @param string $response
1102 * @param string $folder
1105 function sqimap_append_checkresponse($response, $folder) {
1107 if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
1108 global $squirrelmail_language, $color;
1109 set_up_language($squirrelmail_language);
1110 require_once(SM_PATH
. 'functions/display_messages.php');
1113 if ($regs[2] == 'NO') {
1114 $string = "<b><font color=\"$color[2]\">\n" .
1115 _("ERROR: Could not append message to") ." $folder." .
1117 _("Server responded:") . ' ' .
1118 $reason . "<br />\n";
1119 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1120 $string .= _("Solution:") . ' ' .
1121 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1124 $string .= "</font>\n";
1125 error_box($string,$color);
1127 $string = "<b><font color=\"$color[2]\">\n" .
1128 _("ERROR: Bad or malformed request.") .
1130 _("Server responded:") . ' ' .
1131 $reason . "</font><br />\n";
1132 error_box($string,$color);
1139 * Allows mapping of IMAP server address with custom function
1140 * see map_yp_alias()
1141 * @param string $imap_server imap server address or mapping
1142 * @param string $username
1146 function sqimap_get_user_server ($imap_server, $username) {
1147 if (substr($imap_server, 0, 4) != "map:") {
1148 return $imap_server;
1150 $function = substr($imap_server, 4);
1151 return $function($username);
1155 * This is an example that gets IMAP servers from yellowpages (NIS).
1156 * you can simple put map:map_yp_alias in your $imap_server_address
1157 * in config.php use your own function instead map_yp_alias to map your
1158 * LDAP whatever way to find the users IMAP server.
1160 * Requires access to external ypmatch program
1161 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1162 * @param string $username
1166 function map_yp_alias($username) {
1167 $yp = `ypmatch
$username aliases`
;
1168 return chop(substr($yp, strlen($username)+
1));