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>';
308 function sqimap_error_box($title, $query = '', $message_title = '', $message = '')
310 global $color, $squirrelmail_language;
312 set_up_language($squirrelmail_language);
313 require_once(SM_PATH
. 'functions/display_messages.php');
314 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
316 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
317 if ($message_title != '')
318 $string .= $message_title;
320 $string .= htmlspecialchars($message);
321 $string .= "</font><br>\n";
322 error_box($string,$color);
326 * Reads the output from the IMAP stream. If handle_errors is set to true,
327 * this will also handle all errors that are received. If it is not set,
328 * the errors will be sent back through $response and $message
331 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
332 &$response, &$message, $query = '',
333 $filter = false, $outputstream = false, $no_return = false) {
334 global $color, $squirrelmail_language;
336 if (!is_array($message)) $message = array();
337 if (!is_array($response)) $response = array();
338 $resultlist = array();
340 $read = sqimap_fgets($imap_stream);
348 $read = sqimap_fgets($imap_stream);
353 /* get the command */
356 $s = substr($read,$i);
357 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
358 $arg = substr($s,0,$j);
360 $found_tag = substr($read,0,$i-1);
369 $response[$found_tag] = $arg;
370 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
372 $resultlist[] = $data;
374 $aResponse[$found_tag] = $resultlist;
375 $data = $resultlist = array();
376 if ($found_tag == $tag) {
377 break 3; /* switch switch while */
381 /* this shouldn't happen */
382 $response[$found_tag] = $arg;
383 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
385 $resultlist[] = $data;
387 $aResponse[$found_tag] = $resultlist;
388 $data = $resultlist = array();
389 if ($found_tag == $tag) {
390 break 3; /* switch switch while */
394 $read = sqimap_fgets($imap_stream);
395 if ($read === false) { /* error */
396 break 3; /* switch switch while */
399 } // end case $tag{0}
403 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
404 /* check for literal */
405 $s = substr($read,-3);
406 $fetch_data = array();
407 do { /* outer loop, continue until next untagged fetch
409 do { /* innerloop for fetching literals. with this loop
410 we prohibid that literal responses appear in the
411 outer loop so we can trust the untagged and
412 tagged info provided by $read */
413 if ($s === "}\r\n") {
414 $j = strrpos($read,'{');
415 $iLit = substr($read,$j+
1,-3);
416 $fetch_data[] = $read;
417 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
418 if ($sLiteral === false) { /* error */
419 break 4; /* while while switch while */
421 /* backwards compattibility */
422 $aLiteral = explode("\n", $sLiteral);
423 /* release not neaded data */
425 foreach ($aLiteral as $line) {
426 $fetch_data[] = $line ."\n";
428 /* release not neaded data */
430 /* next fgets belongs to this fetch because
431 we just got the exact literalsize and there
432 must follow data to complete the response */
433 $read = sqimap_fgets($imap_stream);
434 if ($read === false) { /* error */
435 break 4; /* while while switch while */
437 $fetch_data[] = $read;
439 $fetch_data[] = $read;
441 /* retrieve next line and check in the while
442 statements if it belongs to this fetch response */
443 $read = sqimap_fgets($imap_stream);
444 if ($read === false) { /* error */
445 break 4; /* while while switch while */
447 /* check for next untagged reponse and break */
448 if ($read{0} == '*') break 2;
449 $s = substr($read,-3);
450 } while ($s === "}\r\n");
451 $s = substr($read,-3);
452 } while ($read{0} !== '*' &&
453 substr($read,0,strlen($tag)) !== $tag);
454 $resultlist[] = $fetch_data;
455 /* release not neaded data */
458 $s = substr($read,-3);
460 if ($s === "}\r\n") {
461 $j = strrpos($read,'{');
462 $iLit = substr($read,$j+
1,-3);
464 $sLiteral = fread($imap_stream,$iLit);
465 if ($sLiteral === false) { /* error */
467 break 3; /* while switch while */
470 $data[] = sqimap_fgets($imap_stream);
474 $read = sqimap_fgets($imap_stream);
475 if ($read === false) {
476 break 3; /* while switch while */
477 } else if ($read{0} == '*') {
480 $s = substr($read,-3);
481 } while ($s === "}\r\n");
489 /* error processing in case $read is false */
490 if ($read === false) {
492 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
496 /* Set $resultlist array */
498 //$resultlist[] = $data;
500 elseif (empty($resultlist)) {
501 $resultlist[] = array();
504 /* Return result or handle errors */
505 if ($handle_errors == false) {
507 return( $resultlist ); //?? Why this?
509 switch ($response[$tag]) {
514 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
515 if (strstr($message[$tag], 'command resulted in') === false) {
516 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
517 echo '</body></html>';
522 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
523 echo '</body></html>';
526 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
527 echo '</body></html>';
530 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
531 /* the error is displayed but because we don't know the reponse we
532 return the result anyway */
538 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
539 &$response, &$message, $query = '',
540 $filter=false,$outputstream=false,$no_return=false) {
542 $tag_uid_a = explode(' ',trim($tag_uid));
543 $tag = $tag_uid_a[0];
545 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
546 $response, $message, $query,$filter,$outputstream,$no_return);
547 /* sqimap_read_data should be called for one response
548 but since it just calls sqimap_retrieve_imap_response which
549 handles multiple responses we need to check for that
550 and merge the $res array IF they are seperated and
551 IF it was a FETCH response. */
553 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
554 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
555 // $result = array();
556 // foreach($res as $index=>$value) {
557 // $result = array_merge($result, $res["$index"]);
560 if (isset($result)) {
561 return $result[$tag];
569 * Logs the user into the imap server. If $hide is set, no error messages
570 * will be displayed. This function returns the imap connection handle.
572 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
573 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
575 if (!isset($onetimepad) ||
empty($onetimepad)) {
576 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
578 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
579 $host=$imap_server_address;
581 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
582 /* Use TLS by prefixing "tls://" to the hostname */
583 $imap_server_address = 'tls://' . $imap_server_address;
586 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
588 /* Do some error correction */
591 set_up_language($squirrelmail_language, true);
592 require_once(SM_PATH
. 'functions/display_messages.php');
593 $string = sprintf (_("Error connecting to IMAP server: %s.") .
594 "<br>\r\n", $imap_server_address) .
595 "$error_number : $error_string<br>\r\n";
596 logout_error($string,$color);
601 $server_info = fgets ($imap_stream, 1024);
603 /* Decrypt the password */
604 $password = OneTimePadDecrypt($password, $onetimepad);
606 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
607 // We're using some sort of authentication OTHER than plain or login
608 $tag=sqimap_session_id(false);
609 if ($imap_auth_mech == 'digest-md5') {
610 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
611 } elseif ($imap_auth_mech == 'cram-md5') {
612 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
614 fputs($imap_stream,$query);
615 $answer=sqimap_fgets($imap_stream);
616 // Trim the "+ " off the front
617 $response=explode(" ",$answer,3);
618 if ($response[0] == '+') {
619 // Got a challenge back
620 $challenge=$response[1];
621 if ($imap_auth_mech == 'digest-md5') {
622 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
623 } elseif ($imap_auth_mech == 'cram-md5') {
624 $reply = cram_md5_response($username,$password,$challenge);
626 fputs($imap_stream,$reply);
627 $read=sqimap_fgets($imap_stream);
628 if ($imap_auth_mech == 'digest-md5') {
629 // DIGEST-MD5 has an extra step..
630 if (substr($read,0,1) == '+') { // OK so far..
631 fputs($imap_stream,"\r\n");
632 $read=sqimap_fgets($imap_stream);
635 $results=explode(" ",$read,3);
636 $response=$results[1];
637 $message=$results[2];
639 // Fake the response, so the error trap at the bottom will work
641 $message='IMAP server does not appear to support the authentication method selected.';
642 $message .= ' Please contact your system administrator.';
644 } elseif ($imap_auth_mech == 'login') {
645 // Original IMAP login code
646 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
647 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
648 } elseif ($imap_auth_mech == 'plain') {
649 /* Replace this with SASL PLAIN if it ever gets implemented */
651 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
654 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
657 /* If the connection was not successful, lets see why */
658 if ($response != 'OK') {
660 if ($response != 'NO') {
661 /* "BAD" and anything else gets reported here. */
662 $message = htmlspecialchars($message);
663 set_up_language($squirrelmail_language, true);
664 require_once(SM_PATH
. 'functions/display_messages.php');
665 if ($response == 'BAD') {
666 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
668 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
670 if (isset($read) && is_array($read)) {
671 $string .= '<br>' . _("Read data:") . "<br>\n";
672 foreach ($read as $line) {
673 $string .= htmlspecialchars($line) . "<br>\n";
676 error_box($string,$color);
680 * If the user does not log in with the correct
681 * username and password it is not possible to get the
682 * correct locale from the user's preferences.
683 * Therefore, apply the same hack as on the login
686 * $squirrelmail_language is set by a cookie when
687 * the user selects language and logs out
690 set_up_language($squirrelmail_language, true);
691 include_once(SM_PATH
. 'functions/display_messages.php' );
693 logout_error( _("Unknown user or password incorrect.") );
703 /* Simply logs out the IMAP session */
704 function sqimap_logout ($imap_stream) {
705 /* Logout is not valid until the server returns 'BYE'
706 * If we don't have an imap_ stream we're already logged out */
707 if(isset($imap_stream) && $imap_stream)
708 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
711 function sqimap_capability($imap_stream, $capability='') {
712 global $sqimap_capabilities;
713 if (!is_array($sqimap_capabilities)) {
714 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
716 $c = explode(' ', $read[0]);
717 for ($i=2; $i < count($c); $i++
) {
718 $cap_list = explode('=', $c[$i]);
719 if (isset($cap_list[1])) {
720 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
722 $sqimap_capabilities[$cap_list[0]] = TRUE;
727 if (isset($sqimap_capabilities[$capability])) {
728 return $sqimap_capabilities[$capability];
733 return $sqimap_capabilities;
736 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
737 function sqimap_get_delimiter ($imap_stream = false) {
738 global $sqimap_delimiter, $optional_delimiter;
740 /* Use configured delimiter if set */
741 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
742 return $optional_delimiter;
745 /* Do some caching here */
746 if (!$sqimap_delimiter) {
747 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
749 * According to something that I can't find, this is supposed to work on all systems
750 * OS: This won't work in Courier IMAP.
751 * OS: According to rfc2342 response from NAMESPACE command is:
752 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
753 * OS: We want to lookup all personal NAMESPACES...
755 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
756 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
757 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
760 $pna = explode(')(', $pn);
761 while (list($k, $v) = each($pna)) {
762 $lst = explode('"', $v);
763 if (isset($lst[3])) {
764 $pn[$lst[1]] = $lst[3];
770 $sqimap_delimiter = $pn[0];
772 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
773 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
774 $quote_position = strpos ($read[0], '"');
775 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
778 return $sqimap_delimiter;
782 function sqimap_encode_mailbox_name($what)
784 if (ereg("[\"\\\r\n]", $what))
785 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
786 return '"' . $what . '"'; /* 4.3 quoted string form */
790 /* Gets the number of messages in the current mailbox. */
791 function sqimap_get_num_messages ($imap_stream, $mailbox) {
792 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
793 for ($i = 0; $i < count($read_ary); $i++
) {
794 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
798 return false; //"BUG! Couldn't get number of messages in $mailbox!";
802 function parseAddress($address, $max=0) {
805 $iCnt = strlen($address);
806 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
807 $aReplace = array(' (',' <',' ,',' ;',' :');
808 $address = str_replace($aSpecials,$aReplace,$address);
809 $i = $iAddrFound = $bGroup = 0;
811 $cChar = $address{$i};
815 $iEnd = strpos($address,'>',$i+
1);
817 $sToken = substr($address,$i);
820 $sToken = substr($address,$i,$iEnd - $i +
1);
823 $sToken = str_replace($aReplace, $aSpecials,$sToken);
824 $aTokens[] = $sToken;
827 $iEnd = strpos($address,$cChar,$i+
1);
829 // skip escaped quotes
830 $prev_char = $address{$iEnd-1};
831 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
832 $iEnd = strpos($address,$cChar,$iEnd+
1);
834 $prev_char = $address{$iEnd-1};
841 $sToken = substr($address,$i);
844 // also remove the surrounding quotes
845 $sToken = substr($address,$i+
1,$iEnd - $i -1);
848 $sToken = str_replace($aReplace, $aSpecials,$sToken);
849 if ($sToken) $aTokens[] = $sToken;
852 $iEnd = strpos($address,')',$i);
854 $sToken = substr($address,$i);
857 $sToken = substr($address,$i,$iEnd - $i +
1);
860 $sToken = str_replace($aReplace, $aSpecials,$sToken);
861 $aTokens[] = $sToken;
871 if ($max && $max == $iAddrFound) {
883 $iEnd = strpos($address,' ',$i+
1);
885 $sToken = trim(substr($address,$i,$iEnd - $i));
888 $sToken = trim(substr($address,$i));
891 if ($sToken) $aTokens[] = $sToken;
895 $sPersonal = $sEmail = $sComment = $sGroup = '';
896 $aStack = $aComment = array();
897 foreach ($aTokens as $sToken) {
898 if ($max && $max == count($aAddress)) {
910 $aComment[] = substr($sToken,1,-1);
914 $sEmail = trim(implode(' ',$aStack));
915 $aAddress[] = array($sGroup,$sEmail);
916 $aStack = $aComment = array();
922 while (count($aStack) && !$sEmail) {
923 $sEmail = trim(array_pop($aStack));
926 if (count($aStack)) {
927 $sPersonal = trim(implode('',$aStack));
931 if (!$sPersonal && count($aComment)) {
932 $sComment = implode(' ',$aComment);
933 $sPersonal .= $sComment;
935 $aAddress[] = array($sEmail,$sPersonal);
936 $sPersonal = $sComment = $sEmail = '';
937 $aStack = $aComment = array();
940 $sGroup = implode(' ',$aStack); break;
944 $sEmail = trim(substr($sToken,1,-1));
949 default: $aStack[] = $sToken; break;
952 /* now do the action again for the last address */
954 while (count($aStack) && !$sEmail) {
955 $sEmail = trim(array_pop($aStack));
958 if (count($aStack)) {
959 $sPersonal = trim(implode('',$aStack));
963 if (!$sPersonal && count($aComment)) {
964 $sComment = implode(' ',$aComment);
965 $sPersonal .= $sComment;
967 $aAddress[] = array($sEmail,$sPersonal);
974 * Returns the number of unseen messages in this folder
976 function sqimap_unseen_messages ($imap_stream, $mailbox) {
977 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
979 $regs = array(false, false);
980 while (isset($read_ary[$i])) {
981 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
990 * Returns the number of total/unseen/recent messages in this folder
992 function sqimap_status_messages ($imap_stream, $mailbox) {
993 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
995 $messages = $unseen = $recent = false;
996 $regs = array(false,false);
997 while (isset($read_ary[$i])) {
998 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1001 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1002 $messages = $regs[1];
1004 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1009 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1014 * Saves a message to a given folder -- used for saving sent messages
1016 function sqimap_append ($imap_stream, $sent_folder, $length) {
1017 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1018 $tmp = fgets ($imap_stream, 1024);
1021 function sqimap_append_done ($imap_stream, $folder='') {
1022 global $squirrelmail_language, $color;
1023 fputs ($imap_stream, "\r\n");
1024 $tmp = fgets ($imap_stream, 1024);
1025 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1026 set_up_language($squirrelmail_language);
1027 require_once(SM_PATH
. 'functions/display_messages.php');
1029 if ($regs[2] == 'NO') {
1030 $string = "<b><font color=$color[2]>\n" .
1031 _("ERROR : Could not append message to") ." $folder." .
1033 _("Server responded: ") .
1035 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1036 $string .= _("Solution: ") .
1037 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1040 $string .= "</font>\n";
1041 error_box($string,$color);
1043 $string = "<b><font color=$color[2]>\n" .
1044 _("ERROR : Bad or malformed request.") .
1046 _("Server responded: ") .
1047 $tmp . "</font><br>\n";
1048 error_box($string,$color);
1054 function sqimap_get_user_server ($imap_server, $username) {
1055 if (substr($imap_server, 0, 4) != "map:") {
1056 return $imap_server;
1058 $function = substr($imap_server, 4);
1059 return $function($username);
1062 /* This is an example that gets imapservers from yellowpages (NIS).
1063 * you can simple put map:map_yp_alias in your $imap_server_address
1064 * in config.php use your own function instead map_yp_alias to map your
1065 * LDAP whatever way to find the users imapserver. */
1067 function map_yp_alias($username) {
1068 $yp = `ypmatch
$username aliases`
;
1069 return chop(substr($yp, strlen($username)+
1));