4a8b55767a04f044c4727218e9eacbd5762ffe5d
[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 /* SASL PLAIN */
643 $tag=sqimap_session_id(false);
644 $auth = base64_encode("$username\0$username\0$password");
645
646 $query = $tag . " AUTHENTICATE PLAIN\r\n";
647 fputs($imap_stream, $query);
648 $read=sqimap_fgets($imap_stream);
649
650 if (substr($read,0,1) == '+') { // OK so far..
651 fputs($imap_stream, "$auth\r\n");
652 $read = sqimap_fgets($imap_stream);
653 }
654
655 $results=explode(" ",$read,3);
656 $response=$results[1];
657 $message=$results[2];
658 } else {
659 $response="BAD";
660 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
661 }
662
663 /* If the connection was not successful, lets see why */
664 if ($response != 'OK') {
665 if (!$hide) {
666 if ($response != 'NO') {
667 /* "BAD" and anything else gets reported here. */
668 $message = htmlspecialchars($message);
669 set_up_language($squirrelmail_language, true);
670 require_once(SM_PATH . 'functions/display_messages.php');
671 if ($response == 'BAD') {
672 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
673 } else {
674 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
675 }
676 if (isset($read) && is_array($read)) {
677 $string .= '<br>' . _("Read data:") . "<br>\n";
678 foreach ($read as $line) {
679 $string .= htmlspecialchars($line) . "<br>\n";
680 }
681 }
682 error_box($string,$color);
683 exit;
684 } else {
685 /*
686 * If the user does not log in with the correct
687 * username and password it is not possible to get the
688 * correct locale from the user's preferences.
689 * Therefore, apply the same hack as on the login
690 * screen.
691 *
692 * $squirrelmail_language is set by a cookie when
693 * the user selects language and logs out
694 */
695
696 set_up_language($squirrelmail_language, true);
697 include_once(SM_PATH . 'functions/display_messages.php' );
698 sqsession_destroy();
699 logout_error( _("Unknown user or password incorrect.") );
700 exit;
701 }
702 } else {
703 exit;
704 }
705 }
706 return $imap_stream;
707 }
708
709 /* Simply logs out the IMAP session */
710 function sqimap_logout ($imap_stream) {
711 /* Logout is not valid until the server returns 'BYE'
712 * If we don't have an imap_ stream we're already logged out */
713 if(isset($imap_stream) && $imap_stream)
714 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
715 }
716
717 function sqimap_capability($imap_stream, $capability='') {
718 global $sqimap_capabilities;
719 if (!is_array($sqimap_capabilities)) {
720 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
721
722 $c = explode(' ', $read[0]);
723 for ($i=2; $i < count($c); $i++) {
724 $cap_list = explode('=', $c[$i]);
725 if (isset($cap_list[1])) {
726 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
727 } else {
728 $sqimap_capabilities[$cap_list[0]] = TRUE;
729 }
730 }
731 }
732 if ($capability) {
733 if (isset($sqimap_capabilities[$capability])) {
734 return $sqimap_capabilities[$capability];
735 } else {
736 return false;
737 }
738 }
739 return $sqimap_capabilities;
740 }
741
742 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
743 function sqimap_get_delimiter ($imap_stream = false) {
744 global $sqimap_delimiter, $optional_delimiter;
745
746 /* Use configured delimiter if set */
747 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
748 return $optional_delimiter;
749 }
750
751 /* Do some caching here */
752 if (!$sqimap_delimiter) {
753 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
754 /*
755 * According to something that I can't find, this is supposed to work on all systems
756 * OS: This won't work in Courier IMAP.
757 * OS: According to rfc2342 response from NAMESPACE command is:
758 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
759 * OS: We want to lookup all personal NAMESPACES...
760 */
761 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
762 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
763 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
764 $pn = $data2[1];
765 }
766 $pna = explode(')(', $pn);
767 while (list($k, $v) = each($pna)) {
768 $lst = explode('"', $v);
769 if (isset($lst[3])) {
770 $pn[$lst[1]] = $lst[3];
771 } else {
772 $pn[$lst[1]] = '';
773 }
774 }
775 }
776 $sqimap_delimiter = $pn[0];
777 } else {
778 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
779 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
780 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
781 $quote_position = strpos ($read[0], '"');
782 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
783 }
784 }
785 return $sqimap_delimiter;
786 }
787
788
789 function sqimap_encode_mailbox_name($what)
790 {
791 if (ereg("[\"\\\r\n]", $what))
792 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
793 return '"' . $what . '"'; /* 4.3 quoted string form */
794 }
795
796
797 /* Gets the number of messages in the current mailbox. */
798 function sqimap_get_num_messages ($imap_stream, $mailbox) {
799 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
800 for ($i = 0; $i < count($read_ary); $i++) {
801 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
802 return $regs[1];
803 }
804 }
805 return false; //"BUG! Couldn't get number of messages in $mailbox!";
806 }
807
808
809 function parseAddress($address, $max=0) {
810 $aTokens = array();
811 $aAddress = array();
812 $iCnt = strlen($address);
813 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
814 $aReplace = array(' (',' <',' ,',' ;',' :');
815 $address = str_replace($aSpecials,$aReplace,$address);
816 $i = $iAddrFound = $bGroup = 0;
817 while ($i < $iCnt) {
818 $cChar = $address{$i};
819 switch($cChar)
820 {
821 case '<':
822 $iEnd = strpos($address,'>',$i+1);
823 if (!$iEnd) {
824 $sToken = substr($address,$i);
825 $i = $iCnt;
826 } else {
827 $sToken = substr($address,$i,$iEnd - $i +1);
828 $i = $iEnd;
829 }
830 $sToken = str_replace($aReplace, $aSpecials,$sToken);
831 $aTokens[] = $sToken;
832 break;
833 case '"':
834 $iEnd = strpos($address,$cChar,$i+1);
835 if ($iEnd) {
836 // skip escaped quotes
837 $prev_char = $address{$iEnd-1};
838 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
839 $iEnd = strpos($address,$cChar,$iEnd+1);
840 if ($iEnd) {
841 $prev_char = $address{$iEnd-1};
842 } else {
843 $prev_char = false;
844 }
845 }
846 }
847 if (!$iEnd) {
848 $sToken = substr($address,$i);
849 $i = $iCnt;
850 } else {
851 // also remove the surrounding quotes
852 $sToken = substr($address,$i+1,$iEnd - $i -1);
853 $i = $iEnd;
854 }
855 $sToken = str_replace($aReplace, $aSpecials,$sToken);
856 if ($sToken) $aTokens[] = $sToken;
857 break;
858 case '(':
859 $iEnd = strpos($address,')',$i);
860 if (!$iEnd) {
861 $sToken = substr($address,$i);
862 $i = $iCnt;
863 } else {
864 $sToken = substr($address,$i,$iEnd - $i + 1);
865 $i = $iEnd;
866 }
867 $sToken = str_replace($aReplace, $aSpecials,$sToken);
868 $aTokens[] = $sToken;
869 break;
870 case ',':
871 ++$iAddrFound;
872 case ';':
873 if (!$bGroup) {
874 ++$iAddrFound;
875 } else {
876 $bGroup = false;
877 }
878 if ($max && $max == $iAddrFound) {
879 break 2;
880 } else {
881 $aTokens[] = $cChar;
882 break;
883 }
884 case ':':
885 $bGroup = true;
886 case ' ':
887 $aTokens[] = $cChar;
888 break;
889 default:
890 $iEnd = strpos($address,' ',$i+1);
891 if ($iEnd) {
892 $sToken = trim(substr($address,$i,$iEnd - $i));
893 $i = $iEnd-1;
894 } else {
895 $sToken = trim(substr($address,$i));
896 $i = $iCnt;
897 }
898 if ($sToken) $aTokens[] = $sToken;
899 }
900 ++$i;
901 }
902 $sPersonal = $sEmail = $sComment = $sGroup = '';
903 $aStack = $aComment = array();
904 foreach ($aTokens as $sToken) {
905 if ($max && $max == count($aAddress)) {
906 return $aAddress;
907 }
908 $cChar = $sToken{0};
909 switch ($cChar)
910 {
911 case '=':
912 case '"':
913 case ' ':
914 $aStack[] = $sToken;
915 break;
916 case '(':
917 $aComment[] = substr($sToken,1,-1);
918 break;
919 case ';':
920 if ($sGroup) {
921 $sEmail = trim(implode(' ',$aStack));
922 $aAddress[] = array($sGroup,$sEmail);
923 $aStack = $aComment = array();
924 $sGroup = '';
925 break;
926 }
927 case ',':
928 if (!$sEmail) {
929 while (count($aStack) && !$sEmail) {
930 $sEmail = trim(array_pop($aStack));
931 }
932 }
933 if (count($aStack)) {
934 $sPersonal = trim(implode('',$aStack));
935 } else {
936 $sPersonal = '';
937 }
938 if (!$sPersonal && count($aComment)) {
939 $sComment = implode(' ',$aComment);
940 $sPersonal .= $sComment;
941 }
942 $aAddress[] = array($sEmail,$sPersonal);
943 $sPersonal = $sComment = $sEmail = '';
944 $aStack = $aComment = array();
945 break;
946 case ':':
947 $sGroup = implode(' ',$aStack); break;
948 $aStack = array();
949 break;
950 case '<':
951 $sEmail = trim(substr($sToken,1,-1));
952 break;
953 case '>':
954 /* skip */
955 break;
956 default: $aStack[] = $sToken; break;
957 }
958 }
959 /* now do the action again for the last address */
960 if (!$sEmail) {
961 while (count($aStack) && !$sEmail) {
962 $sEmail = trim(array_pop($aStack));
963 }
964 }
965 if (count($aStack)) {
966 $sPersonal = trim(implode('',$aStack));
967 } else {
968 $sPersonal = '';
969 }
970 if (!$sPersonal && count($aComment)) {
971 $sComment = implode(' ',$aComment);
972 $sPersonal .= $sComment;
973 }
974 $aAddress[] = array($sEmail,$sPersonal);
975 return $aAddress;
976 }
977
978
979
980 /*
981 * Returns the number of unseen messages in this folder
982 */
983 function sqimap_unseen_messages ($imap_stream, $mailbox) {
984 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
985 $i = 0;
986 $regs = array(false, false);
987 while (isset($read_ary[$i])) {
988 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
989 break;
990 }
991 $i++;
992 }
993 return $regs[1];
994 }
995
996 /*
997 * Returns the number of total/unseen/recent messages in this folder
998 */
999 function sqimap_status_messages ($imap_stream, $mailbox) {
1000 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1001 $i = 0;
1002 $messages = $unseen = $recent = false;
1003 $regs = array(false,false);
1004 while (isset($read_ary[$i])) {
1005 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1006 $unseen = $regs[1];
1007 }
1008 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1009 $messages = $regs[1];
1010 }
1011 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1012 $recent = $regs[1];
1013 }
1014 $i++;
1015 }
1016 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1017 }
1018
1019
1020 /*
1021 * Saves a message to a given folder -- used for saving sent messages
1022 */
1023 function sqimap_append ($imap_stream, $sent_folder, $length) {
1024 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1025 $tmp = fgets ($imap_stream, 1024);
1026 }
1027
1028 function sqimap_append_done ($imap_stream, $folder='') {
1029 global $squirrelmail_language, $color;
1030 fputs ($imap_stream, "\r\n");
1031 $tmp = fgets ($imap_stream, 1024);
1032 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1033 set_up_language($squirrelmail_language);
1034 require_once(SM_PATH . 'functions/display_messages.php');
1035 $reason = $regs[3];
1036 if ($regs[2] == 'NO') {
1037 $string = "<b><font color=$color[2]>\n" .
1038 _("ERROR : Could not append message to") ." $folder." .
1039 "</b><br>\n" .
1040 _("Server responded: ") .
1041 $reason . "<br>\n";
1042 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1043 $string .= _("Solution: ") .
1044 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1045 ."<br>\n";
1046 }
1047 $string .= "</font>\n";
1048 error_box($string,$color);
1049 } else {
1050 $string = "<b><font color=$color[2]>\n" .
1051 _("ERROR : Bad or malformed request.") .
1052 "</b><br>\n" .
1053 _("Server responded: ") .
1054 $tmp . "</font><br>\n";
1055 error_box($string,$color);
1056 exit;
1057 }
1058 }
1059 }
1060
1061 function sqimap_get_user_server ($imap_server, $username) {
1062 if (substr($imap_server, 0, 4) != "map:") {
1063 return $imap_server;
1064 }
1065 $function = substr($imap_server, 4);
1066 return $function($username);
1067 }
1068
1069 /* This is an example that gets imapservers from yellowpages (NIS).
1070 * you can simple put map:map_yp_alias in your $imap_server_address
1071 * in config.php use your own function instead map_yp_alias to map your
1072 * LDAP whatever way to find the users imapserver. */
1073
1074 function map_yp_alias($username) {
1075 $yp = `ypmatch $username aliases`;
1076 return chop(substr($yp, strlen($username)+1));
1077 }
1078
1079 ?>