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