6 * This implements all functions that do general IMAP functions.
8 * @copyright © 1999-2007 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];
63 //FIXME: obey $handle_errors below!
65 global $squirrelmail_language, $color;
66 set_up_language($squirrelmail_language);
67 //FIXME: NO HTML IN CORE!
68 $string = "<b><font color=\"$color[2]\">\n" .
69 _("ERROR: No available IMAP stream.") .
70 //FIXME: NO HTML IN CORE!
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];
116 //FIXME: obey $handle_errors below!
118 global $squirrelmail_language, $color;
119 set_up_language($squirrelmail_language);
120 //FIXME: NO HTML IN CORE!
121 $string = "<b><font color=\"$color[2]\">\n" .
122 _("ERROR: No available IMAP stream.") .
123 //FIXME: NO HTML IN CORE!
131 * @param mixed $new_query
133 * @param array $aQuery
134 * @param boolean $unique_id see sqimap_session_id()
137 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
138 $sid = sqimap_session_id($unique_id);
139 $tag_uid_a = explode(' ',trim($sid));
140 $tag = $tag_uid_a[0];
141 $query = $sid . ' '.$new_query."\r\n";
142 $aQuery[$tag] = $query;
146 * @param stream $imap_stream imap stream
147 * @param array $aQueryList
148 * @param boolean $handle_errors
149 * @param array $aServerResponse
150 * @param array $aServerMessage
151 * @param boolean $unique_id see sqimap_session_id()
152 * @param boolean $filter see sqimap_fread()
153 * @param mixed $outputstream see sqimap_fread()
154 * @param boolean $no_return see sqimap_fread()
157 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
158 &$aServerResponse, &$aServerMessage, $unique_id = false,
159 $filter=false,$outputstream=false,$no_return=false) {
163 Do not fire all calls at once to the IMAP server but split the calls up
164 in portions of $iChunkSize. If we do not do that I think we misbehave as
165 IMAP client or should handle BYE calls if the IMAP server drops the
166 connection because the number of queries is to large. This isn't tested
167 but a wild guess how it could work in the field.
169 After testing it on Exchange 2000 we discovered that a chunksize of 32
170 was quicker then when we raised it to 128.
172 $iQueryCount = count($aQueryList);
174 // array_chunk would also do the job but it's supported from php > 4.2
175 $aQueryChunks = array();
176 $iLoops = floor($iQueryCount / $iChunkSize);
178 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
180 if (!function_exists('array_chunk')) { // arraychunk replacement
182 for($i=0;$i<$iLoops;++
$i) {
183 for($j=0;$j<$iChunkSize;++
$j) {
184 $key = key($aQueryList);
185 $aTmp[$key] = $aQueryList[$key];
186 if (next($aQueryList) === false) break;
188 $aQueryChunks[] = $aTmp;
191 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
194 for ($i=0;$i<$iLoops;++
$i) {
195 $aQuery = $aQueryChunks[$i];
196 foreach($aQuery as $tag => $query) {
197 fputs($imap_stream,$query);
198 $aResults[$tag] = false;
200 foreach($aQuery as $tag => $query) {
201 if ($aResults[$tag] == false) {
202 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
203 $handle_errors, $response, $message, $query,
204 $filter,$outputstream,$no_return);
205 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
206 if (!empty($aResponse)) {
207 $aResults[$returned_tag] = $aResponse[0];
209 $aResults[$returned_tag] = $aResponse;
211 $aServerResponse[$returned_tag] = $response[$returned_tag];
212 $aServerMessage[$returned_tag] = $message[$returned_tag];
221 * Custom fgets function: gets a line from the IMAP server,
222 * no matter how big it may be.
223 * @param stream $imap_stream the stream to read from
224 * @return string a line
227 function sqimap_fgets($imap_stream) {
232 while (strpos($results, "\r\n", $offset) === false) {
233 if (!($read = fgets($imap_stream, $buffer))) {
234 /* this happens in case of an error */
235 /* reset $results because it's useless */
239 if ( $results != '' ) {
240 $offset = strlen($results) - 1;
248 * @param stream $imap_stream
249 * @param integer $iSize
250 * @param boolean $filter
251 * @param mixed $outputstream stream or 'php://stdout' string
252 * @param boolean $no_return controls data returned by function
256 function sqimap_fread($imap_stream,$iSize,$filter=false,
257 $outputstream=false, $no_return=false) {
258 if (!$filter ||
!$outputstream) {
259 $iBufferSize = $iSize;
261 // see php bug 24033. They changed fread behaviour %$^&$%
262 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
264 if ($iSize < $iBufferSize) {
265 $iBufferSize = $iSize;
270 $sRead = $sReadRem = '';
271 // NB: fread can also stop at end of a packet on sockets.
272 while ($iRetrieved < $iSize) {
273 $sRead = fread($imap_stream,$iBufferSize);
274 $iLength = strlen($sRead);
275 $iRetrieved +
= $iLength ;
276 $iRemaining = $iSize - $iRetrieved;
277 if ($iRemaining < $iBufferSize) {
278 $iBufferSize = $iRemaining;
284 if ($sReadRem != '') {
285 $sRead = $sReadRem . $sRead;
289 if ($filter && $sRead != '') {
290 // in case the filter is base64 decoding we return a remainder
291 $sReadRem = $filter($sRead);
293 if ($outputstream && $sRead != '') {
294 if (is_resource($outputstream)) {
295 fwrite($outputstream,$sRead);
296 } else if ($outputstream == 'php://stdout') {
311 * Obsolete function, inform plugins that use it
312 * @param stream $imap_stream
314 * @param boolean $handle_errors
315 * @param array $response
316 * @param array $message
317 * @param string $query
319 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
321 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
322 &$response, &$message, $query = '') {
323 global $color, $oTemplate, $squirrelmail_language;
324 set_up_language($squirrelmail_language);
325 //FIXME: NO HTML IN CORE!
326 $string = "<b><font color=\"$color[2]\">\n" .
327 _("ERROR: Bad function call.") .
328 //FIXME: NO HTML IN CORE!
331 'There is a plugin installed which make use of the <br />' .
332 'SquirrelMail internal function sqimap_read_data_list.<br />'.
333 'Please adapt the installed plugin and let it use<br />'.
334 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
335 'The following query was issued:<br />'.
336 //FIXME: NO HTML IN CORE!
337 htmlspecialchars($query) . '<br />' . "</font><br />\n";
339 $oTemplate->display('footer.tpl');
344 * Function to display an error related to an IMAP query.
345 * @param string title the caption of the error box
346 * @param string query the query that went wrong
347 * @param string message_title optional message title
348 * @param string message optional error message
349 * @param string $link an optional link to try again
353 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
355 global $color, $squirrelmail_language;
357 set_up_language($squirrelmail_language);
358 //FIXME: NO HTML IN CORE!
359 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
360 $cmd = explode(' ',$query);
361 $cmd= strtolower($cmd[0]);
363 if ($query != '' && $cmd != 'login')
364 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
365 if ($message_title != '')
366 $string .= $message_title;
368 $string .= htmlspecialchars($message);
369 //FIXME: NO HTML IN CORE!
370 $string .= "</font><br />\n";
377 * Reads the output from the IMAP stream. If handle_errors is set to true,
378 * this will also handle all errors that are received. If it is not set,
379 * the errors will be sent back through $response and $message.
380 * @param stream $imap_stream imap stream
382 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
383 * @param array $response
384 * @param array $message
385 * @param string $query command that can be printed if something fails
386 * @param boolean $filter see sqimap_fread()
387 * @param mixed $outputstream see sqimap_fread()
388 * @param boolean $no_return see sqimap_fread()
391 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
392 &$response, &$message, $query = '',
393 $filter = false, $outputstream = false, $no_return = false) {
394 global $color, $squirrelmail_language;
396 if (!is_array($message)) $message = array();
397 if (!is_array($response)) $response = array();
399 $resultlist = array();
402 if (preg_match("/^(\w+)\s*/",$query,$aMatch)) {
403 $sCommand = strtoupper($aMatch[1]);
405 // error reporting (shouldn't happen)
407 $read = sqimap_fgets($imap_stream);
415 $read = sqimap_fgets($imap_stream);
420 /* get the command */
423 $s = substr($read,$i);
424 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
425 $arg = substr($s,0,$j);
427 $found_tag = substr($read,0,$i-1);
436 $response[$found_tag] = $arg;
437 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
439 $resultlist[] = $data;
441 $aResponse[$found_tag] = $resultlist;
442 $data = $resultlist = array();
443 if ($found_tag == $tag) {
444 break 3; /* switch switch while */
448 /* this shouldn't happen */
449 $response[$found_tag] = $arg;
450 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
452 $resultlist[] = $data;
454 $aResponse[$found_tag] = $resultlist;
455 $data = $resultlist = array();
456 if ($found_tag == $tag) {
457 break 3; /* switch switch while */
461 $read = sqimap_fgets($imap_stream);
462 if ($read === false) { /* error */
463 break 2; /* switch while */
466 } // end case $tag{0}
470 if (($sCommand == "FETCH" ||
$sCommand == "STORE") && preg_match('/^\*\s\d+\sFETCH/',$read)) {
471 /* check for literal */
472 $s = substr($read,-3);
473 $fetch_data = array();
474 do { /* outer loop, continue until next untagged fetch
476 do { /* innerloop for fetching literals. with this loop
477 we prohibid that literal responses appear in the
478 outer loop so we can trust the untagged and
479 tagged info provided by $read */
480 $read_literal = false;
481 if ($s === "}\r\n") {
482 $j = strrpos($read,'{');
483 $iLit = substr($read,$j+
1,-3);
484 $fetch_data[] = $read;
485 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
486 if ($sLiteral === false) { /* error */
487 break 4; /* while while switch while */
489 /* backwards compattibility */
490 $aLiteral = explode("\n", $sLiteral);
491 /* release not neaded data */
493 foreach ($aLiteral as $line) {
494 $fetch_data[] = $line ."\n";
496 /* release not neaded data */
498 /* next fgets belongs to this fetch because
499 we just got the exact literalsize and there
500 must follow data to complete the response */
501 $read = sqimap_fgets($imap_stream);
502 if ($read === false) { /* error */
503 break 4; /* while while switch while */
505 $s = substr($read,-3);
506 $read_literal = true;
509 $fetch_data[] = $read;
511 /* retrieve next line and check in the while
512 statements if it belongs to this fetch response */
513 $read = sqimap_fgets($imap_stream);
514 if ($read === false) { /* error */
515 break 4; /* while while switch while */
517 /* check for next untagged reponse and break */
518 if ($read{0} == '*') break 2;
519 $s = substr($read,-3);
520 } while ($s === "}\r\n" ||
$read_literal);
521 $s = substr($read,-3);
522 } while ($read{0} !== '*' &&
523 substr($read,0,strlen($tag)) !== $tag);
524 $resultlist[] = $fetch_data;
525 /* release not neaded data */
528 $s = substr($read,-3);
530 if ($s === "}\r\n") {
531 $j = strrpos($read,'{');
532 $iLit = substr($read,$j+
1,-3);
533 // check for numeric value to avoid that untagged responses like:
534 // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
535 // will trigger literal fetching ({SET:debug=51} !== int )
536 if (is_numeric($iLit)) {
538 $sLiteral = fread($imap_stream,$iLit);
539 if ($sLiteral === false) { /* error */
541 break 3; /* while switch while */
544 $data[] = sqimap_fgets($imap_stream);
551 $read = sqimap_fgets($imap_stream);
552 if ($read === false) {
553 break 3; /* while switch while */
554 } else if ($read{0} == '*') {
557 $s = substr($read,-3);
558 } while ($s === "}\r\n");
566 /* error processing in case $read is false */
567 if ($read === false) {
568 // try to retrieve an untagged bye respons from the results
569 $sResponse = array_pop($data);
570 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
571 if (!$handle_errors) {
574 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
575 //FIXME: NO HTML IN CORE!
576 echo '</body></html>';
578 } else if ($handle_errors) {
580 sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
585 /* Set $resultlist array */
587 //$resultlist[] = $data;
589 elseif (empty($resultlist)) {
590 $resultlist[] = array();
593 /* Return result or handle errors */
594 if ($handle_errors == false) {
597 switch ($response[$tag]) {
602 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
603 if (strstr($message[$tag], 'command resulted in') === false) {
604 sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
605 echo '</body></html>';
610 sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
611 //FIXME: NO HTML IN CORE!
612 echo '</body></html>';
615 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
616 //FIXME: NO HTML IN CORE!
617 echo '</body></html>';
620 sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
621 /* the error is displayed but because we don't know the reponse we
622 return the result anyway */
629 * @param stream $imap_stream imap string
630 * @param string $tag_uid
631 * @param boolean $handle_errors
632 * @param array $response
633 * @param array $message
634 * @param string $query (since 1.2.5)
635 * @param boolean $filter (since 1.4.1) see sqimap_fread()
636 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
637 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
639 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
640 &$response, &$message, $query = '',
641 $filter=false,$outputstream=false,$no_return=false) {
643 $tag_uid_a = explode(' ',trim($tag_uid));
644 $tag = $tag_uid_a[0];
646 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
647 $response, $message, $query,$filter,$outputstream,$no_return);
652 * Connects to the IMAP server and returns a resource identifier for use with
653 * the other SquirrelMail IMAP functions. Does NOT login!
654 * @param string server hostname of IMAP server
655 * @param int port port number to connect to
656 * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
657 * Argument was boolean before 1.5.1.
658 * @return imap-stream resource identifier
659 * @since 1.5.0 (usable only in 1.5.1 or later)
661 function sqimap_create_stream($server,$port,$tls=0) {
662 global $squirrelmail_language;
664 if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
665 // numerical IPv6 address must be enclosed in square brackets
666 $server = '['.$server.']';
670 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
671 /* Use TLS by prefixing "tls://" to the hostname */
672 $server = 'tls://' . $server;
674 require_once(SM_PATH
. 'functions/display_messages.php');
675 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
677 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
679 _("Please contact your system administrator and report this error."),
680 sprintf(_("Error connecting to IMAP server: %s."), $server));
684 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
686 /* Do some error correction */
688 set_up_language($squirrelmail_language, true);
689 require_once(SM_PATH
. 'functions/display_messages.php');
690 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
691 //FIXME: NO HTML IN CORE!
692 "<br />\r\n$error_number : $error_string<br />\r\n",
693 sprintf(_("Error connecting to IMAP server: %s."), $server) );
696 $server_info = fgets ($imap_stream, 1024);
699 * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
700 * http://www.php.net/stream-socket-enable-crypto
703 if (function_exists('stream_socket_enable_crypto')) {
704 // check starttls capability, don't use cached capability version
705 if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
706 // imap server does not declare starttls support
707 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
709 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
713 // issue starttls command and check response
714 sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
716 if ($starttls_response!='OK') {
717 // starttls command failed
718 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
720 _("Server replied:") . ' ',
725 // start crypto on connection. suppress function errors.
726 if (@stream_socket_enable_crypto
($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
727 // starttls was successful
730 * RFC 2595 requires to discard CAPABILITY information after successful
731 * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
732 * information only after successful login (src/redirect.php) and cached information
733 * is used only in other php script connections after successful STARTTLS. If script
734 * issues sqimap_capability() call before sqimap_login() and wants to get initial
735 * capability response, script should set third sqimap_capability() argument to false.
737 //sqsession_unregister('sqimap_capabilities');
740 * stream_socket_enable_crypto() call failed. Possible issues:
741 * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
742 * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
743 * suppressed in stream_socket_enable_crypto() call)
745 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
747 _("Unable to start TLS."));
749 * Bug: stream_socket_enable_crypto() does not register SSL errors in
750 * openssl_error_string() or stream notification wrapper and displays
751 * them in E_WARNING level message. It is impossible to retrieve error
752 * message without own error handler.
757 // php install does not support stream_socket_enable_crypto() function
758 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
760 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
768 * Logs the user into the IMAP server. If $hide is set, no error messages
769 * will be displayed (if set to 1, just exits, if set to 2, returns FALSE).
770 * This function returns the IMAP connection handle.
771 * @param string $username user name
772 * @param string $password password encrypted with onetimepad. Since 1.5.2
773 * function can use internal password functions, if parameter is set to
775 * @param string $imap_server_address address of imap server
776 * @param integer $imap_port port of imap server
777 * @param int $hide controls display connection errors:
779 * 1 = show no errors (just exit)
780 * 2 = show no errors (return FALSE)
781 * 3 = show no errors (return error string)
782 * @return mixed The IMAP connection stream, or if the connection fails,
783 * FALSE if $hide is set to 2 or an error string if $hide
786 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
787 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
788 $imap_auth_mech, $sqimap_capabilities;
790 // Note/TODO: This hack grabs the $authz argument from the session. In the short future,
791 // a new argument in function sqimap_login() will be used instead.
794 sqgetglobalvar('authz' , $authz , SQ_SESSION
);
797 /* authz plugin - specific:
798 * Get proxy login parameters from authz plugin configuration. If they
799 * exist, they will override the current ones.
800 * This is useful if we want to use different SASL authentication mechanism
801 * and/or different TLS settings for proxy logins. */
802 global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
803 $imap_auth_mech = !empty($authz_imap_auth_mech) ?
strtolower($authz_imap_auth_mech) : $imap_auth_mech;
804 $use_imap_tls = !empty($authz_use_imap_tls)?
$authz_use_imap_tls : $use_imap_tls;
805 $imap_port = !empty($authz_use_imap_tls)?
$authz_imapPort_tls : $imap_port;
807 if($imap_auth_mech == 'login' ||
$imap_auth_mech == 'cram-md5') {
808 logout_error("Misconfigured Plugin (authz or equivalent):<br/>".
809 "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
814 /* get imap login password */
815 if ($password===false) {
816 /* standard functions */
817 $password = sqauth_read_password();
819 /* old way. $key must be extracted from cookie */
820 if (!isset($onetimepad) ||
empty($onetimepad)) {
821 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
823 /* Decrypt the password */
824 $password = OneTimePadDecrypt($password, $onetimepad);
827 if (!isset($sqimap_capabilities)) {
828 sqgetglobalvar('sqimap_capabilities' , $sqimap_capabilities , SQ_SESSION
);
831 $host = $imap_server_address;
832 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
834 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
836 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
837 // We're using some sort of authentication OTHER than plain or login
838 $tag=sqimap_session_id(false);
839 if ($imap_auth_mech == 'digest-md5') {
840 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
841 } elseif ($imap_auth_mech == 'cram-md5') {
842 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
844 fputs($imap_stream,$query);
845 $answer=sqimap_fgets($imap_stream);
846 // Trim the "+ " off the front
847 $response=explode(" ",$answer,3);
848 if ($response[0] == '+') {
849 // Got a challenge back
850 $challenge=$response[1];
851 if ($imap_auth_mech == 'digest-md5') {
852 $reply = digest_md5_response($username,$password,$challenge,'imap',$host,$authz);
853 } elseif ($imap_auth_mech == 'cram-md5') {
854 $reply = cram_md5_response($username,$password,$challenge);
856 fputs($imap_stream,$reply);
857 $read=sqimap_fgets($imap_stream);
858 if ($imap_auth_mech == 'digest-md5') {
859 // DIGEST-MD5 has an extra step..
860 if (substr($read,0,1) == '+') { // OK so far..
861 fputs($imap_stream,"\r\n");
862 $read=sqimap_fgets($imap_stream);
865 $results=explode(" ",$read,3);
866 $response=$results[1];
867 $message=$results[2];
869 // Fake the response, so the error trap at the bottom will work
871 $message='IMAP server does not appear to support the authentication method selected.';
872 $message .= ' Please contact your system administrator.';
874 } elseif ($imap_auth_mech == 'login') {
875 // Original IMAP login code
876 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
877 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
878 } elseif ($imap_auth_mech == 'plain') {
880 * SASL PLAIN, RFC 4616 (updates 2595)
882 * The mechanism consists of a single message, a string of [UTF-8]
883 * encoded [Unicode] characters, from the client to the server. The
884 * client presents the authorization identity (identity to act as),
885 * followed by a NUL (U+0000) character, followed by the authentication
886 * identity (identity whose password will be used), followed by a NUL
887 * (U+0000) character, followed by the clear-text password. As with
888 * other SASL mechanisms, the client does not provide an authorization
889 * identity when it wishes the server to derive an identity from the
890 * credentials and use that as the authorization identity.
892 $tag=sqimap_session_id(false);
893 $sasl = (isset($sqimap_capabilities['SASL-IR']) && $sqimap_capabilities['SASL-IR']) ?
true : false;
895 $auth = base64_encode("$username\0$authz\0$password");
897 $auth = base64_encode("$username\0$username\0$password");
900 // IMAP Extension for SASL Initial Client Response
901 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
902 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
903 fputs($imap_stream, $query);
904 $read = sqimap_fgets($imap_stream);
906 $query = $tag . " AUTHENTICATE PLAIN\r\n";
907 fputs($imap_stream, $query);
908 $read=sqimap_fgets($imap_stream);
909 if (substr($read,0,1) == '+') { // OK so far..
910 fputs($imap_stream, "$auth\r\n");
911 $read = sqimap_fgets($imap_stream);
914 $results=explode(" ",$read,3);
915 $response=$results[1];
916 $message=$results[2];
920 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
923 /* If the connection was not successful, lets see why */
924 if ($response != 'OK') {
925 if (!$hide ||
$hide == 3) {
926 //FIXME: UUURG... We don't want HTML in error messages, should also do html sanitizing of error messages elsewhere; should't assume output is destined for an HTML browser here
927 if ($response != 'NO') {
928 /* "BAD" and anything else gets reported here. */
929 $message = htmlspecialchars($message);
930 set_up_language($squirrelmail_language, true);
931 if ($response == 'BAD') {
932 if ($hide == 3) return sprintf(_("Bad request: %s"), $message);
933 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
935 if ($hide == 3) return sprintf(_("Unknown error: %s"), $message);
936 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
938 if (isset($read) && is_array($read)) {
939 $string .= '<br />' . _("Read data:") . "<br />\n";
940 foreach ($read as $line) {
941 $string .= htmlspecialchars($line) . "<br />\n";
948 * If the user does not log in with the correct
949 * username and password it is not possible to get the
950 * correct locale from the user's preferences.
951 * Therefore, apply the same hack as on the login
954 * $squirrelmail_language is set by a cookie when
955 * the user selects language and logs out
958 set_up_language($squirrelmail_language, true);
961 /* terminate the session nicely */
962 sqimap_logout($imap_stream);
963 if ($hide == 3) return _("Unknown user or password incorrect.");
964 logout_error( _("Unknown user or password incorrect.") );
968 if ($hide == 2) return FALSE;
973 /* Special error case:
974 * Login referrals. The server returns:
975 * ? OK [REFERRAL <imap url>]
976 * Check RFC 2221 for details. Since we do not support login referrals yet
977 * we log the user out.
979 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
980 sqimap_logout($imap_stream);
981 set_up_language($squirrelmail_language, true);
983 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
991 * Simply logs out the IMAP session
992 * @param stream $imap_stream the IMAP connection to log out.
995 function sqimap_logout ($imap_stream) {
996 /* Logout is not valid until the server returns 'BYE'
997 * If we don't have an imap_ stream we're already logged out */
998 if(isset($imap_stream) && $imap_stream)
999 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
1003 * Retrieve the CAPABILITY string from the IMAP server.
1004 * If capability is set, returns only that specific capability,
1005 * else returns array of all capabilities.
1006 * @param stream $imap_stream
1007 * @param string $capability (since 1.3.0)
1008 * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
1009 * @return mixed (string if $capability is set and found,
1010 * false, if $capability is set and not found,
1011 * array if $capability not set)
1013 function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
1014 // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
1016 if (!$bUseCache ||
! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION
)) {
1017 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
1018 $c = explode(' ', $read[0]);
1019 for ($i=2; $i < count($c); $i++
) {
1020 $cap_list = explode('=', $c[$i]);
1021 if (isset($cap_list[1])) {
1022 if(isset($sqimap_capabilities[trim($cap_list[0])]) &&
1023 !is_array($sqimap_capabilities[trim($cap_list[0])])) {
1024 // Remove array key that was added in 'else' block below
1025 // This is to accomodate for capabilities like:
1027 unset($sqimap_capabilities[trim($cap_list[0])]);
1029 $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
1031 if(!isset($sqimap_capabilities[trim($cap_list[0])])) {
1032 $sqimap_capabilities[trim($cap_list[0])] = TRUE;
1038 if (isset($sqimap_capabilities[$capability])) {
1039 return $sqimap_capabilities[$capability];
1044 return $sqimap_capabilities;
1048 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
1049 * @param stream $imap_stream
1052 function sqimap_get_delimiter ($imap_stream = false) {
1053 global $sqimap_delimiter, $optional_delimiter;
1055 /* Use configured delimiter if set */
1056 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
1057 return $optional_delimiter;
1060 /* Delimiter is stored in the session from redirect. Try fetching from there first */
1061 if (empty($sqimap_delimiter)) {
1062 sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION
);
1065 /* Do some caching here */
1066 if (!$sqimap_delimiter) {
1067 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
1069 * According to something that I can't find, this is supposed to work on all systems
1070 * OS: This won't work in Courier IMAP.
1071 * OS: According to rfc2342 response from NAMESPACE command is:
1072 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
1073 * OS: We want to lookup all personal NAMESPACES...
1075 * TODO: remove this in favour of the information from sqimap_get_namespace()
1077 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
1078 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
1079 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
1082 $pna = explode(')(', $pn);
1083 while (list($k, $v) = each($pna)) {
1084 $lst = explode('"', $v);
1085 if (isset($lst[3])) {
1086 $pn[$lst[1]] = $lst[3];
1092 $sqimap_delimiter = $pn[0];
1094 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
1095 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
1096 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
1097 $quote_position = strpos ($read[0], '"');
1098 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
1101 return $sqimap_delimiter;
1105 * Retrieves the namespaces from the IMAP server.
1106 * NAMESPACE is an IMAP extension defined in RFC 2342.
1108 * @param stream $imap_stream
1111 function sqimap_get_namespace($imap_stream) {
1112 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
1113 return sqimap_parse_namespace($read[0]);
1117 * Parses a NAMESPACE response and returns an array with the available
1118 * personal, users and shared namespaces.
1120 * @param string $input
1121 * @return array The returned array has the following format:
1124 * 'personal' => array(
1125 * 0 => array('prefix'=>'INBOX.','delimiter' =>'.'),
1128 * 'users' => array(..
1130 * 'shared' => array( ..
1134 * Note that if a namespace is not defined in the server, then the corresponding
1135 * array will be empty.
1137 function sqimap_parse_namespace(&$input) {
1138 $ns_strings = array(1=>'personal', 2=>'users', 3=>'shared');
1139 $namespace = array();
1141 if(ereg('NAMESPACE (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL)', $input, $regs) !== false) {
1142 for($i=1; $i<=3; $i++
) {
1143 if($regs[$i] == 'NIL') {
1144 $namespace[$ns_strings[$i]] = array();
1146 // Pop-out the first ( and last ) for easier parsing
1147 $ns = substr($regs[$i], 1, sizeof($regs[$i])-2);
1148 if($c = preg_match_all('/\((?:(.*?)\s*?)\)/', $ns, $regs2)) {
1149 $namespace[$ns_strings[$i]] = array();
1150 for($j=0; $j<sizeof($regs2[1]); $j++
) {
1151 preg_match('/"(.*)"\s+("(.*)"|NIL)/', $regs2[1][$j], $regs3);
1152 $namespace[$ns_strings[$i]][$j]['prefix'] = $regs3[1];
1153 if($regs3[2] == 'NIL') {
1154 $namespace[$ns_strings[$i]][$j]['delimiter'] = null;
1156 // $regs[3] is $regs[2] without the quotes
1157 $namespace[$ns_strings[$i]][$j]['delimiter'] = $regs3[3];
1170 * This encodes a mailbox name for use in IMAP commands.
1171 * @param string $what the mailbox to encode
1172 * @return string the encoded mailbox string
1175 function sqimap_encode_mailbox_name($what)
1177 if (ereg("[\"\\\r\n]", $what))
1178 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
1179 return '"' . $what . '"'; /* 4.3 quoted string form */
1183 * Gets the number of messages in the current mailbox.
1185 * OBSOLETE use sqimap_status_messages instead.
1186 * @param stream $imap_stream imap stream
1187 * @param string $mailbox
1190 function sqimap_get_num_messages ($imap_stream, $mailbox) {
1191 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
1192 return $aStatus['MESSAGES'];
1196 * OBSOLETE FUNCTION should be removed after mailbox_display,
1197 * printMessage function is adapted
1198 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
1199 * @param string $address
1200 * @param integer $max
1202 * @deprecated See Rfc822Address.php
1204 function parseAddress($address, $max=0) {
1205 $aAddress = parseRFC822Address($address,array('limit'=> $max));
1207 * Because the expected format of the array element is changed we adapt it now.
1208 * This also implies that this function is obsolete and should be removed after the
1209 * rest of the source is adapted. See Rfc822Address.php for the new function.
1211 array_walk($aAddress, '_adaptAddress');
1216 * OBSOLETE FUNCTION should be removed after mailbox_display,
1217 * printMessage function is adapted
1219 * callback function used for formating of addresses array in
1220 * parseAddress() function
1221 * @param array $aAddr
1222 * @param integer $k array key
1226 function _adaptAddress(&$aAddr,$k) {
1227 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
1228 $aAddr[SQM_ADDR_PERSONAL
] : '';
1229 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
1230 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
1231 $aAddr[SQM_ADDR_MAILBOX
];
1232 $aAddr = array($sEmail,$sPersonal);
1236 * Returns the number of unseen messages in this folder.
1237 * obsoleted by sqimap_status_messages !
1238 * Arguments differ in 1.0.x
1239 * @param stream $imap_stream
1240 * @param string $mailbox
1244 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1245 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1246 return $aStatus['UNSEEN'];
1250 * Returns the status items of a mailbox.
1251 * Default it returns MESSAGES,UNSEEN and RECENT
1252 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1253 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1254 * @param stream $imap_stream imap stream
1255 * @param string $mailbox mail folder
1256 * @param array $aStatusItems status items
1260 function sqimap_status_messages ($imap_stream, $mailbox,
1261 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1263 $aStatusItems = implode(' ',$aStatusItems);
1264 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1265 " ($aStatusItems)", false, $result, $message);
1267 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1268 $regs = array(false,false);
1269 while (isset($read_ary[$i])) {
1270 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1273 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1274 $messages = $regs[1];
1276 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1279 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1280 $uidnext = $regs[1];
1282 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1283 $uidvalidity = $regs[1];
1288 $status=array('MESSAGES' => $messages,
1290 'RECENT' => $recent,
1291 'UIDNEXT' => $uidnext,
1292 'UIDVALIDITY' => $uidvalidity);
1294 if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
1295 if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
1296 if (!empty($recent)) { $hook_status['RECENT']=$recent; }
1297 if (!empty($hook_status)) {
1298 $hook_status['MAILBOX']=$mailbox;
1299 $hook_status['CALLER']='sqimap_status_messages';
1300 do_hook('folder_status', $hook_status);
1307 * Saves a message to a given folder -- used for saving sent messages
1308 * @param stream $imap_stream
1309 * @param string $sent_folder
1311 * @return string $sid
1313 function sqimap_append ($imap_stream, $sMailbox, $length) {
1314 $sid = sqimap_session_id();
1315 $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
1316 fputs ($imap_stream, "$query\r\n");
1317 $tmp = fgets ($imap_stream, 1024);
1318 sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
1323 * @param stream imap_stream
1324 * @param string $folder (since 1.3.2)
1326 function sqimap_append_done ($imap_stream, $sMailbox='') {
1327 fputs ($imap_stream, "\r\n");
1328 $tmp = fgets ($imap_stream, 1024);
1329 while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
1330 $tmp = fgets ($imap_stream, 1024);
1335 * Displays error messages, if there are errors in responses to
1336 * commands issues by sqimap_append() and sqimap_append_done() functions.
1337 * @param string $response
1338 * @param string $sMailbox
1339 * @return bool $bDone
1340 * @since 1.5.1 and 1.4.5
1342 function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
1343 // static vars to keep them available when sqimap_append_done calls this function.
1344 static $imapquery, $imapsid;
1349 $imapquery = $query;
1354 if ($response{0} == '+') {
1355 // continuation request triggerd by sqimap_append()
1358 $i = strpos($response, ' ');
1359 $sRsp = substr($response,0,$i);
1360 $sMsg = substr($response,$i+
1);
1361 $aExtra = array('MAILBOX' => $sMailbox);
1363 case '*': //untagged response
1364 $i = strpos($sMsg, ' ');
1365 $sRsp = strtoupper(substr($sMsg,0,$i));
1366 $sMsg = substr($sMsg,$i+
1);
1367 if ($sRsp == 'NO' ||
$sRsp == 'BAD') {
1368 // for the moment disabled. Enable after 1.5.1 release.
1369 // Notices could give valueable information about the mailbox
1370 // sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
1375 // $imapsid<space>$sRsp<space>$sMsg
1377 $i = strpos($sMsg, ' ');
1378 $sRsp = strtoupper(substr($sMsg,0,$i));
1379 $sMsg = substr($sMsg,$i+
1);
1382 if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
1383 sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1385 sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1389 sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1392 sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
1401 // should be false because of the unexpected response but i'm not sure if
1402 // that will cause an endless loop in sqimap_append_done
1410 * Allows mapping of IMAP server address with custom function
1411 * see map_yp_alias()
1412 * @param string $imap_server imap server address or mapping
1413 * @param string $username
1417 function sqimap_get_user_server ($imap_server, $username) {
1418 if (substr($imap_server, 0, 4) != "map:") {
1419 return $imap_server;
1421 $function = substr($imap_server, 4);
1422 return $function($username);
1426 * This is an example that gets IMAP servers from yellowpages (NIS).
1427 * you can simple put map:map_yp_alias in your $imap_server_address
1428 * in config.php use your own function instead map_yp_alias to map your
1429 * LDAP whatever way to find the users IMAP server.
1431 * Requires access to external ypmatch program
1432 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1433 * @param string $username
1437 function map_yp_alias($username) {
1438 $yp = `ypmatch
$username aliases`
;
1439 return chop(substr($yp, strlen($username)+
1));