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