Correct on the fly base64 decode algoritm in case the returned data does not
[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 $iBufferSize = 62400; // multiple of 78 in case of base64 decoding.
191 }
192 $iRet = $iSize - $iBufferSize;
193 $iRetrieved = 0;
194 $i = 0;
195 $results = $sReadRem = '';
196 $bFinished = $bBufferSizeAdapted = $bBufferIsOk = false;
197 while (($iRetrieved < ($iSize - $iBufferSize))) {
198 $sRead = fread($imap_stream,$iBufferSize);
199 if (!$sRead) {
200 $results = false;
201 break;
202 }
203 $iRetrieved += $iBufferSize;
204 // if the returned lines are split, do not end with \n
205 // then we have a problem and need to adjust (happened with uw)
206 if ($bBufferSizeAdapted && substr($sRead,-1) !== "\n") {
207 // use fgets because it stops at \n.
208 // we can do it because it's for correction
209 $sRead .= fgets($imap_stream,$iBufferSize);
210 $iRetrieved += strlen($sRead);
211 if ($iRetrieved == $iSize) {
212 $bFinished = true;
213 }
214 }
215 if ($filter) {
216 // in case line-endings do not appear at position 78 we adapt the buffersize so we can base64 decode on the fly
217 if (!$bBufferSizeAdapted) {
218 $i = strpos($sRead,"\n");
219 if ($i) {
220 ++$i;
221 $iFragments = floor($iBufferSize / $i);
222 $iNewBufferSize = $iFragments * $i;
223 $iRemainder = $iNewBufferSize + $i - $iBufferSize;
224 if ($iNewBufferSize == $iBufferSize) {
225 $bBufferIsOk = true;
226 $iRemainder = 0;
227 $iNewBufferSize = $iBufferSize;
228 $bBufferSizeAdapted = true;
229 }
230 if (!$bBufferIsOk && ($iRemainder + $iBufferSize) < $iSize) {
231 $sReadRem = fread($imap_stream,$iRemainder);
232 } else if (!$bBufferIsOk) {
233 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
234 $bFinished = true;
235 }
236 if (!$sReadRem && $sReadRem !== '') {
237 $results = false;
238 break;
239 }
240 $iBufferSize = $iNewBufferSize;
241 $bBufferSizeAdapted = true;
242 } else {
243 $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
244 $bFinished = true;
245 if (!$sReadRem) {
246 $results = false;
247 break;
248 }
249 }
250 $sRead .= $sReadRem;
251 $iRetrieved += $iRemainder;
252 unset($sReadRem);
253 }
254 $filter($sRead);
255 }
256 if ($outputstream) {
257 if (is_resource($outputstream)) {
258 fwrite($outputstream,$sRead);
259 } else if ($outputstream == 'php://stdout') {
260 echo $sRead;
261 }
262 }
263 if ($no_return) {
264 $sRead = '';
265 }
266 $results .= $sRead;
267 }
268 if (!$results && !$bFinished) {
269 $sRead = fread($imap_stream,($iSize - ($iRetrieved)));
270 if ($filter) {
271 $filter($sRead);
272 }
273 if ($outputstream) {
274 if (is_resource($outputstream)) {
275 fwrite($outputstream,$sRead);
276 } else if ($outputstream == 'php://stdout') { // FIXME
277 echo $sRead;
278 }
279 }
280 if ($no_return) {
281 $sRead = '';
282 }
283 $results .= $sRead;
284 }
285 return $results;
286 }
287 /* obsolete function, inform plugins that use it */
288 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
289 &$response, &$message, $query = '') {
290 global $color, $squirrelmail_language;
291 set_up_language($squirrelmail_language);
292 require_once(SM_PATH . 'functions/display_messages.php');
293 $string = "<b><font color=$color[2]>\n" .
294 _("ERROR : Bad function call.") .
295 "</b><br>\n" .
296 _("Reason:") . ' '.
297 'There is a plugin installed which make use of the <br>' .
298 'SquirrelMail internal function sqimap_read_data_list.<br>'.
299 'Please adapt the installed plugin and let it use<br>'.
300 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
301 'The following query was issued:<br>'.
302 htmlspecialchars($query) . '<br>' . "</font><br>\n";
303 error_box($string,$color);
304 echo '</body></html>';
305 exit;
306 }
307
308 /*
309 * Reads the output from the IMAP stream. If handle_errors is set to true,
310 * this will also handle all errors that are received. If it is not set,
311 * the errors will be sent back through $response and $message
312 */
313
314 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
315 &$response, &$message, $query = '',
316 $filter = false, $outputstream = false, $no_return = false) {
317 global $color, $squirrelmail_language;
318 $read = '';
319 if (!is_array($message)) $message = array();
320 if (!is_array($response)) $response = array();
321 $resultlist = array();
322 $data = array();
323 $read = sqimap_fgets($imap_stream);
324 $i = $k = 0;
325 while ($read) {
326 $char = $read{0};
327 switch ($char)
328 {
329 case '+':
330 default:
331 $read = sqimap_fgets($imap_stream);
332 break;
333
334 case $tag{0}:
335 {
336 /* get the command */
337 $arg = '';
338 $i = strlen($tag)+1;
339 $s = substr($read,$i);
340 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
341 $arg = substr($s,0,$j);
342 }
343 $found_tag = substr($read,0,$i-1);
344 if ($found_tag) {
345 switch ($arg)
346 {
347 case 'OK':
348 case 'BAD':
349 case 'NO':
350 case 'BYE':
351 case 'PREAUTH':
352 $response[$found_tag] = $arg;
353 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
354 if (!empty($data)) {
355 $resultlist[] = $data;
356 }
357 $aResponse[$found_tag] = $resultlist;
358 $data = $resultlist = array();
359 if ($found_tag == $tag) {
360 break 3; /* switch switch while */
361 }
362 break;
363 default:
364 /* this shouldn't happen */
365 $response[$found_tag] = $arg;
366 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
367 if (!empty($data)) {
368 $resultlist[] = $data;
369 }
370 $aResponse[$found_tag] = $resultlist;
371 $data = $resultlist = array();
372 if ($found_tag == $tag) {
373 break 3; /* switch switch while */
374 }
375 }
376 }
377 $read = sqimap_fgets($imap_stream);
378 if ($read === false) { /* error */
379 break 3; /* switch switch while */
380 }
381 break;
382 } // end case $tag{0}
383
384 case '*':
385 {
386 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
387 /* check for literal */
388 $s = substr($read,-3);
389 $fetch_data = array();
390 do { /* outer loop, continue until next untagged fetch
391 or tagged reponse */
392 do { /* innerloop for fetching literals. with this loop
393 we prohibid that literal responses appear in the
394 outer loop so we can trust the untagged and
395 tagged info provided by $read */
396 if ($s === "}\r\n") {
397 $j = strrpos($read,'{');
398 $iLit = substr($read,$j+1,-3);
399 $fetch_data[] = $read;
400 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
401 if ($sLiteral === false) { /* error */
402 break 4; /* while while switch while */
403 }
404 /* backwards compattibility */
405 $aLiteral = explode("\n", $sLiteral);
406 /* release not neaded data */
407 unset($sLiteral);
408 foreach ($aLiteral as $line) {
409 $fetch_data[] = $line ."\n";
410 }
411 /* release not neaded data */
412 unset($aLiteral);
413 /* next fgets belongs to this fetch because
414 we just got the exact literalsize and there
415 must follow data to complete the response */
416 $read = sqimap_fgets($imap_stream);
417 if ($read === false) { /* error */
418 break 4; /* while while switch while */
419 }
420 $fetch_data[] = $read;
421 } else {
422 $fetch_data[] = $read;
423 }
424 /* retrieve next line and check in the while
425 statements if it belongs to this fetch response */
426 $read = sqimap_fgets($imap_stream);
427 if ($read === false) { /* error */
428 break 4; /* while while switch while */
429 }
430 /* check for next untagged reponse and break */
431 if ($read{0} == '*') break 2;
432 $s = substr($read,-3);
433 } while ($s === "}\r\n");
434 $s = substr($read,-3);
435 } while ($read{0} !== '*' &&
436 substr($read,0,strlen($tag)) !== $tag);
437 $resultlist[] = $fetch_data;
438 /* release not neaded data */
439 unset ($fetch_data);
440 } else {
441 $s = substr($read,-3);
442 do {
443 if ($s === "}\r\n") {
444 $j = strrpos($read,'{');
445 $iLit = substr($read,$j+1,-3);
446 $data[] = $read;
447 $sLiteral = fread($imap_stream,$iLit);
448 if ($sLiteral === false) { /* error */
449 $read = false;
450 break 3; /* while switch while */
451 }
452 $data[] = $sLiteral;
453 $data[] = sqimap_fgets($imap_stream);
454 } else {
455 $data[] = $read;
456 }
457 $read = sqimap_fgets($imap_stream);
458 if ($read === false) {
459 break 3; /* while switch while */
460 } else if ($read{0} == '*') {
461 break;
462 }
463 $s = substr($read,-3);
464 } while ($s === "}\r\n");
465 break 1;
466 }
467 break;
468 } // end case '*'
469 } // end switch
470 } // end while
471
472 /* error processing in case $read is false */
473 if ($read === false) {
474 unset($data);
475 set_up_language($squirrelmail_language);
476 require_once(SM_PATH . 'functions/display_messages.php');
477 $string = "<b><font color=$color[2]>\n" .
478 _("ERROR : Connection dropped by imap-server.") .
479 "</b><br>\n" .
480 _("Query:") . ' '.
481 htmlspecialchars($query) . '<br>' . "</font><br>\n";
482 error_box($string,$color);
483 exit;
484 }
485
486 /* Set $resultlist array */
487 if (!empty($data)) {
488 //$resultlist[] = $data;
489 }
490 elseif (empty($resultlist)) {
491 $resultlist[] = array();
492 }
493
494 /* Return result or handle errors */
495 if ($handle_errors == false) {
496 return $aResponse;
497 return( $resultlist );
498 }
499 switch ($response[$tag])
500 {
501 case 'OK':
502 return $aResponse;
503 break;
504 case 'NO':
505 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
506 if (strstr($message[$tag], 'command resulted in') === false) {
507 set_up_language($squirrelmail_language);
508 require_once(SM_PATH . 'functions/display_messages.php');
509 $string = "<b><font color=$color[2]>\n" .
510 _("ERROR : Could not complete request.") .
511 "</b><br>\n" .
512 _("Query:") . ' ' .
513 htmlspecialchars($query) . '<br>' .
514 _("Reason Given: ") .
515 htmlspecialchars($message[$tag]) . "</font><br>\n";
516 error_box($string,$color);
517 echo '</body></html>';
518 exit;
519 }
520 break;
521 case 'BAD':
522 set_up_language($squirrelmail_language);
523 require_once(SM_PATH . 'functions/display_messages.php');
524 $string = "<b><font color=$color[2]>\n" .
525 _("ERROR : Bad or malformed request.") .
526 "</b><br>\n" .
527 _("Query:") . ' '.
528 htmlspecialchars($query) . '<br>' .
529 _("Server responded: ") .
530 htmlspecialchars($message[$tag]) . "</font><br>\n";
531 error_box($string,$color);
532 echo '</body></html>';
533 exit;
534 case 'BYE':
535 set_up_language($squirrelmail_language);
536 require_once(SM_PATH . 'functions/display_messages.php');
537 $string = "<b><font color=$color[2]>\n" .
538 _("ERROR : Imap server closed the connection.") .
539 "</b><br>\n" .
540 _("Query:") . ' '.
541 htmlspecialchars($query) . '<br>' .
542 _("Server responded: ") .
543 htmlspecialchars($message[$tag]) . "</font><br>\n";
544 error_box($string,$color);
545 echo '</body></html>';
546 exit;
547 default:
548 set_up_language($squirrelmail_language);
549 require_once(SM_PATH . 'functions/display_messages.php');
550 $string = "<b><font color=$color[2]>\n" .
551 _("ERROR : Unknown imap response.") .
552 "</b><br>\n" .
553 _("Query:") . ' '.
554 htmlspecialchars($query) . '<br>' .
555 _("Server responded: ") .
556 htmlspecialchars($message[$tag]) . "</font><br>\n";
557 error_box($string,$color);
558 /* the error is displayed but because we don't know the reponse we
559 return the result anyway */
560 return $aResponse;
561 break;
562 }
563 }
564
565 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
566 &$response, &$message, $query = '',
567 $filter=false,$outputstream=false,$no_return=false) {
568
569 $tag_uid_a = explode(' ',trim($tag_uid));
570 $tag = $tag_uid_a[0];
571
572 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
573 $response, $message, $query,$filter,$outputstream,$no_return);
574 /* sqimap_read_data should be called for one response
575 but since it just calls sqimap_retrieve_imap_response which
576 handles multiple responses we need to check for that
577 and merge the $res array IF they are seperated and
578 IF it was a FETCH response. */
579
580 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
581 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
582 // $result = array();
583 // foreach($res as $index=>$value) {
584 // $result = array_merge($result, $res["$index"]);
585 // }
586 // }
587 if (isset($result)) {
588 return $result[$tag];
589 }
590 else {
591 return $res;
592 }
593 }
594
595 /*
596 * Logs the user into the imap server. If $hide is set, no error messages
597 * will be displayed. This function returns the imap connection handle.
598 */
599 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
600 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
601
602 if (!isset($onetimepad) || empty($onetimepad)) {
603 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
604 }
605 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
606 $host=$imap_server_address;
607
608 if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
609 /* Use TLS by prefixing "tls://" to the hostname */
610 $imap_server_address = 'tls://' . $imap_server_address;
611 }
612
613 $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
614
615 /* Do some error correction */
616 if (!$imap_stream) {
617 if (!$hide) {
618 set_up_language($squirrelmail_language, true);
619 require_once(SM_PATH . 'functions/display_messages.php');
620 $string = sprintf (_("Error connecting to IMAP server: %s.") .
621 "<br>\r\n", $imap_server_address) .
622 "$error_number : $error_string<br>\r\n";
623 logout_error($string,$color);
624 }
625 exit;
626 }
627
628 $server_info = fgets ($imap_stream, 1024);
629
630 /* Decrypt the password */
631 $password = OneTimePadDecrypt($password, $onetimepad);
632
633 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
634 // We're using some sort of authentication OTHER than plain or login
635 $tag=sqimap_session_id(false);
636 if ($imap_auth_mech == 'digest-md5') {
637 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
638 } elseif ($imap_auth_mech == 'cram-md5') {
639 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
640 }
641 fputs($imap_stream,$query);
642 $answer=sqimap_fgets($imap_stream);
643 // Trim the "+ " off the front
644 $response=explode(" ",$answer,3);
645 if ($response[0] == '+') {
646 // Got a challenge back
647 $challenge=$response[1];
648 if ($imap_auth_mech == 'digest-md5') {
649 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
650 } elseif ($imap_auth_mech == 'cram-md5') {
651 $reply = cram_md5_response($username,$password,$challenge);
652 }
653 fputs($imap_stream,$reply);
654 $read=sqimap_fgets($imap_stream);
655 if ($imap_auth_mech == 'digest-md5') {
656 // DIGEST-MD5 has an extra step..
657 if (substr($read,0,1) == '+') { // OK so far..
658 fputs($imap_stream,"\r\n");
659 $read=sqimap_fgets($imap_stream);
660 }
661 }
662 $results=explode(" ",$read,3);
663 $response=$results[1];
664 $message=$results[2];
665 } else {
666 // Fake the response, so the error trap at the bottom will work
667 $response="BAD";
668 $message='IMAP server does not appear to support the authentication method selected.';
669 $message .= ' Please contact your system administrator.';
670 }
671 } elseif ($imap_auth_mech == 'login') {
672 // Original IMAP login code
673 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
674 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
675 } elseif ($imap_auth_mech == 'plain') {
676 /* Replace this with SASL PLAIN if it ever gets implemented */
677 $response="BAD";
678 $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
679 } else {
680 $response="BAD";
681 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
682 }
683
684 /* If the connection was not successful, lets see why */
685 if ($response != 'OK') {
686 if (!$hide) {
687 if ($response != 'NO') {
688 /* "BAD" and anything else gets reported here. */
689 $message = htmlspecialchars($message);
690 set_up_language($squirrelmail_language, true);
691 require_once(SM_PATH . 'functions/display_messages.php');
692 if ($response == 'BAD') {
693 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
694 } else {
695 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
696 }
697 if (isset($read) && is_array($read)) {
698 $string .= '<br>' . _("Read data:") . "<br>\n";
699 foreach ($read as $line) {
700 $string .= htmlspecialchars($line) . "<br>\n";
701 }
702 }
703 error_box($string,$color);
704 exit;
705 } else {
706 /*
707 * If the user does not log in with the correct
708 * username and password it is not possible to get the
709 * correct locale from the user's preferences.
710 * Therefore, apply the same hack as on the login
711 * screen.
712 *
713 * $squirrelmail_language is set by a cookie when
714 * the user selects language and logs out
715 */
716
717 set_up_language($squirrelmail_language, true);
718 include_once(SM_PATH . 'functions/display_messages.php' );
719 sqsession_destroy();
720 logout_error( _("Unknown user or password incorrect.") );
721 exit;
722 }
723 } else {
724 exit;
725 }
726 }
727 return $imap_stream;
728 }
729
730 /* Simply logs out the IMAP session */
731 function sqimap_logout ($imap_stream) {
732 /* Logout is not valid until the server returns 'BYE'
733 * If we don't have an imap_ stream we're already logged out */
734 if(isset($imap_stream) && $imap_stream)
735 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
736 }
737
738 function sqimap_capability($imap_stream, $capability='') {
739 global $sqimap_capabilities;
740 if (!is_array($sqimap_capabilities)) {
741 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
742
743 $c = explode(' ', $read[0]);
744 for ($i=2; $i < count($c); $i++) {
745 $cap_list = explode('=', $c[$i]);
746 if (isset($cap_list[1])) {
747 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
748 } else {
749 $sqimap_capabilities[$cap_list[0]] = TRUE;
750 }
751 }
752 }
753 if ($capability) {
754 if (isset($sqimap_capabilities[$capability])) {
755 return $sqimap_capabilities[$capability];
756 } else {
757 return false;
758 }
759 }
760 return $sqimap_capabilities;
761 }
762
763 /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
764 function sqimap_get_delimiter ($imap_stream = false) {
765 global $sqimap_delimiter, $optional_delimiter;
766
767 /* Use configured delimiter if set */
768 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
769 return $optional_delimiter;
770 }
771
772 /* Do some caching here */
773 if (!$sqimap_delimiter) {
774 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
775 /*
776 * According to something that I can't find, this is supposed to work on all systems
777 * OS: This won't work in Courier IMAP.
778 * OS: According to rfc2342 response from NAMESPACE command is:
779 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
780 * OS: We want to lookup all personal NAMESPACES...
781 */
782 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
783 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
784 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
785 $pn = $data2[1];
786 }
787 $pna = explode(')(', $pn);
788 while (list($k, $v) = each($pna)) {
789 $lst = explode('"', $v);
790 if (isset($lst[3])) {
791 $pn[$lst[1]] = $lst[3];
792 } else {
793 $pn[$lst[1]] = '';
794 }
795 }
796 }
797 $sqimap_delimiter = $pn[0];
798 } else {
799 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
800 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
801 $quote_position = strpos ($read[0], '"');
802 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
803 }
804 }
805 return $sqimap_delimiter;
806 }
807
808
809 /* This is a straight copy of imap_mailbox.php:encode_mailbox_name() */
810 function sqimap_encode_mailbox_name($what)
811 {
812 if (ereg("[\"\\\r\n]", $what))
813 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
814 return '"' . $what . '"'; /* 4.3 quoted string form */
815 }
816
817
818 /* Gets the number of messages in the current mailbox. */
819 function sqimap_get_num_messages ($imap_stream, $mailbox) {
820 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
821 for ($i = 0; $i < count($read_ary); $i++) {
822 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
823 return $regs[1];
824 }
825 }
826 return false; //"BUG! Couldn't get number of messages in $mailbox!";
827 }
828
829
830 function parseAddress($address, $max=0) {
831 $aTokens = array();
832 $aAddress = array();
833 $iCnt = strlen($address);
834 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
835 $aReplace = array(' (',' <',' ,',' ;',' :');
836 $address = str_replace($aSpecials,$aReplace,$address);
837 $i = $iAddrFound = $bGroup = 0;
838 while ($i < $iCnt) {
839 $cChar = $address{$i};
840 switch($cChar)
841 {
842 case '<':
843 $iEnd = strpos($address,'>',$i+1);
844 if (!$iEnd) {
845 $sToken = substr($address,$i);
846 $i = $iCnt;
847 } else {
848 $sToken = substr($address,$i,$iEnd - $i +1);
849 $i = $iEnd;
850 }
851 $sToken = str_replace($aReplace, $aSpecials,$sToken);
852 $aTokens[] = $sToken;
853 break;
854 case '"':
855 $iEnd = strpos($address,$cChar,$i+1);
856 if ($iEnd) {
857 // skip escaped quotes
858 $prev_char = $address{$iEnd-1};
859 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
860 $iEnd = strpos($address,$cChar,$iEnd+1);
861 if ($iEnd) {
862 $prev_char = $address{$iEnd-1};
863 } else {
864 $prev_char = false;
865 }
866 }
867 }
868 if (!$iEnd) {
869 $sToken = substr($address,$i);
870 $i = $iCnt;
871 } else {
872 // also remove the surrounding quotes
873 $sToken = substr($address,$i+1,$iEnd - $i -1);
874 $i = $iEnd;
875 }
876 $sToken = str_replace($aReplace, $aSpecials,$sToken);
877 if ($sToken) $aTokens[] = $sToken;
878 break;
879 case '(':
880 $iEnd = strpos($address,')',$i);
881 if (!$iEnd) {
882 $sToken = substr($address,$i);
883 $i = $iCnt;
884 } else {
885 $sToken = substr($address,$i,$iEnd - $i + 1);
886 $i = $iEnd;
887 }
888 $sToken = str_replace($aReplace, $aSpecials,$sToken);
889 $aTokens[] = $sToken;
890 break;
891 case ',':
892 ++$iAddrFound;
893 case ';':
894 if (!$bGroup) {
895 ++$iAddrFound;
896 } else {
897 $bGroup = false;
898 }
899 if ($max && $max == $iAddrFound) {
900 break 2;
901 } else {
902 $aTokens[] = $cChar;
903 break;
904 }
905 case ':':
906 $bGroup = true;
907 case ' ':
908 $aTokens[] = $cChar;
909 break;
910 default:
911 $iEnd = strpos($address,' ',$i+1);
912 if ($iEnd) {
913 $sToken = trim(substr($address,$i,$iEnd - $i));
914 $i = $iEnd-1;
915 } else {
916 $sToken = trim(substr($address,$i));
917 $i = $iCnt;
918 }
919 if ($sToken) $aTokens[] = $sToken;
920 }
921 ++$i;
922 }
923 $sPersonal = $sEmail = $sComment = $sGroup = '';
924 $aStack = $aComment = array();
925 foreach ($aTokens as $sToken) {
926 if ($max && $max == count($aAddress)) {
927 return $aAddress;
928 }
929 $cChar = $sToken{0};
930 switch ($cChar)
931 {
932 case '=':
933 case '"':
934 case ' ':
935 $aStack[] = $sToken;
936 break;
937 case '(':
938 $aComment[] = substr($sToken,1,-1);
939 break;
940 case ';':
941 if ($sGroup) {
942 $sEmail = trim(implode(' ',$aStack));
943 $aAddress[] = array($sGroup,$sEmail);
944 $aStack = $aComment = array();
945 $sGroup = '';
946 break;
947 }
948 case ',':
949 if (!$sEmail) {
950 while (count($aStack) && !$sEmail) {
951 $sEmail = trim(array_pop($aStack));
952 }
953 }
954 if (count($aStack)) {
955 $sPersonal = trim(implode('',$aStack));
956 } else {
957 $sPersonal = '';
958 }
959 if (!$sPersonal && count($aComment)) {
960 $sComment = implode(' ',$aComment);
961 $sPersonal .= $sComment;
962 }
963 $aAddress[] = array($sEmail,$sPersonal);
964 $sPersonal = $sComment = $sEmail = '';
965 $aStack = $aComment = array();
966 break;
967 case ':':
968 $sGroup = implode(' ',$aStack); break;
969 $aStack = array();
970 break;
971 case '<':
972 $sEmail = trim(substr($sToken,1,-1));
973 break;
974 case '>':
975 /* skip */
976 break;
977 default: $aStack[] = $sToken; break;
978 }
979 }
980 /* now do the action again for the last address */
981 if (!$sEmail) {
982 while (count($aStack) && !$sEmail) {
983 $sEmail = trim(array_pop($aStack));
984 }
985 }
986 if (count($aStack)) {
987 $sPersonal = trim(implode('',$aStack));
988 } else {
989 $sPersonal = '';
990 }
991 if (!$sPersonal && count($aComment)) {
992 $sComment = implode(' ',$aComment);
993 $sPersonal .= $sComment;
994 }
995 $aAddress[] = array($sEmail,$sPersonal);
996 return $aAddress;
997 }
998
999
1000
1001 /*
1002 * Returns the number of unseen messages in this folder
1003 */
1004 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1005 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
1006 $i = 0;
1007 $regs = array(false, false);
1008 while (isset($read_ary[$i])) {
1009 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
1010 break;
1011 }
1012 $i++;
1013 }
1014 return $regs[1];
1015 }
1016
1017 /*
1018 * Returns the number of unseen/total messages in this folder
1019 */
1020 function sqimap_status_messages ($imap_stream, $mailbox) {
1021 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1022 $i = 0;
1023 $messages = $unseen = $recent = false;
1024 $regs = array(false,false);
1025 while (isset($read_ary[$i])) {
1026 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1027 $unseen = $regs[1];
1028 }
1029 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1030 $messages = $regs[1];
1031 }
1032 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1033 $recent = $regs[1];
1034 }
1035 $i++;
1036 }
1037 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1038 }
1039
1040
1041 /*
1042 * Saves a message to a given folder -- used for saving sent messages
1043 */
1044 function sqimap_append ($imap_stream, $sent_folder, $length) {
1045 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1046 $tmp = fgets ($imap_stream, 1024);
1047 }
1048
1049 function sqimap_append_done ($imap_stream, $folder='') {
1050 global $squirrelmail_language, $color;
1051 fputs ($imap_stream, "\r\n");
1052 $tmp = fgets ($imap_stream, 1024);
1053 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1054 set_up_language($squirrelmail_language);
1055 require_once(SM_PATH . 'functions/display_messages.php');
1056 $reason = $regs[3];
1057 if ($regs[2] == 'NO') {
1058 $string = "<b><font color=$color[2]>\n" .
1059 _("ERROR : Could not append message to") ." $folder." .
1060 "</b><br>\n" .
1061 _("Server responded: ") .
1062 $reason . "<br>\n";
1063 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1064 $string .= _("Solution: ") .
1065 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1066 ."<br>\n";
1067 }
1068 $string .= "</font>\n";
1069 error_box($string,$color);
1070 } else {
1071 $string = "<b><font color=$color[2]>\n" .
1072 _("ERROR : Bad or malformed request.") .
1073 "</b><br>\n" .
1074 _("Server responded: ") .
1075 $tmp . "</font><br>\n";
1076 error_box($string,$color);
1077 exit;
1078 }
1079 }
1080 }
1081
1082 function sqimap_get_user_server ($imap_server, $username) {
1083 if (substr($imap_server, 0, 4) != "map:") {
1084 return $imap_server;
1085 }
1086 $function = substr($imap_server, 4);
1087 return $function($username);
1088 }
1089
1090 /* This is an example that gets imapservers from yellowpages (NIS).
1091 * you can simple put map:map_yp_alias in your $imap_server_address
1092 * in config.php use your own function instead map_yp_alias to map your
1093 * LDAP whatever way to find the users imapserver. */
1094
1095 function map_yp_alias($username) {
1096 $yp = `ypmatch $username aliases`;
1097 return chop(substr($yp, strlen($username)+1));
1098 }
1099
1100 ?>