6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This implements all functions that do general imap functions.
14 require_once(SM_PATH
. 'functions/page_header.php');
15 require_once(SM_PATH
. 'functions/auth.php');
18 global $sqimap_session_id;
19 $sqimap_session_id = 1;
21 /* Sets an unique session id in order to avoid simultanous sessions crash. */
22 function sqimap_session_id($unique_id = false) {
23 global $data_dir, $username, $sqimap_session_id;
25 return( sprintf("A%03d", $sqimap_session_id++
) );
27 return( sprintf("A%03d", $sqimap_session_id++
) . ' UID' );
32 * Both send a command and accept the result from the command.
33 * This is to allow proper session number handling.
35 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
37 $sid = sqimap_session_id($unique_id);
38 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
39 $tag_uid_a = explode(' ',trim($sid));
41 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
42 /* get the response and the message */
43 $message = $message[$tag];
44 $response = $response[$tag];
47 global $squirrelmail_language, $color;
48 set_up_language($squirrelmail_language);
49 require_once(SM_PATH
. 'functions/display_messages.php');
50 $string = "<b><font color=$color[2]>\n" .
51 _("ERROR : No available imapstream.") .
53 error_box($string,$color);
58 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
59 &$message, $unique_id = false,$filter=false,
60 $outputstream=false,$no_return=false) {
62 $sid = sqimap_session_id($unique_id);
63 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
64 $tag_uid_a = explode(' ',trim($sid));
67 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
68 $message, $query,$filter,$outputstream,$no_return);
69 /* retrieve the response and the message */
70 $response = $response[$tag];
71 $message = $message[$tag];
73 if (!empty($read[$tag])) {
74 return $read[$tag][0];
79 global $squirrelmail_language, $color;
80 set_up_language($squirrelmail_language);
81 require_once(SM_PATH
. 'functions/display_messages.php');
82 $string = "<b><font color=$color[2]>\n" .
83 _("ERROR : No available imapstream.") .
85 error_box($string,$color);
89 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
90 $sid = sqimap_session_id($unique_id);
91 $tag_uid_a = explode(' ',trim($sid));
93 $query = $sid . ' '.$new_query."\r\n";
94 $aQuery[$tag] = $query;
97 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
98 &$aServerResponse, &$aServerMessage, $unique_id = false,
99 $filter=false,$outputstream=false,$no_return=false) {
103 Do not fire all calls at once to the imap-server but split the calls up
104 in portions of $iChunkSize. If we do not do that I think we misbehave as
105 IMAP client or should handle BYE calls if the IMAP-server drops the
106 connection because the number of queries is to large. This isn't tested
107 but a wild guess how it could work in the field.
109 After testing it on Exchange 2000 we discovered that a chunksize of 32
110 was quicker then when we raised it to 128.
112 $iQueryCount = count($aQueryList);
114 // array_chunk would also do the job but it's supported from php > 4.2
115 $aQueryChunks = array();
116 $iLoops = floor($iQueryCount / $iChunkSize);
118 if ($iLoops * $iChunkSize != $iQueryCount) ++
$iLoops;
120 if (!function_exists('array_chunk')) { // arraychunk replacement
122 for($i=0;$i<$iLoops;++
$i) {
123 for($j=0;$j<$iChunkSize;++
$j) {
124 $key = key($aQueryList);
125 $aTmp[$key] = $aQueryList[$key];
126 if (next($aQueryList) === false) break;
128 $aQueryChunks[] = $aTmp;
131 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
134 for ($i=0;$i<$iLoops;++
$i) {
135 $aQuery = $aQueryChunks[$i];
136 foreach($aQuery as $tag => $query) {
137 fputs($imap_stream,$query);
138 $aResults[$tag] = false;
140 foreach($aQuery as $tag => $query) {
141 if ($aResults[$tag] == false) {
142 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
143 $handle_errors, $response, $message, $query,
144 $filter,$outputstream,$no_return);
145 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
146 if (!empty($aResponse)) {
147 $aResults[$returned_tag] = $aResponse[0];
149 $aResults[$returned_tag] = $aResponse;
151 $aServerResponse[$returned_tag] = $response[$returned_tag];
152 $aServerMessage[$returned_tag] = $message[$returned_tag];
161 * custom fgets function. gets a line from IMAP
162 * no matter how big it may be
165 function sqimap_fgets($imap_stream) {
170 while (strpos($results, "\r\n", $offset) === false) {
171 if (!($read = fgets($imap_stream, $buffer))) {
172 /* this happens in case of an error */
173 /* reset $results because it's useless */
177 if ( $results != '' ) {
178 $offset = strlen($results) - 1;
185 function sqimap_fread($imap_stream,$iSize,$filter=false,
186 $outputstream=false, $no_return=false) {
187 if (!$filter ||
!$outputstream) {
188 $iBufferSize = $iSize;
190 $iBufferSize = 62400; // multiple of 78 in case of base64 decoding.
192 $iRet = $iSize - $iBufferSize;
195 $results = $sReadRem = '';
196 $bFinished = $bBufferSizeAdapted = $bBufferIsOk = false;
197 while (($iRetrieved < ($iSize - $iBufferSize))) {
198 $sRead = fread($imap_stream,$iBufferSize);
203 $iRetrieved +
= $iBufferSize;
204 // if the returned lines are split, do not end with \n
205 // then we have a problem and need to adjust (happened with uw)
206 if ($bBufferSizeAdapted && substr($sRead,-1) !== "\n") {
207 // use fgets because it stops at \n.
208 // we can do it because it's for correction
209 $sRead .= fgets($imap_stream,$iBufferSize);
210 $iRetrieved +
= strlen($sRead);
211 if ($iRetrieved == $iSize) {
216 // in case line-endings do not appear at position 78 we adapt the buffersize so we can base64 decode on the fly
217 if (!$bBufferSizeAdapted) {
218 $i = strpos($sRead,"\n");
221 $iFragments = floor($iBufferSize / $i);
222 $iNewBufferSize = $iFragments * $i;
223 $iRemainder = $iNewBufferSize +
$i - $iBufferSize;
224 if ($iNewBufferSize == $iBufferSize) {
227 $iNewBufferSize = $iBufferSize;
228 $bBufferSizeAdapted = true;
230 if (!$bBufferIsOk && ($iRemainder +
$iBufferSize) < $iSize) {
231 $sReadRem = fread($imap_stream,$iRemainder);
232 } else if (!$bBufferIsOk) {
233 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
236 if (!$sReadRem && $sReadRem !== '') {
240 $iBufferSize = $iNewBufferSize;
241 $bBufferSizeAdapted = true;
243 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
251 $iRetrieved +
= $iRemainder;
257 if (is_resource($outputstream)) {
258 fwrite($outputstream,$sRead);
259 } else if ($outputstream == 'php://stdout') {
268 if (!$results && !$bFinished) {
269 $sRead = fread($imap_stream,($iSize - ($iRetrieved)));
274 if (is_resource($outputstream)) {
275 fwrite($outputstream,$sRead);
276 } else if ($outputstream == 'php://stdout') { // FIXME
287 /* obsolete function, inform plugins that use it */
288 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
289 &$response, &$message, $query = '') {
290 global $color, $squirrelmail_language;
291 set_up_language($squirrelmail_language);
292 require_once(SM_PATH
. 'functions/display_messages.php');
293 $string = "<b><font color=$color[2]>\n" .
294 _("ERROR : Bad function call.") .
297 'There is a plugin installed which make use of the <br>' .
298 'SquirrelMail internal function sqimap_read_data_list.<br>'.
299 'Please adapt the installed plugin and let it use<br>'.
300 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
301 'The following query was issued:<br>'.
302 htmlspecialchars($query) . '<br>' . "</font><br>\n";
303 error_box($string,$color);
304 echo '</body></html>';
309 * Reads the output from the IMAP stream. If handle_errors is set to true,
310 * this will also handle all errors that are received. If it is not set,
311 * the errors will be sent back through $response and $message
314 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
315 &$response, &$message, $query = '',
316 $filter = false, $outputstream = false, $no_return = false) {
317 global $color, $squirrelmail_language;
319 if (!is_array($message)) $message = array();
320 if (!is_array($response)) $response = array();
321 $resultlist = array();
323 $read = sqimap_fgets($imap_stream);
331 $read = sqimap_fgets($imap_stream);
336 /* get the command */
339 $s = substr($read,$i);
340 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
341 $arg = substr($s,0,$j);
343 $found_tag = substr($read,0,$i-1);
352 $response[$found_tag] = $arg;
353 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
355 $resultlist[] = $data;
357 $aResponse[$found_tag] = $resultlist;
358 $data = $resultlist = array();
359 if ($found_tag == $tag) {
360 break 3; /* switch switch while */
364 /* this shouldn't happen */
365 $response[$found_tag] = $arg;
366 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
368 $resultlist[] = $data;
370 $aResponse[$found_tag] = $resultlist;
371 $data = $resultlist = array();
372 if ($found_tag == $tag) {
373 break 3; /* switch switch while */
377 $read = sqimap_fgets($imap_stream);
378 if ($read === false) { /* error */
379 break 3; /* switch switch while */
382 } // end case $tag{0}
386 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
387 /* check for literal */
388 $s = substr($read,-3);
389 $fetch_data = array();
390 do { /* outer loop, continue until next untagged fetch
392 do { /* innerloop for fetching literals. with this loop
393 we prohibid that literal responses appear in the
394 outer loop so we can trust the untagged and
395 tagged info provided by $read */
396 if ($s === "}\r\n") {
397 $j = strrpos($read,'{');
398 $iLit = substr($read,$j+
1,-3);
399 $fetch_data[] = $read;
400 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
401 if ($sLiteral === false) { /* error */
402 break 4; /* while while switch while */
404 /* backwards compattibility */
405 $aLiteral = explode("\n", $sLiteral);
406 /* release not neaded data */
408 foreach ($aLiteral as $line) {
409 $fetch_data[] = $line ."\n";
411 /* release not neaded data */
413 /* next fgets belongs to this fetch because
414 we just got the exact literalsize and there
415 must follow data to complete the response */
416 $read = sqimap_fgets($imap_stream);
417 if ($read === false) { /* error */
418 break 4; /* while while switch while */
420 $fetch_data[] = $read;
422 $fetch_data[] = $read;
424 /* retrieve next line and check in the while
425 statements if it belongs to this fetch response */
426 $read = sqimap_fgets($imap_stream);
427 if ($read === false) { /* error */
428 break 4; /* while while switch while */
430 /* check for next untagged reponse and break */
431 if ($read{0} == '*') break 2;
432 $s = substr($read,-3);
433 } while ($s === "}\r\n");
434 $s = substr($read,-3);
435 } while ($read{0} !== '*' &&
436 substr($read,0,strlen($tag)) !== $tag);
437 $resultlist[] = $fetch_data;
438 /* release not neaded data */
441 $s = substr($read,-3);
443 if ($s === "}\r\n") {
444 $j = strrpos($read,'{');
445 $iLit = substr($read,$j+
1,-3);
447 $sLiteral = fread($imap_stream,$iLit);
448 if ($sLiteral === false) { /* error */
450 break 3; /* while switch while */
453 $data[] = sqimap_fgets($imap_stream);
457 $read = sqimap_fgets($imap_stream);
458 if ($read === false) {
459 break 3; /* while switch while */
460 } else if ($read{0} == '*') {
463 $s = substr($read,-3);
464 } while ($s === "}\r\n");
472 /* error processing in case $read is false */
473 if ($read === false) {
475 set_up_language($squirrelmail_language);
476 require_once(SM_PATH
. 'functions/display_messages.php');
477 $string = "<b><font color=$color[2]>\n" .
478 _("ERROR : Connection dropped by imap-server.") .
481 htmlspecialchars($query) . '<br>' . "</font><br>\n";
482 error_box($string,$color);
486 /* Set $resultlist array */
488 //$resultlist[] = $data;
490 elseif (empty($resultlist)) {
491 $resultlist[] = array();
494 /* Return result or handle errors */
495 if ($handle_errors == false) {
497 return( $resultlist );
499 switch ($response[$tag])
505 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
506 if (strstr($message[$tag], 'command resulted in') === false) {
507 set_up_language($squirrelmail_language);
508 require_once(SM_PATH
. 'functions/display_messages.php');
509 $string = "<b><font color=$color[2]>\n" .
510 _("ERROR : Could not complete request.") .
513 htmlspecialchars($query) . '<br>' .
514 _("Reason Given: ") .
515 htmlspecialchars($message[$tag]) . "</font><br>\n";
516 error_box($string,$color);
517 echo '</body></html>';
522 set_up_language($squirrelmail_language);
523 require_once(SM_PATH
. 'functions/display_messages.php');
524 $string = "<b><font color=$color[2]>\n" .
525 _("ERROR : Bad or malformed request.") .
528 htmlspecialchars($query) . '<br>' .
529 _("Server responded: ") .
530 htmlspecialchars($message[$tag]) . "</font><br>\n";
531 error_box($string,$color);
532 echo '</body></html>';
535 set_up_language($squirrelmail_language);
536 require_once(SM_PATH
. 'functions/display_messages.php');
537 $string = "<b><font color=$color[2]>\n" .
538 _("ERROR : Imap server closed the connection.") .
541 htmlspecialchars($query) . '<br>' .
542 _("Server responded: ") .
543 htmlspecialchars($message[$tag]) . "</font><br>\n";
544 error_box($string,$color);
545 echo '</body></html>';
548 set_up_language($squirrelmail_language);
549 require_once(SM_PATH
. 'functions/display_messages.php');
550 $string = "<b><font color=$color[2]>\n" .
551 _("ERROR : Unknown imap response.") .
554 htmlspecialchars($query) . '<br>' .
555 _("Server responded: ") .
556 htmlspecialchars($message[$tag]) . "</font><br>\n";
557 error_box($string,$color);
558 /* the error is displayed but because we don't know the reponse we
559 return the result anyway */
565 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
566 &$response, &$message, $query = '',
567 $filter=false,$outputstream=false,$no_return=false) {
569 $tag_uid_a = explode(' ',trim($tag_uid));
570 $tag = $tag_uid_a[0];
572 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
573 $response, $message, $query,$filter,$outputstream,$no_return);
574 /* sqimap_read_data should be called for one response
575 but since it just calls sqimap_retrieve_imap_response which
576 handles multiple responses we need to check for that
577 and merge the $res array IF they are seperated and
578 IF it was a FETCH response. */
580 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
581 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
582 // $result = array();
583 // foreach($res as $index=>$value) {
584 // $result = array_merge($result, $res["$index"]);
587 if (isset($result)) {
588 return $result[$tag];
596 * Logs the user into the imap server. If $hide is set, no error messages
597 * will be displayed. This function returns the imap connection handle.
599 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
600 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
602 if (!isset($onetimepad) ||
empty($onetimepad)) {
603 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
605 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
606 $host=$imap_server_address;
608 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
609 /* Use TLS by prefixing "tls://" to the hostname */
610 $imap_server_address = 'tls://' . $imap_server_address;
613 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
615 /* Do some error correction */
618 set_up_language($squirrelmail_language, true);
619 require_once(SM_PATH
. 'functions/display_messages.php');
620 $string = sprintf (_("Error connecting to IMAP server: %s.") .
621 "<br>\r\n", $imap_server_address) .
622 "$error_number : $error_string<br>\r\n";
623 logout_error($string,$color);
628 $server_info = fgets ($imap_stream, 1024);
630 /* Decrypt the password */
631 $password = OneTimePadDecrypt($password, $onetimepad);
633 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
634 // We're using some sort of authentication OTHER than plain or login
635 $tag=sqimap_session_id(false);
636 if ($imap_auth_mech == 'digest-md5') {
637 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
638 } elseif ($imap_auth_mech == 'cram-md5') {
639 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
641 fputs($imap_stream,$query);
642 $answer=sqimap_fgets($imap_stream);
643 // Trim the "+ " off the front
644 $response=explode(" ",$answer,3);
645 if ($response[0] == '+') {
646 // Got a challenge back
647 $challenge=$response[1];
648 if ($imap_auth_mech == 'digest-md5') {
649 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
650 } elseif ($imap_auth_mech == 'cram-md5') {
651 $reply = cram_md5_response($username,$password,$challenge);
653 fputs($imap_stream,$reply);
654 $read=sqimap_fgets($imap_stream);
655 if ($imap_auth_mech == 'digest-md5') {
656 // DIGEST-MD5 has an extra step..
657 if (substr($read,0,1) == '+') { // OK so far..
658 fputs($imap_stream,"\r\n");
659 $read=sqimap_fgets($imap_stream);
662 $results=explode(" ",$read,3);
663 $response=$results[1];
664 $message=$results[2];
666 // Fake the response, so the error trap at the bottom will work
668 $message='IMAP server does not appear to support the authentication method selected.';
669 $message .= ' Please contact your system administrator.';
671 } elseif ($imap_auth_mech == 'login') {
672 // Original IMAP login code
673 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
674 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
675 } elseif ($imap_auth_mech == 'plain') {
676 /* Replace this with SASL PLAIN if it ever gets implemented */
678 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
681 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
684 /* If the connection was not successful, lets see why */
685 if ($response != 'OK') {
687 if ($response != 'NO') {
688 /* "BAD" and anything else gets reported here. */
689 $message = htmlspecialchars($message);
690 set_up_language($squirrelmail_language, true);
691 require_once(SM_PATH
. 'functions/display_messages.php');
692 if ($response == 'BAD') {
693 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
695 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
697 if (isset($read) && is_array($read)) {
698 $string .= '<br>' . _("Read data:") . "<br>\n";
699 foreach ($read as $line) {
700 $string .= htmlspecialchars($line) . "<br>\n";
703 error_box($string,$color);
707 * If the user does not log in with the correct
708 * username and password it is not possible to get the
709 * correct locale from the user's preferences.
710 * Therefore, apply the same hack as on the login
713 * $squirrelmail_language is set by a cookie when
714 * the user selects language and logs out
717 set_up_language($squirrelmail_language, true);
718 include_once(SM_PATH
. 'functions/display_messages.php' );
720 logout_error( _("Unknown user or password incorrect.") );
730 /* Simply logs out the IMAP session */
731 function sqimap_logout ($imap_stream) {
732 /* Logout is not valid until the server returns 'BYE'
733 * If we don't have an imap_ stream we're already logged out */
734 if(isset($imap_stream) && $imap_stream)
735 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
738 function sqimap_capability($imap_stream, $capability='') {
739 global $sqimap_capabilities;
740 if (!is_array($sqimap_capabilities)) {
741 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
743 $c = explode(' ', $read[0]);
744 for ($i=2; $i < count($c); $i++
) {
745 $cap_list = explode('=', $c[$i]);
746 if (isset($cap_list[1])) {
747 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
749 $sqimap_capabilities[$cap_list[0]] = TRUE;
754 if (isset($sqimap_capabilities[$capability])) {
755 return $sqimap_capabilities[$capability];
760 return $sqimap_capabilities;
763 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
764 function sqimap_get_delimiter ($imap_stream = false) {
765 global $sqimap_delimiter, $optional_delimiter;
767 /* Use configured delimiter if set */
768 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
769 return $optional_delimiter;
772 /* Do some caching here */
773 if (!$sqimap_delimiter) {
774 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
776 * According to something that I can't find, this is supposed to work on all systems
777 * OS: This won't work in Courier IMAP.
778 * OS: According to rfc2342 response from NAMESPACE command is:
779 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
780 * OS: We want to lookup all personal NAMESPACES...
782 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
783 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
784 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
787 $pna = explode(')(', $pn);
788 while (list($k, $v) = each($pna)) {
789 $lst = explode('"', $v);
790 if (isset($lst[3])) {
791 $pn[$lst[1]] = $lst[3];
797 $sqimap_delimiter = $pn[0];
799 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
800 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
801 $quote_position = strpos ($read[0], '"');
802 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
805 return $sqimap_delimiter;
809 /* This is a straight copy of imap_mailbox.php:encode_mailbox_name() */
810 function sqimap_encode_mailbox_name($what)
812 if (ereg("[\"\\\r\n]", $what))
813 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
814 return '"' . $what . '"'; /* 4.3 quoted string form */
818 /* Gets the number of messages in the current mailbox. */
819 function sqimap_get_num_messages ($imap_stream, $mailbox) {
820 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
821 for ($i = 0; $i < count($read_ary); $i++
) {
822 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
826 return false; //"BUG! Couldn't get number of messages in $mailbox!";
830 function parseAddress($address, $max=0) {
833 $iCnt = strlen($address);
834 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
835 $aReplace = array(' (',' <',' ,',' ;',' :');
836 $address = str_replace($aSpecials,$aReplace,$address);
837 $i = $iAddrFound = $bGroup = 0;
839 $cChar = $address{$i};
843 $iEnd = strpos($address,'>',$i+
1);
845 $sToken = substr($address,$i);
848 $sToken = substr($address,$i,$iEnd - $i +
1);
851 $sToken = str_replace($aReplace, $aSpecials,$sToken);
852 $aTokens[] = $sToken;
855 $iEnd = strpos($address,$cChar,$i+
1);
857 // skip escaped quotes
858 $prev_char = $address{$iEnd-1};
859 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
860 $iEnd = strpos($address,$cChar,$iEnd+
1);
862 $prev_char = $address{$iEnd-1};
869 $sToken = substr($address,$i);
872 // also remove the surrounding quotes
873 $sToken = substr($address,$i+
1,$iEnd - $i -1);
876 $sToken = str_replace($aReplace, $aSpecials,$sToken);
877 if ($sToken) $aTokens[] = $sToken;
880 $iEnd = strpos($address,')',$i);
882 $sToken = substr($address,$i);
885 $sToken = substr($address,$i,$iEnd - $i +
1);
888 $sToken = str_replace($aReplace, $aSpecials,$sToken);
889 $aTokens[] = $sToken;
899 if ($max && $max == $iAddrFound) {
911 $iEnd = strpos($address,' ',$i+
1);
913 $sToken = trim(substr($address,$i,$iEnd - $i));
916 $sToken = trim(substr($address,$i));
919 if ($sToken) $aTokens[] = $sToken;
923 $sPersonal = $sEmail = $sComment = $sGroup = '';
924 $aStack = $aComment = array();
925 foreach ($aTokens as $sToken) {
926 if ($max && $max == count($aAddress)) {
938 $aComment[] = substr($sToken,1,-1);
942 $sEmail = trim(implode(' ',$aStack));
943 $aAddress[] = array($sGroup,$sEmail);
944 $aStack = $aComment = array();
950 while (count($aStack) && !$sEmail) {
951 $sEmail = trim(array_pop($aStack));
954 if (count($aStack)) {
955 $sPersonal = trim(implode('',$aStack));
959 if (!$sPersonal && count($aComment)) {
960 $sComment = implode(' ',$aComment);
961 $sPersonal .= $sComment;
963 $aAddress[] = array($sEmail,$sPersonal);
964 $sPersonal = $sComment = $sEmail = '';
965 $aStack = $aComment = array();
968 $sGroup = implode(' ',$aStack); break;
972 $sEmail = trim(substr($sToken,1,-1));
977 default: $aStack[] = $sToken; break;
980 /* now do the action again for the last address */
982 while (count($aStack) && !$sEmail) {
983 $sEmail = trim(array_pop($aStack));
986 if (count($aStack)) {
987 $sPersonal = trim(implode('',$aStack));
991 if (!$sPersonal && count($aComment)) {
992 $sComment = implode(' ',$aComment);
993 $sPersonal .= $sComment;
995 $aAddress[] = array($sEmail,$sPersonal);
1002 * Returns the number of unseen messages in this folder
1004 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1005 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
1007 $regs = array(false, false);
1008 while (isset($read_ary[$i])) {
1009 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
1018 * Returns the number of unseen/total messages in this folder
1020 function sqimap_status_messages ($imap_stream, $mailbox) {
1021 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1023 $messages = $unseen = $recent = false;
1024 $regs = array(false,false);
1025 while (isset($read_ary[$i])) {
1026 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1029 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1030 $messages = $regs[1];
1032 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1037 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1042 * Saves a message to a given folder -- used for saving sent messages
1044 function sqimap_append ($imap_stream, $sent_folder, $length) {
1045 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1046 $tmp = fgets ($imap_stream, 1024);
1049 function sqimap_append_done ($imap_stream, $folder='') {
1050 global $squirrelmail_language, $color;
1051 fputs ($imap_stream, "\r\n");
1052 $tmp = fgets ($imap_stream, 1024);
1053 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1054 set_up_language($squirrelmail_language);
1055 require_once(SM_PATH
. 'functions/display_messages.php');
1057 if ($regs[2] == 'NO') {
1058 $string = "<b><font color=$color[2]>\n" .
1059 _("ERROR : Could not append message to") ." $folder." .
1061 _("Server responded: ") .
1063 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1064 $string .= _("Solution: ") .
1065 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1068 $string .= "</font>\n";
1069 error_box($string,$color);
1071 $string = "<b><font color=$color[2]>\n" .
1072 _("ERROR : Bad or malformed request.") .
1074 _("Server responded: ") .
1075 $tmp . "</font><br>\n";
1076 error_box($string,$color);
1082 function sqimap_get_user_server ($imap_server, $username) {
1083 if (substr($imap_server, 0, 4) != "map:") {
1084 return $imap_server;
1086 $function = substr($imap_server, 4);
1087 return $function($username);
1090 /* This is an example that gets imapservers from yellowpages (NIS).
1091 * you can simple put map:map_yp_alias in your $imap_server_address
1092 * in config.php use your own function instead map_yp_alias to map your
1093 * LDAP whatever way to find the users imapserver. */
1095 function map_yp_alias($username) {
1096 $yp = `ypmatch
$username aliases`
;
1097 return chop(substr($yp, strlen($username)+
1));