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