6 * This implements all functions that do general IMAP functions.
8 * @copyright 1999-2012 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 /* sqimap_read_data should be called for one response
113 but since it just calls sqimap_retrieve_imap_response
114 which handles multiple responses we need to check for
115 that and merge the $read[$tag] array IF they are
116 separated and IF it was a FETCH response. */
118 if (isset($read[$tag][1]) && is_array($read[$tag][1]) && isset($read[$tag][1][0])
119 && preg_match('/^\* \d+ FETCH/', $read[$tag][1][0])) {
121 foreach($read[$tag] as $index => $value) {
122 $result = array_merge($result, $read[$tag]["$index"]);
127 return $read[$tag][0];
131 //FIXME: obey $handle_errors below!
133 global $squirrelmail_language, $color;
134 set_up_language($squirrelmail_language);
135 //FIXME: NO HTML IN CORE!
136 $string = "<b><font color=\"$color[2]\">\n" .
137 _("ERROR: No available IMAP stream.") .
138 //FIXME: NO HTML IN CORE!
146 * @param mixed $new_query
148 * @param array $aQuery
149 * @param boolean $unique_id see sqimap_session_id()
152 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
153 $sid = sqimap_session_id($unique_id);
154 $tag_uid_a = explode(' ',trim($sid));
155 $tag = $tag_uid_a[0];
156 $query = $sid . ' '.$new_query."\r\n";
157 $aQuery[$tag] = $query;
161 * @param stream $imap_stream imap stream
162 * @param array $aQueryList
163 * @param boolean $handle_errors
164 * @param array $aServerResponse
165 * @param array $aServerMessage
166 * @param boolean $unique_id see sqimap_session_id()
167 * @param boolean $filter see sqimap_fread()
168 * @param mixed $outputstream see sqimap_fread()
169 * @param boolean $no_return see sqimap_fread()
172 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
173 &$aServerResponse, &$aServerMessage, $unique_id = false,
174 $filter=false,$outputstream=false,$no_return=false) {
178 Do not fire all calls at once to the IMAP server but split the calls up
179 in portions of $iChunkSize. If we do not do that I think we misbehave as
180 IMAP client or should handle BYE calls if the IMAP server drops the
181 connection because the number of queries is to large. This isn't tested
182 but a wild guess how it could work in the field.
184 After testing it on Exchange 2000 we discovered that a chunksize of 32
185 was quicker then when we raised it to 128.
187 $iQueryCount = count($aQueryList);
189 // array_chunk would also do the job but it's supported from php > 4.2
190 $aQueryChunks = array();
191 $iLoops = floor($iQueryCount / $iChunkSize);
193 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
195 if (!function_exists('array_chunk')) { // arraychunk replacement
197 for($i=0;$i<$iLoops;++
$i) {
198 for($j=0;$j<$iChunkSize;++
$j) {
199 $key = key($aQueryList);
200 $aTmp[$key] = $aQueryList[$key];
201 if (next($aQueryList) === false) break;
203 $aQueryChunks[] = $aTmp;
206 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
209 for ($i=0;$i<$iLoops;++
$i) {
210 $aQuery = $aQueryChunks[$i];
211 foreach($aQuery as $tag => $query) {
212 fputs($imap_stream,$query);
213 $aResults[$tag] = false;
215 foreach($aQuery as $tag => $query) {
216 if ($aResults[$tag] == false) {
217 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
218 $handle_errors, $response, $message, $query,
219 $filter,$outputstream,$no_return);
220 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
221 if (!empty($aResponse)) {
222 $aResults[$returned_tag] = $aResponse[0];
224 $aResults[$returned_tag] = $aResponse;
226 $aServerResponse[$returned_tag] = $response[$returned_tag];
227 $aServerMessage[$returned_tag] = $message[$returned_tag];
236 * Custom fgets function: gets a line from the IMAP server,
237 * no matter how big it may be.
238 * @param stream $imap_stream the stream to read from
239 * @return string a line
242 function sqimap_fgets($imap_stream) {
247 while (strpos($results, "\r\n", $offset) === false) {
248 if (!($read = fgets($imap_stream, $buffer))) {
249 /* this happens in case of an error */
250 /* reset $results because it's useless */
254 if ( $results != '' ) {
255 $offset = strlen($results) - 1;
263 * @param stream $imap_stream
264 * @param integer $iSize
265 * @param boolean $filter
266 * @param mixed $outputstream stream or 'php://stdout' string
267 * @param boolean $no_return controls data returned by function
271 function sqimap_fread($imap_stream,$iSize,$filter=false,
272 $outputstream=false, $no_return=false) {
273 if (!$filter ||
!$outputstream) {
274 $iBufferSize = $iSize;
276 // see php bug 24033. They changed fread behaviour %$^&$%
277 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
279 if ($iSize < $iBufferSize) {
280 $iBufferSize = $iSize;
285 $sRead = $sReadRem = '';
286 // NB: fread can also stop at end of a packet on sockets.
287 while ($iRetrieved < $iSize) {
288 $sRead = fread($imap_stream,$iBufferSize);
289 $iLength = strlen($sRead);
290 $iRetrieved +
= $iLength ;
291 $iRemaining = $iSize - $iRetrieved;
292 if ($iRemaining < $iBufferSize) {
293 $iBufferSize = $iRemaining;
299 if ($sReadRem != '') {
300 $sRead = $sReadRem . $sRead;
304 if ($filter && $sRead != '') {
305 // in case the filter is base64 decoding we return a remainder
306 $sReadRem = $filter($sRead);
308 if ($outputstream && $sRead != '') {
309 if (is_resource($outputstream)) {
310 fwrite($outputstream,$sRead);
311 } else if ($outputstream == 'php://stdout') {
326 * Obsolete function, inform plugins that use it
327 * @param stream $imap_stream
329 * @param boolean $handle_errors
330 * @param array $response
331 * @param array $message
332 * @param string $query
334 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
336 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
337 &$response, &$message, $query = '') {
338 global $color, $oTemplate, $squirrelmail_language;
339 set_up_language($squirrelmail_language);
340 //FIXME: NO HTML IN CORE!
341 $string = "<b><font color=\"$color[2]\">\n" .
342 _("ERROR: Bad function call.") .
343 //FIXME: NO HTML IN CORE!
346 'There is a plugin installed which make use of the <br />' .
347 'SquirrelMail internal function sqimap_read_data_list.<br />'.
348 'Please adapt the installed plugin and let it use<br />'.
349 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
350 'The following query was issued:<br />'.
351 //FIXME: NO HTML IN CORE!
352 htmlspecialchars($query) . '<br />' . "</font><br />\n";
354 $oTemplate->display('footer.tpl');
359 * Function to display an error related to an IMAP query.
360 * @param string title the caption of the error box
361 * @param string query the query that went wrong
362 * @param string message_title optional message title
363 * @param string message optional error message
364 * @param string $link an optional link to try again
368 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
370 global $color, $squirrelmail_language;
372 set_up_language($squirrelmail_language);
373 //FIXME: NO HTML IN CORE!
374 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
375 $cmd = explode(' ',$query);
376 $cmd= strtolower($cmd[0]);
378 if ($query != '' && $cmd != 'login')
379 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
380 if ($message_title != '')
381 $string .= $message_title;
383 $string .= htmlspecialchars($message);
384 //FIXME: NO HTML IN CORE!
385 $string .= "</font><br />\n";
392 * Reads the output from the IMAP stream. If handle_errors is set to true,
393 * this will also handle all errors that are received. If it is not set,
394 * the errors will be sent back through $response and $message.
395 * @param stream $imap_stream imap stream
397 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
398 * @param array $response
399 * @param array $message
400 * @param string $query command that can be printed if something fails
401 * @param boolean $filter see sqimap_fread()
402 * @param mixed $outputstream see sqimap_fread()
403 * @param boolean $no_return see sqimap_fread()
406 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
407 &$response, &$message, $query = '',
408 $filter = false, $outputstream = false, $no_return = false) {
409 global $color, $squirrelmail_language;
411 if (!is_array($message)) $message = array();
412 if (!is_array($response)) $response = array();
414 $resultlist = array();
417 if (preg_match("/^(\w+)\s*/",$query,$aMatch)) {
418 $sCommand = strtoupper($aMatch[1]);
420 // error reporting (shouldn't happen)
422 $read = sqimap_fgets($imap_stream);
430 $read = sqimap_fgets($imap_stream);
435 /* get the command */
438 $s = substr($read,$i);
439 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
440 $arg = substr($s,0,$j);
442 $found_tag = substr($read,0,$i-1);
451 $response[$found_tag] = $arg;
452 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
454 $resultlist[] = $data;
456 $aResponse[$found_tag] = $resultlist;
457 $data = $resultlist = array();
458 if ($found_tag == $tag) {
459 break 3; /* switch switch while */
463 /* this shouldn't happen */
464 $response[$found_tag] = $arg;
465 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
467 $resultlist[] = $data;
469 $aResponse[$found_tag] = $resultlist;
470 $data = $resultlist = array();
471 if ($found_tag == $tag) {
472 break 3; /* switch switch while */
476 $read = sqimap_fgets($imap_stream);
477 if ($read === false) { /* error */
478 break 2; /* switch while */
481 } // end case $tag{0}
485 if (($sCommand == "FETCH" ||
$sCommand == "STORE") && preg_match('/^\*\s\d+\sFETCH/',$read)) {
486 /* check for literal */
487 $s = substr($read,-3);
488 $fetch_data = array();
489 do { /* outer loop, continue until next untagged fetch
491 do { /* innerloop for fetching literals. with this loop
492 we prohibid that literal responses appear in the
493 outer loop so we can trust the untagged and
494 tagged info provided by $read */
495 $read_literal = false;
496 if ($s === "}\r\n") {
497 $j = strrpos($read,'{');
498 $iLit = substr($read,$j+
1,-3);
499 $fetch_data[] = $read;
500 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
501 if ($sLiteral === false) { /* error */
502 break 4; /* while while switch while */
504 /* backwards compattibility */
505 $aLiteral = explode("\n", $sLiteral);
506 /* release not neaded data */
508 foreach ($aLiteral as $line) {
509 $fetch_data[] = $line ."\n";
511 /* release not neaded data */
513 /* next fgets belongs to this fetch because
514 we just got the exact literalsize and there
515 must follow data to complete the response */
516 $read = sqimap_fgets($imap_stream);
517 if ($read === false) { /* error */
518 break 4; /* while while switch while */
520 $s = substr($read,-3);
521 $read_literal = true;
524 $fetch_data[] = $read;
526 /* retrieve next line and check in the while
527 statements if it belongs to this fetch response */
528 $read = sqimap_fgets($imap_stream);
529 if ($read === false) { /* error */
530 break 4; /* while while switch while */
532 /* check for next untagged reponse and break */
533 if ($read{0} == '*') break 2;
534 $s = substr($read,-3);
535 } while ($s === "}\r\n" ||
$read_literal);
536 $s = substr($read,-3);
537 } while ($read{0} !== '*' &&
538 substr($read,0,strlen($tag)) !== $tag);
539 $resultlist[] = $fetch_data;
540 /* release not neaded data */
543 $s = substr($read,-3);
545 if ($s === "}\r\n") {
546 $j = strrpos($read,'{');
547 $iLit = substr($read,$j+
1,-3);
548 // check for numeric value to avoid that untagged responses like:
549 // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
550 // will trigger literal fetching ({SET:debug=51} !== int )
551 if (is_numeric($iLit)) {
553 $sLiteral = fread($imap_stream,$iLit);
554 if ($sLiteral === false) { /* error */
556 break 3; /* while switch while */
559 $data[] = sqimap_fgets($imap_stream);
566 $read = sqimap_fgets($imap_stream);
567 if ($read === false) {
568 break 3; /* while switch while */
569 } else if ($read{0} == '*') {
572 $s = substr($read,-3);
573 } while ($s === "}\r\n");
581 /* error processing in case $read is false */
582 if ($read === false) {
583 // try to retrieve an untagged bye respons from the results
584 $sResponse = array_pop($data);
585 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
586 if (!$handle_errors) {
589 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
590 //FIXME: NO HTML IN CORE!
591 echo '</body></html>';
593 } else if ($handle_errors) {
595 sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
600 /* Set $resultlist array */
602 //$resultlist[] = $data;
604 elseif (empty($resultlist)) {
605 $resultlist[] = array();
608 /* Return result or handle errors */
609 if ($handle_errors == false) {
612 switch ($response[$tag]) {
617 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
618 if (strstr($message[$tag], 'command resulted in') === false) {
619 sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
620 echo '</body></html>';
625 sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
626 //FIXME: NO HTML IN CORE!
627 echo '</body></html>';
630 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
631 //FIXME: NO HTML IN CORE!
632 echo '</body></html>';
635 sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
636 /* the error is displayed but because we don't know the reponse we
637 return the result anyway */
644 * @param stream $imap_stream imap string
645 * @param string $tag_uid
646 * @param boolean $handle_errors
647 * @param array $response
648 * @param array $message
649 * @param string $query (since 1.2.5)
650 * @param boolean $filter (since 1.4.1) see sqimap_fread()
651 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
652 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
654 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
655 &$response, &$message, $query = '',
656 $filter=false,$outputstream=false,$no_return=false) {
658 $tag_uid_a = explode(' ',trim($tag_uid));
659 $tag = $tag_uid_a[0];
661 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
662 $response, $message, $query,$filter,$outputstream,$no_return);
667 * Connects to the IMAP server and returns a resource identifier for use with
668 * the other SquirrelMail IMAP functions. Does NOT login!
669 * @param string server hostname of IMAP server
670 * @param int port port number to connect to
671 * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
672 * Argument was boolean before 1.5.1.
673 * @return imap-stream resource identifier
674 * @since 1.5.0 (usable only in 1.5.1 or later)
676 function sqimap_create_stream($server,$port,$tls=0) {
677 global $squirrelmail_language;
679 if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
680 // numerical IPv6 address must be enclosed in square brackets
681 $server = '['.$server.']';
685 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
686 /* Use TLS by prefixing "tls://" to the hostname */
687 $server = 'tls://' . $server;
689 require_once(SM_PATH
. 'functions/display_messages.php');
690 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
692 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
694 _("Please contact your system administrator and report this error."),
695 sprintf(_("Error connecting to IMAP server: %s."), $server));
699 $imap_stream = @fsockopen
($server, $port, $error_number, $error_string, 15);
701 /* Do some error correction */
703 set_up_language($squirrelmail_language, true);
704 require_once(SM_PATH
. 'functions/display_messages.php');
705 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
706 //FIXME: NO HTML IN CORE!
707 "<br />\r\n$error_number : $error_string<br />\r\n",
708 sprintf(_("Error connecting to IMAP server: %s."), $server) );
711 $server_info = fgets ($imap_stream, 1024);
714 * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
715 * http://www.php.net/stream-socket-enable-crypto
718 if (function_exists('stream_socket_enable_crypto')) {
719 // check starttls capability, don't use cached capability version
720 if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
721 // imap server does not declare starttls support
722 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
724 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
728 // issue starttls command and check response
729 sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
731 if ($starttls_response!='OK') {
732 // starttls command failed
733 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
735 _("Server replied:") . ' ',
740 // start crypto on connection. suppress function errors.
741 if (@stream_socket_enable_crypto
($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
742 // starttls was successful
745 * RFC 2595 requires to discard CAPABILITY information after successful
746 * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
747 * information only after successful login (src/redirect.php) and cached information
748 * is used only in other php script connections after successful STARTTLS. If script
749 * issues sqimap_capability() call before sqimap_login() and wants to get initial
750 * capability response, script should set third sqimap_capability() argument to false.
752 //sqsession_unregister('sqimap_capabilities');
755 * stream_socket_enable_crypto() call failed. Possible issues:
756 * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
757 * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
758 * suppressed in stream_socket_enable_crypto() call)
760 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
762 _("Unable to start TLS."));
764 * Bug: stream_socket_enable_crypto() does not register SSL errors in
765 * openssl_error_string() or stream notification wrapper and displays
766 * them in E_WARNING level message. It is impossible to retrieve error
767 * message without own error handler.
772 // php install does not support stream_socket_enable_crypto() function
773 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
775 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
783 * Logs the user into the IMAP server. If $hide is set, no error messages
784 * will be displayed (if set to 1, just exits, if set to 2, returns FALSE).
785 * This function returns the IMAP connection handle.
786 * @param string $username user name
787 * @param string $password password encrypted with onetimepad. Since 1.5.2
788 * function can use internal password functions, if parameter is set to
790 * @param string $imap_server_address address of imap server
791 * @param integer $imap_port port of imap server
792 * @param int $hide controls display connection errors:
794 * 1 = show no errors (just exit)
795 * 2 = show no errors (return FALSE)
796 * 3 = show no errors (return error string)
797 * @return mixed The IMAP connection stream, or if the connection fails,
798 * FALSE if $hide is set to 2 or an error string if $hide
801 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
802 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
803 $imap_auth_mech, $sqimap_capabilities;
805 // Note/TODO: This hack grabs the $authz argument from the session. In the short future,
806 // a new argument in function sqimap_login() will be used instead.
809 sqgetglobalvar('authz' , $authz , SQ_SESSION
);
812 /* authz plugin - specific:
813 * Get proxy login parameters from authz plugin configuration. If they
814 * exist, they will override the current ones.
815 * This is useful if we want to use different SASL authentication mechanism
816 * and/or different TLS settings for proxy logins. */
817 global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
818 $imap_auth_mech = !empty($authz_imap_auth_mech) ?
strtolower($authz_imap_auth_mech) : $imap_auth_mech;
819 $use_imap_tls = !empty($authz_use_imap_tls)?
$authz_use_imap_tls : $use_imap_tls;
820 $imap_port = !empty($authz_use_imap_tls)?
$authz_imapPort_tls : $imap_port;
822 if($imap_auth_mech == 'login' ||
$imap_auth_mech == 'cram-md5') {
823 logout_error("Misconfigured Plugin (authz or equivalent):<br/>".
824 "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
829 /* get imap login password */
830 if ($password===false) {
831 /* standard functions */
832 $password = sqauth_read_password();
834 /* old way. $key must be extracted from cookie */
835 if (!isset($onetimepad) ||
empty($onetimepad)) {
836 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
838 /* Decrypt the password */
839 $password = OneTimePadDecrypt($password, $onetimepad);
842 if (!isset($sqimap_capabilities)) {
843 sqgetglobalvar('sqimap_capabilities' , $sqimap_capabilities , SQ_SESSION
);
846 $host = $imap_server_address;
847 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
849 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
851 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
852 // We're using some sort of authentication OTHER than plain or login
853 $tag=sqimap_session_id(false);
854 if ($imap_auth_mech == 'digest-md5') {
855 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
856 } elseif ($imap_auth_mech == 'cram-md5') {
857 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
859 fputs($imap_stream,$query);
860 $answer=sqimap_fgets($imap_stream);
861 // Trim the "+ " off the front
862 $response=explode(" ",$answer,3);
863 if ($response[0] == '+') {
864 // Got a challenge back
865 $challenge=$response[1];
866 if ($imap_auth_mech == 'digest-md5') {
867 $reply = digest_md5_response($username,$password,$challenge,'imap',$host,$authz);
868 } elseif ($imap_auth_mech == 'cram-md5') {
869 $reply = cram_md5_response($username,$password,$challenge);
871 fputs($imap_stream,$reply);
872 $read=sqimap_fgets($imap_stream);
873 if ($imap_auth_mech == 'digest-md5') {
874 // DIGEST-MD5 has an extra step..
875 if (substr($read,0,1) == '+') { // OK so far..
876 fputs($imap_stream,"\r\n");
877 $read=sqimap_fgets($imap_stream);
880 $results=explode(" ",$read,3);
881 $response=$results[1];
882 $message=$results[2];
884 // Fake the response, so the error trap at the bottom will work
886 $message='IMAP server does not appear to support the authentication method selected.';
887 $message .= ' Please contact your system administrator.';
889 } elseif ($imap_auth_mech == 'login') {
890 // Original IMAP login code
891 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
892 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
893 } elseif ($imap_auth_mech == 'plain') {
895 * SASL PLAIN, RFC 4616 (updates 2595)
897 * The mechanism consists of a single message, a string of [UTF-8]
898 * encoded [Unicode] characters, from the client to the server. The
899 * client presents the authorization identity (identity to act as),
900 * followed by a NUL (U+0000) character, followed by the authentication
901 * identity (identity whose password will be used), followed by a NUL
902 * (U+0000) character, followed by the clear-text password. As with
903 * other SASL mechanisms, the client does not provide an authorization
904 * identity when it wishes the server to derive an identity from the
905 * credentials and use that as the authorization identity.
907 $tag=sqimap_session_id(false);
908 $sasl = (isset($sqimap_capabilities['SASL-IR']) && $sqimap_capabilities['SASL-IR']) ?
true : false;
910 $auth = base64_encode("$username\0$authz\0$password");
912 $auth = base64_encode("$username\0$username\0$password");
915 // IMAP Extension for SASL Initial Client Response
916 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
917 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
918 fputs($imap_stream, $query);
919 $read = sqimap_fgets($imap_stream);
921 $query = $tag . " AUTHENTICATE PLAIN\r\n";
922 fputs($imap_stream, $query);
923 $read=sqimap_fgets($imap_stream);
924 if (substr($read,0,1) == '+') { // OK so far..
925 fputs($imap_stream, "$auth\r\n");
926 $read = sqimap_fgets($imap_stream);
929 $results=explode(" ",$read,3);
930 $response=$results[1];
931 $message=$results[2];
935 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
938 /* If the connection was not successful, lets see why */
939 if ($response != 'OK') {
940 if (!$hide ||
$hide == 3) {
941 //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
942 if ($response != 'NO') {
943 /* "BAD" and anything else gets reported here. */
944 $message = htmlspecialchars($message);
945 set_up_language($squirrelmail_language, true);
946 if ($response == 'BAD') {
947 if ($hide == 3) return sprintf(_("Bad request: %s"), $message);
948 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
950 if ($hide == 3) return sprintf(_("Unknown error: %s"), $message);
951 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
953 if (isset($read) && is_array($read)) {
954 $string .= '<br />' . _("Read data:") . "<br />\n";
955 foreach ($read as $line) {
956 $string .= htmlspecialchars($line) . "<br />\n";
963 * If the user does not log in with the correct
964 * username and password it is not possible to get the
965 * correct locale from the user's preferences.
966 * Therefore, apply the same hack as on the login
969 * $squirrelmail_language is set by a cookie when
970 * the user selects language and logs out
973 set_up_language($squirrelmail_language, true);
976 /* terminate the session nicely */
977 sqimap_logout($imap_stream);
978 if ($hide == 3) return _("Unknown user or password incorrect.");
979 logout_error( _("Unknown user or password incorrect.") );
983 if ($hide == 2) return FALSE;
988 /* Special error case:
989 * Login referrals. The server returns:
990 * ? OK [REFERRAL <imap url>]
991 * Check RFC 2221 for details. Since we do not support login referrals yet
992 * we log the user out.
994 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
995 sqimap_logout($imap_stream);
996 set_up_language($squirrelmail_language, true);
998 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
1002 return $imap_stream;
1006 * Simply logs out the IMAP session
1007 * @param stream $imap_stream the IMAP connection to log out.
1010 function sqimap_logout ($imap_stream) {
1011 /* Logout is not valid until the server returns 'BYE'
1012 * If we don't have an imap_ stream we're already logged out */
1013 if(isset($imap_stream) && $imap_stream)
1014 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
1018 * Retrieve the CAPABILITY string from the IMAP server.
1019 * If capability is set, returns only that specific capability,
1020 * else returns array of all capabilities.
1021 * @param stream $imap_stream
1022 * @param string $capability (since 1.3.0)
1023 * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
1024 * @return mixed (string if $capability is set and found,
1025 * false, if $capability is set and not found,
1026 * array if $capability not set)
1028 function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
1029 // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
1031 if (!$bUseCache ||
! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION
)) {
1032 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
1033 $c = explode(' ', $read[0]);
1034 for ($i=2; $i < count($c); $i++
) {
1035 $cap_list = explode('=', $c[$i]);
1036 if (isset($cap_list[1])) {
1037 if(isset($sqimap_capabilities[trim($cap_list[0])]) &&
1038 !is_array($sqimap_capabilities[trim($cap_list[0])])) {
1039 // Remove array key that was added in 'else' block below
1040 // This is to accomodate for capabilities like:
1042 unset($sqimap_capabilities[trim($cap_list[0])]);
1044 $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
1046 if(!isset($sqimap_capabilities[trim($cap_list[0])])) {
1047 $sqimap_capabilities[trim($cap_list[0])] = TRUE;
1053 if (isset($sqimap_capabilities[$capability])) {
1054 return $sqimap_capabilities[$capability];
1059 return $sqimap_capabilities;
1063 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
1064 * @param stream $imap_stream
1067 function sqimap_get_delimiter ($imap_stream = false) {
1068 global $sqimap_delimiter, $optional_delimiter;
1070 /* Use configured delimiter if set */
1071 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
1072 return $optional_delimiter;
1075 /* Delimiter is stored in the session from redirect. Try fetching from there first */
1076 if (empty($sqimap_delimiter)) {
1077 sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION
);
1080 /* Do some caching here */
1081 if (!$sqimap_delimiter) {
1082 if (sqimap_capability($imap_stream, 'NAMESPACE')
1084 * According to something that I can't find, this is supposed to work on all systems
1085 * OS: This won't work in Courier IMAP.
1086 * OS: According to rfc2342 response from NAMESPACE command is:
1087 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
1088 * OS: We want to lookup all personal NAMESPACES...
1090 * TODO: remove this in favour of the information from sqimap_get_namespace()
1092 && ($read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b))
1093 && preg_match('/\* NAMESPACE +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL)/i', $read[0], $data)
1094 && preg_match('/^\( *\((.*)\) *\)/', $data[1], $data2)) {
1096 $pna = explode(')(', $pn);
1098 while (list($k, $v) = each($pna)) {
1099 $lst = explode('"', $v);
1100 if (isset($lst[3])) {
1101 $delnew[$lst[1]] = $lst[3];
1103 $delnew[$lst[1]] = '';
1106 $sqimap_delimiter = array_shift($delnew);
1108 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
1109 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
1110 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
1111 $quote_position = strpos ($read[0], '"');
1112 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
1115 return $sqimap_delimiter;
1119 * Retrieves the namespaces from the IMAP server.
1120 * NAMESPACE is an IMAP extension defined in RFC 2342.
1122 * @param stream $imap_stream
1125 function sqimap_get_namespace($imap_stream) {
1126 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
1127 return sqimap_parse_namespace($read[0]);
1131 * Parses a NAMESPACE response and returns an array with the available
1132 * personal, users and shared namespaces.
1134 * @param string $input
1135 * @return array The returned array has the following format:
1138 * 'personal' => array(
1139 * 0 => array('prefix'=>'INBOX.','delimiter' =>'.'),
1142 * 'users' => array(..
1144 * 'shared' => array( ..
1148 * Note that if a namespace is not defined in the server, then the corresponding
1149 * array will be empty.
1151 function sqimap_parse_namespace(&$input) {
1152 $ns_strings = array(1=>'personal', 2=>'users', 3=>'shared');
1153 $namespace = array();
1155 if (preg_match('/NAMESPACE (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL)/', $input, $regs)) {
1156 for($i=1; $i<=3; $i++
) {
1157 if($regs[$i] == 'NIL') {
1158 $namespace[$ns_strings[$i]] = array();
1160 // Pop-out the first ( and last ) for easier parsing
1161 $ns = substr($regs[$i], 1, sizeof($regs[$i])-2);
1162 if($c = preg_match_all('/\((?:(.*?)\s*?)\)/', $ns, $regs2)) {
1163 $namespace[$ns_strings[$i]] = array();
1164 for($j=0; $j<sizeof($regs2[1]); $j++
) {
1165 preg_match('/"(.*)"\s+("(.*)"|NIL)/', $regs2[1][$j], $regs3);
1166 $namespace[$ns_strings[$i]][$j]['prefix'] = $regs3[1];
1167 if($regs3[2] == 'NIL') {
1168 $namespace[$ns_strings[$i]][$j]['delimiter'] = null;
1170 // $regs[3] is $regs[2] without the quotes
1171 $namespace[$ns_strings[$i]][$j]['delimiter'] = $regs3[3];
1184 * This encodes a mailbox name for use in IMAP commands.
1185 * @param string $what the mailbox to encode
1186 * @return string the encoded mailbox string
1189 function sqimap_encode_mailbox_name($what)
1191 if (preg_match('/["\\\r\n]/', $what))
1192 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
1193 return '"' . $what . '"'; /* 4.3 quoted string form */
1197 * Gets the number of messages in the current mailbox.
1199 * OBSOLETE use sqimap_status_messages instead.
1200 * @param stream $imap_stream imap stream
1201 * @param string $mailbox
1204 function sqimap_get_num_messages ($imap_stream, $mailbox) {
1205 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
1206 return $aStatus['MESSAGES'];
1210 * OBSOLETE FUNCTION should be removed after mailbox_display,
1211 * printMessage function is adapted
1212 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
1213 * @param string $address
1214 * @param integer $max
1216 * @deprecated See Rfc822Address.php
1218 function parseAddress($address, $max=0) {
1219 $aAddress = parseRFC822Address($address,array('limit'=> $max));
1221 * Because the expected format of the array element is changed we adapt it now.
1222 * This also implies that this function is obsolete and should be removed after the
1223 * rest of the source is adapted. See Rfc822Address.php for the new function.
1225 array_walk($aAddress, '_adaptAddress');
1230 * OBSOLETE FUNCTION should be removed after mailbox_display,
1231 * printMessage function is adapted
1233 * callback function used for formating of addresses array in
1234 * parseAddress() function
1235 * @param array $aAddr
1236 * @param integer $k array key
1240 function _adaptAddress(&$aAddr,$k) {
1241 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL
]) && $aAddr[SQM_ADDR_PERSONAL
]) ?
1242 $aAddr[SQM_ADDR_PERSONAL
] : '';
1243 $sEmail = ($aAddr[SQM_ADDR_HOST
]) ?
1244 $aAddr[SQM_ADDR_MAILBOX
] . '@'.$aAddr[SQM_ADDR_HOST
] :
1245 $aAddr[SQM_ADDR_MAILBOX
];
1246 $aAddr = array($sEmail,$sPersonal);
1250 * Returns the number of unseen messages in this folder.
1251 * obsoleted by sqimap_status_messages !
1252 * Arguments differ in 1.0.x
1253 * @param stream $imap_stream
1254 * @param string $mailbox
1258 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1259 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1260 return $aStatus['UNSEEN'];
1264 * Returns the status items of a mailbox.
1265 * Default it returns MESSAGES,UNSEEN and RECENT
1266 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1267 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1268 * @param stream $imap_stream imap stream
1269 * @param string $mailbox mail folder
1270 * @param array $aStatusItems status items
1274 function sqimap_status_messages ($imap_stream, $mailbox,
1275 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1277 $aStatusItems = implode(' ',$aStatusItems);
1278 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1279 " ($aStatusItems)", false, $result, $message);
1281 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1282 $regs = array(false,false);
1283 while (isset($read_ary[$i])) {
1284 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1287 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1288 $messages = $regs[1];
1290 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1293 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1294 $uidnext = $regs[1];
1296 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1297 $uidvalidity = $regs[1];
1302 $status=array('MESSAGES' => $messages,
1304 'RECENT' => $recent,
1305 'UIDNEXT' => $uidnext,
1306 'UIDVALIDITY' => $uidvalidity);
1308 if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
1309 if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
1310 if (!empty($recent)) { $hook_status['RECENT']=$recent; }
1311 if (!empty($hook_status)) {
1312 $hook_status['MAILBOX']=$mailbox;
1313 $hook_status['CALLER']='sqimap_status_messages';
1314 do_hook('folder_status', $hook_status);
1321 * Saves a message to a given folder -- used for saving sent messages
1322 * @param stream $imap_stream
1323 * @param string $sent_folder
1325 * @return string $sid
1327 function sqimap_append ($imap_stream, $sMailbox, $length) {
1328 $sid = sqimap_session_id();
1329 $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
1330 fputs ($imap_stream, "$query\r\n");
1331 $tmp = fgets ($imap_stream, 1024);
1332 sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
1337 * @param stream imap_stream
1338 * @param string $folder (since 1.3.2)
1340 function sqimap_append_done ($imap_stream, $sMailbox='') {
1341 fputs ($imap_stream, "\r\n");
1342 $tmp = fgets ($imap_stream, 1024);
1343 while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
1344 $tmp = fgets ($imap_stream, 1024);
1349 * Displays error messages, if there are errors in responses to
1350 * commands issues by sqimap_append() and sqimap_append_done() functions.
1351 * @param string $response
1352 * @param string $sMailbox
1353 * @return bool $bDone
1354 * @since 1.5.1 and 1.4.5
1356 function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
1357 // static vars to keep them available when sqimap_append_done calls this function.
1358 static $imapquery, $imapsid;
1363 $imapquery = $query;
1368 if ($response{0} == '+') {
1369 // continuation request triggerd by sqimap_append()
1372 $i = strpos($response, ' ');
1373 $sRsp = substr($response,0,$i);
1374 $sMsg = substr($response,$i+
1);
1375 $aExtra = array('MAILBOX' => $sMailbox);
1377 case '*': //untagged response
1378 $i = strpos($sMsg, ' ');
1379 $sRsp = strtoupper(substr($sMsg,0,$i));
1380 $sMsg = substr($sMsg,$i+
1);
1381 if ($sRsp == 'NO' ||
$sRsp == 'BAD') {
1382 // for the moment disabled. Enable after 1.5.1 release.
1383 // Notices could give valueable information about the mailbox
1384 // Update: seems this was forgotten, but now it is finally enabled
1385 sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
1390 // $imapsid<space>$sRsp<space>$sMsg
1392 $i = strpos($sMsg, ' ');
1393 $sRsp = strtoupper(substr($sMsg,0,$i));
1394 $sMsg = substr($sMsg,$i+
1);
1397 if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
1398 sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1400 sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1404 sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1407 sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
1416 // should be false because of the unexpected response but i'm not sure if
1417 // that will cause an endless loop in sqimap_append_done
1425 * Allows mapping of IMAP server address with custom function
1426 * see map_yp_alias()
1427 * @param string $imap_server imap server address or mapping
1428 * @param string $username
1432 function sqimap_get_user_server ($imap_server, $username) {
1433 if (substr($imap_server, 0, 4) != "map:") {
1434 return $imap_server;
1436 $function = substr($imap_server, 4);
1437 return $function($username);
1441 * This is an example that gets IMAP servers from yellowpages (NIS).
1442 * you can simple put map:map_yp_alias in your $imap_server_address
1443 * in config.php use your own function instead map_yp_alias to map your
1444 * LDAP whatever way to find the users IMAP server.
1446 * Requires access to external ypmatch program
1447 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1448 * @param string $username
1452 function map_yp_alias($username) {
1453 $safe_username = escapeshellarg($username);
1454 $yp = `ypmatch
$safe_username aliases`
;
1455 return chop(substr($yp, strlen($username)+
1));