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 // see php bug 24033. They changed fread behaviour %$^&$%
191 $iBufferSize = 780; // multiple of 78 in case of base64 decoding.
193 $iRet = $iSize - $iBufferSize;
196 $results = $sReadRem = '';
197 $bFinished = $bBufferSizeAdapted = $bBufferIsOk = false;
198 while (($iRetrieved < ($iSize - $iBufferSize))) {
199 $sRead = fread($imap_stream,$iBufferSize);
204 $iRetrieved +
= $iBufferSize;
206 // in case line-endings do not appear at position 78 we adapt the buffersize so we can base64 decode on the fly
207 if (!$bBufferSizeAdapted) {
208 $i = strpos($sRead,"\n");
211 $iFragments = floor($iBufferSize / $i);
212 $iNewBufferSize = $iFragments * $i;
213 $iRemainder = $iNewBufferSize +
$i - $iBufferSize;
214 if ($iNewBufferSize == $iBufferSize) {
217 $iNewBufferSize = $iBufferSize;
218 $bBufferSizeAdapted = true;
220 if (!$bBufferIsOk && ($iRemainder +
$iBufferSize) < $iSize) {
221 $sReadRem = fread($imap_stream,$iRemainder);
222 } else if (!$bBufferIsOk) {
223 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
226 if (!$sReadRem && $sReadRem !== '') {
230 $iBufferSize = $iNewBufferSize;
231 $bBufferSizeAdapted = true;
233 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
241 $iRetrieved +
= $iRemainder;
247 if (is_resource($outputstream)) {
248 fwrite($outputstream,$sRead);
249 } else if ($outputstream == 'php://stdout') {
258 if (!$results && !$bFinished) {
259 $sRead = fread($imap_stream,($iSize - ($iRetrieved)));
264 if (is_resource($outputstream)) {
265 fwrite($outputstream,$sRead);
266 } else if ($outputstream == 'php://stdout') { // FIXME
277 /* obsolete function, inform plugins that use it */
278 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
279 &$response, &$message, $query = '') {
280 global $color, $squirrelmail_language;
281 set_up_language($squirrelmail_language);
282 require_once(SM_PATH
. 'functions/display_messages.php');
283 $string = "<b><font color=$color[2]>\n" .
284 _("ERROR : Bad function call.") .
287 'There is a plugin installed which make use of the <br>' .
288 'SquirrelMail internal function sqimap_read_data_list.<br>'.
289 'Please adapt the installed plugin and let it use<br>'.
290 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
291 'The following query was issued:<br>'.
292 htmlspecialchars($query) . '<br>' . "</font><br>\n";
293 error_box($string,$color);
294 echo '</body></html>';
298 function sqimap_error_box($title, $query = '', $message_title = '', $message = '')
300 global $color, $squirrelmail_language;
302 set_up_language($squirrelmail_language);
303 require_once(SM_PATH
. 'functions/display_messages.php');
304 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
306 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
307 if ($message_title != '')
308 $string .= $message_title;
310 $string .= htmlspecialchars($message);
311 $string .= "</font><br>\n";
312 error_box($string,$color);
316 * Reads the output from the IMAP stream. If handle_errors is set to true,
317 * this will also handle all errors that are received. If it is not set,
318 * the errors will be sent back through $response and $message
321 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
322 &$response, &$message, $query = '',
323 $filter = false, $outputstream = false, $no_return = false) {
324 global $color, $squirrelmail_language;
326 if (!is_array($message)) $message = array();
327 if (!is_array($response)) $response = array();
328 $resultlist = array();
330 $read = sqimap_fgets($imap_stream);
338 $read = sqimap_fgets($imap_stream);
343 /* get the command */
346 $s = substr($read,$i);
347 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
348 $arg = substr($s,0,$j);
350 $found_tag = substr($read,0,$i-1);
359 $response[$found_tag] = $arg;
360 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
362 $resultlist[] = $data;
364 $aResponse[$found_tag] = $resultlist;
365 $data = $resultlist = array();
366 if ($found_tag == $tag) {
367 break 3; /* switch switch while */
371 /* this shouldn't happen */
372 $response[$found_tag] = $arg;
373 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
375 $resultlist[] = $data;
377 $aResponse[$found_tag] = $resultlist;
378 $data = $resultlist = array();
379 if ($found_tag == $tag) {
380 break 3; /* switch switch while */
384 $read = sqimap_fgets($imap_stream);
385 if ($read === false) { /* error */
386 break 3; /* switch switch while */
389 } // end case $tag{0}
393 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
394 /* check for literal */
395 $s = substr($read,-3);
396 $fetch_data = array();
397 do { /* outer loop, continue until next untagged fetch
399 do { /* innerloop for fetching literals. with this loop
400 we prohibid that literal responses appear in the
401 outer loop so we can trust the untagged and
402 tagged info provided by $read */
403 if ($s === "}\r\n") {
404 $j = strrpos($read,'{');
405 $iLit = substr($read,$j+
1,-3);
406 $fetch_data[] = $read;
407 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
408 if ($sLiteral === false) { /* error */
409 break 4; /* while while switch while */
411 /* backwards compattibility */
412 $aLiteral = explode("\n", $sLiteral);
413 /* release not neaded data */
415 foreach ($aLiteral as $line) {
416 $fetch_data[] = $line ."\n";
418 /* release not neaded data */
420 /* next fgets belongs to this fetch because
421 we just got the exact literalsize and there
422 must follow data to complete the response */
423 $read = sqimap_fgets($imap_stream);
424 if ($read === false) { /* error */
425 break 4; /* while while switch while */
427 $fetch_data[] = $read;
429 $fetch_data[] = $read;
431 /* retrieve next line and check in the while
432 statements if it belongs to this fetch response */
433 $read = sqimap_fgets($imap_stream);
434 if ($read === false) { /* error */
435 break 4; /* while while switch while */
437 /* check for next untagged reponse and break */
438 if ($read{0} == '*') break 2;
439 $s = substr($read,-3);
440 } while ($s === "}\r\n");
441 $s = substr($read,-3);
442 } while ($read{0} !== '*' &&
443 substr($read,0,strlen($tag)) !== $tag);
444 $resultlist[] = $fetch_data;
445 /* release not neaded data */
448 $s = substr($read,-3);
450 if ($s === "}\r\n") {
451 $j = strrpos($read,'{');
452 $iLit = substr($read,$j+
1,-3);
454 $sLiteral = fread($imap_stream,$iLit);
455 if ($sLiteral === false) { /* error */
457 break 3; /* while switch while */
460 $data[] = sqimap_fgets($imap_stream);
464 $read = sqimap_fgets($imap_stream);
465 if ($read === false) {
466 break 3; /* while switch while */
467 } else if ($read{0} == '*') {
470 $s = substr($read,-3);
471 } while ($s === "}\r\n");
479 /* error processing in case $read is false */
480 if ($read === false) {
482 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
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 ); //?? Why this?
499 switch ($response[$tag]) {
504 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
505 if (strstr($message[$tag], 'command resulted in') === false) {
506 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
507 echo '</body></html>';
512 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
513 echo '</body></html>';
516 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
517 echo '</body></html>';
520 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
521 /* the error is displayed but because we don't know the reponse we
522 return the result anyway */
528 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
529 &$response, &$message, $query = '',
530 $filter=false,$outputstream=false,$no_return=false) {
532 $tag_uid_a = explode(' ',trim($tag_uid));
533 $tag = $tag_uid_a[0];
535 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
536 $response, $message, $query,$filter,$outputstream,$no_return);
537 /* sqimap_read_data should be called for one response
538 but since it just calls sqimap_retrieve_imap_response which
539 handles multiple responses we need to check for that
540 and merge the $res array IF they are seperated and
541 IF it was a FETCH response. */
543 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
544 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
545 // $result = array();
546 // foreach($res as $index=>$value) {
547 // $result = array_merge($result, $res["$index"]);
550 if (isset($result)) {
551 return $result[$tag];
559 * Logs the user into the imap server. If $hide is set, no error messages
560 * will be displayed. This function returns the imap connection handle.
562 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
563 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
565 if (!isset($onetimepad) ||
empty($onetimepad)) {
566 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
568 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
569 $host=$imap_server_address;
571 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
572 /* Use TLS by prefixing "tls://" to the hostname */
573 $imap_server_address = 'tls://' . $imap_server_address;
576 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
578 /* Do some error correction */
581 set_up_language($squirrelmail_language, true);
582 require_once(SM_PATH
. 'functions/display_messages.php');
583 $string = sprintf (_("Error connecting to IMAP server: %s.") .
584 "<br>\r\n", $imap_server_address) .
585 "$error_number : $error_string<br>\r\n";
586 logout_error($string,$color);
591 $server_info = fgets ($imap_stream, 1024);
593 /* Decrypt the password */
594 $password = OneTimePadDecrypt($password, $onetimepad);
596 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
597 // We're using some sort of authentication OTHER than plain or login
598 $tag=sqimap_session_id(false);
599 if ($imap_auth_mech == 'digest-md5') {
600 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
601 } elseif ($imap_auth_mech == 'cram-md5') {
602 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
604 fputs($imap_stream,$query);
605 $answer=sqimap_fgets($imap_stream);
606 // Trim the "+ " off the front
607 $response=explode(" ",$answer,3);
608 if ($response[0] == '+') {
609 // Got a challenge back
610 $challenge=$response[1];
611 if ($imap_auth_mech == 'digest-md5') {
612 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
613 } elseif ($imap_auth_mech == 'cram-md5') {
614 $reply = cram_md5_response($username,$password,$challenge);
616 fputs($imap_stream,$reply);
617 $read=sqimap_fgets($imap_stream);
618 if ($imap_auth_mech == 'digest-md5') {
619 // DIGEST-MD5 has an extra step..
620 if (substr($read,0,1) == '+') { // OK so far..
621 fputs($imap_stream,"\r\n");
622 $read=sqimap_fgets($imap_stream);
625 $results=explode(" ",$read,3);
626 $response=$results[1];
627 $message=$results[2];
629 // Fake the response, so the error trap at the bottom will work
631 $message='IMAP server does not appear to support the authentication method selected.';
632 $message .= ' Please contact your system administrator.';
634 } elseif ($imap_auth_mech == 'login') {
635 // Original IMAP login code
636 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
637 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
638 } elseif ($imap_auth_mech == 'plain') {
639 /* Replace this with SASL PLAIN if it ever gets implemented */
641 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
644 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
647 /* If the connection was not successful, lets see why */
648 if ($response != 'OK') {
650 if ($response != 'NO') {
651 /* "BAD" and anything else gets reported here. */
652 $message = htmlspecialchars($message);
653 set_up_language($squirrelmail_language, true);
654 require_once(SM_PATH
. 'functions/display_messages.php');
655 if ($response == 'BAD') {
656 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
658 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
660 if (isset($read) && is_array($read)) {
661 $string .= '<br>' . _("Read data:") . "<br>\n";
662 foreach ($read as $line) {
663 $string .= htmlspecialchars($line) . "<br>\n";
666 error_box($string,$color);
670 * If the user does not log in with the correct
671 * username and password it is not possible to get the
672 * correct locale from the user's preferences.
673 * Therefore, apply the same hack as on the login
676 * $squirrelmail_language is set by a cookie when
677 * the user selects language and logs out
680 set_up_language($squirrelmail_language, true);
681 include_once(SM_PATH
. 'functions/display_messages.php' );
683 logout_error( _("Unknown user or password incorrect.") );
693 /* Simply logs out the IMAP session */
694 function sqimap_logout ($imap_stream) {
695 /* Logout is not valid until the server returns 'BYE'
696 * If we don't have an imap_ stream we're already logged out */
697 if(isset($imap_stream) && $imap_stream)
698 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
701 function sqimap_capability($imap_stream, $capability='') {
702 global $sqimap_capabilities;
703 if (!is_array($sqimap_capabilities)) {
704 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
706 $c = explode(' ', $read[0]);
707 for ($i=2; $i < count($c); $i++
) {
708 $cap_list = explode('=', $c[$i]);
709 if (isset($cap_list[1])) {
710 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
712 $sqimap_capabilities[$cap_list[0]] = TRUE;
717 if (isset($sqimap_capabilities[$capability])) {
718 return $sqimap_capabilities[$capability];
723 return $sqimap_capabilities;
726 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
727 function sqimap_get_delimiter ($imap_stream = false) {
728 global $sqimap_delimiter, $optional_delimiter;
730 /* Use configured delimiter if set */
731 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
732 return $optional_delimiter;
735 /* Do some caching here */
736 if (!$sqimap_delimiter) {
737 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
739 * According to something that I can't find, this is supposed to work on all systems
740 * OS: This won't work in Courier IMAP.
741 * OS: According to rfc2342 response from NAMESPACE command is:
742 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
743 * OS: We want to lookup all personal NAMESPACES...
745 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
746 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
747 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
750 $pna = explode(')(', $pn);
751 while (list($k, $v) = each($pna)) {
752 $lst = explode('"', $v);
753 if (isset($lst[3])) {
754 $pn[$lst[1]] = $lst[3];
760 $sqimap_delimiter = $pn[0];
762 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
763 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
764 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
765 $quote_position = strpos ($read[0], '"');
766 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
769 return $sqimap_delimiter;
773 function sqimap_encode_mailbox_name($what)
775 if (ereg("[\"\\\r\n]", $what))
776 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
777 return '"' . $what . '"'; /* 4.3 quoted string form */
781 /* Gets the number of messages in the current mailbox. */
782 function sqimap_get_num_messages ($imap_stream, $mailbox) {
783 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
784 for ($i = 0; $i < count($read_ary); $i++
) {
785 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
789 return false; //"BUG! Couldn't get number of messages in $mailbox!";
793 function parseAddress($address, $max=0) {
796 $iCnt = strlen($address);
797 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
798 $aReplace = array(' (',' <',' ,',' ;',' :');
799 $address = str_replace($aSpecials,$aReplace,$address);
800 $i = $iAddrFound = $bGroup = 0;
802 $cChar = $address{$i};
806 $iEnd = strpos($address,'>',$i+
1);
808 $sToken = substr($address,$i);
811 $sToken = substr($address,$i,$iEnd - $i +
1);
814 $sToken = str_replace($aReplace, $aSpecials,$sToken);
815 $aTokens[] = $sToken;
818 $iEnd = strpos($address,$cChar,$i+
1);
820 // skip escaped quotes
821 $prev_char = $address{$iEnd-1};
822 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
823 $iEnd = strpos($address,$cChar,$iEnd+
1);
825 $prev_char = $address{$iEnd-1};
832 $sToken = substr($address,$i);
835 // also remove the surrounding quotes
836 $sToken = substr($address,$i+
1,$iEnd - $i -1);
839 $sToken = str_replace($aReplace, $aSpecials,$sToken);
840 if ($sToken) $aTokens[] = $sToken;
843 $iEnd = strpos($address,')',$i);
845 $sToken = substr($address,$i);
848 $sToken = substr($address,$i,$iEnd - $i +
1);
851 $sToken = str_replace($aReplace, $aSpecials,$sToken);
852 $aTokens[] = $sToken;
862 if ($max && $max == $iAddrFound) {
874 $iEnd = strpos($address,' ',$i+
1);
876 $sToken = trim(substr($address,$i,$iEnd - $i));
879 $sToken = trim(substr($address,$i));
882 if ($sToken) $aTokens[] = $sToken;
886 $sPersonal = $sEmail = $sComment = $sGroup = '';
887 $aStack = $aComment = array();
888 foreach ($aTokens as $sToken) {
889 if ($max && $max == count($aAddress)) {
901 $aComment[] = substr($sToken,1,-1);
905 $sEmail = trim(implode(' ',$aStack));
906 $aAddress[] = array($sGroup,$sEmail);
907 $aStack = $aComment = array();
913 while (count($aStack) && !$sEmail) {
914 $sEmail = trim(array_pop($aStack));
917 if (count($aStack)) {
918 $sPersonal = trim(implode('',$aStack));
922 if (!$sPersonal && count($aComment)) {
923 $sComment = implode(' ',$aComment);
924 $sPersonal .= $sComment;
926 $aAddress[] = array($sEmail,$sPersonal);
927 $sPersonal = $sComment = $sEmail = '';
928 $aStack = $aComment = array();
931 $sGroup = implode(' ',$aStack); break;
935 $sEmail = trim(substr($sToken,1,-1));
940 default: $aStack[] = $sToken; break;
943 /* now do the action again for the last address */
945 while (count($aStack) && !$sEmail) {
946 $sEmail = trim(array_pop($aStack));
949 if (count($aStack)) {
950 $sPersonal = trim(implode('',$aStack));
954 if (!$sPersonal && count($aComment)) {
955 $sComment = implode(' ',$aComment);
956 $sPersonal .= $sComment;
958 $aAddress[] = array($sEmail,$sPersonal);
965 * Returns the number of unseen messages in this folder
967 function sqimap_unseen_messages ($imap_stream, $mailbox) {
968 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
970 $regs = array(false, false);
971 while (isset($read_ary[$i])) {
972 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
981 * Returns the number of total/unseen/recent messages in this folder
983 function sqimap_status_messages ($imap_stream, $mailbox) {
984 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
986 $messages = $unseen = $recent = false;
987 $regs = array(false,false);
988 while (isset($read_ary[$i])) {
989 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
992 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
993 $messages = $regs[1];
995 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1000 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1005 * Saves a message to a given folder -- used for saving sent messages
1007 function sqimap_append ($imap_stream, $sent_folder, $length) {
1008 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1009 $tmp = fgets ($imap_stream, 1024);
1012 function sqimap_append_done ($imap_stream, $folder='') {
1013 global $squirrelmail_language, $color;
1014 fputs ($imap_stream, "\r\n");
1015 $tmp = fgets ($imap_stream, 1024);
1016 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1017 set_up_language($squirrelmail_language);
1018 require_once(SM_PATH
. 'functions/display_messages.php');
1020 if ($regs[2] == 'NO') {
1021 $string = "<b><font color=$color[2]>\n" .
1022 _("ERROR : Could not append message to") ." $folder." .
1024 _("Server responded: ") .
1026 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1027 $string .= _("Solution: ") .
1028 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1031 $string .= "</font>\n";
1032 error_box($string,$color);
1034 $string = "<b><font color=$color[2]>\n" .
1035 _("ERROR : Bad or malformed request.") .
1037 _("Server responded: ") .
1038 $tmp . "</font><br>\n";
1039 error_box($string,$color);
1045 function sqimap_get_user_server ($imap_server, $username) {
1046 if (substr($imap_server, 0, 4) != "map:") {
1047 return $imap_server;
1049 $function = substr($imap_server, 4);
1050 return $function($username);
1053 /* This is an example that gets imapservers from yellowpages (NIS).
1054 * you can simple put map:map_yp_alias in your $imap_server_address
1055 * in config.php use your own function instead map_yp_alias to map your
1056 * LDAP whatever way to find the users imapserver. */
1058 function map_yp_alias($username) {
1059 $yp = `ypmatch
$username aliases`
;
1060 return chop(substr($yp, strlen($username)+
1));