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