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