Request a sqimap_run_command_list instead of a sqimap_run_command because in
[squirrelmail.git] / functions / imap_general.php
CommitLineData
59177427 1<?php
bccadd02 2
35586184 3/**
a6fd80f5 4 * imap_general.php
35586184 5 *
0e1a248b 6 * This implements all functions that do general IMAP functions.
35586184 7 *
47ccfad4 8 * @copyright &copy; 1999-2006 The SquirrelMail Project Team
4b4abf93 9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
eb19bc67 10 * @version $Id$
d6c32258 11 * @package squirrelmail
eb19bc67 12 * @subpackage imap
35586184 13 */
14
d6c32258 15/** Includes.. */
b68edc75 16require_once(SM_PATH . 'functions/page_header.php');
47a29326 17require_once(SM_PATH . 'functions/auth.php');
938d39ca 18include_once(SM_PATH . 'functions/rfc822address.php');
47a29326 19
35586184 20
48af4b64 21/**
22 * Generates a new session ID by incrementing the last one used;
23 * this ensures that each command has a unique ID.
0e1a248b 24 * @param bool $unique_id (since 1.3.0) controls use of unique
b35a5862 25 * identifiers/message sequence numbers in IMAP commands. See IMAP
26 * rfc 'UID command' chapter.
48af4b64 27 * @return string IMAP session id of the form 'A000'.
b35a5862 28 * @since 1.2.0
48af4b64 29 */
2aca19a1 30function sqimap_session_id($unique_id = FALSE) {
31 static $sqimap_session_id = 1;
32
487daa81 33 if (!$unique_id) {
098ea084 34 return( sprintf("A%03d", $sqimap_session_id++) );
487daa81 35 } else {
098ea084 36 return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
487daa81 37 }
9c737111 38}
39
48af4b64 40/**
3411d4ec 41 * Both send a command and accept the result from the command.
42 * This is to allow proper session number handling.
95e3afc1 43 * @param stream $imap_stream imap connection resource
b35a5862 44 * @param string $query imap command
45 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
95e3afc1 46 * @param array $response
47 * @param array $message
48 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
0e1a248b 49 * @return mixed returns false on imap error. displays error message
b35a5862 50 * if imap stream is not available.
51 * @since 1.2.3
3411d4ec 52 */
487daa81 53function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
c5809184 54 if ($imap_stream) {
098ea084 55 $sid = sqimap_session_id($unique_id);
56 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
bc78cc6e 57 $tag_uid_a = explode(' ',trim($sid));
58 $tag = $tag_uid_a[0];
0dc05a81 59 $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
bc78cc6e 60 /* get the response and the message */
61 $message = $message[$tag];
1e0a2f0e 62 $response = $response[$tag];
bc78cc6e 63 return $read[$tag];
c5809184 64 } else {
65 global $squirrelmail_language, $color;
66 set_up_language($squirrelmail_language);
67 require_once(SM_PATH . 'functions/display_messages.php');
6fd95361 68 $string = "<b><font color=\"$color[2]\">\n" .
0e1a248b 69 _("ERROR: No available IMAP stream.") .
c5809184 70 "</b></font>\n";
71 error_box($string,$color);
098ea084 72 return false;
c5809184 73 }
1c72b151 74}
75
b35a5862 76/**
95e3afc1 77 * @param stream $imap_stream imap connection resource
b35a5862 78 * @param string $query imap command
79 * @param boolean $handle_errors see sqimap_retrieve_imap_response()
95e3afc1 80 * @param array $response empty string, if return = false
81 * @param array $message empty string, if return = false
82 * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
83 * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
84 * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
85 * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
0e1a248b 86 * @return mixed returns false on imap error. displays error message
b35a5862 87 * if imap stream is not available.
88 * @since 1.2.3
89 */
1e0a2f0e 90function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
7c7b74b3 91 &$message, $unique_id = false,$filter=false,
92 $outputstream=false,$no_return=false) {
c5809184 93 if ($imap_stream) {
94 $sid = sqimap_session_id($unique_id);
1e0a2f0e 95 fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
bc78cc6e 96 $tag_uid_a = explode(' ',trim($sid));
97 $tag = $tag_uid_a[0];
1e0a2f0e 98
bc78cc6e 99 $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
7c7b74b3 100 $message, $query,$filter,$outputstream,$no_return);
0e1a248b 101 if (empty($read)) { //IMAP server dropped its connection
ec73f243 102 $response = '';
103 $message = '';
104 return false;
105 }
bc78cc6e 106 /* retrieve the response and the message */
107 $response = $response[$tag];
108 $message = $message[$tag];
1e0a2f0e 109
bc78cc6e 110 if (!empty($read[$tag])) {
111 return $read[$tag][0];
112 } else {
113 return $read[$tag];
114 }
c5809184 115 } else {
116 global $squirrelmail_language, $color;
117 set_up_language($squirrelmail_language);
118 require_once(SM_PATH . 'functions/display_messages.php');
6fd95361 119 $string = "<b><font color=\"$color[2]\">\n" .
0e1a248b 120 _("ERROR: No available IMAP stream.") .
c5809184 121 "</b></font>\n";
122 error_box($string,$color);
098ea084 123 return false;
1e0a2f0e 124 }
bc78cc6e 125}
48af4b64 126
0022f6db 127/**
128 * @param mixed $new_query
129 * @param string $tag
130 * @param array $aQuery
95e3afc1 131 * @param boolean $unique_id see sqimap_session_id()
0022f6db 132 * @since 1.5.0
133 */
bc78cc6e 134function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
135 $sid = sqimap_session_id($unique_id);
136 $tag_uid_a = explode(' ',trim($sid));
137 $tag = $tag_uid_a[0];
0b38d197 138 $query = $sid . ' '.$new_query."\r\n";
bc78cc6e 139 $aQuery[$tag] = $query;
42a07ac1 140}
141
0022f6db 142/**
95e3afc1 143 * @param stream $imap_stream imap stream
0022f6db 144 * @param array $aQueryList
145 * @param boolean $handle_errors
146 * @param array $aServerResponse
147 * @param array $aServerMessage
95e3afc1 148 * @param boolean $unique_id see sqimap_session_id()
149 * @param boolean $filter see sqimap_fread()
150 * @param mixed $outputstream see sqimap_fread()
151 * @param boolean $no_return see sqimap_fread()
0022f6db 152 * @since 1.5.0
153 */
1e0a2f0e 154function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
bc78cc6e 155 &$aServerResponse, &$aServerMessage, $unique_id = false,
1e0a2f0e 156 $filter=false,$outputstream=false,$no_return=false) {
bc78cc6e 157 $aResponse = false;
5c300c60 158
1e0a2f0e 159 /*
0e1a248b 160 Do not fire all calls at once to the IMAP server but split the calls up
1e0a2f0e 161 in portions of $iChunkSize. If we do not do that I think we misbehave as
0e1a248b 162 IMAP client or should handle BYE calls if the IMAP server drops the
52c8b585 163 connection because the number of queries is to large. This isn't tested
164 but a wild guess how it could work in the field.
1e0a2f0e 165
166 After testing it on Exchange 2000 we discovered that a chunksize of 32
0b38d197 167 was quicker then when we raised it to 128.
52c8b585 168 */
169 $iQueryCount = count($aQueryList);
170 $iChunkSize = 32;
171 // array_chunk would also do the job but it's supported from php > 4.2
172 $aQueryChunks = array();
173 $iLoops = floor($iQueryCount / $iChunkSize);
174
5c300c60 175 if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
52c8b585 176
177 if (!function_exists('array_chunk')) { // arraychunk replacement
5c300c60 178 reset($aQueryList);
52c8b585 179 for($i=0;$i<$iLoops;++$i) {
5c300c60 180 for($j=0;$j<$iChunkSize;++$j) {
181 $key = key($aQueryList);
182 $aTmp[$key] = $aQueryList[$key];
183 if (next($aQueryList) === false) break;
184 }
185 $aQueryChunks[] = $aTmp;
1e0a2f0e 186 }
52c8b585 187 } else {
188 $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
bc78cc6e 189 }
1e0a2f0e 190
52c8b585 191 for ($i=0;$i<$iLoops;++$i) {
192 $aQuery = $aQueryChunks[$i];
193 foreach($aQuery as $tag => $query) {
194 fputs($imap_stream,$query);
195 $aResults[$tag] = false;
196 }
52c8b585 197 foreach($aQuery as $tag => $query) {
5c300c60 198 if ($aResults[$tag] == false) {
1e0a2f0e 199 $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
bc78cc6e 200 $handle_errors, $response, $message, $query,
201 $filter,$outputstream,$no_return);
52c8b585 202 foreach ($aReturnedResponse as $returned_tag => $aResponse) {
5c300c60 203 if (!empty($aResponse)) {
52c8b585 204 $aResults[$returned_tag] = $aResponse[0];
5c300c60 205 } else {
206 $aResults[$returned_tag] = $aResponse;
207 }
52c8b585 208 $aServerResponse[$returned_tag] = $response[$returned_tag];
209 $aServerMessage[$returned_tag] = $message[$returned_tag];
210 }
bc78cc6e 211 }
212 }
213 }
b7277e4f 214 return $aResults;
bc78cc6e 215}
9c737111 216
1e0a2f0e 217/**
0e1a248b 218 * Custom fgets function: gets a line from the IMAP server,
48af4b64 219 * no matter how big it may be.
95e3afc1 220 * @param stream $imap_stream the stream to read from
48af4b64 221 * @return string a line
0022f6db 222 * @since 1.2.8
b8c285ab 223 */
b8c285ab 224function sqimap_fgets($imap_stream) {
225 $read = '';
226 $buffer = 4096;
227 $results = '';
c41daf03 228 $offset = 0;
229 while (strpos($results, "\r\n", $offset) === false) {
b8c285ab 230 if (!($read = fgets($imap_stream, $buffer))) {
329a7ca5 231 /* this happens in case of an error */
232 /* reset $results because it's useless */
233 $results = false;
b8c285ab 234 break;
235 }
c41daf03 236 if ( $results != '' ) {
237 $offset = strlen($results) - 1;
238 }
b8c285ab 239 $results .= $read;
240 }
241 return $results;
242}
243
0022f6db 244/**
245 * @param stream $imap_stream
246 * @param integer $iSize
95e3afc1 247 * @param boolean $filter
248 * @param mixed $outputstream stream or 'php://stdout' string
0e1a248b 249 * @param boolean $no_return controls data returned by function
0022f6db 250 * @return string
251 * @since 1.4.1
252 */
7c7b74b3 253function sqimap_fread($imap_stream,$iSize,$filter=false,
254 $outputstream=false, $no_return=false) {
255 if (!$filter || !$outputstream) {
256 $iBufferSize = $iSize;
257 } else {
811318c5 258 // see php bug 24033. They changed fread behaviour %$^&$%
977a6085 259 $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
260 }
261 if ($iSize < $iBufferSize) {
262 $iBufferSize = $iSize;
7c7b74b3 263 }
7c0ec1d8 264
5eba0be2 265 $iRetrieved = 0;
977a6085 266 $results = '';
267 $sRead = $sReadRem = '';
1e0a2f0e 268 // NB: fread can also stop at end of a packet on sockets.
977a6085 269 while ($iRetrieved < $iSize) {
7c7b74b3 270 $sRead = fread($imap_stream,$iBufferSize);
977a6085 271 $iLength = strlen($sRead);
272 $iRetrieved += $iLength ;
273 $iRemaining = $iSize - $iRetrieved;
274 if ($iRemaining < $iBufferSize) {
275 $iBufferSize = $iRemaining;
276 }
13aabbcf 277 if ($sRead == '') {
7c7b74b3 278 $results = false;
279 break;
280 }
13aabbcf 281 if ($sReadRem != '') {
977a6085 282 $sRead = $sReadRem . $sRead;
283 $sReadRem = '';
284 }
7c0ec1d8 285
13aabbcf 286 if ($filter && $sRead != '') {
1e0a2f0e 287 // in case the filter is base64 decoding we return a remainder
7c0ec1d8 288 $sReadRem = $filter($sRead);
7c7b74b3 289 }
13aabbcf 290 if ($outputstream && $sRead != '') {
7c7b74b3 291 if (is_resource($outputstream)) {
292 fwrite($outputstream,$sRead);
293 } else if ($outputstream == 'php://stdout') {
294 echo $sRead;
295 }
296 }
297 if ($no_return) {
298 $sRead = '';
1e0a2f0e 299 } else {
977a6085 300 $results .= $sRead;
7c7b74b3 301 }
7c7b74b3 302 }
1e0a2f0e 303 return $results;
304}
977a6085 305
7c0ec1d8 306
48af4b64 307/**
308 * Obsolete function, inform plugins that use it
95e3afc1 309 * @param stream $imap_stream
310 * @param string $tag
311 * @param boolean $handle_errors
312 * @param array $response
313 * @param array $message
314 * @param string $query
b35a5862 315 * @since 1.1.3
316 * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
48af4b64 317 */
1e0a2f0e 318function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
0dc05a81 319 &$response, &$message, $query = '') {
320 global $color, $squirrelmail_language;
321 set_up_language($squirrelmail_language);
322 require_once(SM_PATH . 'functions/display_messages.php');
6fd95361 323 $string = "<b><font color=\"$color[2]\">\n" .
0e1a248b 324 _("ERROR: Bad function call.") .
6fd95361 325 "</b><br />\n" .
0dc05a81 326 _("Reason:") . ' '.
6fd95361 327 'There is a plugin installed which make use of the <br />' .
328 'SquirrelMail internal function sqimap_read_data_list.<br />'.
329 'Please adapt the installed plugin and let it use<br />'.
330 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
331 'The following query was issued:<br />'.
332 htmlspecialchars($query) . '<br />' . "</font><br />\n";
0dc05a81 333 error_box($string,$color);
1e0a2f0e 334 echo '</body></html>';
335 exit;
0dc05a81 336}
7c7b74b3 337
48af4b64 338/**
0e1a248b 339 * Function to display an error related to an IMAP query.
48af4b64 340 * @param string title the caption of the error box
341 * @param string query the query that went wrong
ec73f243 342 * @param string message_title optional message title
343 * @param string message optional error message
344 * @param string $link an optional link to try again
48af4b64 345 * @return void
0022f6db 346 * @since 1.5.0
48af4b64 347 */
ec73f243 348function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
4974c2a0 349{
350 global $color, $squirrelmail_language;
351
352 set_up_language($squirrelmail_language);
353 require_once(SM_PATH . 'functions/display_messages.php');
6fd95361 354 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
bf15f116 355 $cmd = explode(' ',$query);
356 $cmd= strtolower($cmd[0]);
357
358 if ($query != '' && $cmd != 'login')
6fd95361 359 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
4974c2a0 360 if ($message_title != '')
361 $string .= $message_title;
362 if ($message != '')
363 $string .= htmlspecialchars($message);
6fd95361 364 $string .= "</font><br />\n";
ec73f243 365 if ($link != '')
366 $string .= $link;
4974c2a0 367 error_box($string,$color);
368}
369
48af4b64 370/**
3411d4ec 371 * Reads the output from the IMAP stream. If handle_errors is set to true,
372 * this will also handle all errors that are received. If it is not set,
48af4b64 373 * the errors will be sent back through $response and $message.
95e3afc1 374 * @param stream $imap_stream imap stream
375 * @param string $tag
376 * @param boolean $handle_errors handle errors internally or send them in $response and $message.
0022f6db 377 * @param array $response
378 * @param array $message
95e3afc1 379 * @param string $query command that can be printed if something fails
380 * @param boolean $filter see sqimap_fread()
381 * @param mixed $outputstream see sqimap_fread()
382 * @param boolean $no_return see sqimap_fread()
0022f6db 383 * @since 1.5.0
bee165ef 384 */
1e0a2f0e 385function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
7c7b74b3 386 &$response, &$message, $query = '',
387 $filter = false, $outputstream = false, $no_return = false) {
9c737111 388 global $color, $squirrelmail_language;
9c737111 389 $read = '';
bc78cc6e 390 if (!is_array($message)) $message = array();
391 if (!is_array($response)) $response = array();
ec73f243 392 $aResponse = '';
b8c285ab 393 $resultlist = array();
394 $data = array();
395 $read = sqimap_fgets($imap_stream);
8d8da447 396 $i = 0;
bea3eb1e 397 while ($read) {
398 $char = $read{0};
399 switch ($char)
400 {
15bc7f66 401 case '+':
402 default:
403 $read = sqimap_fgets($imap_stream);
404 break;
405
406 case $tag{0}:
407 {
bea3eb1e 408 /* get the command */
409 $arg = '';
410 $i = strlen($tag)+1;
411 $s = substr($read,$i);
412 if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
413 $arg = substr($s,0,$j);
414 }
415 $found_tag = substr($read,0,$i-1);
5c300c60 416 if ($found_tag) {
bea3eb1e 417 switch ($arg)
418 {
15bc7f66 419 case 'OK':
420 case 'BAD':
421 case 'NO':
422 case 'BYE':
423 case 'PREAUTH':
bc78cc6e 424 $response[$found_tag] = $arg;
425 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
426 if (!empty($data)) {
427 $resultlist[] = $data;
428 }
5c300c60 429 $aResponse[$found_tag] = $resultlist;
430 $data = $resultlist = array();
431 if ($found_tag == $tag) {
432 break 3; /* switch switch while */
433 }
434 break;
1e0a2f0e 435 default:
bea3eb1e 436 /* this shouldn't happen */
bc78cc6e 437 $response[$found_tag] = $arg;
438 $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
439 if (!empty($data)) {
440 $resultlist[] = $data;
441 }
442 $aResponse[$found_tag] = $resultlist;
5c300c60 443 $data = $resultlist = array();
444 if ($found_tag == $tag) {
445 break 3; /* switch switch while */
446 }
bc78cc6e 447 }
bea3eb1e 448 }
5c300c60 449 $read = sqimap_fgets($imap_stream);
450 if ($read === false) { /* error */
4920e1e0 451 break 2; /* switch while */
5c300c60 452 }
453 break;
15bc7f66 454 } // end case $tag{0}
455
456 case '*':
457 {
bea3eb1e 458 if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
459 /* check for literal */
460 $s = substr($read,-3);
461 $fetch_data = array();
462 do { /* outer loop, continue until next untagged fetch
463 or tagged reponse */
464 do { /* innerloop for fetching literals. with this loop
465 we prohibid that literal responses appear in the
466 outer loop so we can trust the untagged and
467 tagged info provided by $read */
468 if ($s === "}\r\n") {
469 $j = strrpos($read,'{');
470 $iLit = substr($read,$j+1,-3);
471 $fetch_data[] = $read;
7c7b74b3 472 $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
329a7ca5 473 if ($sLiteral === false) { /* error */
474 break 4; /* while while switch while */
475 }
bea3eb1e 476 /* backwards compattibility */
477 $aLiteral = explode("\n", $sLiteral);
478 /* release not neaded data */
479 unset($sLiteral);
480 foreach ($aLiteral as $line) {
481 $fetch_data[] = $line ."\n";
482 }
483 /* release not neaded data */
1e0a2f0e 484 unset($aLiteral);
bea3eb1e 485 /* next fgets belongs to this fetch because
486 we just got the exact literalsize and there
487 must follow data to complete the response */
329a7ca5 488 $read = sqimap_fgets($imap_stream);
489 if ($read === false) { /* error */
490 break 4; /* while while switch while */
491 }
c0b23345 492 $fetch_data[] = $read;
bea3eb1e 493 } else {
329a7ca5 494 $fetch_data[] = $read;
bea3eb1e 495 }
496 /* retrieve next line and check in the while
497 statements if it belongs to this fetch response */
498 $read = sqimap_fgets($imap_stream);
329a7ca5 499 if ($read === false) { /* error */
500 break 4; /* while while switch while */
501 }
bea3eb1e 502 /* check for next untagged reponse and break */
503 if ($read{0} == '*') break 2;
504 $s = substr($read,-3);
505 } while ($s === "}\r\n");
506 $s = substr($read,-3);
507 } while ($read{0} !== '*' &&
106d4087 508 substr($read,0,strlen($tag)) !== $tag);
329a7ca5 509 $resultlist[] = $fetch_data;
bea3eb1e 510 /* release not neaded data */
511 unset ($fetch_data);
512 } else {
513 $s = substr($read,-3);
514 do {
515 if ($s === "}\r\n") {
516 $j = strrpos($read,'{');
517 $iLit = substr($read,$j+1,-3);
518 $data[] = $read;
329a7ca5 519 $sLiteral = fread($imap_stream,$iLit);
c0b23345 520 if ($sLiteral === false) { /* error */
329a7ca5 521 $read = false;
522 break 3; /* while switch while */
523 }
c0b23345 524 $data[] = $sLiteral;
b7277e4f 525 $data[] = sqimap_fgets($imap_stream);
bea3eb1e 526 } else {
329a7ca5 527 $data[] = $read;
bea3eb1e 528 }
529 $read = sqimap_fgets($imap_stream);
329a7ca5 530 if ($read === false) {
531 break 3; /* while switch while */
532 } else if ($read{0} == '*') {
106d4087 533 break;
534 }
bea3eb1e 535 $s = substr($read,-3);
536 } while ($s === "}\r\n");
537 break 1;
1e0a2f0e 538 }
bea3eb1e 539 break;
15bc7f66 540 } // end case '*'
541 } // end switch
c0b23345 542 } // end while
1e0a2f0e 543
c0b23345 544 /* error processing in case $read is false */
d7542838 545 if ($read === false) {
d3d9ef2d 546 // try to retrieve an untagged bye respons from the results
547 $sResponse = array_pop($data);
d7542838 548 if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
549 if (!$handle_errors) {
550 $query = '';
551 }
0e1a248b 552 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
d7542838 553 echo '</body></html>';
554 exit;
555 } else if ($handle_errors) {
1e0a2f0e 556 unset($data);
0e1a248b 557 sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
ec73f243 558 exit;
559 }
b8c285ab 560 }
1e0a2f0e 561
15bc7f66 562 /* Set $resultlist array */
b8c285ab 563 if (!empty($data)) {
bc78cc6e 564 //$resultlist[] = $data;
9c737111 565 }
b8c285ab 566 elseif (empty($resultlist)) {
1e0a2f0e 567 $resultlist[] = array();
b8c285ab 568 }
15bc7f66 569
570 /* Return result or handle errors */
bee165ef 571 if ($handle_errors == false) {
bc78cc6e 572 return $aResponse;
dd381002 573 }
4974c2a0 574 switch ($response[$tag]) {
dd381002 575 case 'OK':
bc78cc6e 576 return $aResponse;
329a7ca5 577 break;
1e0a2f0e 578 case 'NO':
dd381002 579 /* ignore this error from M$ exchange, it is not fatal (aka bug) */
6b6c2e06 580 if (strstr($message[$tag], 'command resulted in') === false) {
0e1a248b 581 sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
329a7ca5 582 echo '</body></html>';
052e0c26 583 exit;
9c737111 584 }
329a7ca5 585 break;
1e0a2f0e 586 case 'BAD':
0e1a248b 587 sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
1e0a2f0e 588 echo '</body></html>';
589 exit;
590 case 'BYE':
0e1a248b 591 sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
1e0a2f0e 592 echo '</body></html>';
9c737111 593 exit;
1e0a2f0e 594 default:
0e1a248b 595 sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
329a7ca5 596 /* the error is displayed but because we don't know the reponse we
597 return the result anyway */
1e0a2f0e 598 return $aResponse;
329a7ca5 599 break;
9c737111 600 }
9c737111 601}
602
0022f6db 603/**
95e3afc1 604 * @param stream $imap_stream imap string
0022f6db 605 * @param string $tag_uid
606 * @param boolean $handle_errors
607 * @param array $response
608 * @param array $message
95e3afc1 609 * @param string $query (since 1.2.5)
610 * @param boolean $filter (since 1.4.1) see sqimap_fread()
611 * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
612 * @param boolean $no_return (since 1.4.1) see sqimap_fread()
0022f6db 613 */
1e0a2f0e 614function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
7c7b74b3 615 &$response, &$message, $query = '',
616 $filter=false,$outputstream=false,$no_return=false) {
bc78cc6e 617
618 $tag_uid_a = explode(' ',trim($tag_uid));
619 $tag = $tag_uid_a[0];
620
1e0a2f0e 621 $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
622 $response, $message, $query,$filter,$outputstream,$no_return);
623 return $res;
9c737111 624}
625
48af4b64 626/**
b98732e8 627 * Connects to the IMAP server and returns a resource identifier for use with
a15f9d93 628 * the other SquirrelMail IMAP functions. Does NOT login!
48af4b64 629 * @param string server hostname of IMAP server
630 * @param int port port number to connect to
a15f9d93 631 * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
632 * Argument was boolean before 1.5.1.
48af4b64 633 * @return imap-stream resource identifier
0022f6db 634 * @since 1.5.0 (usable only in 1.5.1 or later)
b98732e8 635 */
a15f9d93 636function sqimap_create_stream($server,$port,$tls=0) {
ce68b76b 637 global $squirrelmail_language;
b98732e8 638
a15f9d93 639 // FIXME: ipv6 address support
640
641 if ($tls == 1) {
b98732e8 642 if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
643 /* Use TLS by prefixing "tls://" to the hostname */
57ffe0af 644 $server = 'tls://' . $server;
b98732e8 645 } else {
646 require_once(SM_PATH . 'functions/display_messages.php');
3b151851 647 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
648 '<br />'.
649 _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
650 '<br /><br />'.
0a6be7d1 651 _("Please contact your system administrator and report this error."),
652 sprintf(_("Error connecting to IMAP server: %s."), $server));
b98732e8 653 }
654 }
655
82f403aa 656 $imap_stream = @fsockopen($server, $port, $error_number, $error_string, 15);
b98732e8 657
658 /* Do some error correction */
659 if (!$imap_stream) {
660 set_up_language($squirrelmail_language, true);
661 require_once(SM_PATH . 'functions/display_messages.php');
3b151851 662 logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
0a6be7d1 663 "<br />\r\n$error_number : $error_string<br />\r\n",
664 sprintf(_("Error connecting to IMAP server: %s."), $server) );
b98732e8 665 exit;
666 }
667 $server_info = fgets ($imap_stream, 1024);
a15f9d93 668
669 /**
670 * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
671 * http://www.php.net/stream-socket-enable-crypto
672 */
673 if ($tls == 2) {
674 if (function_exists('stream_socket_enable_crypto')) {
675 // check starttls capability, don't use cached capability version
676 if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
677 // imap server does not declare starttls support
678 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
679 '','',
680 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
681 exit;
682 }
683
684 // issue starttls command and check response
685 sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
686 // check response
687 if ($starttls_response!='OK') {
688 // starttls command failed
689 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
690 'STARTTLS',
691 _("Server replied: "),
692 $starttls_message);
693 exit();
694 }
695
696 // start crypto on connection. suppress function errors.
697 if (@stream_socket_enable_crypto($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
698 // starttls was successful
699
700 /**
701 * RFC 2595 requires to discard CAPABILITY information after successful
702 * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
703 * information only after successful login (src/redirect.php) and cached information
704 * is used only in other php script connections after successful STARTTLS. If script
705 * issues sqimap_capability() call before sqimap_login() and wants to get initial
706 * capability response, script should set third sqimap_capability() argument to false.
707 */
708 //sqsession_unregister('sqimap_capabilities');
709 } else {
710 /**
711 * stream_socket_enable_crypto() call failed. Possible issues:
712 * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
713 * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
714 * suppressed in stream_socket_enable_crypto() call)
715 */
716 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
717 '','',
718 _("Unable to start TLS."));
719 /**
720 * Bug: stream_socket_enable_crypto() does not register SSL errors in
721 * openssl_error_string() or stream notification wrapper and displays
722 * them in E_WARNING level message. It is impossible to retrieve error
723 * message without own error handler.
724 */
725 exit;
726 }
727 } else {
728 // php install does not support stream_socket_enable_crypto() function
729 sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
730 '','',
731 _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
732 exit;
733 }
734 }
b98732e8 735 return $imap_stream;
736}
737
48af4b64 738/**
0e1a248b 739 * Logs the user into the IMAP server. If $hide is set, no error messages
740 * will be displayed. This function returns the IMAP connection handle.
0022f6db 741 * @param string $username user name
742 * @param string $password encrypted password
743 * @param string $imap_server_address address of imap server
744 * @param integer $imap_port port of imap server
745 * @param boolean $hide controls display connection errors
746 * @return stream
3411d4ec 747 */
9c737111 748function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
fe55c7c7 749 global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
750 $imap_auth_mech, $sqimap_capabilities;
85fc999e 751
eb2f6102 752 if (!isset($onetimepad) || empty($onetimepad)) {
753 sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
754 }
fe55c7c7 755 if (!isset($sqimap_capabilities)) {
756 sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION );
757 }
758
b98732e8 759 $host = $imap_server_address;
bd9829d7 760 $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
fe55c7c7 761
b98732e8 762 $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
fe55c7c7 763
2f1f7a12 764 /* Decrypt the password */
765 $password = OneTimePadDecrypt($password, $onetimepad);
766
b98732e8 767 if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
3b151851 768 // We're using some sort of authentication OTHER than plain or login
b98732e8 769 $tag=sqimap_session_id(false);
770 if ($imap_auth_mech == 'digest-md5') {
098ea084 771 $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
b98732e8 772 } elseif ($imap_auth_mech == 'cram-md5') {
098ea084 773 $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
b98732e8 774 }
775 fputs($imap_stream,$query);
776 $answer=sqimap_fgets($imap_stream);
777 // Trim the "+ " off the front
778 $response=explode(" ",$answer,3);
779 if ($response[0] == '+') {
098ea084 780 // Got a challenge back
b98732e8 781 $challenge=$response[1];
782 if ($imap_auth_mech == 'digest-md5') {
783 $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
784 } elseif ($imap_auth_mech == 'cram-md5') {
785 $reply = cram_md5_response($username,$password,$challenge);
786 }
787 fputs($imap_stream,$reply);
788 $read=sqimap_fgets($imap_stream);
789 if ($imap_auth_mech == 'digest-md5') {
3b151851 790 // DIGEST-MD5 has an extra step..
b98732e8 791 if (substr($read,0,1) == '+') { // OK so far..
098ea084 792 fputs($imap_stream,"\r\n");
793 $read=sqimap_fgets($imap_stream);
098ea084 794 }
b98732e8 795 }
796 $results=explode(" ",$read,3);
797 $response=$results[1];
798 $message=$results[2];
799 } else {
3b151851 800 // Fake the response, so the error trap at the bottom will work
b98732e8 801 $response="BAD";
802 $message='IMAP server does not appear to support the authentication method selected.';
803 $message .= ' Please contact your system administrator.';
804 }
fe0b18b3 805 } elseif ($imap_auth_mech == 'login') {
b98732e8 806 // Original IMAP login code
807 $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
808 $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
1e7fc1cb 809 } elseif ($imap_auth_mech == 'plain') {
fe55c7c7 810 /***
811 * SASL PLAIN
812 *
813 * RFC 2595 Chapter 6
814 *
815 * The mechanism consists of a single message from the client to the
816 * server. The client sends the authorization identity (identity to
817 * login as), followed by a US-ASCII NUL character, followed by the
818 * authentication identity (identity whose password will be used),
819 * followed by a US-ASCII NUL character, followed by the clear-text
820 * password. The client may leave the authorization identity empty to
821 * indicate that it is the same as the authentication identity.
822 *
823 **/
b98732e8 824 $tag=sqimap_session_id(false);
2bd6b461 825 $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ? true : false;
b98732e8 826 $auth = base64_encode("$username\0$username\0$password");
fe55c7c7 827 if ($sasl) {
828 // IMAP Extension for SASL Initial Client Response
2bd6b461 829 // <draft-siemborski-imap-sasl-initial-response-01b.txt>
fe55c7c7 830 $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
831 fputs($imap_stream, $query);
b98732e8 832 $read = sqimap_fgets($imap_stream);
fe55c7c7 833 } else {
834 $query = $tag . " AUTHENTICATE PLAIN\r\n";
835 fputs($imap_stream, $query);
836 $read=sqimap_fgets($imap_stream);
837 if (substr($read,0,1) == '+') { // OK so far..
838 fputs($imap_stream, "$auth\r\n");
839 $read = sqimap_fgets($imap_stream);
840 }
098ea084 841 }
b98732e8 842 $results=explode(" ",$read,3);
843 $response=$results[1];
844 $message=$results[2];
845 } else {
846 $response="BAD";
847 $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
848 }
fe55c7c7 849
b98732e8 850 /* If the connection was not successful, lets see why */
9c737111 851 if ($response != 'OK') {
852 if (!$hide) {
74424a43 853 if ($response != 'NO') {
3411d4ec 854 /* "BAD" and anything else gets reported here. */
098ea084 855 $message = htmlspecialchars($message);
9c737111 856 set_up_language($squirrelmail_language, true);
098ea084 857 require_once(SM_PATH . 'functions/display_messages.php');
9c737111 858 if ($response == 'BAD') {
6fd95361 859 $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
9c737111 860 } else {
6fd95361 861 $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
9c737111 862 }
1e7fc1cb 863 if (isset($read) && is_array($read)) {
6fd95361 864 $string .= '<br />' . _("Read data:") . "<br />\n";
9c737111 865 foreach ($read as $line) {
6fd95361 866 $string .= htmlspecialchars($line) . "<br />\n";
9c737111 867 }
868 }
098ea084 869 error_box($string,$color);
9c737111 870 exit;
165e24a7 871 } else {
3411d4ec 872 /*
873 * If the user does not log in with the correct
1c72b151 874 * username and password it is not possible to get the
875 * correct locale from the user's preferences.
876 * Therefore, apply the same hack as on the login
877 * screen.
3411d4ec 878 *
879 * $squirrelmail_language is set by a cookie when
1c72b151 880 * the user selects language and logs out
bee165ef 881 */
fe55c7c7 882
9c737111 883 set_up_language($squirrelmail_language, true);
bd9c880b 884 include_once(SM_PATH . 'functions/display_messages.php' );
098ea084 885 sqsession_destroy();
d5c472f1 886 /* terminate the session nicely */
887 sqimap_logout($imap_stream);
bd9c880b 888 logout_error( _("Unknown user or password incorrect.") );
9c737111 889 exit;
052e0c26 890 }
9c737111 891 } else {
052e0c26 892 exit;
9c737111 893 }
894 }
1d20443c 895
896 /* Special error case:
897 * Login referrals. The server returns:
0e1a248b 898 * ? OK [REFERRAL <imap url>]
899 * Check RFC 2221 for details. Since we do not support login referrals yet
900 * we log the user out.
901 */
2da1524c 902 if ( stristr($message, 'REFERRAL imap') === TRUE ) {
0e1a248b 903 sqimap_logout($imap_stream);
1d20443c 904 set_up_language($squirrelmail_language, true);
905 include_once(SM_PATH . 'functions/display_messages.php' );
906 sqsession_destroy();
edde1f5c 907 logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
1d20443c 908 exit;
909 }
0e1a248b 910
9c737111 911 return $imap_stream;
912}
f1e6f580 913
48af4b64 914/**
915 * Simply logs out the IMAP session
95e3afc1 916 * @param stream $imap_stream the IMAP connection to log out.
48af4b64 917 * @return void
918 */
9c737111 919function sqimap_logout ($imap_stream) {
8d936b0c 920 /* Logout is not valid until the server returns 'BYE'
921 * If we don't have an imap_ stream we're already logged out */
26a2cc8b 922 if(isset($imap_stream) && $imap_stream)
8d936b0c 923 sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
9c737111 924}
925
48af4b64 926/**
95e3afc1 927 * Retrieve the CAPABILITY string from the IMAP server.
48af4b64 928 * If capability is set, returns only that specific capability,
929 * else returns array of all capabilities.
95e3afc1 930 * @param stream $imap_stream
a15f9d93 931 * @param string $capability (since 1.3.0)
932 * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
0e1a248b 933 * @return mixed (string if $capability is set and found,
0022f6db 934 * false, if $capability is set and not found,
935 * array if $capability not set)
48af4b64 936 */
a15f9d93 937function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
938 // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
0493ed11 939
a15f9d93 940 if (!$bUseCache || ! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION)) {
1c72b151 941 $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
942
9c737111 943 $c = explode(' ', $read[0]);
944 for ($i=2; $i < count($c); $i++) {
945 $cap_list = explode('=', $c[$i]);
3411d4ec 946 if (isset($cap_list[1])) {
3cfa833d 947 $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
3411d4ec 948 } else {
3cfa833d 949 $sqimap_capabilities[trim($cap_list[0])] = TRUE;
3411d4ec 950 }
f1e6f580 951 }
9c737111 952 }
487daa81 953 if ($capability) {
098ea084 954 if (isset($sqimap_capabilities[$capability])) {
955 return $sqimap_capabilities[$capability];
956 } else {
957 return false;
958 }
f1e6f580 959 }
487daa81 960 return $sqimap_capabilities;
9c737111 961}
962
48af4b64 963/**
95e3afc1 964 * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
0022f6db 965 * @param stream $imap_stream
966 * @return string
48af4b64 967 */
9c737111 968function sqimap_get_delimiter ($imap_stream = false) {
3411d4ec 969 global $sqimap_delimiter, $optional_delimiter;
85fc999e 970
9c737111 971 /* Use configured delimiter if set */
972 if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
973 return $optional_delimiter;
974 }
85fc999e 975
7eb6261e 976 /* Delimiter is stored in the session from redirect. Try fetching from there first */
cc54580f 977 if (empty($sqimap_delimiter)) {
7eb6261e 978 sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION);
979 }
980
9c737111 981 /* Do some caching here */
982 if (!$sqimap_delimiter) {
983 if (sqimap_capability($imap_stream, 'NAMESPACE')) {
3411d4ec 984 /*
985 * According to something that I can't find, this is supposed to work on all systems
986 * OS: This won't work in Courier IMAP.
987 * OS: According to rfc2342 response from NAMESPACE command is:
988 * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
989 * OS: We want to lookup all personal NAMESPACES...
990 */
1c72b151 991 $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
f1e6f580 992 if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
9c737111 993 if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
f1e6f580 994 $pn = $data2[1];
9c737111 995 }
f1e6f580 996 $pna = explode(')(', $pn);
9c737111 997 while (list($k, $v) = each($pna)) {
862ff2d3 998 $lst = explode('"', $v);
999 if (isset($lst[3])) {
1000 $pn[$lst[1]] = $lst[3];
1001 } else {
74424a43 1002 $pn[$lst[1]] = '';
862ff2d3 1003 }
f1e6f580 1004 }
1005 }
1006 $sqimap_delimiter = $pn[0];
1007 } else {
1008 fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
1009 $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
91e0dccc 1010 $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
f1e6f580 1011 $quote_position = strpos ($read[0], '"');
1012 $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
1013 }
1014 }
1015 return $sqimap_delimiter;
9c737111 1016}
052e0c26 1017
48af4b64 1018/**
1019 * This encodes a mailbox name for use in IMAP commands.
95e3afc1 1020 * @param string $what the mailbox to encode
48af4b64 1021 * @return string the encoded mailbox string
0022f6db 1022 * @since 1.5.0
48af4b64 1023 */
b2306cbe 1024function sqimap_encode_mailbox_name($what)
1025{
91e0dccc 1026 if (ereg("[\"\\\r\n]", $what))
1027 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
1028 return '"' . $what . '"'; /* 4.3 quoted string form */
b2306cbe 1029}
1030
48af4b64 1031/**
1032 * Gets the number of messages in the current mailbox.
1e0a2f0e 1033 *
1034 * OBSOLETE use sqimap_status_messages instead.
95e3afc1 1035 * @param stream $imap_stream imap stream
1036 * @param string $mailbox
1037 * @deprecated
48af4b64 1038 */
9c737111 1039function sqimap_get_num_messages ($imap_stream, $mailbox) {
b2306cbe 1040 $read_ary = sqimap_run_command ($imap_stream, 'EXAMINE ' . sqimap_encode_mailbox_name($mailbox), false, $result, $message);
9c737111 1041 for ($i = 0; $i < count($read_ary); $i++) {
85fc999e 1042 if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
1043 return $regs[1];
1044 }
9c737111 1045 }
1f720b34 1046 return false; //"BUG! Couldn't get number of messages in $mailbox!";
9c737111 1047}
95e3afc1 1048
1e0a2f0e 1049/**
1050 * OBSOLETE FUNCTION should be removed after mailbox_display,
1051 * printMessage function is adapted
95e3afc1 1052 * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
1053 * @param string $address
1054 * @param integer $max
1055 * @since 1.4.0
1056 * @deprecated See Rfc822Address.php
1e0a2f0e 1057 */
91688e5f 1058function parseAddress($address, $max=0) {
1e0a2f0e 1059 $aAddress = parseRFC822Address($address,array('limit'=> $max));
1060 /*
1061 * Because the expected format of the array element is changed we adapt it now.
1062 * This also implies that this function is obsolete and should be removed after the
1063 * rest of the source is adapted. See Rfc822Address.php for the new function.
1064 */
1065 array_walk($aAddress, '_adaptAddress');
1066 return $aAddress;
1067}
91688e5f 1068
1e0a2f0e 1069/**
1070 * OBSOLETE FUNCTION should be removed after mailbox_display,
1071 * printMessage function is adapted
95e3afc1 1072 *
0e1a248b 1073 * callback function used for formating of addresses array in
95e3afc1 1074 * parseAddress() function
1075 * @param array $aAddr
1076 * @param integer $k array key
1077 * @since 1.5.1
1078 * @deprecated
1e0a2f0e 1079 */
1080function _adaptAddress(&$aAddr,$k) {
1081 $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL]) && $aAddr[SQM_ADDR_PERSONAL]) ?
1082 $aAddr[SQM_ADDR_PERSONAL] : '';
1083 $sEmail = ($aAddr[SQM_ADDR_HOST]) ?
3cd52f38 1084 $aAddr[SQM_ADDR_MAILBOX] . '@'.$aAddr[SQM_ADDR_HOST] :
1085 $aAddr[SQM_ADDR_MAILBOX];
1e0a2f0e 1086 $aAddr = array($sEmail,$sPersonal);
1087}
91688e5f 1088
48af4b64 1089/**
1090 * Returns the number of unseen messages in this folder.
26e90c74 1091 * obsoleted by sqimap_status_messages !
95e3afc1 1092 * Arguments differ in 1.0.x
1093 * @param stream $imap_stream
1094 * @param string $mailbox
1095 * @return integer
1096 * @deprecated
3411d4ec 1097 */
9c737111 1098function sqimap_unseen_messages ($imap_stream, $mailbox) {
26e90c74 1099 $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
1100 return $aStatus['UNSEEN'];
9c737111 1101}
1102
48af4b64 1103/**
26e90c74 1104 * Returns the status items of a mailbox.
1105 * Default it returns MESSAGES,UNSEEN and RECENT
0e1a248b 1106 * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
95e3afc1 1107 * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
1108 * @param stream $imap_stream imap stream
1109 * @param string $mailbox mail folder
1110 * @param array $aStatusItems status items
1111 * @return array
1112 * @since 1.3.2
1f720b34 1113 */
1e0a2f0e 1114function sqimap_status_messages ($imap_stream, $mailbox,
26e90c74 1115 $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
1116
3fedd15b 1117 $aStatusItems = implode(' ',$aStatusItems);
26e90c74 1118 $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
1119 " ($aStatusItems)", false, $result, $message);
1f720b34 1120 $i = 0;
26e90c74 1121 $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
1f720b34 1122 $regs = array(false,false);
1123 while (isset($read_ary[$i])) {
1124 if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
098ea084 1125 $unseen = $regs[1];
1126 }
1f720b34 1127 if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
098ea084 1128 $messages = $regs[1];
1129 }
b8ec18ef 1130 if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
098ea084 1131 $recent = $regs[1];
1e0a2f0e 1132 }
26e90c74 1133 if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1134 $uidnext = $regs[1];
1e0a2f0e 1135 }
26e90c74 1136 if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
1137 $uidvalidity = $regs[1];
1e0a2f0e 1138 }
1f720b34 1139 $i++;
1140 }
1e0a2f0e 1141 return array('MESSAGES' => $messages,
1142 'UNSEEN'=>$unseen,
26e90c74 1143 'RECENT' => $recent,
1144 'UIDNEXT' => $uidnext,
1145 'UIDVALIDITY' => $uidvalidity);
1f720b34 1146}
1147
9c737111 1148
48af4b64 1149/**
1150 * Saves a message to a given folder -- used for saving sent messages
95e3afc1 1151 * @param stream $imap_stream
1152 * @param string $sent_folder
1153 * @param $length
3411d4ec 1154 */
9c737111 1155function sqimap_append ($imap_stream, $sent_folder, $length) {
d9c93379 1156 fputs ($imap_stream, sqimap_session_id() . ' APPEND ' . sqimap_encode_mailbox_name($sent_folder) . " (\\Seen) {".$length."}\r\n");
85fc999e 1157 $tmp = fgets ($imap_stream, 1024);
7ec3a6b9 1158 sqimap_append_checkresponse($tmp, $sent_folder);
9c737111 1159}
1160
95e3afc1 1161/**
1162 * @param stream imap_stream
1163 * @param string $folder (since 1.3.2)
1164 */
8813fb15 1165function sqimap_append_done ($imap_stream, $folder='') {
9c737111 1166 fputs ($imap_stream, "\r\n");
1167 $tmp = fgets ($imap_stream, 1024);
7ec3a6b9 1168 sqimap_append_checkresponse($tmp, $folder);
1169}
1170
95e3afc1 1171/**
0e1a248b 1172 * Displays error messages, if there are errors in responses to
95e3afc1 1173 * commands issues by sqimap_append() and sqimap_append_done() functions.
1174 * @param string $response
1175 * @param string $folder
1176 * @since 1.5.1
1177 */
7ec3a6b9 1178function sqimap_append_checkresponse($response, $folder) {
0e1a248b 1179
7ec3a6b9 1180 if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
1181 global $squirrelmail_language, $color;
69146537 1182 set_up_language($squirrelmail_language);
1f720b34 1183 require_once(SM_PATH . 'functions/display_messages.php');
7ec3a6b9 1184
098ea084 1185 $reason = $regs[3];
1186 if ($regs[2] == 'NO') {
6fd95361 1187 $string = "<b><font color=\"$color[2]\">\n" .
0e1a248b 1188 _("ERROR: Could not append message to") ." $folder." .
6fd95361 1189 "</b><br />\n" .
0e1a248b 1190 _("Server responded:") . ' ' .
6fd95361 1191 $reason . "<br />\n";
098ea084 1192 if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
0e1a248b 1193 $string .= _("Solution:") . ' ' .
1e0a2f0e 1194 _("Remove unneccessary messages from your folder and start with your Trash folder.")
6fd95361 1195 ."<br />\n";
098ea084 1196 }
1197 $string .= "</font>\n";
1198 error_box($string,$color);
1199 } else {
6fd95361 1200 $string = "<b><font color=\"$color[2]\">\n" .
0e1a248b 1201 _("ERROR: Bad or malformed request.") .
6fd95361 1202 "</b><br />\n" .
0e1a248b 1203 _("Server responded:") . ' ' .
7ec3a6b9 1204 $reason . "</font><br />\n";
098ea084 1205 error_box($string,$color);
8813fb15 1206 exit;
098ea084 1207 }
69146537 1208 }
9c737111 1209}
85fc999e 1210
95e3afc1 1211/**
0e1a248b 1212 * Allows mapping of IMAP server address with custom function
95e3afc1 1213 * see map_yp_alias()
1214 * @param string $imap_server imap server address or mapping
1215 * @param string $username
1216 * @return string
1217 * @since 1.3.0
1218 */
bd9829d7 1219function sqimap_get_user_server ($imap_server, $username) {
bd9829d7 1220 if (substr($imap_server, 0, 4) != "map:") {
1221 return $imap_server;
1222 }
bd9829d7 1223 $function = substr($imap_server, 4);
1224 return $function($username);
1225}
1226
48af4b64 1227/**
0e1a248b 1228 * This is an example that gets IMAP servers from yellowpages (NIS).
1e0a2f0e 1229 * you can simple put map:map_yp_alias in your $imap_server_address
bd9829d7 1230 * in config.php use your own function instead map_yp_alias to map your
0e1a248b 1231 * LDAP whatever way to find the users IMAP server.
1232 *
95e3afc1 1233 * Requires access to external ypmatch program
1234 * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
1235 * @param string $username
1236 * @return string
1237 * @since 1.3.0
48af4b64 1238 */
bd9829d7 1239function map_yp_alias($username) {
1240 $yp = `ypmatch $username aliases`;
1241 return chop(substr($yp, strlen($username)+1));
1e0a2f0e 1242}
bd9829d7 1243
3cfa833d 1244?>