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