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