two more subpackage blocks
[squirrelmail.git] / functions / imap_general.php
1 <?php
2
3 /**
4 * imap_general.php
5 *
6 * Copyright (c) 1999-2004 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 * @version $Id$
12 * @package squirrelmail
13 * @subpackage imap
14 */
15
16 /** Includes.. */
17 require_once(SM_PATH . 'functions/page_header.php');
18 require_once(SM_PATH . 'functions/auth.php');
19
20
21 /**
22 * Generates a new session ID by incrementing the last one used;
23 * this ensures that each command has a unique ID.
24 * @param bool unique_id
25 * @return string IMAP session id of the form 'A000'.
26 */
27 function sqimap_session_id($unique_id = FALSE) {
28 static $sqimap_session_id = 1;
29
30 if (!$unique_id) {
31 return( sprintf("A%03d", $sqimap_session_id++) );
32 } else {
33 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
34 }
35 }
36
37 /**
38 * Both send a command and accept the result from the command.
39 * This is to allow proper session number handling.
40 */
41 function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
42 if ($imap_stream) {
43 $sid = sqimap_session_id($unique_id);
44 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
45 $tag_uid_a = explode(' ',trim($sid));
46 $tag = $tag_uid_a[0];
47 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
48 /* get the response and the message */
49 $message = $message[$tag];
50 $response = $response[$tag];
51 return $read[$tag];
52 } else {
53 global $squirrelmail_language, $color;
54 set_up_language($squirrelmail_language);
55 require_once(SM_PATH . 'functions/display_messages.php');
56 $string = "<b><font color=$color[2]>\n" .
57 _("ERROR : No available imapstream.") .
58 "</b></font>\n";
59 error_box($string,$color);
60 return false;
61 }
62 }
63
64 function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
65 &$message, $unique_id = false,$filter=false,
66 $outputstream=false,$no_return=false) {
67 if ($imap_stream) {
68 $sid = sqimap_session_id($unique_id);
69 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
70 $tag_uid_a = explode(' ',trim($sid));
71 $tag = $tag_uid_a[0];
72
73 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
74 $message, $query,$filter,$outputstream,$no_return);
75 if (empty($read)) { //Imap server dropped its connection
76 $response = '';
77 $message = '';
78 return false;
79 }
80 /* retrieve the response and the message */
81 $response = $response[$tag];
82 $message = $message[$tag];
83
84 if (!empty($read[$tag])) {
85 return $read[$tag][0];
86 } else {
87 return $read[$tag];
88 }
89 } else {
90 global $squirrelmail_language, $color;
91 set_up_language($squirrelmail_language);
92 require_once(SM_PATH . 'functions/display_messages.php');
93 $string = "<b><font color=$color[2]>\n" .
94 _("ERROR : No available imapstream.") .
95 "</b></font>\n";
96 error_box($string,$color);
97 return false;
98 }
99 }
100
101 function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
102 $sid = sqimap_session_id($unique_id);
103 $tag_uid_a = explode(' ',trim($sid));
104 $tag = $tag_uid_a[0];
105 $query = $sid . ' '.$new_query."\r\n";
106 $aQuery[$tag] = $query;
107 }
108
109 function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
110 &$aServerResponse, &$aServerMessage, $unique_id = false,
111 $filter=false,$outputstream=false,$no_return=false) {
112 $aResponse = false;
113
114 /*
115 Do not fire all calls at once to the imap-server but split the calls up
116 in portions of $iChunkSize. If we do not do that I think we misbehave as
117 IMAP client or should handle BYE calls if the IMAP-server drops the
118 connection because the number of queries is to large. This isn't tested
119 but a wild guess how it could work in the field.
120
121 After testing it on Exchange 2000 we discovered that a chunksize of 32
122 was quicker then when we raised it to 128.
123 */
124 $iQueryCount = count($aQueryList);
125 $iChunkSize = 32;
126 // array_chunk would also do the job but it's supported from php > 4.2
127 $aQueryChunks = array();
128 $iLoops = floor($iQueryCount / $iChunkSize);
129
130 if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
131
132 if (!function_exists('array_chunk')) { // arraychunk replacement
133 reset($aQueryList);
134 for($i=0;$i<$iLoops;++$i) {
135 for($j=0;$j<$iChunkSize;++$j) {
136 $key = key($aQueryList);
137 $aTmp[$key] = $aQueryList[$key];
138 if (next($aQueryList) === false) break;
139 }
140 $aQueryChunks[] = $aTmp;
141 }
142 } else {
143 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
144 }
145
146 for ($i=0;$i<$iLoops;++$i) {
147 $aQuery = $aQueryChunks[$i];
148 foreach($aQuery as $tag => $query) {
149 fputs($imap_stream,$query);
150 $aResults[$tag] = false;
151 }
152 foreach($aQuery as $tag => $query) {
153 if ($aResults[$tag] == false) {
154 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
155 $handle_errors, $response, $message, $query,
156 $filter,$outputstream,$no_return);
157 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
158 if (!empty($aResponse)) {
159 $aResults[$returned_tag] = $aResponse[0];
160 } else {
161 $aResults[$returned_tag] = $aResponse;
162 }
163 $aServerResponse[$returned_tag] = $response[$returned_tag];
164 $aServerMessage[$returned_tag] = $message[$returned_tag];
165 }
166 }
167 }
168 }
169 return $aResults;
170 }
171
172 /**
173 * Custom fgets function: gets a line from the IMAP-server,
174 * no matter how big it may be.
175 * @param stream imap_stream the stream to read from
176 * @return string a line
177 */
178 function sqimap_fgets($imap_stream) {
179 $read = '';
180 $buffer = 4096;
181 $results = '';
182 $offset = 0;
183 while (strpos($results, "\r\n", $offset) === false) {
184 if (!($read = fgets($imap_stream, $buffer))) {
185 /* this happens in case of an error */
186 /* reset $results because it's useless */
187 $results = false;
188 break;
189 }
190 if ( $results != '' ) {
191 $offset = strlen($results) - 1;
192 }
193 $results .= $read;
194 }
195 return $results;
196 }
197
198 function sqimap_fread($imap_stream,$iSize,$filter=false,
199 $outputstream=false, $no_return=false) {
200 if (!$filter || !$outputstream) {
201 $iBufferSize = $iSize;
202 } else {
203 // see php bug 24033. They changed fread behaviour %$^&$%
204 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
205 }
206 if ($iSize < $iBufferSize) {
207 $iBufferSize = $iSize;
208 }
209 $iRetrieved = 0;
210 $results = '';
211 $sRead = $sReadRem = '';
212 // NB: fread can also stop at end of a packet on sockets.
213 while ($iRetrieved < $iSize) {
214 $sRead = fread($imap_stream,$iBufferSize);
215 $iLength = strlen($sRead);
216 $iRetrieved += $iLength ;
217 $iRemaining = $iSize - $iRetrieved;
218 if ($iRemaining < $iBufferSize) {
219 $iBufferSize = $iRemaining;
220 }
221 if (!$sRead) {
222 $results = false;
223 break;
224 }
225 if ($sReadRem) {
226 $sRead = $sReadRem . $sRead;
227 $sReadRem = '';
228 }
229 if (substr($sRead,-1) !== "\n") {
230 $i = strrpos($sRead,"\n");
231 if ($i !== false && $iRetrieved<$iSize) {
232 ++$i;
233 $sReadRem = substr($sRead,$i);
234 $sRead = substr($sRead,0,$i);
235 } else if ($iLength && $iRetrieved<$iSize) { // linelength > received buffer
236 $sReadRem = $sRead;
237 $sRead = '';
238 }
239 }
240 if ($filter && $sRead) {
241 $filter($sRead);
242 }
243 if ($outputstream && $sRead) {
244 if (is_resource($outputstream)) {
245 fwrite($outputstream,$sRead);
246 } else if ($outputstream == 'php://stdout') {
247 echo $sRead;
248 }
249 }
250 if ($no_return) {
251 $sRead = '';
252 } else {
253 $results .= $sRead;
254 }
255 }
256 return $results;
257 }
258
259 /**
260 * Obsolete function, inform plugins that use it
261 * @deprecated use sqimap_run_command or sqimap_run_command_list instead
262 */
263 function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
264 &$response, &$message, $query = '') {
265 global $color, $squirrelmail_language;
266 set_up_language($squirrelmail_language);
267 require_once(SM_PATH . 'functions/display_messages.php');
268 $string = "<b><font color=$color[2]>\n" .
269 _("ERROR : Bad function call.") .
270 "</b><br>\n" .
271 _("Reason:") . ' '.
272 'There is a plugin installed which make use of the <br>' .
273 'SquirrelMail internal function sqimap_read_data_list.<br>'.
274 'Please adapt the installed plugin and let it use<br>'.
275 'sqimap_run_command or sqimap_run_command_list instead<br><br>'.
276 'The following query was issued:<br>'.
277 htmlspecialchars($query) . '<br>' . "</font><br>\n";
278 error_box($string,$color);
279 echo '</body></html>';
280 exit;
281 }
282
283 /**
284 * Function to display an error related to an IMAP-query.
285 * @param string title the caption of the error box
286 * @param string query the query that went wrong
287 * @param string message_title optional message title
288 * @param string message optional error message
289 * @param string $link an optional link to try again
290 * @return void
291 */
292 function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
293 {
294 global $color, $squirrelmail_language;
295
296 set_up_language($squirrelmail_language);
297 require_once(SM_PATH . 'functions/display_messages.php');
298 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
299 $cmd = explode(' ',$query);
300 $cmd= strtolower($cmd[0]);
301
302 if ($query != '' && $cmd != 'login')
303 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
304 if ($message_title != '')
305 $string .= $message_title;
306 if ($message != '')
307 $string .= htmlspecialchars($message);
308 $string .= "</font><br>\n";
309 if ($link != '')
310 $string .= $link;
311 error_box($string,$color);
312 }
313
314 /**
315 * Reads the output from the IMAP stream. If handle_errors is set to true,
316 * this will also handle all errors that are received. If it is not set,
317 * the errors will be sent back through $response and $message.
318 */
319 function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
320 &$response, &$message, $query = '',
321 $filter = false, $outputstream = false, $no_return = false) {
322 global $color, $squirrelmail_language;
323 $read = '';
324 if (!is_array($message)) $message = array();
325 if (!is_array($response)) $response = array();
326 $aResponse = '';
327 $resultlist = array();
328 $data = array();
329 $read = sqimap_fgets($imap_stream);
330 $i = $k = 0;
331 while ($read) {
332 $char = $read{0};
333 switch ($char)
334 {
335 case '+':
336 default:
337 $read = sqimap_fgets($imap_stream);
338 break;
339
340 case $tag{0}:
341 {
342 /* get the command */
343 $arg = '';
344 $i = strlen($tag)+1;
345 $s = substr($read,$i);
346 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
347 $arg = substr($s,0,$j);
348 }
349 $found_tag = substr($read,0,$i-1);
350 if ($found_tag) {
351 switch ($arg)
352 {
353 case 'OK':
354 case 'BAD':
355 case 'NO':
356 case 'BYE':
357 case 'PREAUTH':
358 $response[$found_tag] = $arg;
359 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
360 if (!empty($data)) {
361 $resultlist[] = $data;
362 }
363 $aResponse[$found_tag] = $resultlist;
364 $data = $resultlist = array();
365 if ($found_tag == $tag) {
366 break 3; /* switch switch while */
367 }
368 break;
369 default:
370 /* this shouldn't happen */
371 $response[$found_tag] = $arg;
372 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
373 if (!empty($data)) {
374 $resultlist[] = $data;
375 }
376 $aResponse[$found_tag] = $resultlist;
377 $data = $resultlist = array();
378 if ($found_tag == $tag) {
379 break 3; /* switch switch while */
380 }
381 }
382 }
383 $read = sqimap_fgets($imap_stream);
384 if ($read === false) { /* error */
385 break 3; /* switch switch while */
386 }
387 break;
388 } // end case $tag{0}
389
390 case '*':
391 {
392 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
393 /* check for literal */
394 $s = substr($read,-3);
395 $fetch_data = array();
396 do { /* outer loop, continue until next untagged fetch
397 or tagged reponse */
398 do { /* innerloop for fetching literals. with this loop
399 we prohibid that literal responses appear in the
400 outer loop so we can trust the untagged and
401 tagged info provided by $read */
402 if ($s === "}\r\n") {
403 $j = strrpos($read,'{');
404 $iLit = substr($read,$j+1,-3);
405 $fetch_data[] = $read;
406 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
407 if ($sLiteral === false) { /* error */
408 break 4; /* while while switch while */
409 }
410 /* backwards compattibility */
411 $aLiteral = explode("\n", $sLiteral);
412 /* release not neaded data */
413 unset($sLiteral);
414 foreach ($aLiteral as $line) {
415 $fetch_data[] = $line ."\n";
416 }
417 /* release not neaded data */
418 unset($aLiteral);
419 /* next fgets belongs to this fetch because
420 we just got the exact literalsize and there
421 must follow data to complete the response */
422 $read = sqimap_fgets($imap_stream);
423 if ($read === false) { /* error */
424 break 4; /* while while switch while */
425 }
426 $fetch_data[] = $read;
427 } else {
428 $fetch_data[] = $read;
429 }
430 /* retrieve next line and check in the while
431 statements if it belongs to this fetch response */
432 $read = sqimap_fgets($imap_stream);
433 if ($read === false) { /* error */
434 break 4; /* while while switch while */
435 }
436 /* check for next untagged reponse and break */
437 if ($read{0} == '*') break 2;
438 $s = substr($read,-3);
439 } while ($s === "}\r\n");
440 $s = substr($read,-3);
441 } while ($read{0} !== '*' &&
442 substr($read,0,strlen($tag)) !== $tag);
443 $resultlist[] = $fetch_data;
444 /* release not neaded data */
445 unset ($fetch_data);
446 } else {
447 $s = substr($read,-3);
448 do {
449 if ($s === "}\r\n") {
450 $j = strrpos($read,'{');
451 $iLit = substr($read,$j+1,-3);
452 $data[] = $read;
453 $sLiteral = fread($imap_stream,$iLit);
454 if ($sLiteral === false) { /* error */
455 $read = false;
456 break 3; /* while switch while */
457 }
458 $data[] = $sLiteral;
459 $data[] = sqimap_fgets($imap_stream);
460 } else {
461 $data[] = $read;
462 }
463 $read = sqimap_fgets($imap_stream);
464 if ($read === false) {
465 break 3; /* while switch while */
466 } else if ($read{0} == '*') {
467 break;
468 }
469 $s = substr($read,-3);
470 } while ($s === "}\r\n");
471 break 1;
472 }
473 break;
474 } // end case '*'
475 } // end switch
476 } // end while
477
478 /* error processing in case $read is false */
479 if ($read === false) {
480 unset($data);
481 if ($handle_errors) {
482 sqimap_error_box(_("ERROR : Connection dropped by imap-server."), $query);
483 exit;
484 }
485 }
486
487 /* Set $resultlist array */
488 if (!empty($data)) {
489 //$resultlist[] = $data;
490 }
491 elseif (empty($resultlist)) {
492 $resultlist[] = array();
493 }
494
495 /* Return result or handle errors */
496 if ($handle_errors == false) {
497 return $aResponse;
498 }
499 switch ($response[$tag]) {
500 case 'OK':
501 return $aResponse;
502 break;
503 case 'NO':
504 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
505 if (strstr($message[$tag], 'command resulted in') === false) {
506 sqimap_error_box(_("ERROR : Could not complete request."), $query, _("Reason Given: "), $message[$tag]);
507 echo '</body></html>';
508 exit;
509 }
510 break;
511 case 'BAD':
512 sqimap_error_box(_("ERROR : Bad or malformed request."), $query, _("Server responded: "), $message[$tag]);
513 echo '</body></html>';
514 exit;
515 case 'BYE':
516 sqimap_error_box(_("ERROR : Imap server closed the connection."), $query, _("Server responded: "), $message[$tag]);
517 echo '</body></html>';
518 exit;
519 default:
520 sqimap_error_box(_("ERROR : Unknown imap response."), $query, _("Server responded: "), $message[$tag]);
521 /* the error is displayed but because we don't know the reponse we
522 return the result anyway */
523 return $aResponse;
524 break;
525 }
526 }
527
528 function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
529 &$response, &$message, $query = '',
530 $filter=false,$outputstream=false,$no_return=false) {
531
532 $tag_uid_a = explode(' ',trim($tag_uid));
533 $tag = $tag_uid_a[0];
534
535 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
536 $response, $message, $query,$filter,$outputstream,$no_return);
537 /* sqimap_read_data should be called for one response
538 but since it just calls sqimap_retrieve_imap_response which
539 handles multiple responses we need to check for that
540 and merge the $res array IF they are seperated and
541 IF it was a FETCH response. */
542
543 // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
544 // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
545 // $result = array();
546 // foreach($res as $index=>$value) {
547 // $result = array_merge($result, $res["$index"]);
548 // }
549 // }
550 if (isset($result)) {
551 return $result[$tag];
552 }
553 else {
554 return $res;
555 }
556 }
557
558 /**
559 * Connects to the IMAP server and returns a resource identifier for use with
560 * the other SquirrelMail IMAP functions. Does NOT login!
561 * @param string server hostname of IMAP server
562 * @param int port port number to connect to
563 * @param bool tls whether to use TLS when connecting.
564 * @return imap-stream resource identifier
565 */
566 function sqimap_create_stream($server,$port,$tls=false) {
567 global $username, $use_imap_tls;
568
569 if ($tls == true) {
570 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
571 /* Use TLS by prefixing "tls://" to the hostname */
572 $server = 'tls://' . $server;
573 } else {
574 require_once(SM_PATH . 'functions/display_messages.php');
575 $string = "Unable to connect to IMAP server!<br>TLS is enabled, but this " .
576 "version of PHP does not support TLS sockets, or is missing the openssl " .
577 "extension.<br><br>Please contact your system administrator.";
578 logout_error($string,$color);
579 }
580 }
581
582 $imap_stream = fsockopen($server, $port, $error_number, $error_string, 15);
583
584 /* Do some error correction */
585 if (!$imap_stream) {
586 set_up_language($squirrelmail_language, true);
587 require_once(SM_PATH . 'functions/display_messages.php');
588 $string = sprintf (_("Error connecting to IMAP server: %s.") .
589 "<br>\r\n", $server) .
590 "$error_number : $error_string<br>\r\n";
591 logout_error($string,$color);
592 exit;
593 }
594 $server_info = fgets ($imap_stream, 1024);
595 return $imap_stream;
596 }
597
598 /**
599 * Logs the user into the imap server. If $hide is set, no error messages
600 * will be displayed. This function returns the imap connection handle.
601 */
602 function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
603 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
604 $imap_auth_mech, $sqimap_capabilities;
605
606 if (!isset($onetimepad) || empty($onetimepad)) {
607 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
608 }
609 if (!isset($sqimap_capabilities)) {
610 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION );
611 }
612
613 $host = $imap_server_address;
614 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
615
616 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
617
618 /* Decrypt the password */
619 $password = OneTimePadDecrypt($password, $onetimepad);
620
621 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
622 // We're using some sort of authentication OTHER than plain or login
623 $tag=sqimap_session_id(false);
624 if ($imap_auth_mech == 'digest-md5') {
625 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
626 } elseif ($imap_auth_mech == 'cram-md5') {
627 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
628 }
629 fputs($imap_stream,$query);
630 $answer=sqimap_fgets($imap_stream);
631 // Trim the "+ " off the front
632 $response=explode(" ",$answer,3);
633 if ($response[0] == '+') {
634 // Got a challenge back
635 $challenge=$response[1];
636 if ($imap_auth_mech == 'digest-md5') {
637 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
638 } elseif ($imap_auth_mech == 'cram-md5') {
639 $reply = cram_md5_response($username,$password,$challenge);
640 }
641 fputs($imap_stream,$reply);
642 $read=sqimap_fgets($imap_stream);
643 if ($imap_auth_mech == 'digest-md5') {
644 // DIGEST-MD5 has an extra step..
645 if (substr($read,0,1) == '+') { // OK so far..
646 fputs($imap_stream,"\r\n");
647 $read=sqimap_fgets($imap_stream);
648 }
649 }
650 $results=explode(" ",$read,3);
651 $response=$results[1];
652 $message=$results[2];
653 } else {
654 // Fake the response, so the error trap at the bottom will work
655 $response="BAD";
656 $message='IMAP server does not appear to support the authentication method selected.';
657 $message .= ' Please contact your system administrator.';
658 }
659 } elseif ($imap_auth_mech == 'login') {
660 // Original IMAP login code
661 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
662 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
663 } elseif ($imap_auth_mech == 'plain') {
664 /***
665 * SASL PLAIN
666 *
667 * RFC 2595 Chapter 6
668 *
669 * The mechanism consists of a single message from the client to the
670 * server. The client sends the authorization identity (identity to
671 * login as), followed by a US-ASCII NUL character, followed by the
672 * authentication identity (identity whose password will be used),
673 * followed by a US-ASCII NUL character, followed by the clear-text
674 * password. The client may leave the authorization identity empty to
675 * indicate that it is the same as the authentication identity.
676 *
677 **/
678 $tag=sqimap_session_id(false);
679 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ? true : false;
680 $auth = base64_encode("$username\0$username\0$password");
681 if ($sasl) {
682 // IMAP Extension for SASL Initial Client Response
683 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
684 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
685 fputs($imap_stream, $query);
686 $read = sqimap_fgets($imap_stream);
687 } else {
688 $query = $tag . " AUTHENTICATE PLAIN\r\n";
689 fputs($imap_stream, $query);
690 $read=sqimap_fgets($imap_stream);
691 if (substr($read,0,1) == '+') { // OK so far..
692 fputs($imap_stream, "$auth\r\n");
693 $read = sqimap_fgets($imap_stream);
694 }
695 }
696 $results=explode(" ",$read,3);
697 $response=$results[1];
698 $message=$results[2];
699 } else {
700 $response="BAD";
701 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
702 }
703
704 /* If the connection was not successful, lets see why */
705 if ($response != 'OK') {
706 if (!$hide) {
707 if ($response != 'NO') {
708 /* "BAD" and anything else gets reported here. */
709 $message = htmlspecialchars($message);
710 set_up_language($squirrelmail_language, true);
711 require_once(SM_PATH . 'functions/display_messages.php');
712 if ($response == 'BAD') {
713 $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
714 } else {
715 $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
716 }
717 if (isset($read) && is_array($read)) {
718 $string .= '<br>' . _("Read data:") . "<br>\n";
719 foreach ($read as $line) {
720 $string .= htmlspecialchars($line) . "<br>\n";
721 }
722 }
723 error_box($string,$color);
724 exit;
725 } else {
726 /*
727 * If the user does not log in with the correct
728 * username and password it is not possible to get the
729 * correct locale from the user's preferences.
730 * Therefore, apply the same hack as on the login
731 * screen.
732 *
733 * $squirrelmail_language is set by a cookie when
734 * the user selects language and logs out
735 */
736
737 set_up_language($squirrelmail_language, true);
738 include_once(SM_PATH . 'functions/display_messages.php' );
739 sqsession_destroy();
740 logout_error( _("Unknown user or password incorrect.") );
741 exit;
742 }
743 } else {
744 exit;
745 }
746 }
747 return $imap_stream;
748 }
749
750 /**
751 * Simply logs out the IMAP session
752 * @param stream imap_stream the IMAP connection to log out.
753 * @return void
754 */
755 function sqimap_logout ($imap_stream) {
756 /* Logout is not valid until the server returns 'BYE'
757 * If we don't have an imap_ stream we're already logged out */
758 if(isset($imap_stream) && $imap_stream)
759 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
760 }
761
762 /**
763 * Retreive the CAPABILITY string from the IMAP server.
764 * If capability is set, returns only that specific capability,
765 * else returns array of all capabilities.
766 */
767 function sqimap_capability($imap_stream, $capability='') {
768 global $sqimap_capabilities;
769 if (!is_array($sqimap_capabilities)) {
770 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
771
772 $c = explode(' ', $read[0]);
773 for ($i=2; $i < count($c); $i++) {
774 $cap_list = explode('=', $c[$i]);
775 if (isset($cap_list[1])) {
776 $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
777 } else {
778 $sqimap_capabilities[$cap_list[0]] = TRUE;
779 }
780 }
781 }
782 if ($capability) {
783 if (isset($sqimap_capabilities[$capability])) {
784 return $sqimap_capabilities[$capability];
785 } else {
786 return false;
787 }
788 }
789 return $sqimap_capabilities;
790 }
791
792 /**
793 * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
794 */
795 function sqimap_get_delimiter ($imap_stream = false) {
796 global $sqimap_delimiter, $optional_delimiter;
797
798 /* Use configured delimiter if set */
799 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
800 return $optional_delimiter;
801 }
802
803 /* Do some caching here */
804 if (!$sqimap_delimiter) {
805 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
806 /*
807 * According to something that I can't find, this is supposed to work on all systems
808 * OS: This won't work in Courier IMAP.
809 * OS: According to rfc2342 response from NAMESPACE command is:
810 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
811 * OS: We want to lookup all personal NAMESPACES...
812 */
813 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
814 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
815 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
816 $pn = $data2[1];
817 }
818 $pna = explode(')(', $pn);
819 while (list($k, $v) = each($pna)) {
820 $lst = explode('"', $v);
821 if (isset($lst[3])) {
822 $pn[$lst[1]] = $lst[3];
823 } else {
824 $pn[$lst[1]] = '';
825 }
826 }
827 }
828 $sqimap_delimiter = $pn[0];
829 } else {
830 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
831 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
832 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
833 $quote_position = strpos ($read[0], '"');
834 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
835 }
836 }
837 return $sqimap_delimiter;
838 }
839
840 /**
841 * This encodes a mailbox name for use in IMAP commands.
842 * @param string what the mailbox to encode
843 * @return string the encoded mailbox string
844 */
845 function sqimap_encode_mailbox_name($what)
846 {
847 if (ereg("[\"\\\r\n]", $what))
848 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
849 return '"' . $what . '"'; /* 4.3 quoted string form */
850 }
851
852
853 /**
854 * Gets the number of messages in the current mailbox.
855 */
856 function sqimap_get_num_messages ($imap_stream, $mailbox) {
857 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
858 for ($i = 0; $i < count($read_ary); $i++) {
859 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
860 return $regs[1];
861 }
862 }
863 return false; //"BUG! Couldn't get number of messages in $mailbox!";
864 }
865
866 function parseAddress($address, $max=0) {
867 $aTokens = array();
868 $aAddress = array();
869 $iCnt = strlen($address);
870 $aSpecials = array('(' ,'<' ,',' ,';' ,':');
871 $aReplace = array(' (',' <',' ,',' ;',' :');
872 $address = str_replace($aSpecials,$aReplace,$address);
873 $i = $iAddrFound = $bGroup = 0;
874 while ($i < $iCnt) {
875 $cChar = $address{$i};
876 switch($cChar)
877 {
878 case '<':
879 $iEnd = strpos($address,'>',$i+1);
880 if (!$iEnd) {
881 $sToken = substr($address,$i);
882 $i = $iCnt;
883 } else {
884 $sToken = substr($address,$i,$iEnd - $i +1);
885 $i = $iEnd;
886 }
887 $sToken = str_replace($aReplace, $aSpecials,$sToken);
888 $aTokens[] = $sToken;
889 break;
890 case '"':
891 $iEnd = strpos($address,$cChar,$i+1);
892 if ($iEnd) {
893 // skip escaped quotes
894 $prev_char = $address{$iEnd-1};
895 while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
896 $iEnd = strpos($address,$cChar,$iEnd+1);
897 if ($iEnd) {
898 $prev_char = $address{$iEnd-1};
899 } else {
900 $prev_char = false;
901 }
902 }
903 }
904 if (!$iEnd) {
905 $sToken = substr($address,$i);
906 $i = $iCnt;
907 } else {
908 // also remove the surrounding quotes
909 $sToken = substr($address,$i+1,$iEnd - $i -1);
910 $i = $iEnd;
911 }
912 $sToken = str_replace($aReplace, $aSpecials,$sToken);
913 if ($sToken) $aTokens[] = $sToken;
914 break;
915 case '(':
916 $iEnd = strpos($address,')',$i);
917 if (!$iEnd) {
918 $sToken = substr($address,$i);
919 $i = $iCnt;
920 } else {
921 $sToken = substr($address,$i,$iEnd - $i + 1);
922 $i = $iEnd;
923 }
924 $sToken = str_replace($aReplace, $aSpecials,$sToken);
925 $aTokens[] = $sToken;
926 break;
927 case ',':
928 ++$iAddrFound;
929 case ';':
930 if (!$bGroup) {
931 ++$iAddrFound;
932 } else {
933 $bGroup = false;
934 }
935 if ($max && $max == $iAddrFound) {
936 break 2;
937 } else {
938 $aTokens[] = $cChar;
939 break;
940 }
941 case ':':
942 $bGroup = true;
943 case ' ':
944 $aTokens[] = $cChar;
945 break;
946 default:
947 $iEnd = strpos($address,' ',$i+1);
948 if ($iEnd) {
949 $sToken = trim(substr($address,$i,$iEnd - $i));
950 $i = $iEnd-1;
951 } else {
952 $sToken = trim(substr($address,$i));
953 $i = $iCnt;
954 }
955 if ($sToken) $aTokens[] = $sToken;
956 }
957 ++$i;
958 }
959 $sPersonal = $sEmail = $sComment = $sGroup = '';
960 $aStack = $aComment = array();
961 foreach ($aTokens as $sToken) {
962 if ($max && $max == count($aAddress)) {
963 return $aAddress;
964 }
965 $cChar = $sToken{0};
966 switch ($cChar)
967 {
968 case '=':
969 case '"':
970 case ' ':
971 $aStack[] = $sToken;
972 break;
973 case '(':
974 $aComment[] = substr($sToken,1,-1);
975 break;
976 case ';':
977 if ($sGroup) {
978 $sEmail = trim(implode(' ',$aStack));
979 $aAddress[] = array($sGroup,$sEmail);
980 $aStack = $aComment = array();
981 $sGroup = '';
982 break;
983 }
984 case ',':
985 if (!$sEmail) {
986 while (count($aStack) && !$sEmail) {
987 $sEmail = trim(array_pop($aStack));
988 }
989 }
990 if (count($aStack)) {
991 $sPersonal = trim(implode('',$aStack));
992 } else {
993 $sPersonal = '';
994 }
995 if (!$sPersonal && count($aComment)) {
996 $sComment = implode(' ',$aComment);
997 $sPersonal .= $sComment;
998 }
999 $aAddress[] = array($sEmail,$sPersonal);
1000 $sPersonal = $sComment = $sEmail = '';
1001 $aStack = $aComment = array();
1002 break;
1003 case ':':
1004 $sGroup = implode(' ',$aStack); break;
1005 $aStack = array();
1006 break;
1007 case '<':
1008 $sEmail = trim(substr($sToken,1,-1));
1009 break;
1010 case '>':
1011 /* skip */
1012 break;
1013 default: $aStack[] = $sToken; break;
1014 }
1015 }
1016 /* now do the action again for the last address */
1017 if (!$sEmail) {
1018 while (count($aStack) && !$sEmail) {
1019 $sEmail = trim(array_pop($aStack));
1020 }
1021 }
1022 if (count($aStack)) {
1023 $sPersonal = trim(implode('',$aStack));
1024 } else {
1025 $sPersonal = '';
1026 }
1027 if (!$sPersonal && count($aComment)) {
1028 $sComment = implode(' ',$aComment);
1029 $sPersonal .= $sComment;
1030 }
1031 $aAddress[] = array($sEmail,$sPersonal);
1032 return $aAddress;
1033 }
1034
1035
1036 /**
1037 * Returns the number of unseen messages in this folder.
1038 */
1039 function sqimap_unseen_messages ($imap_stream, $mailbox) {
1040 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (UNSEEN)', false, $result, $message);
1041 $i = 0;
1042 $regs = array(false, false);
1043 while (isset($read_ary[$i])) {
1044 if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
1045 break;
1046 }
1047 $i++;
1048 }
1049 return $regs[1];
1050 }
1051
1052 /**
1053 * Returns the number of total/unseen/recent messages in this folder
1054 */
1055 function sqimap_status_messages ($imap_stream, $mailbox) {
1056 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . ' (MESSAGES UNSEEN RECENT)', false, $result, $message);
1057 $i = 0;
1058 $messages = $unseen = $recent = false;
1059 $regs = array(false,false);
1060 while (isset($read_ary[$i])) {
1061 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1062 $unseen = $regs[1];
1063 }
1064 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1065 $messages = $regs[1];
1066 }
1067 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1068 $recent = $regs[1];
1069 }
1070 $i++;
1071 }
1072 return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
1073 }
1074
1075
1076 /**
1077 * Saves a message to a given folder -- used for saving sent messages
1078 */
1079 function sqimap_append ($imap_stream, $sent_folder, $length) {
1080 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) \{$length}\r\n");
1081 $tmp = fgets ($imap_stream, 1024);
1082 }
1083
1084 function sqimap_append_done ($imap_stream, $folder='') {
1085 global $squirrelmail_language, $color;
1086 fputs ($imap_stream, "\r\n");
1087 $tmp = fgets ($imap_stream, 1024);
1088 if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
1089 set_up_language($squirrelmail_language);
1090 require_once(SM_PATH . 'functions/display_messages.php');
1091 $reason = $regs[3];
1092 if ($regs[2] == 'NO') {
1093 $string = "<b><font color=$color[2]>\n" .
1094 _("ERROR : Could not append message to") ." $folder." .
1095 "</b><br>\n" .
1096 _("Server responded: ") .
1097 $reason . "<br>\n";
1098 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
1099 $string .= _("Solution: ") .
1100 _("Remove unneccessary messages from your folder and start with your Trash folder.")
1101 ."<br>\n";
1102 }
1103 $string .= "</font>\n";
1104 error_box($string,$color);
1105 } else {
1106 $string = "<b><font color=$color[2]>\n" .
1107 _("ERROR : Bad or malformed request.") .
1108 "</b><br>\n" .
1109 _("Server responded: ") .
1110 $tmp . "</font><br>\n";
1111 error_box($string,$color);
1112 exit;
1113 }
1114 }
1115 }
1116
1117 function sqimap_get_user_server ($imap_server, $username) {
1118 if (substr($imap_server, 0, 4) != "map:") {
1119 return $imap_server;
1120 }
1121 $function = substr($imap_server, 4);
1122 return $function($username);
1123 }
1124
1125 /**
1126 * This is an example that gets imapservers from yellowpages (NIS).
1127 * you can simple put map:map_yp_alias in your $imap_server_address
1128 * in config.php use your own function instead map_yp_alias to map your
1129 * LDAP whatever way to find the users imapserver.
1130 */
1131 function map_yp_alias($username) {
1132 $yp = `ypmatch $username aliases`;
1133 return chop(substr($yp, strlen($username)+1));
1134 }
1135
1136 ?>