One more place with Russian koi-8r -> utf-8 changes
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This implements all functions that do general imap functions.
10 *
11 * $Id$
12 */
13
14 require_once(SM_PATH . 'functions/page_header.php');
15 require_once(SM_PATH . 'functions/auth.php');
16
17
18 global $sqimap_session_id;
19 $sqimap_session_id = 1;
20
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;
24 if (!$unique_id) {
25 return( sprintf("A%03d", $sqimap_session_id++) );
26 } else {
27 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
28 }
29 }
30
31 /*
32 * Both send a command and accept the result from the command.
33 * This is to allow proper session number handling.
34 */
35 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
36 if ($imap_stream) {
37 $sid = sqimap_session_id($unique_id);
38 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
39 $tag_uid_a = explode(' ',trim($sid));
40 $tag = $tag_uid_a[0];
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];
45 return $read[$tag];
46 } else {
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.") .
52 "</b></font>\n";
53 error_box($string,$color);
54 return false;
55 }
56 }
57
58 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
59 &$message, $unique_id = false,$filter=false,
60 $outputstream=false,$no_return=false) {
61 if ($imap_stream) {
62 $sid = sqimap_session_id($unique_id);
63 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
64 $tag_uid_a = explode(' ',trim($sid));
65 $tag = $tag_uid_a[0];
66
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];
72
73 if (!empty($read[$tag])) {
74 return $read[$tag][0];
75 } else {
76 return $read[$tag];
77 }
78 } else {
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.") .
84 "</b></font>\n";
85 error_box($string,$color);
86 return false;
87 }
88 }
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));
92 $tag = $tag_uid_a[0];
93 $query = $sid . ' '.$new_query."\r\n";
94 $aQuery[$tag] = $query;
95 }
96
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) {
100 $aResponse = false;
101
102 /*
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.
108
109 After testing it on Exchange 2000 we discovered that a chunksize of 32
110 was quicker then when we raised it to 128.
111 */
112 $iQueryCount = count($aQueryList);
113 $iChunkSize = 32;
114 // array_chunk would also do the job but it's supported from php > 4.2
115 $aQueryChunks = array();
116 $iLoops = floor($iQueryCount / $iChunkSize);
117
118 if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
119
120 if (!function_exists('array_chunk')) { // arraychunk replacement
121 reset($aQueryList);
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;
127 }
128 $aQueryChunks[] = $aTmp;
129 }
130 } else {
131 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
132 }
133
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;
139 }
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];
148 } else {
149 $aResults[$returned_tag] = $aResponse;
150 }
151 $aServerResponse[$returned_tag] = $response[$returned_tag];
152 $aServerMessage[$returned_tag] = $message[$returned_tag];
153 }
154 }
155 }
156 }
157 return $aResults;
158 }
159
160 /*
161 * custom fgets function. gets a line from IMAP
162 * no matter how big it may be
163 */
164
165 function sqimap_fgets($imap_stream) {
166 $read = '';
167 $buffer = 4096;
168 $results = '';
169 $offset = 0;
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 */
174 $results = false;
175 break;
176 }
177 if ( $results != '' ) {
178 $offset = strlen($results) - 1;
179 }
180 $results .= $read;
181 }
182 return $results;
183 }
184
185 function sqimap_fread($imap_stream,$iSize,$filter=false,
186 $outputstream=false, $no_return=false) {
187 if (!$filter || !$outputstream) {
188 $iBufferSize = $iSize;
189 } else {
190 // see php bug 24033. They changed fread behaviour %$^&$%
191 $iBufferSize = 780; // multiple of 78 in case of base64 decoding.
192 }
193 $iRet = $iSize - $iBufferSize;
194 $iRetrieved = 0;
195 $i = 0;
196 $results = $sReadRem = '';
197 $bFinished = $bBufferSizeAdapted = $bBufferIsOk = false;
198 while (($iRetrieved < ($iSize - $iBufferSize))) {
199 $sRead = fread($imap_stream,$iBufferSize);
200 if (!$sRead) {
201 $results = false;
202 break;
203 }
204 $iRetrieved += $iBufferSize;
205 if ($filter) {
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");
209 if ($i) {
210 ++$i;
211 $iFragments = floor($iBufferSize / $i);
212 $iNewBufferSize = $iFragments * $i;
213 $iRemainder = $iNewBufferSize + $i - $iBufferSize;
214 if ($iNewBufferSize == $iBufferSize) {
215 $bBufferIsOk = true;
216 $iRemainder = 0;
217 $iNewBufferSize = $iBufferSize;
218 $bBufferSizeAdapted = true;
219 }
220 if (!$bBufferIsOk && ($iRemainder + $iBufferSize) < $iSize) {
221 $sReadRem = fread($imap_stream,$iRemainder);
222 } else if (!$bBufferIsOk) {
223 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
224 $bFinished = true;
225 }
226 if (!$sReadRem && $sReadRem !== '') {
227 $results = false;
228 break;
229 }
230 $iBufferSize = $iNewBufferSize;
231 $bBufferSizeAdapted = true;
232 } else {
233 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
234 $bFinished = true;
235 if (!$sReadRem) {
236 $results = false;
237 break;
238 }
239 }
240 $sRead .= $sReadRem;
241 $iRetrieved += $iRemainder;
242 unset($sReadRem);
243 }
244 $filter($sRead);
245 }
246 if ($outputstream) {
247 if (is_resource($outputstream)) {
248 fwrite($outputstream,$sRead);
249 } else if ($outputstream == 'php://stdout') {
250 echo $sRead;
251 }
252 }
253 if ($no_return) {
254 $sRead = '';
255 }
256 $results .= $sRead;
257 }
258 if (!$results && !$bFinished) {
259 $sRead = fread($imap_stream,($iSize - ($iRetrieved)));
260 if ($filter) {
261 $filter($sRead);
262 }
263 if ($outputstream) {
264 if (is_resource($outputstream)) {
265 fwrite($outputstream,$sRead);
266 } else if ($outputstream == 'php://stdout') { // FIXME
267 echo $sRead;
268 }
269 }
270 if ($no_return) {
271 $sRead = '';
272 }
273 $results .= $sRead;
274 }
275 return $results;
276 }
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.") .
285 "</b><br>\n" .
286 _("Reason:") . ' '.
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>';
295 exit;
296 }
297
298 function sqimap_error_box($title, $query = '', $message_title = '', $message = '')
299 {
300 global $color, $squirrelmail_language;
301
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]);
307
308 if ($query != '' && $cmd != 'login')
309 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
310 if ($message_title != '')
311 $string .= $message_title;
312 if ($message != '')
313 $string .= htmlspecialchars($message);
314 $string .= "</font><br>\n";
315 error_box($string,$color);
316 }
317
318 /*
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
322 */
323
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;
328 $read = '';
329 if (!is_array($message)) $message = array();
330 if (!is_array($response)) $response = array();
331 $resultlist = array();
332 $data = array();
333 $read = sqimap_fgets($imap_stream);
334 $i = $k = 0;
335 while ($read) {
336 $char = $read{0};
337 switch ($char)
338 {
339 case '+':
340 default:
341 $read = sqimap_fgets($imap_stream);
342 break;
343
344 case $tag{0}:
345 {
346 /* get the command */
347 $arg = '';
348 $i = strlen($tag)+1;
349 $s = substr($read,$i);
350 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
351 $arg = substr($s,0,$j);
352 }
353 $found_tag = substr($read,0,$i-1);
354 if ($found_tag) {
355 switch ($arg)
356 {
357 case 'OK':
358 case 'BAD':
359 case 'NO':
360 case 'BYE':
361 case 'PREAUTH':
362 $response[$found_tag] = $arg;
363 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
364 if (!empty($data)) {
365 $resultlist[] = $data;
366 }
367 $aResponse[$found_tag] = $resultlist;
368 $data = $resultlist = array();
369 if ($found_tag == $tag) {
370 break 3; /* switch switch while */
371 }
372 break;
373 default:
374 /* this shouldn't happen */
375 $response[$found_tag] = $arg;
376 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
377 if (!empty($data)) {
378 $resultlist[] = $data;
379 }
380 $aResponse[$found_tag] = $resultlist;
381 $data = $resultlist = array();
382 if ($found_tag == $tag) {
383 break 3; /* switch switch while */
384 }
385 }
386 }
387 $read = sqimap_fgets($imap_stream);
388 if ($read === false) { /* error */
389 break 3; /* switch switch while */
390 }
391 break;
392 } // end case $tag{0}
393
394 case '*':
395 {
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
401 or tagged reponse */
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 */
413 }
414 /* backwards compattibility */
415 $aLiteral = explode("\n", $sLiteral);
416 /* release not neaded data */
417 unset($sLiteral);
418 foreach ($aLiteral as $line) {
419 $fetch_data[] = $line ."\n";
420 }
421 /* release not neaded data */
422 unset($aLiteral);
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 */
429 }
430 $fetch_data[] = $read;
431 } else {
432 $fetch_data[] = $read;
433 }
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 */
439 }
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 */
449 unset ($fetch_data);
450 } else {
451 $s = substr($read,-3);
452 do {
453 if ($s === "}\r\n") {
454 $j = strrpos($read,'{');
455 $iLit = substr($read,$j+1,-3);
456 $data[] = $read;
457 $sLiteral = fread($imap_stream,$iLit);
458 if ($sLiteral === false) { /* error */
459 $read = false;
460 break 3; /* while switch while */
461 }
462 $data[] = $sLiteral;
463 $data[] = sqimap_fgets($imap_stream);
464 } else {
465 $data[] = $read;
466 }
467 $read = sqimap_fgets($imap_stream);
468 if ($read === false) {
469 break 3; /* while switch while */
470 } else if ($read{0} == '*') {
471 break;
472 }
473 $s = substr($read,-3);
474 } while ($s === "}\r\n");
475 break 1;
476 }
477 break;
478 } // end case '*'
479 } // end switch
480 } // end while
481
482 /* error processing in case $read is false */
483 if ($read === false) {
484 unset($data);
485 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
486 exit;
487 }
488
489 /* Set $resultlist array */
490 if (!empty($data)) {
491 //$resultlist[] = $data;
492 }
493 elseif (empty($resultlist)) {
494 $resultlist[] = array();
495 }
496
497 /* Return result or handle errors */
498 if ($handle_errors == false) {
499 return $aResponse;
500 return( $resultlist ); //?? Why this?
501 }
502 switch ($response[$tag]) {
503 case 'OK':
504 return $aResponse;
505 break;
506 case 'NO':
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>';
511 exit;
512 }
513 break;
514 case 'BAD':
515 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
516 echo '</body></html>';
517 exit;
518 case 'BYE':
519 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
520 echo '</body></html>';
521 exit;
522 default:
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 */
526 return $aResponse;
527 break;
528 }
529 }
530
531 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
532 &$response, &$message, $query = '',
533 $filter=false,$outputstream=false,$no_return=false) {
534
535 $tag_uid_a = explode(' ',trim($tag_uid));
536 $tag = $tag_uid_a[0];
537
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. */
545
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"]);
551 // }
552 // }
553 if (isset($result)) {
554 return $result[$tag];
555 }
556 else {
557 return $res;
558 }
559 }
560
561 /*
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.
564 */
565 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
566 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
567
568 if (!isset($onetimepad) || empty($onetimepad)) {
569 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
570 }
571 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
572 $host=$imap_server_address;
573
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;
577 }
578
579 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
580
581 /* Do some error correction */
582 if (!$imap_stream) {
583 if (!$hide) {
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);
590 }
591 exit;
592 }
593
594 $server_info = fgets ($imap_stream, 1024);
595
596 /* Decrypt the password */
597 $password = OneTimePadDecrypt($password, $onetimepad);
598
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";
606 }
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);
618 }
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);
626 }
627 }
628 $results=explode(" ",$read,3);
629 $response=$results[1];
630 $message=$results[2];
631 } else {
632 // Fake the response, so the error trap at the bottom will work
633 $response="BAD";
634 $message='IMAP server does not appear to support the authentication method selected.';
635 $message .= ' Please contact your system administrator.';
636 }
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 */
643 $response="BAD";
644 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
645 } else {
646 $response="BAD";
647 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
648 }
649
650 /* If the connection was not successful, lets see why */
651 if ($response != 'OK') {
652 if (!$hide) {
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);
660 } else {
661 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
662 }
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";
667 }
668 }
669 error_box($string,$color);
670 exit;
671 } else {
672 /*
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
677 * screen.
678 *
679 * $squirrelmail_language is set by a cookie when
680 * the user selects language and logs out
681 */
682
683 set_up_language($squirrelmail_language, true);
684 include_once(SM_PATH . 'functions/display_messages.php' );
685 sqsession_destroy();
686 logout_error( _("Unknown user or password incorrect.") );
687 exit;
688 }
689 } else {
690 exit;
691 }
692 }
693 return $imap_stream;
694 }
695
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);
702 }
703
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);
708
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];
714 } else {
715 $sqimap_capabilities[$cap_list[0]] = TRUE;
716 }
717 }
718 }
719 if ($capability) {
720 if (isset($sqimap_capabilities[$capability])) {
721 return $sqimap_capabilities[$capability];
722 } else {
723 return false;
724 }
725 }
726 return $sqimap_capabilities;
727 }
728
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;
732
733 /* Use configured delimiter if set */
734 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
735 return $optional_delimiter;
736 }
737
738 /* Do some caching here */
739 if (!$sqimap_delimiter) {
740 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
741 /*
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...
747 */
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)) {
751 $pn = $data2[1];
752 }
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];
758 } else {
759 $pn[$lst[1]] = '';
760 }
761 }
762 }
763 $sqimap_delimiter = $pn[0];
764 } else {
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);
770 }
771 }
772 return $sqimap_delimiter;
773 }
774
775
776 function sqimap_encode_mailbox_name($what)
777 {
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 */
781 }
782
783
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)) {
789 return $regs[1];
790 }
791 }
792 return false; //"BUG! Couldn't get number of messages in $mailbox!";
793 }
794
795
796 function parseAddress($address, $max=0) {
797 $aTokens = array();
798 $aAddress = array();
799 $iCnt = strlen($address);
800 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
801 $aReplace = array(' (',' <',' ,',' ;',' :');
802 $address = str_replace($aSpecials,$aReplace,$address);
803 $i = $iAddrFound = $bGroup = 0;
804 while ($i < $iCnt) {
805 $cChar = $address{$i};
806 switch($cChar)
807 {
808 case '<':
809 $iEnd = strpos($address,'>',$i+1);
810 if (!$iEnd) {
811 $sToken = substr($address,$i);
812 $i = $iCnt;
813 } else {
814 $sToken = substr($address,$i,$iEnd - $i +1);
815 $i = $iEnd;
816 }
817 $sToken = str_replace($aReplace, $aSpecials,$sToken);
818 $aTokens[] = $sToken;
819 break;
820 case '"':
821 $iEnd = strpos($address,$cChar,$i+1);
822 if ($iEnd) {
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);
827 if ($iEnd) {
828 $prev_char = $address{$iEnd-1};
829 } else {
830 $prev_char = false;
831 }
832 }
833 }
834 if (!$iEnd) {
835 $sToken = substr($address,$i);
836 $i = $iCnt;
837 } else {
838 // also remove the surrounding quotes
839 $sToken = substr($address,$i+1,$iEnd - $i -1);
840 $i = $iEnd;
841 }
842 $sToken = str_replace($aReplace, $aSpecials,$sToken);
843 if ($sToken) $aTokens[] = $sToken;
844 break;
845 case '(':
846 $iEnd = strpos($address,')',$i);
847 if (!$iEnd) {
848 $sToken = substr($address,$i);
849 $i = $iCnt;
850 } else {
851 $sToken = substr($address,$i,$iEnd - $i + 1);
852 $i = $iEnd;
853 }
854 $sToken = str_replace($aReplace, $aSpecials,$sToken);
855 $aTokens[] = $sToken;
856 break;
857 case ',':
858 ++$iAddrFound;
859 case ';':
860 if (!$bGroup) {
861 ++$iAddrFound;
862 } else {
863 $bGroup = false;
864 }
865 if ($max && $max == $iAddrFound) {
866 break 2;
867 } else {
868 $aTokens[] = $cChar;
869 break;
870 }
871 case ':':
872 $bGroup = true;
873 case ' ':
874 $aTokens[] = $cChar;
875 break;
876 default:
877 $iEnd = strpos($address,' ',$i+1);
878 if ($iEnd) {
879 $sToken = trim(substr($address,$i,$iEnd - $i));
880 $i = $iEnd-1;
881 } else {
882 $sToken = trim(substr($address,$i));
883 $i = $iCnt;
884 }
885 if ($sToken) $aTokens[] = $sToken;
886 }
887 ++$i;
888 }
889 $sPersonal = $sEmail = $sComment = $sGroup = '';
890 $aStack = $aComment = array();
891 foreach ($aTokens as $sToken) {
892 if ($max && $max == count($aAddress)) {
893 return $aAddress;
894 }
895 $cChar = $sToken{0};
896 switch ($cChar)
897 {
898 case '=':
899 case '"':
900 case ' ':
901 $aStack[] = $sToken;
902 break;
903 case '(':
904 $aComment[] = substr($sToken,1,-1);
905 break;
906 case ';':
907 if ($sGroup) {
908 $sEmail = trim(implode(' ',$aStack));
909 $aAddress[] = array($sGroup,$sEmail);
910 $aStack = $aComment = array();
911 $sGroup = '';
912 break;
913 }
914 case ',':
915 if (!$sEmail) {
916 while (count($aStack) && !$sEmail) {
917 $sEmail = trim(array_pop($aStack));
918 }
919 }
920 if (count($aStack)) {
921 $sPersonal = trim(implode('',$aStack));
922 } else {
923 $sPersonal = '';
924 }
925 if (!$sPersonal && count($aComment)) {
926 $sComment = implode(' ',$aComment);
927 $sPersonal .= $sComment;
928 }
929 $aAddress[] = array($sEmail,$sPersonal);
930 $sPersonal = $sComment = $sEmail = '';
931 $aStack = $aComment = array();
932 break;
933 case ':':
934 $sGroup = implode(' ',$aStack); break;
935 $aStack = array();
936 break;
937 case '<':
938 $sEmail = trim(substr($sToken,1,-1));
939 break;
940 case '>':
941 /* skip */
942 break;
943 default: $aStack[] = $sToken; break;
944 }
945 }
946 /* now do the action again for the last address */
947 if (!$sEmail) {
948 while (count($aStack) && !$sEmail) {
949 $sEmail = trim(array_pop($aStack));
950 }
951 }
952 if (count($aStack)) {
953 $sPersonal = trim(implode('',$aStack));
954 } else {
955 $sPersonal = '';
956 }
957 if (!$sPersonal && count($aComment)) {
958 $sComment = implode(' ',$aComment);
959 $sPersonal .= $sComment;
960 }
961 $aAddress[] = array($sEmail,$sPersonal);
962 return $aAddress;
963 }
964
965
966
967 /*
968 * Returns the number of unseen messages in this folder
969 */
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);
972 $i = 0;
973 $regs = array(false, false);
974 while (isset($read_ary[$i])) {
975 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
976 break;
977 }
978 $i++;
979 }
980 return $regs[1];
981 }
982
983 /*
984 * Returns the number of total/unseen/recent messages in this folder
985 */
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);
988 $i = 0;
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)) {
993 $unseen = $regs[1];
994 }
995 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
996 $messages = $regs[1];
997 }
998 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
999 $recent = $regs[1];
1000 }
1001 $i++;
1002 }
1003 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1004 }
1005
1006
1007 /*
1008 * Saves a message to a given folder -- used for saving sent messages
1009 */
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);
1013 }
1014
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');
1022 $reason = $regs[3];
1023 if ($regs[2] == 'NO') {
1024 $string = "<b><font color=$color[2]>\n" .
1025 _("ERROR : Could not append message to") ." $folder." .
1026 "</b><br>\n" .
1027 _("Server responded: ") .
1028 $reason . "<br>\n";
1029 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1030 $string .= _("Solution: ") .
1031 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1032 ."<br>\n";
1033 }
1034 $string .= "</font>\n";
1035 error_box($string,$color);
1036 } else {
1037 $string = "<b><font color=$color[2]>\n" .
1038 _("ERROR : Bad or malformed request.") .
1039 "</b><br>\n" .
1040 _("Server responded: ") .
1041 $tmp . "</font><br>\n";
1042 error_box($string,$color);
1043 exit;
1044 }
1045 }
1046 }
1047
1048 function sqimap_get_user_server ($imap_server, $username) {
1049 if (substr($imap_server, 0, 4) != "map:") {
1050 return $imap_server;
1051 }
1052 $function = substr($imap_server, 4);
1053 return $function($username);
1054 }
1055
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. */
1060
1061 function map_yp_alias($username) {
1062 $yp = `ypmatch $username aliases`;
1063 return chop(substr($yp, strlen($username)+1));
1064 }
1065
1066 ?>