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