fsf changes, meant to be rebased on upstream
[squirrelmail.git] / functions / imap_general.php
... / ...
CommitLineData
1<?php
2
3/**
4 * imap_general.php
5 *
6 * This implements all functions that do general IMAP functions.
7 *
8 * @copyright 1999-2022 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 * @subpackage imap
13 */
14
15/** Includes.. */
16
17require_once(SM_PATH . 'functions/rfc822address.php');
18
19
20/**
21 * Generates a new session ID by incrementing the last one used;
22 * this ensures that each command has a unique ID.
23 * @param bool $unique_id (since 1.3.0) controls use of unique
24 * identifiers/message sequence numbers in IMAP commands. See IMAP
25 * rfc 'UID command' chapter.
26 * @return string IMAP session id of the form 'A000'.
27 * @since 1.2.0
28 */
29function sqimap_session_id($unique_id = FALSE) {
30 static $sqimap_session_id = 1;
31
32 if (!$unique_id) {
33 return( sprintf("A%03d", $sqimap_session_id++) );
34 } else {
35 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
36 }
37}
38
39/**
40 * Both send a command and accept the result from the command.
41 * This is to allow proper session number handling.
42 * @param stream $imap_stream imap connection resource
43 * @param string $query imap command
44 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
45 * @param array $response
46 * @param array $message
47 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
48 * @return mixed returns false on imap error. displays error message
49 * if imap stream is not available.
50 * @since 1.2.3
51 */
52function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
53 if ($imap_stream) {
54 $sid = sqimap_session_id($unique_id);
55 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
56 $tag_uid_a = explode(' ',trim($sid));
57 $tag = $tag_uid_a[0];
58 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
59 /* get the response and the message */
60 $message = $message[$tag];
61 $response = $response[$tag];
62 return $read[$tag];
63//FIXME: obey $handle_errors below!
64 } else {
65 global $squirrelmail_language, $color;
66 set_up_language($squirrelmail_language);
67//FIXME: NO HTML IN CORE!
68 $string = "<b><font color=\"$color[2]\">\n" .
69 _("ERROR: No available IMAP stream.") .
70//FIXME: NO HTML IN CORE!
71 "</b></font>\n";
72 error_box($string);
73 return false;
74 }
75}
76
77/**
78 * @param stream $imap_stream imap connection resource
79 * @param string $query imap command
80 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
81 * @param array $response empty string, if return = false
82 * @param array $message empty string, if return = false
83 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
84 * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
85 * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
86 * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
87 * @return mixed returns false on imap error. displays error message
88 * if imap stream is not available.
89 * @since 1.2.3
90 */
91function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
92 &$message, $unique_id = false,$filter=false,
93 $outputstream=false,$no_return=false) {
94 if ($imap_stream) {
95 $sid = sqimap_session_id($unique_id);
96 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
97 $tag_uid_a = explode(' ',trim($sid));
98 $tag = $tag_uid_a[0];
99
100 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
101 $message, $query,$filter,$outputstream,$no_return);
102 if (empty($read)) { //IMAP server dropped its connection
103 $response = '';
104 $message = '';
105 return false;
106 }
107 /* retrieve the response and the message */
108 $response = $response[$tag];
109 $message = $message[$tag];
110
111 if (!empty($read[$tag])) {
112 /* sqimap_read_data should be called for one response
113 but since it just calls sqimap_retrieve_imap_response
114 which handles multiple responses we need to check for
115 that and merge the $read[$tag] array IF they are
116 separated and IF it was a FETCH response. */
117
118 if (isset($read[$tag][1]) && is_array($read[$tag][1]) && isset($read[$tag][1][0])
119 && preg_match('/^\* \d+ FETCH/', $read[$tag][1][0])) {
120 $result = array();
121 foreach($read[$tag] as $index => $value) {
122 $result = array_merge($result, $read[$tag]["$index"]);
123 }
124 return $result;
125 }
126
127 return $read[$tag][0];
128 } else {
129 return $read[$tag];
130 }
131//FIXME: obey $handle_errors below!
132 } else {
133 global $squirrelmail_language, $color;
134 set_up_language($squirrelmail_language);
135//FIXME: NO HTML IN CORE!
136 $string = "<b><font color=\"$color[2]\">\n" .
137 _("ERROR: No available IMAP stream.") .
138//FIXME: NO HTML IN CORE!
139 "</b></font>\n";
140 error_box($string);
141 return false;
142 }
143}
144
145/**
146 * @param mixed $new_query
147 * @param string $tag
148 * @param array $aQuery
149 * @param boolean $unique_id see sqimap_session_id()
150 * @since 1.5.0
151 */
152function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
153 $sid = sqimap_session_id($unique_id);
154 $tag_uid_a = explode(' ',trim($sid));
155 $tag = $tag_uid_a[0];
156 $query = $sid . ' '.$new_query."\r\n";
157 $aQuery[$tag] = $query;
158}
159
160/**
161 * @param stream $imap_stream imap stream
162 * @param array $aQueryList
163 * @param boolean $handle_errors
164 * @param array $aServerResponse
165 * @param array $aServerMessage
166 * @param boolean $unique_id see sqimap_session_id()
167 * @param boolean $filter see sqimap_fread()
168 * @param mixed $outputstream see sqimap_fread()
169 * @param boolean $no_return see sqimap_fread()
170 * @since 1.5.0
171 */
172function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
173 &$aServerResponse, &$aServerMessage, $unique_id = false,
174 $filter=false,$outputstream=false,$no_return=false) {
175 $aResponse = false;
176
177 /*
178 Do not fire all calls at once to the IMAP server but split the calls up
179 in portions of $iChunkSize. If we do not do that I think we misbehave as
180 IMAP client or should handle BYE calls if the IMAP server drops the
181 connection because the number of queries is to large. This isn't tested
182 but a wild guess how it could work in the field.
183
184 After testing it on Exchange 2000 we discovered that a chunksize of 32
185 was quicker then when we raised it to 128.
186 */
187 $iQueryCount = count($aQueryList);
188 $iChunkSize = 32;
189 // array_chunk would also do the job but it's supported from php > 4.2
190 $aQueryChunks = array();
191 $iLoops = floor($iQueryCount / $iChunkSize);
192
193 if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
194
195 if (!function_exists('array_chunk')) { // arraychunk replacement
196 reset($aQueryList);
197 for($i=0;$i<$iLoops;++$i) {
198 for($j=0;$j<$iChunkSize;++$j) {
199 $key = key($aQueryList);
200 $aTmp[$key] = $aQueryList[$key];
201 if (next($aQueryList) === false) break;
202 }
203 $aQueryChunks[] = $aTmp;
204 }
205 } else {
206 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
207 }
208
209 for ($i=0;$i<$iLoops;++$i) {
210 $aQuery = $aQueryChunks[$i];
211 foreach($aQuery as $tag => $query) {
212 fputs($imap_stream,$query);
213 $aResults[$tag] = false;
214 }
215 foreach($aQuery as $tag => $query) {
216 if ($aResults[$tag] == false) {
217 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
218 $handle_errors, $response, $message, $query,
219 $filter,$outputstream,$no_return);
220 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
221 if (!empty($aResponse)) {
222 $aResults[$returned_tag] = $aResponse[0];
223 } else {
224 $aResults[$returned_tag] = $aResponse;
225 }
226 $aServerResponse[$returned_tag] = $response[$returned_tag];
227 $aServerMessage[$returned_tag] = $message[$returned_tag];
228 }
229 }
230 }
231 }
232 return $aResults;
233}
234
235/**
236 * Custom fgets function: gets a line from the IMAP server,
237 * no matter how big it may be.
238 * @param stream $imap_stream the stream to read from
239 * @return string a line
240 * @since 1.2.8
241 */
242function sqimap_fgets($imap_stream) {
243 $read = '';
244 $buffer = 4096;
245 $results = '';
246 $offset = 0;
247 while (strpos($results, "\r\n", $offset) === false) {
248 if (!($read = fgets($imap_stream, $buffer))) {
249 /* this happens in case of an error */
250 /* reset $results because it's useless */
251 $results = false;
252 break;
253 }
254 if ( $results != '' ) {
255 $offset = strlen($results) - 1;
256 }
257 $results .= $read;
258 }
259 return $results;
260}
261
262/**
263 * @param stream $imap_stream
264 * @param integer $iSize
265 * @param boolean $filter
266 * @param mixed $outputstream stream or 'php://stdout' string
267 * @param boolean $no_return controls data returned by function
268 * @return string
269 * @since 1.4.1
270 */
271function sqimap_fread($imap_stream,$iSize,$filter=false,
272 $outputstream=false, $no_return=false) {
273 if (!$filter || !$outputstream) {
274 $iBufferSize = $iSize;
275 } else {
276 // see php bug 24033. They changed fread behaviour %$^&$%
277 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
278 }
279 if ($iSize < $iBufferSize) {
280 $iBufferSize = $iSize;
281 }
282
283 $iRetrieved = 0;
284 $results = '';
285 $sRead = $sReadRem = '';
286 // NB: fread can also stop at end of a packet on sockets.
287 while ($iRetrieved < $iSize) {
288 $sRead = fread($imap_stream,$iBufferSize);
289 $iLength = strlen($sRead);
290 $iRetrieved += $iLength ;
291 $iRemaining = $iSize - $iRetrieved;
292 if ($iRemaining < $iBufferSize) {
293 $iBufferSize = $iRemaining;
294 }
295 if ($sRead == '') {
296 $results = false;
297 break;
298 }
299 if ($sReadRem != '') {
300 $sRead = $sReadRem . $sRead;
301 $sReadRem = '';
302 }
303
304 if ($filter && $sRead != '') {
305 // in case the filter is base64 decoding we return a remainder
306 $sReadRem = $filter($sRead);
307 }
308 if ($outputstream && $sRead != '') {
309 if (is_resource($outputstream)) {
310 fwrite($outputstream,$sRead);
311 } else if ($outputstream == 'php://stdout') {
312 echo $sRead;
313 }
314 }
315 if ($no_return) {
316 $sRead = '';
317 } else {
318 $results .= $sRead;
319 }
320 }
321 return $results;
322}
323
324
325/**
326 * Obsolete function, inform plugins that use it
327 * @param stream $imap_stream
328 * @param string $tag
329 * @param boolean $handle_errors
330 * @param array $response
331 * @param array $message
332 * @param string $query
333 * @since 1.1.3
334 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
335 */
336function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
337 &$response, &$message, $query = '') {
338 global $color, $oTemplate, $squirrelmail_language;
339 set_up_language($squirrelmail_language);
340//FIXME: NO HTML IN CORE!
341 $string = "<b><font color=\"$color[2]\">\n" .
342 _("ERROR: Bad function call.") .
343//FIXME: NO HTML IN CORE!
344 "</b><br />\n" .
345 _("Reason:") . ' '.
346 'There is a plugin installed which make use of the <br />' .
347 'SquirrelMail internal function sqimap_read_data_list.<br />'.
348 'Please adapt the installed plugin and let it use<br />'.
349 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
350 'The following query was issued:<br />'.
351//FIXME: NO HTML IN CORE!
352 sm_encode_html_special_chars($query) . '<br />' . "</font><br />\n";
353 error_box($string);
354 $oTemplate->display('footer.tpl');
355 exit;
356}
357
358/**
359 * Function to display an error related to an IMAP query.
360 * @param string title the caption of the error box
361 * @param string query the query that went wrong
362 * @param string message_title optional message title
363 * @param string message optional error message
364 * @param string $link an optional link to try again
365 * @return void
366 * @since 1.5.0
367 */
368function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
369{
370 global $color, $squirrelmail_language;
371
372 set_up_language($squirrelmail_language);
373//FIXME: NO HTML IN CORE!
374 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
375 $cmd = explode(' ',$query);
376 $cmd= strtolower($cmd[0]);
377
378 if ($query != '' && $cmd != 'login')
379 $string .= _("Query:") . ' ' . sm_encode_html_special_chars($query) . '<br />';
380 if ($message_title != '')
381 $string .= $message_title;
382 if ($message != '')
383 $string .= sm_encode_html_special_chars($message);
384//FIXME: NO HTML IN CORE!
385 $string .= "</font><br />\n";
386 if ($link != '')
387 $string .= $link;
388 error_box($string);
389}
390
391/**
392 * Reads the output from the IMAP stream. If handle_errors is set to true,
393 * this will also handle all errors that are received. If it is not set,
394 * the errors will be sent back through $response and $message.
395 * @param stream $imap_stream imap stream
396 * @param string $tag
397 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
398 * @param array $response
399 * @param array $message
400 * @param string $query command that can be printed if something fails
401 * @param boolean $filter see sqimap_fread()
402 * @param mixed $outputstream see sqimap_fread()
403 * @param boolean $no_return see sqimap_fread()
404 * @since 1.5.0
405 */
406function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
407 &$response, &$message, $query = '',
408 $filter = false, $outputstream = false, $no_return = false) {
409 global $color, $squirrelmail_language;
410 $read = '';
411 if (!is_array($message)) $message = array();
412 if (!is_array($response)) $response = array();
413 $aResponse = array();
414 $resultlist = array();
415 $data = array();
416 $sCommand = '';
417 if (preg_match("/^(\w+)\s*/",$query,$aMatch)) {
418 $sCommand = strtoupper($aMatch[1]);
419 } else {
420 // error reporting (shouldn't happen)
421 }
422 $read = sqimap_fgets($imap_stream);
423 $i = 0;
424 while ($read) {
425 $char = $read[0];
426 switch ($char)
427 {
428 case '+':
429 default:
430 $read = sqimap_fgets($imap_stream);
431 break;
432
433 case $tag[0]:
434 {
435 /* get the command */
436 $arg = '';
437 $i = strlen($tag)+1;
438 $s = substr($read,$i);
439 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
440 $arg = substr($s,0,$j);
441 }
442 $found_tag = substr($read,0,$i-1);
443 if ($found_tag) {
444 switch ($arg)
445 {
446 case 'OK':
447 case 'BAD':
448 case 'NO':
449 case 'BYE':
450 case 'PREAUTH':
451 $response[$found_tag] = $arg;
452 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
453 if (!empty($data)) {
454 $resultlist[] = $data;
455 }
456 $aResponse[$found_tag] = $resultlist;
457 $data = $resultlist = array();
458 if ($found_tag == $tag) {
459 break 3; /* switch switch while */
460 }
461 break;
462 default:
463 /* this shouldn't happen */
464 $response[$found_tag] = $arg;
465 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
466 if (!empty($data)) {
467 $resultlist[] = $data;
468 }
469 $aResponse[$found_tag] = $resultlist;
470 $data = $resultlist = array();
471 if ($found_tag == $tag) {
472 break 3; /* switch switch while */
473 }
474 }
475 }
476 $read = sqimap_fgets($imap_stream);
477 if ($read === false) { /* error */
478 break 2; /* switch while */
479 }
480 break;
481 } // end case $tag[0]
482
483 case '*':
484 {
485 if (($sCommand == "FETCH" || $sCommand == "STORE") && preg_match('/^\*\s\d+\sFETCH/',$read)) {
486 /* check for literal */
487 $s = substr($read,-3);
488 $fetch_data = array();
489 do { /* outer loop, continue until next untagged fetch
490 or tagged reponse */
491 do { /* innerloop for fetching literals. with this loop
492 we prohibid that literal responses appear in the
493 outer loop so we can trust the untagged and
494 tagged info provided by $read */
495 $read_literal = false;
496 if ($s === "}\r\n") {
497 $j = strrpos($read,'{');
498 $iLit = substr($read,$j+1,-3);
499 $fetch_data[] = $read;
500 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
501 if ($sLiteral === false) { /* error */
502 break 4; /* while while switch while */
503 }
504 /* backwards compattibility */
505 $aLiteral = explode("\n", $sLiteral);
506 /* release not neaded data */
507 unset($sLiteral);
508 foreach ($aLiteral as $line) {
509 $fetch_data[] = $line ."\n";
510 }
511 /* release not neaded data */
512 unset($aLiteral);
513 /* next fgets belongs to this fetch because
514 we just got the exact literalsize and there
515 must follow data to complete the response */
516 $read = sqimap_fgets($imap_stream);
517 if ($read === false) { /* error */
518 break 4; /* while while switch while */
519 }
520 $s = substr($read,-3);
521 $read_literal = true;
522 continue;
523 } else {
524 $fetch_data[] = $read;
525 }
526 /* retrieve next line and check in the while
527 statements if it belongs to this fetch response */
528 $read = sqimap_fgets($imap_stream);
529 if ($read === false) { /* error */
530 break 4; /* while while switch while */
531 }
532 /* check for next untagged reponse and break */
533 if ($read[0] == '*') break 2;
534 $s = substr($read,-3);
535 } while ($s === "}\r\n" || $read_literal);
536 $s = substr($read,-3);
537 } while ($read[0] !== '*' &&
538 substr($read,0,strlen($tag)) !== $tag);
539 $resultlist[] = $fetch_data;
540 /* release not neaded data */
541 unset ($fetch_data);
542 } else {
543 $s = substr($read,-3);
544 do {
545 if ($s === "}\r\n") {
546 $j = strrpos($read,'{');
547 $iLit = substr($read,$j+1,-3);
548 // check for numeric value to avoid that untagged responses like:
549 // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
550 // will trigger literal fetching ({SET:debug=51} !== int )
551 if (is_numeric($iLit)) {
552 $data[] = $read;
553 $sLiteral = fread($imap_stream,$iLit);
554 if ($sLiteral === false) { /* error */
555 $read = false;
556 break 3; /* while switch while */
557 }
558 $data[] = $sLiteral;
559 $data[] = sqimap_fgets($imap_stream);
560 } else {
561 $data[] = $read;
562 }
563 } else {
564 $data[] = $read;
565 }
566 $read = sqimap_fgets($imap_stream);
567 if ($read === false) {
568 break 3; /* while switch while */
569 } else if ($read[0] == '*') {
570 break;
571 }
572 $s = substr($read,-3);
573 } while ($s === "}\r\n");
574 break 1;
575 }
576 break;
577 } // end case '*'
578 } // end switch
579 } // end while
580
581 /* error processing in case $read is false */
582 if ($read === false) {
583 // try to retrieve an untagged bye respons from the results
584 $sResponse = array_pop($data);
585 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
586 if (!$handle_errors) {
587 $query = '';
588 }
589 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
590//FIXME: NO HTML IN CORE!
591 echo '</body></html>';
592 exit;
593 } else if ($handle_errors) {
594 unset($data);
595 sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
596 exit;
597 }
598 }
599
600 /* Set $resultlist array */
601 if (!empty($data)) {
602 //$resultlist[] = $data;
603 }
604 elseif (empty($resultlist)) {
605 $resultlist[] = array();
606 }
607
608 /* Return result or handle errors */
609 if ($handle_errors == false) {
610 return $aResponse;
611 }
612 switch ($response[$tag]) {
613 case 'OK':
614 return $aResponse;
615 break;
616 case 'NO':
617 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
618 if (strstr($message[$tag], 'command resulted in') === false) {
619 sqsession_register('NO', 'IMAP_FATAL_ERROR_TYPE');
620 sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
621 sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
622 sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
623 echo '</body></html>';
624 exit;
625 }
626 break;
627 case 'BAD':
628 sqsession_register('BAD', 'IMAP_FATAL_ERROR_TYPE');
629 sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
630 sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
631 sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
632//FIXME: NO HTML IN CORE!
633 echo '</body></html>';
634 exit;
635 case 'BYE':
636 sqsession_register('BYE', 'IMAP_FATAL_ERROR_TYPE');
637 sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
638 sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
639 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
640//FIXME: NO HTML IN CORE!
641 echo '</body></html>';
642 exit;
643 default:
644 sqsession_register('UNKNOWN', 'IMAP_FATAL_ERROR_TYPE');
645 sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
646 sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
647 sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
648 /* the error is displayed but because we don't know the reponse we
649 return the result anyway */
650 return $aResponse;
651 break;
652 }
653}
654
655/**
656 * @param stream $imap_stream imap string
657 * @param string $tag_uid
658 * @param boolean $handle_errors
659 * @param array $response
660 * @param array $message
661 * @param string $query (since 1.2.5)
662 * @param boolean $filter (since 1.4.1) see sqimap_fread()
663 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
664 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
665 */
666function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
667 &$response, &$message, $query = '',
668 $filter=false,$outputstream=false,$no_return=false) {
669
670 $tag_uid_a = explode(' ',trim($tag_uid));
671 $tag = $tag_uid_a[0];
672
673 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
674 $response, $message, $query,$filter,$outputstream,$no_return);
675 return $res;
676}
677
678/**
679 * Connects to the IMAP server and returns a resource identifier for use with
680 * the other SquirrelMail IMAP functions. Does NOT login!
681 * @param string server hostname of IMAP server
682 * @param int port port number to connect to
683 * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
684 * Argument was boolean before 1.5.1.
685 * @param array $stream_options Stream context options, see config_local.php
686 * for more details (OPTIONAL)
687 * @return imap-stream resource identifier
688 * @since 1.5.0 (usable only in 1.5.1 or later)
689 */
690function sqimap_create_stream($server,$port,$tls=0,$stream_options=array()) {
691 global $squirrelmail_language;
692
693 if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
694 // numerical IPv6 address must be enclosed in square brackets
695 $server = '['.$server.']';
696 }
697
698 // NB: Using "ssl://" ensures the highest possible TLS version
699 // will be negotiated with the server (whereas "tls://" only
700 // uses TLS version 1.0)
701 //
702 if ($tls == 1) {
703 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
704 if (function_exists('stream_socket_client')) {
705 $server_address = 'ssl://' . $server . ':' . $port;
706 $ssl_context = @stream_context_create($stream_options);
707 $connect_timeout = ini_get('default_socket_timeout');
708 // null timeout is broken
709 if ($connect_timeout == 0)
710 $connect_timeout = 15;
711 $imap_stream = @stream_socket_client($server_address, $error_number, $error_string, $connect_timeout, STREAM_CLIENT_CONNECT, $ssl_context);
712 } else {
713 $imap_stream = @fsockopen('ssl://' . $server, $port, $error_number, $error_string, 15);
714 }
715 } else {
716 require_once(SM_PATH . 'functions/display_messages.php');
717 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
718 '<br />'.
719 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
720 '<br /><br />'.
721 _("Please contact your system administrator and report this error."),
722 sprintf(_("Error connecting to IMAP server: %s."), $server));
723 }
724 } else {
725 $imap_stream = @fsockopen($server, $port, $error_number, $error_string, 15);
726 }
727
728
729 /* Do some error correction */
730 if (!$imap_stream) {
731 set_up_language($squirrelmail_language, true);
732 require_once(SM_PATH . 'functions/display_messages.php');
733 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
734//FIXME: NO HTML IN CORE!
735 "<br />\r\n$error_number : $error_string<br />\r\n",
736 sprintf(_("Error connecting to IMAP server: %s."), $server) );
737 exit;
738 }
739 $server_info = fgets ($imap_stream, 1024);
740
741 /**
742 * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
743 * http://www.php.net/stream-socket-enable-crypto
744 */
745 if ($tls === 2) {
746 if (function_exists('stream_socket_enable_crypto')) {
747 // check starttls capability, don't use cached capability version
748 if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
749 // imap server does not declare starttls support
750 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
751 '','',
752 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
753 exit;
754 }
755
756 // issue starttls command and check response
757 sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
758 // check response
759 if ($starttls_response!='OK') {
760 // starttls command failed
761 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
762 'STARTTLS',
763 _("Server replied:") . ' ',
764 $starttls_message);
765 exit();
766 }
767
768 // start crypto on connection. suppress function errors.
769 if (@stream_socket_enable_crypto($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
770 // starttls was successful
771
772 /**
773 * RFC 2595 requires to discard CAPABILITY information after successful
774 * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
775 * information only after successful login (src/redirect.php) and cached information
776 * is used only in other php script connections after successful STARTTLS. If script
777 * issues sqimap_capability() call before sqimap_login() and wants to get initial
778 * capability response, script should set third sqimap_capability() argument to false.
779 */
780 //sqsession_unregister('sqimap_capabilities');
781 } else {
782 /**
783 * stream_socket_enable_crypto() call failed. Possible issues:
784 * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
785 * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
786 * suppressed in stream_socket_enable_crypto() call)
787 */
788 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
789 '','',
790 _("Unable to start TLS."));
791 /**
792 * Bug: stream_socket_enable_crypto() does not register SSL errors in
793 * openssl_error_string() or stream notification wrapper and displays
794 * them in E_WARNING level message. It is impossible to retrieve error
795 * message without own error handler.
796 */
797 exit;
798 }
799 } else {
800 // php install does not support stream_socket_enable_crypto() function
801 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
802 '','',
803 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
804 exit;
805 }
806 }
807 return $imap_stream;
808}
809
810/**
811 * Logs the user into the IMAP server. If $hide is set, no error messages
812 * will be displayed (if set to 1, just exits, if set to 2, returns FALSE).
813 * This function returns the IMAP connection handle.
814 * @param string $username user name
815 * @param string $password password encrypted with onetimepad. Since 1.5.2
816 * function can use internal password functions, if parameter is set to
817 * boolean false.
818 * @param string $imap_server_address address of imap server
819 * @param integer $imap_port port of imap server
820 * @param int $hide controls display connection errors:
821 * 0 = do not hide
822 * 1 = show no errors (just exit)
823 * 2 = show no errors (return FALSE)
824 * 3 = show no errors (return error string)
825 * @param array $stream_options Stream context options, see config_local.php
826 * for more details (OPTIONAL)
827 * @return mixed The IMAP connection stream, or if the connection fails,
828 * FALSE if $hide is set to 2 or an error string if $hide
829 * is set to 3.
830 */
831function sqimap_login ($username, $password, $imap_server_address,
832 $imap_port, $hide, $stream_options=array()) {
833 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
834 $imap_auth_mech, $sqimap_capabilities, $display_imap_login_error;
835
836 // Note/TODO: This hack grabs the $authz argument from the session. In the short future,
837 // a new argument in function sqimap_login() will be used instead.
838 $authz = '';
839 global $authz;
840 sqgetglobalvar('authz' , $authz , SQ_SESSION);
841
842 if(!empty($authz)) {
843 /* authz plugin - specific:
844 * Get proxy login parameters from authz plugin configuration. If they
845 * exist, they will override the current ones.
846 * This is useful if we want to use different SASL authentication mechanism
847 * and/or different TLS settings for proxy logins. */
848 global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
849 $imap_auth_mech = !empty($authz_imap_auth_mech) ? strtolower($authz_imap_auth_mech) : $imap_auth_mech;
850 $use_imap_tls = !empty($authz_use_imap_tls)? $authz_use_imap_tls : $use_imap_tls;
851 $imap_port = !empty($authz_use_imap_tls)? $authz_imapPort_tls : $imap_port;
852
853 if($imap_auth_mech == 'login' || $imap_auth_mech == 'cram-md5') {
854 logout_error("Misconfigured Plugin (authz or equivalent):<br/>".
855 "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
856 exit;
857 }
858 }
859
860 /* get imap login password */
861 if ($password===false) {
862 /* standard functions */
863 $password = sqauth_read_password();
864 } else {
865 /* old way. $key must be extracted from cookie */
866 if (!isset($onetimepad) || empty($onetimepad)) {
867 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
868 }
869 /* Decrypt the password */
870 $password = OneTimePadDecrypt($password, $onetimepad);
871 }
872
873 if (!isset($sqimap_capabilities)) {
874 sqgetglobalvar('sqimap_capabilities' , $sqimap_capabilities , SQ_SESSION );
875 }
876
877 $host = $imap_server_address;
878 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
879
880 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls,$stream_options);
881
882 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
883 // We're using some sort of authentication OTHER than plain or login
884 $tag=sqimap_session_id(false);
885 if ($imap_auth_mech == 'digest-md5') {
886 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
887 } elseif ($imap_auth_mech == 'cram-md5') {
888 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
889 }
890 fputs($imap_stream,$query);
891 $answer=sqimap_fgets($imap_stream);
892 // Trim the "+ " off the front
893 $response=explode(" ",$answer,3);
894 if ($response[0] == '+') {
895 // Got a challenge back
896 $challenge=$response[1];
897 if ($imap_auth_mech == 'digest-md5') {
898 $reply = digest_md5_response($username,$password,$challenge,'imap',$host,$authz);
899 } elseif ($imap_auth_mech == 'cram-md5') {
900 $reply = cram_md5_response($username,$password,$challenge);
901 }
902 fputs($imap_stream,$reply);
903 $read=sqimap_fgets($imap_stream);
904 if ($imap_auth_mech == 'digest-md5') {
905 // DIGEST-MD5 has an extra step..
906 if (substr($read,0,1) == '+') { // OK so far..
907 fputs($imap_stream,"\r\n");
908 $read=sqimap_fgets($imap_stream);
909 }
910 }
911 // IMAP server might return some untagged info before
912 // the tagged login command response - skip over that
913 while ($read[0] === '*') {
914 $read = sqimap_fgets($imap_stream);
915 }
916 $results=explode(" ",$read,3);
917 $response=$results[1];
918 $message=$results[2];
919 } else {
920 // Fake the response, so the error trap at the bottom will work
921 $response="BAD";
922 $message='IMAP server does not appear to support the authentication method selected.';
923 $message .= ' Please contact your system administrator.';
924 }
925 } elseif ($imap_auth_mech == 'login') {
926 // Original IMAP login code
927 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
928 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
929 } elseif ($imap_auth_mech == 'plain') {
930 /***
931 * SASL PLAIN, RFC 4616 (updates 2595)
932 *
933 * The mechanism consists of a single message, a string of [UTF-8]
934 * encoded [Unicode] characters, from the client to the server. The
935 * client presents the authorization identity (identity to act as),
936 * followed by a NUL (U+0000) character, followed by the authentication
937 * identity (identity whose password will be used), followed by a NUL
938 * (U+0000) character, followed by the clear-text password. As with
939 * other SASL mechanisms, the client does not provide an authorization
940 * identity when it wishes the server to derive an identity from the
941 * credentials and use that as the authorization identity.
942 */
943 $tag=sqimap_session_id(false);
944 $sasl = sqimap_capability($imap_stream, 'SASL-IR');
945 if(!empty($authz)) {
946 $auth = base64_encode("$username\0$authz\0$password");
947 } else {
948 $auth = base64_encode("$username\0$username\0$password");
949 }
950 if ($sasl) {
951 // IMAP Extension for SASL Initial Client Response
952 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
953 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
954 fputs($imap_stream, $query);
955 $read = sqimap_fgets($imap_stream);
956 } else {
957 $query = $tag . " AUTHENTICATE PLAIN\r\n";
958 fputs($imap_stream, $query);
959 $read=sqimap_fgets($imap_stream);
960 if (substr($read,0,1) == '+') { // OK so far..
961 fputs($imap_stream, "$auth\r\n");
962 $read = sqimap_fgets($imap_stream);
963 }
964 }
965 // IMAP server might return some untagged info before
966 // the tagged login command response - skip over that
967 while ($read[0] === '*') {
968 $read = sqimap_fgets($imap_stream);
969 }
970 $results=explode(" ",$read,3);
971 $response=$results[1];
972 $message=$results[2];
973
974 } else {
975 $response="BAD";
976 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
977 }
978
979 /* If the connection was not successful, lets see why */
980 if ($response != 'OK') {
981 if (!$hide || $hide == 3) {
982//FIXME: UUURG... We don't want HTML in error messages, should also do html sanitizing of error messages elsewhere; should't assume output is destined for an HTML browser here
983 if ($response != 'NO') {
984 /* "BAD" and anything else gets reported here. */
985 $message = sm_encode_html_special_chars($message);
986 set_up_language($squirrelmail_language, true);
987 if ($response == 'BAD') {
988 if ($hide == 3) return sprintf(_("Bad request: %s"), $message);
989 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
990 } else {
991 if ($hide == 3) return sprintf(_("Unknown error: %s"), $message);
992 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
993 }
994 if (isset($read) && is_array($read)) {
995 $string .= '<br />' . _("Read data:") . "<br />\n";
996 foreach ($read as $line) {
997 $string .= sm_encode_html_special_chars($line) . "<br />\n";
998 }
999 }
1000 error_box($string);
1001 exit;
1002 } else {
1003 /*
1004 * If the user does not log in with the correct
1005 * username and password it is not possible to get the
1006 * correct locale from the user's preferences.
1007 * Therefore, apply the same hack as on the login
1008 * screen.
1009 *
1010 * $squirrelmail_language is set by a cookie when
1011 * the user selects language and logs out
1012 */
1013
1014 set_up_language($squirrelmail_language, true);
1015 sqsession_destroy();
1016
1017 /* terminate the session nicely */
1018 sqimap_logout($imap_stream);
1019
1020 // determine what error message to use
1021 //
1022 $fail_msg = _("Unknown user or password incorrect.");
1023 if ($display_imap_login_error) {
1024 // See if there is an error message from the server
1025 // Skip any rfc5530 response code: '[something]' at the
1026 // start of the message
1027 if (!empty($message)
1028 && $message[0] == '['
1029 && ($end = strstr($message, ']'))
1030 && $end != ']') {
1031 $message = substr($end, 1);
1032 }
1033 // Remove surrounding spaces and if there
1034 // is anything left, display that as the
1035 // error message:
1036 $message = trim($message);
1037 if (strlen($message))
1038 $fail_msg = _($message);
1039 }
1040
1041 if ($hide == 3) return $fail_msg;
1042 logout_error($fail_msg);
1043 exit;
1044 }
1045 } else {
1046 if ($hide == 2) return FALSE;
1047 exit;
1048 }
1049 }
1050
1051 /* Special error case:
1052 * Login referrals. The server returns:
1053 * ? OK [REFERRAL <imap url>]
1054 * Check RFC 2221 for details. Since we do not support login referrals yet
1055 * we log the user out.
1056 */
1057 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
1058 sqimap_logout($imap_stream);
1059 set_up_language($squirrelmail_language, true);
1060 sqsession_destroy();
1061 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
1062 exit;
1063 }
1064
1065 // Run ID command if configured - RFC 2971
1066 //
1067 // Administrator must declare a configuration variable called
1068 // $imap_id_command_args in config/config_local.php which must
1069 // be an array, where each key is an attibute to be sent in the
1070 // IMAP ID command to the server. Values will be sent as-is
1071 // except if the value is "###REMOTE ADDRESS###" (without quotes)
1072 // in which case the current user's real IP address will be
1073 // substituted. If "###X-FORWARDED-FOR###" is used and a
1074 // "X-FORWARDED-FOR" header is present in the client request,
1075 // the contents of that header are used (careful, this can be
1076 // forged). If "###X-FORWARDED-FOR OR REMOTE ADDRESS###" is
1077 // used, then the "X-FORWARDED-FOR" header is used if it is
1078 // present in the request, otherwise, the client's connecting
1079 // IP address is used. The following attributes will always be
1080 // added unless they are specifically overridden with a blank
1081 // value:
1082 // name, vendor, support-url, version
1083 // A parsed representation of server's response is made available
1084 // to plugins as both a global and session variable named
1085 // "imap_server_id_response" (a simple key/value array) unless
1086 // response parsing is turned off by way of setting a variable
1087 // named $do_not_parse_imap_id_command_response in
1088 // config/config_local.php to TRUE, in which case, the stored
1089 // response will be the unparsed IMAP response.
1090 //
1091 global $imap_id_command_args, $do_not_parse_imap_id_command_response;
1092 if (!empty($imap_id_command_args) && is_array($imap_id_command_args)
1093 && sqimap_capability($imap_stream, 'ID')) {
1094
1095 static $args = array();
1096 if (empty($args)) {
1097 if (!isset($imap_id_command_args['name']))
1098 $imap_id_command_args['name'] = 'SquirrelMail';
1099 if (!isset($imap_id_command_args['vendor']))
1100 $imap_id_command_args['vendor'] = 'SquirrelMail Project Team';
1101 if (!isset($imap_id_command_args['support-url']))
1102 $imap_id_command_args['support-url'] = 'https://squirrelmail.org';
1103 if (!isset($imap_id_command_args['version'])) {
1104 $imap_id_command_args['version'] = SM_VERSION;
1105 }
1106 foreach ($imap_id_command_args as $key => $value) {
1107 $key = trim($key);
1108 $value = trim($value);
1109 if ($key === '' || $value === '')
1110 continue;
1111 if ($value === '###REMOTE ADDRESS###' && sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER))
1112 $value = $remote_addr;
1113 else if ($value === '###X-FORWARDED-FOR###' && sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $remote_addr, SQ_SERVER))
1114 $value = $remote_addr;
1115 else if ($value === '###X-FORWARDED-FOR OR REMOTE ADDRESS###') {
1116 if (sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $remote_addr, SQ_SERVER))
1117 $value = $remote_addr;
1118 else if (sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER))
1119 $value = $remote_addr;
1120 }
1121 else if ($value === '###REMOTE ADDRESS###' && sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER)) {
1122 $value = $remote_addr;
1123 }
1124 $args[] = '"' . str_replace(array('"', '\\'), array('\\"', '\\\\'), $key)
1125 . '" "' . str_replace(array('"', '\\'), array('\\"', '\\\\'), $value) . '"';
1126 }
1127 }
1128 $read_ary = sqimap_run_command($imap_stream, 'ID (' . implode(' ', $args) . ')', false, $response, $message);
1129 if (!empty($read_ary) && is_array($read_ary)) {
1130 global $imap_server_id_response;
1131 if ($do_not_parse_imap_id_command_response)
1132 $imap_server_id_response = $read_ary;
1133 else
1134 {
1135 $imap_server_id_response = array();
1136
1137 // NOTE that this parser ignores closing ) sign, so
1138 // technically some kind of malformed server
1139 // response could cause extra junk to be included here
1140 foreach ($read_ary as $info)
1141 {
1142 $parsed_info = explode('(', $info, 2);
1143 if (!empty($parsed_info[1]))
1144 {
1145 // find opening quote for the next key name
1146 while ($parsed_info = explode('"', $parsed_info[1], 2))
1147 {
1148 if (empty($parsed_info[1]))
1149 break;
1150 else
1151 {
1152 // find closing quote for the key name
1153 $pos = strpos($parsed_info[1], '"');
1154 if ($pos === FALSE)
1155 break;
1156 else
1157 {
1158 $key = substr($parsed_info[1], 0, $pos);
1159 $parsed_info[1] = substr($parsed_info[1], $pos + 1);
1160
1161 // find opening quote for the key's value
1162 $parsed_info = explode('"', $parsed_info[1], 2);
1163 if (empty($parsed_info[1]))
1164 break;
1165 else
1166 {
1167 // find closing quote for the key's value
1168 $pos = strpos($parsed_info[1], '"');
1169 if ($pos === FALSE)
1170 break;
1171 else
1172 {
1173 $imap_server_id_response[$key] = substr($parsed_info[1], 0, $pos);
1174 $parsed_info[1] = substr($parsed_info[1], $pos + 1);
1175 }
1176 }
1177 }
1178 }
1179 }
1180 }
1181 }
1182 }
1183 sqsession_register($imap_server_id_response, 'imap_server_id_response');
1184 }
1185 }
1186
1187 return $imap_stream;
1188}
1189
1190/**
1191 * Simply logs out the IMAP session
1192 * @param stream $imap_stream the IMAP connection to log out.
1193 * @return void
1194 */
1195function sqimap_logout ($imap_stream) {
1196 /* Logout is not valid until the server returns 'BYE'
1197 * If we don't have an imap_ stream we're already logged out */
1198 if(isset($imap_stream) && $imap_stream) {
1199 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
1200 fclose($imap_stream);
1201 }
1202}
1203
1204/**
1205 * Retrieve the CAPABILITY string from the IMAP server.
1206 * If capability is set, returns only that specific capability,
1207 * else returns array of all capabilities.
1208 * @param stream $imap_stream
1209 * @param string $capability (since 1.3.0)
1210 * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
1211 * @return mixed (string if $capability is set and found,
1212 * false, if $capability is set and not found,
1213 * array if $capability not set)
1214 */
1215function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
1216 // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
1217
1218 if (!$bUseCache || ! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION)) {
1219 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
1220 $c = explode(' ', $read[0]);
1221 for ($i=2; $i < count($c); $i++) {
1222 $cap_list = explode('=', $c[$i]);
1223 if (isset($cap_list[1])) {
1224 if(isset($sqimap_capabilities[trim($cap_list[0])]) &&
1225 !is_array($sqimap_capabilities[trim($cap_list[0])])) {
1226 // Remove array key that was added in 'else' block below
1227 // This is to accomodate for capabilities like:
1228 // SORT SORT=MODSEQ
1229 unset($sqimap_capabilities[trim($cap_list[0])]);
1230 }
1231 $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
1232 } else {
1233 if(!isset($sqimap_capabilities[trim($cap_list[0])])) {
1234 $sqimap_capabilities[trim($cap_list[0])] = TRUE;
1235 }
1236 }
1237 }
1238 }
1239 if ($capability) {
1240 if (isset($sqimap_capabilities[$capability])) {
1241 return $sqimap_capabilities[$capability];
1242 } else {
1243 return false;
1244 }
1245 }
1246 return $sqimap_capabilities;
1247}
1248
1249/**
1250 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
1251 * @param stream $imap_stream
1252 * @return string
1253 */
1254function sqimap_get_delimiter ($imap_stream = false) {
1255 global $sqimap_delimiter, $optional_delimiter;
1256
1257 /* Use configured delimiter if set */
1258 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
1259 return $optional_delimiter;
1260 }
1261
1262 /* Delimiter is stored in the session from redirect. Try fetching from there first */
1263 if (empty($sqimap_delimiter)) {
1264 sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION);
1265 }
1266
1267 /* Do some caching here */
1268 if (!$sqimap_delimiter) {
1269 if (sqimap_capability($imap_stream, 'NAMESPACE')
1270 /*
1271 * According to something that I can't find, this is supposed to work on all systems
1272 * OS: This won't work in Courier IMAP.
1273 * OS: According to rfc2342 response from NAMESPACE command is:
1274 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
1275 * OS: We want to lookup all personal NAMESPACES...
1276 *
1277 * TODO: remove this in favour of the information from sqimap_get_namespace()
1278 */
1279 && ($read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b))
1280 && preg_match('/\* NAMESPACE +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL)/i', $read[0], $data)
1281 && preg_match('/^\( *\((.*)\) *\)/', $data[1], $data2)) {
1282 $pn = $data2[1];
1283 $pna = explode(')(', $pn);
1284 $delnew = array();
1285 foreach ($pna as $v) {
1286 $lst = explode('"', $v);
1287 if (isset($lst[3])) {
1288 $delnew[$lst[1]] = $lst[3];
1289 } else {
1290 $delnew[$lst[1]] = '';
1291 }
1292 }
1293 $sqimap_delimiter = array_shift($delnew);
1294 } else {
1295 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
1296 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
1297 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
1298 $quote_position = strpos ($read[0], '"');
1299 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
1300 }
1301 }
1302 return $sqimap_delimiter;
1303}
1304
1305/**
1306 * Retrieves the namespaces from the IMAP server.
1307 * NAMESPACE is an IMAP extension defined in RFC 2342.
1308 *
1309 * @param stream $imap_stream
1310 * @return array
1311 */
1312function sqimap_get_namespace($imap_stream) {
1313 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
1314 return sqimap_parse_namespace($read[0]);
1315}
1316
1317/**
1318 * Parses a NAMESPACE response and returns an array with the available
1319 * personal, users and shared namespaces.
1320 *
1321 * @param string $input
1322 * @return array The returned array has the following format:
1323 * <pre>
1324 * array(
1325 * 'personal' => array(
1326 * 0 => array('prefix'=>'INBOX.','delimiter' =>'.'),
1327 * 1 => ...
1328 * ),
1329 * 'users' => array(..
1330 * ),
1331 * 'shared' => array( ..
1332 * )
1333 * )
1334 * </pre>
1335 * Note that if a namespace is not defined in the server, then the corresponding
1336 * array will be empty.
1337 */
1338function sqimap_parse_namespace(&$input) {
1339 $ns_strings = array(1=>'personal', 2=>'users', 3=>'shared');
1340 $namespace = array();
1341
1342 if (preg_match('/NAMESPACE (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL)/', $input, $regs)) {
1343 for($i=1; $i<=3; $i++) {
1344 if($regs[$i] == 'NIL') {
1345 $namespace[$ns_strings[$i]] = array();
1346 } else {
1347 // Pop-out the first ( and last ) for easier parsing
1348 $ns = substr($regs[$i], 1, -1);
1349 if($c = preg_match_all('/\((?:(.*?)\s*?)\)/', $ns, $regs2)) {
1350 $namespace[$ns_strings[$i]] = array();
1351 for($j=0; $j<sizeof($regs2[1]); $j++) {
1352 preg_match('/"(.*)"\s+("(.*)"|NIL)/', $regs2[1][$j], $regs3);
1353 $namespace[$ns_strings[$i]][$j]['prefix'] = $regs3[1];
1354 if($regs3[2] == 'NIL') {
1355 $namespace[$ns_strings[$i]][$j]['delimiter'] = null;
1356 } else {
1357 // $regs[3] is $regs[2] without the quotes
1358 $namespace[$ns_strings[$i]][$j]['delimiter'] = $regs3[3];
1359 }
1360 unset($regs3);
1361 }
1362 }
1363 unset($ns);
1364 }
1365 }
1366 }
1367 return($namespace);
1368}
1369
1370/**
1371 * This encodes a mailbox name for use in IMAP commands.
1372 * @param string $what the mailbox to encode
1373 * @return string the encoded mailbox string
1374 * @since 1.5.0
1375 */
1376function sqimap_encode_mailbox_name($what)
1377{
1378 if (preg_match('/["\\\r\n]/', $what))
1379 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
1380 return '"' . $what . '"'; /* 4.3 quoted string form */
1381}
1382
1383/**
1384 * Gets the number of messages in the current mailbox.
1385 *
1386 * OBSOLETE use sqimap_status_messages instead.
1387 * @param stream $imap_stream imap stream
1388 * @param string $mailbox
1389 * @deprecated
1390 */
1391function sqimap_get_num_messages ($imap_stream, $mailbox) {
1392 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
1393 return $aStatus['MESSAGES'];
1394}
1395
1396/**
1397 * OBSOLETE FUNCTION should be removed after mailbox_display,
1398 * printMessage function is adapted
1399 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
1400 * @param string $address
1401 * @param integer $max
1402 * @since 1.4.0
1403 * @deprecated See Rfc822Address.php
1404 */
1405function parseAddress($address, $max=0) {
1406 $aAddress = parseRFC822Address($address,array('limit'=> $max));
1407 /*
1408 * Because the expected format of the array element is changed we adapt it now.
1409 * This also implies that this function is obsolete and should be removed after the
1410 * rest of the source is adapted. See Rfc822Address.php for the new function.
1411 */
1412 array_walk($aAddress, '_adaptAddress');
1413 return $aAddress;
1414}
1415
1416/**
1417 * OBSOLETE FUNCTION should be removed after mailbox_display,
1418 * printMessage function is adapted
1419 *
1420 * callback function used for formating of addresses array in
1421 * parseAddress() function
1422 * @param array $aAddr
1423 * @param integer $k array key
1424 * @since 1.5.1
1425 * @deprecated
1426 */
1427function _adaptAddress(&$aAddr,$k) {
1428 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL]) && $aAddr[SQM_ADDR_PERSONAL]) ?
1429 $aAddr[SQM_ADDR_PERSONAL] : '';
1430 $sEmail = ($aAddr[SQM_ADDR_HOST]) ?
1431 $aAddr[SQM_ADDR_MAILBOX] . '@'.$aAddr[SQM_ADDR_HOST] :
1432 $aAddr[SQM_ADDR_MAILBOX];
1433 $aAddr = array($sEmail,$sPersonal);
1434}
1435
1436/**
1437 * Returns the number of unseen messages in this folder.
1438 * obsoleted by sqimap_status_messages !
1439 * Arguments differ in 1.0.x
1440 * @param stream $imap_stream
1441 * @param string $mailbox
1442 * @return integer
1443 * @deprecated
1444 */
1445function sqimap_unseen_messages ($imap_stream, $mailbox) {
1446 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1447 return $aStatus['UNSEEN'];
1448}
1449
1450/**
1451 * Returns the status items of a mailbox.
1452 * Default it returns MESSAGES,UNSEEN and RECENT
1453 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
1454 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1455 * @param stream $imap_stream imap stream
1456 * @param string $mailbox mail folder
1457 * @param array $aStatusItems status items
1458 * @return array
1459 * @since 1.3.2
1460 */
1461function sqimap_status_messages ($imap_stream, $mailbox,
1462 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1463
1464 $aStatusItems = implode(' ',$aStatusItems);
1465 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1466 " ($aStatusItems)", false, $result, $message);
1467 $i = 0;
1468 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1469 $regs = array(false,false);
1470 while (isset($read_ary[$i])) {
1471 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1472 $unseen = $regs[1];
1473 }
1474 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1475 $messages = $regs[1];
1476 }
1477 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1478 $recent = $regs[1];
1479 }
1480 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1481 $uidnext = $regs[1];
1482 }
1483 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1484 $uidvalidity = $regs[1];
1485 }
1486 $i++;
1487 }
1488
1489 $status=array('MESSAGES' => $messages,
1490 'UNSEEN'=>$unseen,
1491 'RECENT' => $recent,
1492 'UIDNEXT' => $uidnext,
1493 'UIDVALIDITY' => $uidvalidity);
1494
1495 if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
1496 if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
1497 if (!empty($recent)) { $hook_status['RECENT']=$recent; }
1498 if (!empty($hook_status)) {
1499 $hook_status['MAILBOX']=$mailbox;
1500 $hook_status['CALLER']='sqimap_status_messages';
1501 do_hook('folder_status', $hook_status);
1502 }
1503 return $status;
1504}
1505
1506
1507/**
1508 * Saves a message to a given folder -- used for saving sent messages
1509 * @param stream $imap_stream
1510 * @param string $sent_folder
1511 * @param $length
1512 * @return string $sid
1513 */
1514function sqimap_append ($imap_stream, $sMailbox, $length) {
1515 $sid = sqimap_session_id();
1516 $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
1517 fputs ($imap_stream, "$query\r\n");
1518 $tmp = fgets ($imap_stream, 1024);
1519 sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
1520 return $sid;
1521}
1522
1523/**
1524 * @param stream imap_stream
1525 * @param string $folder (since 1.3.2)
1526 */
1527function sqimap_append_done ($imap_stream, $sMailbox='') {
1528 fputs ($imap_stream, "\r\n");
1529 $tmp = fgets ($imap_stream, 1024);
1530 while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
1531 $tmp = fgets ($imap_stream, 1024);
1532 }
1533}
1534
1535/**
1536 * Displays error messages, if there are errors in responses to
1537 * commands issues by sqimap_append() and sqimap_append_done() functions.
1538 * @param string $response
1539 * @param string $sMailbox
1540 * @return bool $bDone
1541 * @since 1.5.1 and 1.4.5
1542 */
1543function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
1544 // static vars to keep them available when sqimap_append_done calls this function.
1545 static $imapquery, $imapsid;
1546
1547 $bDone = false;
1548
1549 if ($query) {
1550 $imapquery = $query;
1551 }
1552 if ($sid) {
1553 $imapsid = $sid;
1554 }
1555 if ($response[0] == '+') {
1556 // continuation request triggerd by sqimap_append()
1557 $bDone = true;
1558 } else {
1559 $i = strpos($response, ' ');
1560 $sRsp = substr($response,0,$i);
1561 $sMsg = substr($response,$i+1);
1562 $aExtra = array('MAILBOX' => $sMailbox);
1563 switch ($sRsp) {
1564 case '*': //untagged response
1565 $i = strpos($sMsg, ' ');
1566 $sRsp = strtoupper(substr($sMsg,0,$i));
1567 $sMsg = substr($sMsg,$i+1);
1568 if ($sRsp == 'NO' || $sRsp == 'BAD') {
1569 // for the moment disabled. Enable after 1.5.1 release.
1570 // Notices could give valueable information about the mailbox
1571 // Update: seems this was forgotten, but now it is finally enabled
1572 sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
1573 }
1574 $bDone = false;
1575 case $imapsid:
1576 // A001 OK message
1577 // $imapsid<space>$sRsp<space>$sMsg
1578 $bDone = true;
1579 $i = strpos($sMsg, ' ');
1580 $sRsp = strtoupper(substr($sMsg,0,$i));
1581 $sMsg = substr($sMsg,$i+1);
1582 switch ($sRsp) {
1583 case 'NO':
1584 if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
1585 sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1586 } else {
1587 sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1588 }
1589 break;
1590 case 'BAD':
1591 sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
1592 break;
1593 case 'BYE':
1594 sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
1595 break;
1596 case 'OK':
1597 break;
1598 default:
1599 break;
1600 }
1601 break;
1602 default:
1603 // should be false because of the unexpected response but i'm not sure if
1604 // that will cause an endless loop in sqimap_append_done
1605 $bDone = true;
1606 }
1607 }
1608 return $bDone;
1609}
1610
1611/**
1612 * Allows mapping of IMAP server address with custom function
1613 * see map_yp_alias()
1614 * @param string $imap_server imap server address or mapping
1615 * @param string $username
1616 * @return string
1617 * @since 1.3.0
1618 */
1619function sqimap_get_user_server ($imap_server, $username) {
1620 if (substr($imap_server, 0, 4) != "map:") {
1621 return $imap_server;
1622 }
1623 $function = substr($imap_server, 4);
1624 return $function($username);
1625}
1626
1627/**
1628 * This is an example that gets IMAP servers from yellowpages (NIS).
1629 * you can simple put map:map_yp_alias in your $imap_server_address
1630 * in config.php use your own function instead map_yp_alias to map your
1631 * LDAP whatever way to find the users IMAP server.
1632 *
1633 * Requires access to external ypmatch program
1634 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1635 * @param string $username
1636 * @return string
1637 * @since 1.3.0
1638 */
1639function map_yp_alias($username) {
1640 $safe_username = escapeshellarg($username);
1641 $yp = `ypmatch $safe_username aliases`;
1642 return chop(substr($yp, strlen($username)+1));
1643}