6 * This implements all functions that do general IMAP functions.
8 * @copyright © 1999-2006 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @package squirrelmail
17 require_once(SM_PATH
. 'functions/rfc822address.php');
21 * Generates a new session ID by incrementing the last one used;
22 * this ensures that each command has a unique ID.
23 * @param bool $unique_id (since 1.3.0) controls use of unique
24 * identifiers/message sequence numbers in IMAP commands. See IMAP
25 * rfc 'UID command' chapter.
26 * @return string IMAP session id of the form 'A000'.
29 function sqimap_session_id($unique_id = FALSE) {
30 static $sqimap_session_id = 1;
33 return( sprintf("A%03d", $sqimap_session_id++
) );
35 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
40 * Both send a command and accept the result from the command.
41 * This is to allow proper session number handling.
42 * @param stream $imap_stream imap connection resource
43 * @param string $query imap command
44 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
45 * @param array $response
46 * @param array $message
47 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
48 * @return mixed returns false on imap error. displays error message
49 * if imap stream is not available.
52 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
54 $sid = sqimap_session_id($unique_id);
55 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
56 $tag_uid_a = explode(' ',trim($sid));
58 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
59 /* get the response and the message */
60 $message = $message[$tag];
61 $response = $response[$tag];
64 global $squirrelmail_language, $color;
65 set_up_language($squirrelmail_language);
66 $string = "<b><font color=\"$color[2]\">\n" .
67 _("ERROR: No available IMAP stream.") .
69 error_box($string,$color);
75 * @param stream $imap_stream imap connection resource
76 * @param string $query imap command
77 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
78 * @param array $response empty string, if return = false
79 * @param array $message empty string, if return = false
80 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
81 * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
82 * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
83 * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
84 * @return mixed returns false on imap error. displays error message
85 * if imap stream is not available.
88 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
89 &$message, $unique_id = false,$filter=false,
90 $outputstream=false,$no_return=false) {
92 $sid = sqimap_session_id($unique_id);
93 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
94 $tag_uid_a = explode(' ',trim($sid));
97 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
98 $message, $query,$filter,$outputstream,$no_return);
99 if (empty($read)) { //IMAP server dropped its connection
104 /* retrieve the response and the message */
105 $response = $response[$tag];
106 $message = $message[$tag];
108 if (!empty($read[$tag])) {
109 return $read[$tag][0];
114 global $squirrelmail_language, $color;
115 set_up_language($squirrelmail_language);
116 $string = "<b><font color=\"$color[2]\">\n" .
117 _("ERROR: No available IMAP stream.") .
119 error_box($string,$color);
125 * @param mixed $new_query
127 * @param array $aQuery
128 * @param boolean $unique_id see sqimap_session_id()
131 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
132 $sid = sqimap_session_id($unique_id);
133 $tag_uid_a = explode(' ',trim($sid));
134 $tag = $tag_uid_a[0];
135 $query = $sid . ' '.$new_query."\r\n";
136 $aQuery[$tag] = $query;
140 * @param stream $imap_stream imap stream
141 * @param array $aQueryList
142 * @param boolean $handle_errors
143 * @param array $aServerResponse
144 * @param array $aServerMessage
145 * @param boolean $unique_id see sqimap_session_id()
146 * @param boolean $filter see sqimap_fread()
147 * @param mixed $outputstream see sqimap_fread()
148 * @param boolean $no_return see sqimap_fread()
151 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
152 &$aServerResponse, &$aServerMessage, $unique_id = false,
153 $filter=false,$outputstream=false,$no_return=false) {
157 Do not fire all calls at once to the IMAP server but split the calls up
158 in portions of $iChunkSize. If we do not do that I think we misbehave as
159 IMAP client or should handle BYE calls if the IMAP server drops the
160 connection because the number of queries is to large. This isn't tested
161 but a wild guess how it could work in the field.
163 After testing it on Exchange 2000 we discovered that a chunksize of 32
164 was quicker then when we raised it to 128.
166 $iQueryCount = count($aQueryList);
168 // array_chunk would also do the job but it's supported from php > 4.2
169 $aQueryChunks = array();
170 $iLoops = floor($iQueryCount / $iChunkSize);
172 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
174 if (!function_exists('array_chunk')) { // arraychunk replacement
176 for($i=0;$i<$iLoops;++
$i) {
177 for($j=0;$j<$iChunkSize;++
$j) {
178 $key = key($aQueryList);
179 $aTmp[$key] = $aQueryList[$key];
180 if (next($aQueryList) === false) break;
182 $aQueryChunks[] = $aTmp;
185 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
188 for ($i=0;$i<$iLoops;++
$i) {
189 $aQuery = $aQueryChunks[$i];
190 foreach($aQuery as $tag => $query) {
191 fputs($imap_stream,$query);
192 $aResults[$tag] = false;
194 foreach($aQuery as $tag => $query) {
195 if ($aResults[$tag] == false) {
196 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
197 $handle_errors, $response, $message, $query,
198 $filter,$outputstream,$no_return);
199 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
200 if (!empty($aResponse)) {
201 $aResults[$returned_tag] = $aResponse[0];
203 $aResults[$returned_tag] = $aResponse;
205 $aServerResponse[$returned_tag] = $response[$returned_tag];
206 $aServerMessage[$returned_tag] = $message[$returned_tag];
215 * Custom fgets function: gets a line from the IMAP server,
216 * no matter how big it may be.
217 * @param stream $imap_stream the stream to read from
218 * @return string a line
221 function sqimap_fgets($imap_stream) {
226 while (strpos($results, "\r\n", $offset) === false) {
227 if (!($read = fgets($imap_stream, $buffer))) {
228 /* this happens in case of an error */
229 /* reset $results because it's useless */
233 if ( $results != '' ) {
234 $offset = strlen($results) - 1;
242 * @param stream $imap_stream
243 * @param integer $iSize
244 * @param boolean $filter
245 * @param mixed $outputstream stream or 'php://stdout' string
246 * @param boolean $no_return controls data returned by function
250 function sqimap_fread($imap_stream,$iSize,$filter=false,
251 $outputstream=false, $no_return=false) {
252 if (!$filter ||
!$outputstream) {
253 $iBufferSize = $iSize;
255 // see php bug 24033. They changed fread behaviour %$^&$%
256 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
258 if ($iSize < $iBufferSize) {
259 $iBufferSize = $iSize;
264 $sRead = $sReadRem = '';
265 // NB: fread can also stop at end of a packet on sockets.
266 while ($iRetrieved < $iSize) {
267 $sRead = fread($imap_stream,$iBufferSize);
268 $iLength = strlen($sRead);
269 $iRetrieved +
= $iLength ;
270 $iRemaining = $iSize - $iRetrieved;
271 if ($iRemaining < $iBufferSize) {
272 $iBufferSize = $iRemaining;
278 if ($sReadRem != '') {
279 $sRead = $sReadRem . $sRead;
283 if ($filter && $sRead != '') {
284 // in case the filter is base64 decoding we return a remainder
285 $sReadRem = $filter($sRead);
287 if ($outputstream && $sRead != '') {
288 if (is_resource($outputstream)) {
289 fwrite($outputstream,$sRead);
290 } else if ($outputstream == 'php://stdout') {
305 * Obsolete function, inform plugins that use it
306 * @param stream $imap_stream
308 * @param boolean $handle_errors
309 * @param array $response
310 * @param array $message
311 * @param string $query
313 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
315 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
316 &$response, &$message, $query = '') {
317 global $color, $squirrelmail_language;
318 set_up_language($squirrelmail_language);
319 $string = "<b><font color=\"$color[2]\">\n" .
320 _("ERROR: Bad function call.") .
323 'There is a plugin installed which make use of the <br />' .
324 'SquirrelMail internal function sqimap_read_data_list.<br />'.
325 'Please adapt the installed plugin and let it use<br />'.
326 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
327 'The following query was issued:<br />'.
328 htmlspecialchars($query) . '<br />' . "</font><br />\n";
329 error_box($string,$color);
330 echo '</body></html>';
335 * Function to display an error related to an IMAP query.
336 * @param string title the caption of the error box
337 * @param string query the query that went wrong
338 * @param string message_title optional message title
339 * @param string message optional error message
340 * @param string $link an optional link to try again
344 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
346 global $color, $squirrelmail_language;
348 set_up_language($squirrelmail_language);
349 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
350 $cmd = explode(' ',$query);
351 $cmd= strtolower($cmd[0]);
353 if ($query != '' && $cmd != 'login')
354 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
355 if ($message_title != '')
356 $string .= $message_title;
358 $string .= htmlspecialchars($message);
359 $string .= "</font><br />\n";
362 error_box($string,$color);
366 * Reads the output from the IMAP stream. If handle_errors is set to true,
367 * this will also handle all errors that are received. If it is not set,
368 * the errors will be sent back through $response and $message.
369 * @param stream $imap_stream imap stream
371 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
372 * @param array $response
373 * @param array $message
374 * @param string $query command that can be printed if something fails
375 * @param boolean $filter see sqimap_fread()
376 * @param mixed $outputstream see sqimap_fread()
377 * @param boolean $no_return see sqimap_fread()
380 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
381 &$response, &$message, $query = '',
382 $filter = false, $outputstream = false, $no_return = false) {
383 global $color, $squirrelmail_language;
385 if (!is_array($message)) $message = array();
386 if (!is_array($response)) $response = array();
388 $resultlist = array();
391 if (preg_match("/^(\w+)\s*/",$query,$aMatch)) {
392 $sCommand = strtoupper($aMatch[1]);
394 // error reporting (shouldn't happen)
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 (($sCommand == "FETCH" ||
$sCommand == "STORE") && 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 integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
633 * Argument was boolean before 1.5.1.
634 * @return imap-stream resource identifier
635 * @since 1.5.0 (usable only in 1.5.1 or later)
637 function sqimap_create_stream($server,$port,$tls=0) {
638 global $squirrelmail_language;
640 if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
641 // numerical IPv6 address must be enclosed in square brackets
642 $server = '['.$server.']';
646 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
647 /* Use TLS by prefixing "tls://" to the hostname */
648 $server = 'tls://' . $server;
650 require_once(SM_PATH
. 'functions/display_messages.php');
651 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
653 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
655 _("Please contact your system administrator and report this error."),
656 sprintf(_("Error connecting to IMAP server: %s."), $server));
660 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
662 /* Do some error correction */
664 set_up_language($squirrelmail_language, true);
665 require_once(SM_PATH
. 'functions/display_messages.php');
666 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
667 "<br />\r\n$error_number : $error_string<br />\r\n",
668 sprintf(_("Error connecting to IMAP server: %s."), $server) );
671 $server_info = fgets ($imap_stream, 1024);
674 * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
675 * http://www.php.net/stream-socket-enable-crypto
678 if (function_exists('stream_socket_enable_crypto')) {
679 // check starttls capability, don't use cached capability version
680 if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
681 // imap server does not declare starttls support
682 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
684 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
688 // issue starttls command and check response
689 sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
691 if ($starttls_response!='OK') {
692 // starttls command failed
693 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
695 _("Server replied:") . ' ',
700 // start crypto on connection. suppress function errors.
701 if (@stream_socket_enable_crypto
($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
702 // starttls was successful
705 * RFC 2595 requires to discard CAPABILITY information after successful
706 * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
707 * information only after successful login (src/redirect.php) and cached information
708 * is used only in other php script connections after successful STARTTLS. If script
709 * issues sqimap_capability() call before sqimap_login() and wants to get initial
710 * capability response, script should set third sqimap_capability() argument to false.
712 //sqsession_unregister('sqimap_capabilities');
715 * stream_socket_enable_crypto() call failed. Possible issues:
716 * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
717 * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
718 * suppressed in stream_socket_enable_crypto() call)
720 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
722 _("Unable to start TLS."));
724 * Bug: stream_socket_enable_crypto() does not register SSL errors in
725 * openssl_error_string() or stream notification wrapper and displays
726 * them in E_WARNING level message. It is impossible to retrieve error
727 * message without own error handler.
732 // php install does not support stream_socket_enable_crypto() function
733 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
735 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
743 * Logs the user into the IMAP server. If $hide is set, no error messages
744 * will be displayed. This function returns the IMAP connection handle.
745 * @param string $username user name
746 * @param string $password encrypted password
747 * @param string $imap_server_address address of imap server
748 * @param integer $imap_port port of imap server
749 * @param boolean $hide controls display connection errors
752 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
753 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
754 $imap_auth_mech, $sqimap_capabilities;
756 if (!isset($onetimepad) ||
empty($onetimepad)) {
757 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
759 if (!isset($sqimap_capabilities)) {
760 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION
);
763 $host = $imap_server_address;
764 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
766 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
768 /* Decrypt the password */
769 $password = OneTimePadDecrypt($password, $onetimepad);
771 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
772 // We're using some sort of authentication OTHER than plain or login
773 $tag=sqimap_session_id(false);
774 if ($imap_auth_mech == 'digest-md5') {
775 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
776 } elseif ($imap_auth_mech == 'cram-md5') {
777 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
779 fputs($imap_stream,$query);
780 $answer=sqimap_fgets($imap_stream);
781 // Trim the "+ " off the front
782 $response=explode(" ",$answer,3);
783 if ($response[0] == '+') {
784 // Got a challenge back
785 $challenge=$response[1];
786 if ($imap_auth_mech == 'digest-md5') {
787 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
788 } elseif ($imap_auth_mech == 'cram-md5') {
789 $reply = cram_md5_response($username,$password,$challenge);
791 fputs($imap_stream,$reply);
792 $read=sqimap_fgets($imap_stream);
793 if ($imap_auth_mech == 'digest-md5') {
794 // DIGEST-MD5 has an extra step..
795 if (substr($read,0,1) == '+') { // OK so far..
796 fputs($imap_stream,"\r\n");
797 $read=sqimap_fgets($imap_stream);
800 $results=explode(" ",$read,3);
801 $response=$results[1];
802 $message=$results[2];
804 // Fake the response, so the error trap at the bottom will work
806 $message='IMAP server does not appear to support the authentication method selected.';
807 $message .= ' Please contact your system administrator.';
809 } elseif ($imap_auth_mech == 'login') {
810 // Original IMAP login code
811 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
812 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
813 } elseif ($imap_auth_mech == 'plain') {
819 * The mechanism consists of a single message from the client to the
820 * server. The client sends the authorization identity (identity to
821 * login as), followed by a US-ASCII NUL character, followed by the
822 * authentication identity (identity whose password will be used),
823 * followed by a US-ASCII NUL character, followed by the clear-text
824 * password. The client may leave the authorization identity empty to
825 * indicate that it is the same as the authentication identity.
828 $tag=sqimap_session_id(false);
829 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ?
true : false;
830 $auth = base64_encode("$username\0$username\0$password");
832 // IMAP Extension for SASL Initial Client Response
833 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
834 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
835 fputs($imap_stream, $query);
836 $read = sqimap_fgets($imap_stream);
838 $query = $tag . " AUTHENTICATE PLAIN\r\n";
839 fputs($imap_stream, $query);
840 $read=sqimap_fgets($imap_stream);
841 if (substr($read,0,1) == '+') { // OK so far..
842 fputs($imap_stream, "$auth\r\n");
843 $read = sqimap_fgets($imap_stream);
846 $results=explode(" ",$read,3);
847 $response=$results[1];
848 $message=$results[2];
851 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
854 /* If the connection was not successful, lets see why */
855 if ($response != 'OK') {
857 if ($response != 'NO') {
858 /* "BAD" and anything else gets reported here. */
859 $message = htmlspecialchars($message);
860 set_up_language($squirrelmail_language, true);
861 if ($response == 'BAD') {
862 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
864 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
866 if (isset($read) && is_array($read)) {
867 $string .= '<br />' . _("Read data:") . "<br />\n";
868 foreach ($read as $line) {
869 $string .= htmlspecialchars($line) . "<br />\n";
872 error_box($string,$color);
876 * If the user does not log in with the correct
877 * username and password it is not possible to get the
878 * correct locale from the user's preferences.
879 * Therefore, apply the same hack as on the login
882 * $squirrelmail_language is set by a cookie when
883 * the user selects language and logs out
886 set_up_language($squirrelmail_language, true);
889 /* terminate the session nicely */
890 sqimap_logout($imap_stream);
891 logout_error( _("Unknown user or password incorrect.") );
899 /* Special error case:
900 * Login referrals. The server returns:
901 * ? OK [REFERRAL <imap url>]
902 * Check RFC 2221 for details. Since we do not support login referrals yet
903 * we log the user out.
905 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
906 sqimap_logout($imap_stream);
907 set_up_language($squirrelmail_language, true);
909 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
917 * Simply logs out the IMAP session
918 * @param stream $imap_stream the IMAP connection to log out.
921 function sqimap_logout ($imap_stream) {
922 /* Logout is not valid until the server returns 'BYE'
923 * If we don't have an imap_ stream we're already logged out */
924 if(isset($imap_stream) && $imap_stream)
925 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
929 * Retrieve the CAPABILITY string from the IMAP server.
930 * If capability is set, returns only that specific capability,
931 * else returns array of all capabilities.
932 * @param stream $imap_stream
933 * @param string $capability (since 1.3.0)
934 * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
935 * @return mixed (string if $capability is set and found,
936 * false, if $capability is set and not found,
937 * array if $capability not set)
939 function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
940 // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
942 if (!$bUseCache ||
! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION
)) {
943 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
944 $c = explode(' ', $read[0]);
945 for ($i=2; $i < count($c); $i++
) {
946 $cap_list = explode('=', $c[$i]);
947 if (isset($cap_list[1])) {
948 $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
950 $sqimap_capabilities[trim($cap_list[0])] = TRUE;
955 if (isset($sqimap_capabilities[$capability])) {
956 return $sqimap_capabilities[$capability];
961 return $sqimap_capabilities;
965 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
966 * @param stream $imap_stream
969 function sqimap_get_delimiter ($imap_stream = false) {
970 global $sqimap_delimiter, $optional_delimiter;
972 /* Use configured delimiter if set */
973 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
974 return $optional_delimiter;
977 /* Delimiter is stored in the session from redirect. Try fetching from there first */
978 if (empty($sqimap_delimiter)) {
979 sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION
);
982 /* Do some caching here */
983 if (!$sqimap_delimiter) {
984 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
986 * According to something that I can't find, this is supposed to work on all systems
987 * OS: This won't work in Courier IMAP.
988 * OS: According to rfc2342 response from NAMESPACE command is:
989 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
990 * OS: We want to lookup all personal NAMESPACES...
992 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
993 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
994 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
997 $pna = explode(')(', $pn);
998 while (list($k, $v) = each($pna)) {
999 $lst = explode('"', $v);
1000 if (isset($lst[3])) {
1001 $pn[$lst[1]] = $lst[3];
1007 $sqimap_delimiter = $pn[0];
1009 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
1010 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
1011 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
1012 $quote_position = strpos ($read[0], '"');
1013 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
1016 return $sqimap_delimiter;
1020 * This encodes a mailbox name for use in IMAP commands.
1021 * @param string $what the mailbox to encode
1022 * @return string the encoded mailbox string
1025 function sqimap_encode_mailbox_name($what)
1027 if (ereg("[\"\\\r\n]", $what))
1028 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
1029 return '"' . $what . '"'; /* 4.3 quoted string form */
1033 * Gets the number of messages in the current mailbox.
1035 * OBSOLETE use sqimap_status_messages instead.
1036 * @param stream $imap_stream imap stream
1037 * @param string $mailbox
1040 function sqimap_get_num_messages ($imap_stream, $mailbox) {
1041 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
1042 return $aStatus['MESSAGES'];
1046 * OBSOLETE FUNCTION should be removed after mailbox_display,
1047 * printMessage function is adapted
1048 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
1049 * @param string $address
1050 * @param integer $max
1052 * @deprecated See Rfc822Address.php
1054 function parseAddress($address, $max=0) {
1055 $aAddress = parseRFC822Address($address,array('limit'=> $max));
1057 * Because the expected format of the array element is changed we adapt it now.
1058 * This also implies that this function is obsolete and should be removed after the
1059 * rest of the source is adapted. See Rfc822Address.php for the new function.
1061 array_walk($aAddress, '_adaptAddress');
1066 * OBSOLETE FUNCTION should be removed after mailbox_display,
1067 * printMessage function is adapted
1069 * callback function used for formating of addresses array in
1070 * parseAddress() function
1071 * @param array $aAddr
1072 * @param integer $k array key
1076 function _adaptAddress(&$aAddr,$k) {
1077 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
1078 $aAddr[SQM_ADDR_PERSONAL
] : '';
1079 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
1080 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
1081 $aAddr[SQM_ADDR_MAILBOX
];
1082 $aAddr = array($sEmail,$sPersonal);
1086 * Returns the number of unseen messages in this folder.
1087 * obsoleted by sqimap_status_messages !
1088 * Arguments differ in 1.0.x
1089 * @param stream $imap_stream
1090 * @param string $mailbox
1094 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1095 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1096 return $aStatus['UNSEEN'];
1100 * Returns the status items of a mailbox.
1101 * Default it returns MESSAGES,UNSEEN and RECENT
1102 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1103 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1104 * @param stream $imap_stream imap stream
1105 * @param string $mailbox mail folder
1106 * @param array $aStatusItems status items
1110 function sqimap_status_messages ($imap_stream, $mailbox,
1111 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1113 $aStatusItems = implode(' ',$aStatusItems);
1114 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1115 " ($aStatusItems)", false, $result, $message);
1117 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1118 $regs = array(false,false);
1119 while (isset($read_ary[$i])) {
1120 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1123 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1124 $messages = $regs[1];
1126 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1129 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1130 $uidnext = $regs[1];
1132 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1133 $uidvalidity = $regs[1];
1138 $status=array('MESSAGES' => $messages,
1140 'RECENT' => $recent,
1141 'UIDNEXT' => $uidnext,
1142 'UIDVALIDITY' => $uidvalidity);
1144 if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
1145 if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
1146 if (!empty($recent)) { $hook_status['RECENT']=$recent; }
1147 if (!empty($hook_status)) {
1148 $hook_status['MAILBOX']=$mailbox;
1149 $hook_status['CALLER']='sqimap_status_messages';
1150 do_hook_function('folder_status',$hook_status);
1157 * Saves a message to a given folder -- used for saving sent messages
1158 * @param stream $imap_stream
1159 * @param string $sent_folder
1161 * @return string $sid
1163 function sqimap_append ($imap_stream, $sMailbox, $length) {
1164 $sid = sqimap_session_id();
1165 $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
1166 fputs ($imap_stream, "$query\r\n");
1167 $tmp = fgets ($imap_stream, 1024);
1168 sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
1173 * @param stream imap_stream
1174 * @param string $folder (since 1.3.2)
1176 function sqimap_append_done ($imap_stream, $sMailbox='') {
1177 fputs ($imap_stream, "\r\n");
1178 $tmp = fgets ($imap_stream, 1024);
1179 while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
1180 $tmp = fgets ($imap_stream, 1024);
1185 * Displays error messages, if there are errors in responses to
1186 * commands issues by sqimap_append() and sqimap_append_done() functions.
1187 * @param string $response
1188 * @param string $sMailbox
1189 * @return bool $bDone
1190 * @since 1.5.1 and 1.4.5
1192 function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
1193 // static vars to keep them available when sqimap_append_done calls this function.
1194 static $imapquery, $imapsid;
1199 $imapquery = $query;
1204 if ($response{0} == '+') {
1205 // continuation request triggerd by sqimap_append()
1208 $i = strpos($response, ' ');
1209 $sRsp = substr($response,0,$i);
1210 $sMsg = substr($response,$i+
1);
1211 $aExtra = array('MAILBOX' => $sMailbox);
1213 case '*': //untagged response
1214 $i = strpos($sMsg, ' ');
1215 $sRsp = strtoupper(substr($sMsg,0,$i));
1216 $sMsg = substr($sMsg,$i+
1);
1217 if ($sRsp == 'NO' ||
$sRsp == 'BAD') {
1218 // for the moment disabled. Enable after 1.5.1 release.
1219 // Notices could give valueable information about the mailbox
1220 // sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
1225 // $imapsid<space>$sRsp<space>$sMsg
1227 $i = strpos($sMsg, ' ');
1228 $sRsp = strtoupper(substr($sMsg,0,$i));
1229 $sMsg = substr($sMsg,$i+
1);
1232 if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
1233 sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1235 sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1239 sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1242 sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
1251 // should be false because of the unexpected response but i'm not sure if
1252 // that will cause an endless loop in sqimap_append_done
1260 * Allows mapping of IMAP server address with custom function
1261 * see map_yp_alias()
1262 * @param string $imap_server imap server address or mapping
1263 * @param string $username
1267 function sqimap_get_user_server ($imap_server, $username) {
1268 if (substr($imap_server, 0, 4) != "map:") {
1269 return $imap_server;
1271 $function = substr($imap_server, 4);
1272 return $function($username);
1276 * This is an example that gets IMAP servers from yellowpages (NIS).
1277 * you can simple put map:map_yp_alias in your $imap_server_address
1278 * in config.php use your own function instead map_yp_alias to map your
1279 * LDAP whatever way to find the users IMAP server.
1281 * Requires access to external ypmatch program
1282 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1283 * @param string $username
1287 function map_yp_alias($username) {
1288 $yp = `ypmatch
$username aliases`
;
1289 return chop(substr($yp, strlen($username)+
1));