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