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";
305 $cmd = explode(' ',$query);
306 $cmd= strtolower($cmd[0]);
308 if ($query != '' && $cmd != 'login')
309 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
310 if ($message_title != '')
311 $string .= $message_title;
313 $string .= htmlspecialchars($message);
314 $string .= "</font><br>\n";
315 error_box($string,$color);
319 * Reads the output from the IMAP stream. If handle_errors is set to true,
320 * this will also handle all errors that are received. If it is not set,
321 * the errors will be sent back through $response and $message
324 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
325 &$response, &$message, $query = '',
326 $filter = false, $outputstream = false, $no_return = false) {
327 global $color, $squirrelmail_language;
329 if (!is_array($message)) $message = array();
330 if (!is_array($response)) $response = array();
331 $resultlist = array();
333 $read = sqimap_fgets($imap_stream);
341 $read = sqimap_fgets($imap_stream);
346 /* get the command */
349 $s = substr($read,$i);
350 if (($j = strpos($s,' ')) ||
($j = strpos($s,"\n"))) {
351 $arg = substr($s,0,$j);
353 $found_tag = substr($read,0,$i-1);
362 $response[$found_tag] = $arg;
363 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
365 $resultlist[] = $data;
367 $aResponse[$found_tag] = $resultlist;
368 $data = $resultlist = array();
369 if ($found_tag == $tag) {
370 break 3; /* switch switch while */
374 /* this shouldn't happen */
375 $response[$found_tag] = $arg;
376 $message[$found_tag] = trim(substr($read,$i+
strlen($arg)));
378 $resultlist[] = $data;
380 $aResponse[$found_tag] = $resultlist;
381 $data = $resultlist = array();
382 if ($found_tag == $tag) {
383 break 3; /* switch switch while */
387 $read = sqimap_fgets($imap_stream);
388 if ($read === false) { /* error */
389 break 3; /* switch switch while */
392 } // end case $tag{0}
396 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
397 /* check for literal */
398 $s = substr($read,-3);
399 $fetch_data = array();
400 do { /* outer loop, continue until next untagged fetch
402 do { /* innerloop for fetching literals. with this loop
403 we prohibid that literal responses appear in the
404 outer loop so we can trust the untagged and
405 tagged info provided by $read */
406 if ($s === "}\r\n") {
407 $j = strrpos($read,'{');
408 $iLit = substr($read,$j+
1,-3);
409 $fetch_data[] = $read;
410 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
411 if ($sLiteral === false) { /* error */
412 break 4; /* while while switch while */
414 /* backwards compattibility */
415 $aLiteral = explode("\n", $sLiteral);
416 /* release not neaded data */
418 foreach ($aLiteral as $line) {
419 $fetch_data[] = $line ."\n";
421 /* release not neaded data */
423 /* next fgets belongs to this fetch because
424 we just got the exact literalsize and there
425 must follow data to complete the response */
426 $read = sqimap_fgets($imap_stream);
427 if ($read === false) { /* error */
428 break 4; /* while while switch while */
430 $fetch_data[] = $read;
432 $fetch_data[] = $read;
434 /* retrieve next line and check in the while
435 statements if it belongs to this fetch response */
436 $read = sqimap_fgets($imap_stream);
437 if ($read === false) { /* error */
438 break 4; /* while while switch while */
440 /* check for next untagged reponse and break */
441 if ($read{0} == '*') break 2;
442 $s = substr($read,-3);
443 } while ($s === "}\r\n");
444 $s = substr($read,-3);
445 } while ($read{0} !== '*' &&
446 substr($read,0,strlen($tag)) !== $tag);
447 $resultlist[] = $fetch_data;
448 /* release not neaded data */
451 $s = substr($read,-3);
453 if ($s === "}\r\n") {
454 $j = strrpos($read,'{');
455 $iLit = substr($read,$j+
1,-3);
457 $sLiteral = fread($imap_stream,$iLit);
458 if ($sLiteral === false) { /* error */
460 break 3; /* while switch while */
463 $data[] = sqimap_fgets($imap_stream);
467 $read = sqimap_fgets($imap_stream);
468 if ($read === false) {
469 break 3; /* while switch while */
470 } else if ($read{0} == '*') {
473 $s = substr($read,-3);
474 } while ($s === "}\r\n");
482 /* error processing in case $read is false */
483 if ($read === false) {
485 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
489 /* Set $resultlist array */
491 //$resultlist[] = $data;
493 elseif (empty($resultlist)) {
494 $resultlist[] = array();
497 /* Return result or handle errors */
498 if ($handle_errors == false) {
500 return( $resultlist ); //?? Why this?
502 switch ($response[$tag]) {
507 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
508 if (strstr($message[$tag], 'command resulted in') === false) {
509 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
510 echo '</body></html>';
515 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
516 echo '</body></html>';
519 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
520 echo '</body></html>';
523 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
524 /* the error is displayed but because we don't know the reponse we
525 return the result anyway */
531 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
532 &$response, &$message, $query = '',
533 $filter=false,$outputstream=false,$no_return=false) {
535 $tag_uid_a = explode(' ',trim($tag_uid));
536 $tag = $tag_uid_a[0];
538 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
539 $response, $message, $query,$filter,$outputstream,$no_return);
540 /* sqimap_read_data should be called for one response
541 but since it just calls sqimap_retrieve_imap_response which
542 handles multiple responses we need to check for that
543 and merge the $res array IF they are seperated and
544 IF it was a FETCH response. */
546 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
547 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
548 // $result = array();
549 // foreach($res as $index=>$value) {
550 // $result = array_merge($result, $res["$index"]);
553 if (isset($result)) {
554 return $result[$tag];
562 * Logs the user into the imap server. If $hide is set, no error messages
563 * will be displayed. This function returns the imap connection handle.
565 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
566 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
568 if (!isset($onetimepad) ||
empty($onetimepad)) {
569 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION
);
571 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
572 $host=$imap_server_address;
574 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
575 /* Use TLS by prefixing "tls://" to the hostname */
576 $imap_server_address = 'tls://' . $imap_server_address;
579 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
581 /* Do some error correction */
584 set_up_language($squirrelmail_language, true);
585 require_once(SM_PATH
. 'functions/display_messages.php');
586 $string = sprintf (_("Error connecting to IMAP server: %s.") .
587 "<br>\r\n", $imap_server_address) .
588 "$error_number : $error_string<br>\r\n";
589 logout_error($string,$color);
594 $server_info = fgets ($imap_stream, 1024);
596 /* Decrypt the password */
597 $password = OneTimePadDecrypt($password, $onetimepad);
599 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
600 // We're using some sort of authentication OTHER than plain or login
601 $tag=sqimap_session_id(false);
602 if ($imap_auth_mech == 'digest-md5') {
603 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
604 } elseif ($imap_auth_mech == 'cram-md5') {
605 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
607 fputs($imap_stream,$query);
608 $answer=sqimap_fgets($imap_stream);
609 // Trim the "+ " off the front
610 $response=explode(" ",$answer,3);
611 if ($response[0] == '+') {
612 // Got a challenge back
613 $challenge=$response[1];
614 if ($imap_auth_mech == 'digest-md5') {
615 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
616 } elseif ($imap_auth_mech == 'cram-md5') {
617 $reply = cram_md5_response($username,$password,$challenge);
619 fputs($imap_stream,$reply);
620 $read=sqimap_fgets($imap_stream);
621 if ($imap_auth_mech == 'digest-md5') {
622 // DIGEST-MD5 has an extra step..
623 if (substr($read,0,1) == '+') { // OK so far..
624 fputs($imap_stream,"\r\n");
625 $read=sqimap_fgets($imap_stream);
628 $results=explode(" ",$read,3);
629 $response=$results[1];
630 $message=$results[2];
632 // Fake the response, so the error trap at the bottom will work
634 $message='IMAP server does not appear to support the authentication method selected.';
635 $message .= ' Please contact your system administrator.';
637 } elseif ($imap_auth_mech == 'login') {
638 // Original IMAP login code
639 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
640 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
641 } elseif ($imap_auth_mech == 'plain') {
642 /* Replace this with SASL PLAIN if it ever gets implemented */
644 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
647 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
650 /* If the connection was not successful, lets see why */
651 if ($response != 'OK') {
653 if ($response != 'NO') {
654 /* "BAD" and anything else gets reported here. */
655 $message = htmlspecialchars($message);
656 set_up_language($squirrelmail_language, true);
657 require_once(SM_PATH
. 'functions/display_messages.php');
658 if ($response == 'BAD') {
659 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
661 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
663 if (isset($read) && is_array($read)) {
664 $string .= '<br>' . _("Read data:") . "<br>\n";
665 foreach ($read as $line) {
666 $string .= htmlspecialchars($line) . "<br>\n";
669 error_box($string,$color);
673 * If the user does not log in with the correct
674 * username and password it is not possible to get the
675 * correct locale from the user's preferences.
676 * Therefore, apply the same hack as on the login
679 * $squirrelmail_language is set by a cookie when
680 * the user selects language and logs out
683 set_up_language($squirrelmail_language, true);
684 include_once(SM_PATH
. 'functions/display_messages.php' );
686 logout_error( _("Unknown user or password incorrect.") );
696 /* Simply logs out the IMAP session */
697 function sqimap_logout ($imap_stream) {
698 /* Logout is not valid until the server returns 'BYE'
699 * If we don't have an imap_ stream we're already logged out */
700 if(isset($imap_stream) && $imap_stream)
701 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
704 function sqimap_capability($imap_stream, $capability='') {
705 global $sqimap_capabilities;
706 if (!is_array($sqimap_capabilities)) {
707 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
709 $c = explode(' ', $read[0]);
710 for ($i=2; $i < count($c); $i++
) {
711 $cap_list = explode('=', $c[$i]);
712 if (isset($cap_list[1])) {
713 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
715 $sqimap_capabilities[$cap_list[0]] = TRUE;
720 if (isset($sqimap_capabilities[$capability])) {
721 return $sqimap_capabilities[$capability];
726 return $sqimap_capabilities;
729 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
730 function sqimap_get_delimiter ($imap_stream = false) {
731 global $sqimap_delimiter, $optional_delimiter;
733 /* Use configured delimiter if set */
734 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
735 return $optional_delimiter;
738 /* Do some caching here */
739 if (!$sqimap_delimiter) {
740 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
742 * According to something that I can't find, this is supposed to work on all systems
743 * OS: This won't work in Courier IMAP.
744 * OS: According to rfc2342 response from NAMESPACE command is:
745 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
746 * OS: We want to lookup all personal NAMESPACES...
748 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
749 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
750 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
753 $pna = explode(')(', $pn);
754 while (list($k, $v) = each($pna)) {
755 $lst = explode('"', $v);
756 if (isset($lst[3])) {
757 $pn[$lst[1]] = $lst[3];
763 $sqimap_delimiter = $pn[0];
765 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
766 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
767 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
768 $quote_position = strpos ($read[0], '"');
769 $sqimap_delimiter = substr ($read[0], $quote_position+
1, 1);
772 return $sqimap_delimiter;
776 function sqimap_encode_mailbox_name($what)
778 if (ereg("[\"\\\r\n]", $what))
779 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
780 return '"' . $what . '"'; /* 4.3 quoted string form */
784 /* Gets the number of messages in the current mailbox. */
785 function sqimap_get_num_messages ($imap_stream, $mailbox) {
786 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
787 for ($i = 0; $i < count($read_ary); $i++
) {
788 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
792 return false; //"BUG! Couldn't get number of messages in $mailbox!";
796 function parseAddress($address, $max=0) {
799 $iCnt = strlen($address);
800 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
801 $aReplace = array(' (',' <',' ,',' ;',' :');
802 $address = str_replace($aSpecials,$aReplace,$address);
803 $i = $iAddrFound = $bGroup = 0;
805 $cChar = $address{$i};
809 $iEnd = strpos($address,'>',$i+
1);
811 $sToken = substr($address,$i);
814 $sToken = substr($address,$i,$iEnd - $i +
1);
817 $sToken = str_replace($aReplace, $aSpecials,$sToken);
818 $aTokens[] = $sToken;
821 $iEnd = strpos($address,$cChar,$i+
1);
823 // skip escaped quotes
824 $prev_char = $address{$iEnd-1};
825 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
826 $iEnd = strpos($address,$cChar,$iEnd+
1);
828 $prev_char = $address{$iEnd-1};
835 $sToken = substr($address,$i);
838 // also remove the surrounding quotes
839 $sToken = substr($address,$i+
1,$iEnd - $i -1);
842 $sToken = str_replace($aReplace, $aSpecials,$sToken);
843 if ($sToken) $aTokens[] = $sToken;
846 $iEnd = strpos($address,')',$i);
848 $sToken = substr($address,$i);
851 $sToken = substr($address,$i,$iEnd - $i +
1);
854 $sToken = str_replace($aReplace, $aSpecials,$sToken);
855 $aTokens[] = $sToken;
865 if ($max && $max == $iAddrFound) {
877 $iEnd = strpos($address,' ',$i+
1);
879 $sToken = trim(substr($address,$i,$iEnd - $i));
882 $sToken = trim(substr($address,$i));
885 if ($sToken) $aTokens[] = $sToken;
889 $sPersonal = $sEmail = $sComment = $sGroup = '';
890 $aStack = $aComment = array();
891 foreach ($aTokens as $sToken) {
892 if ($max && $max == count($aAddress)) {
904 $aComment[] = substr($sToken,1,-1);
908 $sEmail = trim(implode(' ',$aStack));
909 $aAddress[] = array($sGroup,$sEmail);
910 $aStack = $aComment = array();
916 while (count($aStack) && !$sEmail) {
917 $sEmail = trim(array_pop($aStack));
920 if (count($aStack)) {
921 $sPersonal = trim(implode('',$aStack));
925 if (!$sPersonal && count($aComment)) {
926 $sComment = implode(' ',$aComment);
927 $sPersonal .= $sComment;
929 $aAddress[] = array($sEmail,$sPersonal);
930 $sPersonal = $sComment = $sEmail = '';
931 $aStack = $aComment = array();
934 $sGroup = implode(' ',$aStack); break;
938 $sEmail = trim(substr($sToken,1,-1));
943 default: $aStack[] = $sToken; break;
946 /* now do the action again for the last address */
948 while (count($aStack) && !$sEmail) {
949 $sEmail = trim(array_pop($aStack));
952 if (count($aStack)) {
953 $sPersonal = trim(implode('',$aStack));
957 if (!$sPersonal && count($aComment)) {
958 $sComment = implode(' ',$aComment);
959 $sPersonal .= $sComment;
961 $aAddress[] = array($sEmail,$sPersonal);
968 * Returns the number of unseen messages in this folder
970 function sqimap_unseen_messages ($imap_stream, $mailbox) {
971 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
973 $regs = array(false, false);
974 while (isset($read_ary[$i])) {
975 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
984 * Returns the number of total/unseen/recent messages in this folder
986 function sqimap_status_messages ($imap_stream, $mailbox) {
987 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
989 $messages = $unseen = $recent = false;
990 $regs = array(false,false);
991 while (isset($read_ary[$i])) {
992 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
995 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
996 $messages = $regs[1];
998 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1003 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1008 * Saves a message to a given folder -- used for saving sent messages
1010 function sqimap_append ($imap_stream, $sent_folder, $length) {
1011 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1012 $tmp = fgets ($imap_stream, 1024);
1015 function sqimap_append_done ($imap_stream, $folder='') {
1016 global $squirrelmail_language, $color;
1017 fputs ($imap_stream, "\r\n");
1018 $tmp = fgets ($imap_stream, 1024);
1019 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1020 set_up_language($squirrelmail_language);
1021 require_once(SM_PATH
. 'functions/display_messages.php');
1023 if ($regs[2] == 'NO') {
1024 $string = "<b><font color=$color[2]>\n" .
1025 _("ERROR : Could not append message to") ." $folder." .
1027 _("Server responded: ") .
1029 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1030 $string .= _("Solution: ") .
1031 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1034 $string .= "</font>\n";
1035 error_box($string,$color);
1037 $string = "<b><font color=$color[2]>\n" .
1038 _("ERROR : Bad or malformed request.") .
1040 _("Server responded: ") .
1041 $tmp . "</font><br>\n";
1042 error_box($string,$color);
1048 function sqimap_get_user_server ($imap_server, $username) {
1049 if (substr($imap_server, 0, 4) != "map:") {
1050 return $imap_server;
1052 $function = substr($imap_server, 4);
1053 return $function($username);
1056 /* This is an example that gets imapservers from yellowpages (NIS).
1057 * you can simple put map:map_yp_alias in your $imap_server_address
1058 * in config.php use your own function instead map_yp_alias to map your
1059 * LDAP whatever way to find the users imapserver. */
1061 function map_yp_alias($username) {
1062 $yp = `ypmatch
$username aliases`
;
1063 return chop(substr($yp, strlen($username)+
1));