Rewrite of internal message caching
[squirrelmail.git] / functions / imap_messages.php
CommitLineData
59177427 1<?php
7350889b 2
35586184 3/**
0fdc2fb6 4* imap_messages.php
5*
6* Copyright (c) 1999-2004 The SquirrelMail Project Team
7* Licensed under the GNU GPL. For full terms see the file COPYING.
8*
9* This implements functions that manipulate messages
10* NOTE: Quite a few functions in this file are obsolete
11*
12* @version $Id$
13* @package squirrelmail
14* @subpackage imap
15*/
052e0c26 16
d6c32258 17/**
0fdc2fb6 18* Copies specified messages to specified folder
19* @param int $imap_stream The resource ID for the IMAP connection
20* @param string $start Beginning of range to copy
21* @param string $end End of the range to copy
22* @param string $mailbox Which box to copy to
23* @deprecated This function is obsolete and should not be used
24*/
35586184 25function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
6201339c 26 $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
97f7ddf2 27}
28
7c3e0802 29/**
30* copy a range of messages ($id) to another mailbox ($mailbox)
d6c32258 31* @param int $imap_stream The resource ID for the IMAP socket
32* @param string $id The list of messages to copy
33* @param string $mailbox The destination to copy to
34* @return void
7c3e0802 35*/
034fddf9 36function sqimap_msgs_list_copy ($imap_stream, $id, $mailbox) {
1c198ef7 37 $msgs_id = sqimap_message_list_squisher($id);
6201339c 38 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
324ac3c5 39 if ($response == 'OK') {
40 return true;
41 } else {
42 return false;
43 }
7c3e0802 44}
45
46/**
47* move a range of messages ($id) to another mailbox. Deletes the originals.
d6c32258 48* @param int $imap_stream The resource ID for the IMAP socket
49* @param string $id The list of messages to move
50* @param string $mailbox The destination to move to
51* @return void
7c3e0802 52*/
53function sqimap_msgs_list_move ($imap_stream, $id, $mailbox) {
7c3e0802 54 $msgs_id = sqimap_message_list_squisher($id);
324ac3c5 55 if (sqimap_msgs_list_copy ($imap_stream, $id, $mailbox)) {
56 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
57 } else {
58 return false;
59 }
034fddf9 60}
61
62
d6c32258 63/**
0fdc2fb6 64* Deletes specified messages and moves them to trash if possible
65* @deprecated This function is obsolete and should no longer be used
66* @param int $imap_steam The resource ID for the IMAP connection
67* @param string $start Start of range
68* @param string $end End of range
69* @param string $mailbox Mailbox messages are being deleted from
70* @return void
71*/
abafb676 72function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
6201339c 73 global $move_to_trash, $trash_folder, $auto_expunge;
97f7ddf2 74
abafb676 75 if (($move_to_trash == true) && ($bypass_trash != true) &&
76 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
97f7ddf2 77 sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
97f7ddf2 78 }
d8a8203a 79 sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
97f7ddf2 80}
81
6c540963 82function sqimap_msgs_list_delete ($imap_stream, $mailbox, $id, $bypass_trash=false) {
324ac3c5 83 // FIX ME, remove globals by introducing an associative array with properties
84 // as 4th argument as replacement for the bypass_trash var
6201339c 85 global $move_to_trash, $trash_folder;
324ac3c5 86 $bRes = true;
abafb676 87 if (($move_to_trash == true) && ($bypass_trash != true) &&
88 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
324ac3c5 89 $bRes = sqimap_msgs_list_copy ($imap_stream, $id, $trash_folder);
90 }
91 if ($bRes) {
92 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
93 } else {
94 return false;
034fddf9 95 }
034fddf9 96}
97
98
d6c32258 99/**
0fdc2fb6 100* Sets the specified messages with specified flag
101*/
d8a8203a 102function sqimap_messages_flag ($imap_stream, $start, $end, $flag, $handle_errors) {
6201339c 103 $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
97f7ddf2 104}
105
034fddf9 106function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
034fddf9 107 $msgs_id = sqimap_message_list_squisher($id);
108 $set_string = ($set ? '+' : '-');
324ac3c5 109 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
110 // parse the fetch response
111 return parseFetch($aResponse);
034fddf9 112}
113
48af4b64 114/** @deprecated */
97f7ddf2 115function sqimap_get_small_header ($imap_stream, $id, $sent) {
098ea084 116 $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
97f7ddf2 117 return $res[0];
118}
3411d4ec 119
48af4b64 120/**
0fdc2fb6 121* Sort the message list and crunch to be as small as possible
122* (overflow could happen, so make it small if possible)
123*/
97f7ddf2 124function sqimap_message_list_squisher($messages_array) {
125 if( !is_array( $messages_array ) ) {
fe70ae27 126 return $messages_array;
97f7ddf2 127 }
2d34da11 128
97f7ddf2 129 sort($messages_array, SORT_NUMERIC);
130 $msgs_str = '';
131 while ($messages_array) {
132 $start = array_shift($messages_array);
133 $end = $start;
134 while (isset($messages_array[0]) && $messages_array[0] == $end + 1) {
135 $end = array_shift($messages_array);
136 }
137 if ($msgs_str != '') {
138 $msgs_str .= ',';
139 }
140 $msgs_str .= $start;
141 if ($start != $end) {
142 $msgs_str .= ':' . $end;
143 }
144 }
97f7ddf2 145 return $msgs_str;
3411d4ec 146}
97f7ddf2 147
48af4b64 148/**
ffb776c4 149* Retrieves an array with a sorted uid list. Sorting is done on the imap server
324ac3c5 150* @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
ffb776c4 151* @param resource $imap_stream IMAP socket connection
152* @param string $sSortField Field to sort on
153* @param bool $reverse Reverse order search
154* @return array $id sorted uid list
0fdc2fb6 155*/
324ac3c5 156function sqimap_get_sort_order ($imap_stream, $sSortField, $reverse, $search='ALL') {
ffb776c4 157 global $default_charset,
158 $sent_folder;
2d34da11 159
ffb776c4 160 $id = array();
aa0da530 161 $sort_test = array();
162 $sort_query = '';
2d34da11 163
ffb776c4 164 if ($sSortField) {
165 if ($reverse) {
166 $sSortField = 'REVERSE '.$sSortField;
167 }
324ac3c5 168 $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
169 // FIX ME sqimap_run_command should return the parsed data accessible by $aDATA['SORT']
170 $aData = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
171 /* fallback to default charset */
172 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
173 $query = "SORT ($sSortField) US-ASCII $search";
174 $aData = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
cdca177a 175 }
0fdc2fb6 176 }
324ac3c5 177
178 if ($response == 'OK') {
179 return parseUidList($aData,'SORT');
ffb776c4 180 } else {
324ac3c5 181 return false;
182 }
183}
184
185function parseUidList($aData,$sCommand) {
186 $aUid = array();
187 if (isset($aData) && count($aData)) {
188 for ($i=0,$iCnt=count($aData);$i<$iCnt;++$i) {
189 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i], $aMatch)) {
190 $aUid += preg_split("/ /", trim($aMatch[1]));
191 }
192 }
cdca177a 193 }
324ac3c5 194 return array_unique($aUid);
aa0da530 195}
2d34da11 196
26b22b20 197/**
ffb776c4 198* Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
0fdc2fb6 199*
ffb776c4 200* @param resource $imap_stream IMAP socket connection
201* @param string $sSortField Field to sort on
202* @param bool $reverse Reverse order search
76f29d49 203* @return array $aUid sorted uid list
0fdc2fb6 204*/
324ac3c5 205function get_squirrel_sort ($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
206 if ($aUID === NULL) {
207
208 }
e0e30169 209 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
324ac3c5 210 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
e0e30169 211 array($sSortField), array());
ffb776c4 212 } else {
324ac3c5 213 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
e0e30169 214 array(), array($sSortField));
ffb776c4 215 }
c2e29558 216 $aUid = array();
76f29d49 217 $walk = false;
ffb776c4 218 switch ($sSortField) {
76f29d49 219 // natcasesort section
ffb776c4 220 case 'FROM':
ffb776c4 221 case 'TO':
76f29d49 222 case 'CC':
223 if(!$walk) {
224 array_walk($msgs, create_function('&$v,&$k,$f',
225 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
544ab9e2 226 $addr = reset(parseRFC822Address($v[$f],1));
227 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
228 $addr[SQM_ADDR_PERSONAL] : "";
229 $sEmail = ($addr[SQM_ADDR_HOST]) ?
230 $addr[SQM_ADDR_HOST] . "@".$addr[SQM_ADDR_HOST] :
231 $addr[SQM_ADDR_HOST];
232 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal):$sEmail;'),$sSortField);
76f29d49 233 $walk = true;
cdca177a 234 }
76f29d49 235 // nobreak
ffb776c4 236 case 'SUBJECT':
76f29d49 237 if(!$walk) {
238 array_walk($msgs, create_function('&$v,&$k,$f',
239 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
240 $v[$f] = strtolower(decodeHeader(trim($v[$f])));
241 $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
242 $matches[2] : $v[$f];'),$sSortField);
243 $walk = true;
244 }
ffb776c4 245 foreach ($msgs as $item) {
324ac3c5 246 $aUid[$item['UID']] = $item[$sSortField];
ffb776c4 247 }
76f29d49 248 natcasesort($aUid);
249 $aUid = array_keys($aUid);
ffb776c4 250 if ($reverse) {
e432a21c 251 $aUid = array_reverse($aUid);
ffb776c4 252 }
253 break;
76f29d49 254 // \natcasesort section
255 // sort_numeric section
ffb776c4 256 case 'DATE':
76f29d49 257 case 'INTERNALDATE':
258 if(!$walk) {
259 array_walk($msgs, create_function('&$v,$k,$f',
260 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
261 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
262 $walk = true;
ffb776c4 263 }
76f29d49 264 // nobreak;
ffb776c4 265 case 'RFC822.SIZE':
c2e29558 266 if(!$walk) {
267 // redefine $sSortField to maintain the same namespace between
268 // server-side sorting and squirrelmail sorting
269 $sSortField = 'SIZE';
270 }
ffb776c4 271 foreach ($msgs as $item) {
324ac3c5 272 $aUid[$item['UID']] = (isset($item[$sSortField])) ? $item[$sSortField] : 0;
ffb776c4 273 }
274 if ($reverse) {
76f29d49 275 arsort($aUid,SORT_NUMERIC);
ffb776c4 276 } else {
76f29d49 277 asort($aUid, SORT_NUMERIC);
ffb776c4 278 }
76f29d49 279 $aUid = array_keys($aUid);
ffb776c4 280 break;
76f29d49 281 // \sort_numeric section
ffb776c4 282 case 'UID':
76f29d49 283 $aUid = array_reverse($msgs);
ffb776c4 284 break;
6201339c 285 }
76f29d49 286 return $aUid;
cdca177a 287}
288
48af4b64 289/**
0fdc2fb6 290* Returns an indent array for printMessageinfo()
291* This represents the amount of indent needed (value),
292* for this message number (key)
293*/
76f29d49 294
295/*
296 * Notes for future work:
297 * indent_array should contain: indent_level, parent and flags,
298 * sibling notes ..
299 * To achieve that we need to define the following flags:
300 * 0: hasnochildren
301 * 1: haschildren
302 * 2: is first
303 * 4: is last
304 * a node has sibling nodes if it's not the last node
305 * a node has no sibling nodes if it's the last node
306 * By using binary comparations we can store the flag in one var
307 *
308 * example:
309 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
310 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
311 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
312 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
313 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
314 */
ffb776c4 315function get_parent_level ($thread_new) {
48af4b64 316 $parent = '';
317 $child = '';
318 $cutoff = 0;
cdca177a 319
76f29d49 320 /*
321 * loop through the threads and take unwanted characters out
322 * of the thread string then chop it up
323 */
7c612fdd 324 for ($i=0;$i<count($thread_new);$i++) {
325 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
326 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
327 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY);
1c198ef7 328 }
7c612fdd 329 $indent_array = array();
76f29d49 330 if (!$thread_new) {
331 $thread_new = array();
332 }
288bbce0 333 /* looping through the parts of one message thread */
cdca177a 334
7c612fdd 335 for ($i=0;$i<count($thread_new);$i++) {
76f29d49 336 /* first grab the parent, it does not indent */
cdca177a 337
7c612fdd 338 if (isset($thread_new[$i][0])) {
288bbce0 339 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
340 $parent = $regs[1];
341 }
7c612fdd 342 }
343 $indent_array[$parent] = 0;
288bbce0 344
76f29d49 345 /*
346 * now the children, checking each thread portion for
347 * ),(, and space, adjusting the level and space values
348 * to get the indent level
349 */
288bbce0 350 $level = 0;
474528eb 351 $spaces = array();
352 $spaces_total = 0;
7c612fdd 353 $indent = 0;
288bbce0 354 $fake = FALSE;
76f29d49 355 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++$k) {
7c612fdd 356 $chars = count_chars($thread_new[$i][$k], 1);
288bbce0 357 if (isset($chars['40'])) { /* testing for ( */
76f29d49 358 $level += $chars['40'];
7c612fdd 359 }
288bbce0 360 if (isset($chars['41'])) { /* testing for ) */
76f29d49 361 $level -= $chars['41'];
474528eb 362 $spaces[$level] = 0;
288bbce0 363 /* if we were faking lets stop, this portion
76f29d49 364 * of the thread is over
365 */
288bbce0 366 if ($level == $cutoff) {
367 $fake = FALSE;
7c612fdd 368 }
369 }
288bbce0 370 if (isset($chars['32'])) { /* testing for space */
474528eb 371 if (!isset($spaces[$level])) {
372 $spaces[$level] = 0;
373 }
76f29d49 374 $spaces[$level] += $chars['32'];
474528eb 375 }
376 for ($x=0;$x<=$level;$x++) {
377 if (isset($spaces[$x])) {
76f29d49 378 $spaces_total += $spaces[$x];
474528eb 379 }
288bbce0 380 }
474528eb 381 $indent = $level + $spaces_total;
288bbce0 382 /* must have run into a message that broke the thread
76f29d49 383 * so we are adjusting for that portion
384 */
288bbce0 385 if ($fake == TRUE) {
386 $indent = $indent +1;
7c612fdd 387 }
388 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
389 $child = $regs[1];
390 }
288bbce0 391 /* the thread must be broken if $indent == 0
76f29d49 392 * so indent the message once and start faking it
393 */
288bbce0 394 if ($indent == 0) {
395 $indent = 1;
396 $fake = TRUE;
397 $cutoff = $level;
398 }
399 /* dont need abs but if indent was negative
76f29d49 400 * errors would occur
401 */
402 $indent_array[$child] = ($indent < 0) ? 0 : $indent;
474528eb 403 $spaces_total = 0;
cdca177a 404 }
7c612fdd 405 }
406 return $indent_array;
407}
408
409
48af4b64 410/**
0fdc2fb6 411* Returns an array with each element as a string representing one
412* message-thread as returned by the IMAP server.
324ac3c5 413* @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
0fdc2fb6 414*/
324ac3c5 415function get_thread_sort ($imap_stream, $search='ALL') {
ffb776c4 416 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
324ac3c5 417
7c612fdd 418 $thread_temp = array ();
419 if ($sort_by_ref == 1) {
420 $sort_type = 'REFERENCES';
76f29d49 421 } else {
7c612fdd 422 $sort_type = 'ORDEREDSUBJECT';
423 }
324ac3c5 424 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
425
426 $thread_test = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
427 /* fallback to default charset */
428 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
429 $query = "THREAD $sort_type US-ASCII $search";
430 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
431 }
2728fa19 432 if (isset($thread_test[0])) {
9978560b 433 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
76f29d49 434 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
435 $thread_list = trim($regs[1]);
436 break;
437 }
1c198ef7 438 }
76f29d49 439 } else {
440 $thread_list = "";
7c612fdd 441 }
26eca02e 442 if (!preg_match("/OK/", $response)) {
76f29d49 443 $server_sort_array = 'no';
444 return $server_sort_array;
cdca177a 445 }
474528eb 446 if (isset($thread_list)) {
447 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
448 }
76f29d49 449
7c612fdd 450 $char_count = count($thread_temp);
451 $counter = 0;
452 $thread_new = array();
453 $k = 0;
454 $thread_new[0] = "";
76f29d49 455 /*
456 * parse the thread response into separate threads
457 *
458 * example:
459 * [0] => (540)
460 * [1] => (1386)
461 * [2] => (1599 759 959 37)
462 * [3] => (492 1787)
463 * [4] => ((933)(1891))
464 * [5] => (1030 (1497)(845)(1637))
465 */
466 for ($i=0,$iCnt=count($thread_temp);$i<$iCnt;$i++) {
ffb776c4 467 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
468 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
76f29d49 469 } elseif ($thread_temp[$i] == '(') {
ffb776c4 470 $thread_new[$k] .= $thread_temp[$i];
471 $counter++;
76f29d49 472 } elseif ($thread_temp[$i] == ')') {
473 if ($counter > 1) {
474 $thread_new[$k] .= $thread_temp[$i];
475 $counter = $counter - 1;
476 } else {
477 $thread_new[$k] .= $thread_temp[$i];
478 $k++;
479 $thread_new[$k] = "";
480 $counter = $counter - 1;
481 }
ffb776c4 482 }
7c612fdd 483 }
324ac3c5 484
7c612fdd 485 $thread_new = array_reverse($thread_new);
76f29d49 486 /* place the threads after each other in one string */
7c612fdd 487 $thread_list = implode(" ", $thread_new);
488 $thread_list = str_replace("(", " ", $thread_list);
489 $thread_list = str_replace(")", " ", $thread_list);
490 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
60a3e687 491 $server_sort_array = $thread_list;
ffb776c4 492
493 $indent_array = get_parent_level ($thread_new);
324ac3c5 494 return array($thread_list,$indent_array);
7c612fdd 495}
496
034fddf9 497
7b07404c 498function elapsedTime($start) {
0fdc2fb6 499 $stop = gettimeofday();
500 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
501 return $timepassed;
7b07404c 502}
7c612fdd 503
ea5fa593 504// only used in sqimap_get_small_header_list
a18594b2 505function parseString($read,&$i) {
506 $char = $read{$i};
507 $s = '';
508 if ($char == '"') {
0fdc2fb6 509 $iPos = ++$i;
510 while (true) {
511 $iPos = strpos($read,'"',$iPos);
512 if (!$iPos) break;
513 if ($iPos && $read{$iPos -1} != '\\') {
514 $s = substr($read,$i,($iPos-$i));
515 $i = $iPos;
516 break;
517 }
518 $iPos++;
519 if ($iPos > strlen($read)) {
520 break;
521 }
522 }
a18594b2 523 } else if ($char == '{') {
524 $lit_cnt = '';
525 ++$i;
526 $iPos = strpos($read,'}',$i);
527 if ($iPos) {
0fdc2fb6 528 $lit_cnt = substr($read, $i, $iPos - $i);
529 $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
530 /* Now read the literal */
531 $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
532 $i += $lit_cnt;
533 /* temp bugfix (SM 1.5 will have a working clean version)
534 too much work to implement that version right now */
535 --$i;
536 } else { /* should never happen */
a18594b2 537 $i += 3; /* } + \r + \n */
538 $s = '';
0fdc2fb6 539 }
a18594b2 540 } else {
0fdc2fb6 541 return false;
a18594b2 542 }
543 ++$i;
544 return $s;
545}
546
ea5fa593 547// only used in sqimap_get_small_header_list
a18594b2 548function parseArray($read,&$i) {
549 $i = strpos($read,'(',$i);
550 $i_pos = strpos($read,')',$i);
551 $s = substr($read,$i+1,$i_pos - $i -1);
552 $a = explode(' ',$s);
553 if ($i_pos) {
554 $i = $i_pos+1;
555 return $a;
556 } else {
557 return false;
558 }
559}
560
324ac3c5 561function sqimap_get_small_header_list ($imap_stream, $msg_list,
ffb776c4 562 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
8cc8ec79 563 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
ffb776c4 564
324ac3c5 565 $aMessageList = array();
ffb776c4 566 $read_list = array();
567
c075fcfe 568 $bUidFetch = ! in_array('UID', $aFetchItems, true);
8cc8ec79 569
97f7ddf2 570 /* Get the small headers for each message in $msg_list */
324ac3c5 571 if ($msg_list !== NULL) {//$show_num != -1 && $show_num != '*' ) {
a18594b2 572 $msgs_str = sqimap_message_list_squisher($msg_list);
ffb776c4 573 /*
574 * We need to return the data in the same order as the caller supplied
575 * in $msg_list, but IMAP servers are free to return responses in
576 * whatever order they wish... So we need to re-sort manually
577 */
8cc8ec79 578 if ($bUidFetch) {
579 for ($i = 0; $i < sizeof($msg_list); $i++) {
324ac3c5 580 $aMessageList["$msg_list[$i]"] = array();
8cc8ec79 581 }
ffb776c4 582 }
1c198ef7 583 } else {
a18594b2 584 $msgs_str = '1:*';
324ac3c5 585 $aId = array();
a18594b2 586 }
ffb776c4 587
3411d4ec 588 /*
ffb776c4 589 * Create the query
590 */
cdca177a 591
ffb776c4 592 $sFetchItems = '';
593 $query = "FETCH $msgs_str (";
594 if (count($aFetchItems)) {
595 $sFetchItems = implode(' ',$aFetchItems);
596 }
597 if (count($aHeaderFields)) {
598 $sHeaderFields = implode(' ',$aHeaderFields);
599 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
7b07404c 600 }
ffb776c4 601 $query .= trim($sFetchItems) . ')';
324ac3c5 602 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
603 $aMessages = parseFetch($aResponse,$aMessageList);
604 array_reverse($aMessages);
605 return $aMessages;
606}
8cc8ec79 607
324ac3c5 608function parseFetch($aResponse,$aMessageList = array()) {
609 foreach ($aResponse as $r) {
d74abf73 610 $msg = array();
2a9b0fad 611 // use unset because we do isset below
a18594b2 612 $read = implode('',$r);
613
1c198ef7 614 /*
a18594b2 615 * #id<space>FETCH<space>(
616 */
1c198ef7 617
a18594b2 618 /* extract the message id */
619 $i_space = strpos($read,' ',2);
620 $id = substr($read,2,$i_space-2);
324ac3c5 621 $msg['ID'] = $id;
a18594b2 622 $fetch = substr($read,$i_space+1,5);
623 if (!is_numeric($id) && $fetch !== 'FETCH') {
8cc8ec79 624 $msg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
625 break;
a18594b2 626 }
627 $i = strpos($read,'(',$i_space+5);
628 $read = substr($read,$i+1);
629 $i_len = strlen($read);
630 $i = 0;
631 while ($i < $i_len && $i !== false) {
632 /* get argument */
633 $read = trim(substr($read,$i));
634 $i_len = strlen($read);
635 $i = strpos($read,' ');
636 $arg = substr($read,0,$i);
637 ++$i;
638 switch ($arg)
639 {
640 case 'UID':
641 $i_pos = strpos($read,' ',$i);
642 if (!$i_pos) {
643 $i_pos = strpos($read,')',$i);
cdca177a 644 }
a18594b2 645 if ($i_pos) {
646 $unique_id = substr($read,$i,$i_pos-$i);
647 $i = $i_pos+1;
648 } else {
649 break 3;
cdca177a 650 }
a18594b2 651 break;
652 case 'FLAGS':
653 $flags = parseArray($read,$i);
654 if (!$flags) break 3;
ffb776c4 655 $aFlags = array();
a18594b2 656 foreach ($flags as $flag) {
657 $flag = strtolower($flag);
ffb776c4 658 $aFlags[$flag] = true;
cdca177a 659 }
ffb776c4 660 $msg['FLAGS'] = $aFlags;
a18594b2 661 break;
662 case 'RFC822.SIZE':
663 $i_pos = strpos($read,' ',$i);
664 if (!$i_pos) {
665 $i_pos = strpos($read,')',$i);
cdca177a 666 }
a18594b2 667 if ($i_pos) {
ffb776c4 668 $msg['SIZE'] = substr($read,$i,$i_pos-$i);
a18594b2 669 $i = $i_pos+1;
670 } else {
671 break 3;
672 }
1c198ef7 673
8cc8ec79 674 break;
675 case 'ENVELOPE':
676 break; // to be implemented, moving imap code out of the nessages class
677 sqimap_parse_address($read,$i,$msg);
678 break; // to be implemented, moving imap code out of the nessages class
679 case 'BODYSTRUCTURE':
a18594b2 680 break;
681 case 'INTERNALDATE':
c2e29558 682 $msg['INTERNALDATE'] = str_replace(' ', ' ',parseString($read,$i));
a18594b2 683 break;
684 case 'BODY.PEEK[HEADER.FIELDS':
685 case 'BODY[HEADER.FIELDS':
686 $i = strpos($read,'{',$i);
687 $header = parseString($read,$i);
92a52cda 688 if ($header === false) break 2;
2a9b0fad 689 /* First we replace all \r\n by \n, and unfold the header */
690 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
a18594b2 691 /* Now we can make a new header array with */
692 /* each element representing a headerline */
2a9b0fad 693 $hdr = explode("\n" , $hdr);
2714d4ff 694 $aReceived = array();
a18594b2 695 foreach ($hdr as $line) {
696 $pos = strpos($line, ':');
697 if ($pos > 0) {
698 $field = strtolower(substr($line, 0, $pos));
699 if (!strstr($field,' ')) { /* valid field */
700 $value = trim(substr($line, $pos+1));
701 switch($field)
702 {
ffb776c4 703 case 'to': $msg['TO'] = $value; break;
704 case 'cc': $msg['CC'] = $value; break;
705 case 'from': $msg['FROM'] = $value; break;
706 case 'date':
707 $msg['DATE'] = str_replace(' ', ' ', $value);
cdca177a 708 break;
ffb776c4 709 case 'x-priority': $msg['PRIORITY'] = $value; break;
710 case 'subject': $msg['SUBJECT'] = $value; break;
a18594b2 711 case 'content-type':
712 $type = $value;
cdca177a 713 if ($pos = strpos($type, ";")) {
714 $type = substr($type, 0, $pos);
715 }
716 $type = explode("/", $type);
ceacbb9f 717 if(!is_array($type) || count($type) < 2) {
ffb776c4 718 $msg['TYPE0'] = 'text';
719 $msg['TYPE1'] = 'plain';
ceacbb9f 720 } else {
721 $msg['TYPE0'] = strtolower($type[0]);
722 $msg['TYPE1'] = strtolower($type[1]);
cef054e4 723 }
cdca177a 724 break;
2714d4ff 725 case 'received':
726 $aReceived[] = $value;
727 break;
a18594b2 728 default: break;
729 }
cdca177a 730 }
731 }
732 }
2714d4ff 733 if (count($aReceived)) {
734 $msg['RECEIVED'] = $aReceived;
735 }
a18594b2 736 break;
737 default:
738 ++$i;
739 break;
cdca177a 740 }
cdca177a 741 }
6201339c 742 $msgi ="$unique_id";
324ac3c5 743 $msg['UID'] = $unique_id;
ffb776c4 744
324ac3c5 745 $aMessageList[$msgi] = $msg;
a18594b2 746 ++$msgi;
97f7ddf2 747 }
324ac3c5 748 return $aMessageList;
97f7ddf2 749}
750
324ac3c5 751
8cc8ec79 752function sqimap_parse_envelope($read, &$i, &$msg) {
753 $arg_no = 0;
754 $arg_a = array();
755 ++$i;
756 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
757 $char = strtoupper($read{$i});
758 switch ($char) {
759 case '{':
760 case '"':
761 $arg_a[] = parseString($read,$i);
762 ++$arg_no;
763 break;
764 case 'N':
765 /* probably NIL argument */
766 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
767 $arg_a[] = '';
768 ++$arg_no;
769 $i += 2;
770 }
771 break;
772 case '(':
773 /* Address structure (with group support)
774 * Note: Group support is useless on SMTP connections
775 * because the protocol doesn't support it
776 */
777 $addr_a = array();
778 $group = '';
779 $a=0;
780 for (; $i < $cnt && $read{$i} != ')'; ++$i) {
781 if ($read{$i} == '(') {
782 $addr = sqimap_parse_address($read, $i);
783 if (($addr[3] == '') && ($addr[2] != '')) {
784 /* start of group */
785 $group = $addr[2];
786 $group_addr = $addr;
787 $j = $a;
788 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
789 /* end group */
790 if ($a == ($j+1)) { /* no group members */
791 $group_addr[4] = $group;
792 $group_addr[2] = '';
793 $group_addr[0] = "$group: Undisclosed recipients;";
794 $addr_a[] = $group_addr;
795 $group ='';
796 }
797 } else {
798 $addr[4] = $group;
799 $addr_a[] = $addr;
800 }
801 ++$a;
802 }
803 }
804 $arg_a[] = $addr_a;
805 break;
806 default: break;
807 }
808 }
809
810 if (count($arg_a) > 9) {
811 $d = strtr($arg_a[0], array(' ' => ' '));
812 $d = explode(' ', $d);
813 if (!$arg_a[1]) $arg_1[1] = '';
814 $msg['DATE'] = $d; /* argument 1: date */
815 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
816 $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
817 $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
818 $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
819 $msg['TO'] = $arg_a[5]; /* argument 6: to */
820 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
821 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
822 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
823 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
824 }
825}
826
827function sqimap_parse_address($read, &$i) {
828 $arg_a = array();
829 for (; $read{$i} != ')'; ++$i) {
830 $char = strtoupper($read{$i});
831 switch ($char) {
832 case '{':
833 case '"': $arg_a[] = parseString($read,$i); break;
834 case 'n':
835 case 'N':
836 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
837 $arg_a[] = '';
838 $i += 2;
839 }
840 break;
841 default: break;
842 }
843 }
844
845 if (count($arg_a) == 4) {
846 return $arg_a;
847
848// $adr = new AddressStructure();
849// $adr->personal = $arg_a[0];
850// $adr->adl = $arg_a[1];
851// $adr->mailbox = $arg_a[2];
852// $adr->host = $arg_a[3];
853 } else {
854 $adr = '';
855 }
856 return $adr;
857}
858
48af4b64 859/**
0fdc2fb6 860* Returns a message array with all the information about a message.
861* See the documentation folder for more information about this array.
862*/
97f7ddf2 863function sqimap_get_message ($imap_stream, $id, $mailbox) {
461eda6c 864 // typecast to int to prohibit 1:* msgs sets
865 $id = (int) $id;
2d34da11 866 $flags = array();
6201339c 867 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
114f2a24 868 if ($read) {
b69a13a4 869 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
870 if (trim($regs[1])) {
871 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
872 }
873 }
114f2a24 874 } else {
b69a13a4 875 /* the message was not found, maybe the mailbox was modified? */
876 global $sort, $startMessage, $color;
877
878 $errmessage = _("The server couldn't find the message you requested.") .
0fdc2fb6 879 '<p>'._("Most probably your message list was out of date and the message has been moved away or deleted (perhaps by another program accessing the same mailbox).");
b69a13a4 880 /* this will include a link back to the message list */
461eda6c 881 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
b69a13a4 882 exit;
1c198ef7 883 }
2d34da11 884 $bodystructure = implode('',$read);
885 $msg = mime_structure($bodystructure,$flags);
6201339c 886 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
19d470aa 887 $rfc822_header = new Rfc822Header();
767ace1f 888 $rfc822_header->parseHeader($read);
889 $msg->rfc822_header = $rfc822_header;
2d34da11 890 return $msg;
97f7ddf2 891}
892
052e0c26 893?>