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