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