cleanup up filter plugin
[squirrelmail.git] / functions / imap_messages.php
CommitLineData
59177427 1<?php
7350889b 2
35586184 3/**
0fdc2fb6 4* imap_messages.php
5*
6* Copyright (c) 1999-2004 The SquirrelMail Project Team
7* Licensed under the GNU GPL. For full terms see the file COPYING.
8*
9* This implements functions that manipulate messages
10* NOTE: Quite a few functions in this file are obsolete
11*
12* @version $Id$
13* @package squirrelmail
14* @subpackage imap
15*/
052e0c26 16
d6c32258 17/**
0fdc2fb6 18* Copies specified messages to specified folder
19* @param int $imap_stream The resource ID for the IMAP connection
20* @param string $start Beginning of range to copy
21* @param string $end End of the range to copy
22* @param string $mailbox Which box to copy to
23* @deprecated This function is obsolete and should not be used
24*/
35586184 25function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
6201339c 26 $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
97f7ddf2 27}
28
7c3e0802 29/**
30* copy a range of messages ($id) to another mailbox ($mailbox)
d6c32258 31* @param int $imap_stream The resource ID for the IMAP socket
32* @param string $id The list of messages to copy
33* @param string $mailbox The destination to copy to
34* @return void
7c3e0802 35*/
034fddf9 36function sqimap_msgs_list_copy ($imap_stream, $id, $mailbox) {
1c198ef7 37 $msgs_id = sqimap_message_list_squisher($id);
6201339c 38 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
7c3e0802 39}
40
41/**
42* move a range of messages ($id) to another mailbox. Deletes the originals.
d6c32258 43* @param int $imap_stream The resource ID for the IMAP socket
44* @param string $id The list of messages to move
45* @param string $mailbox The destination to move to
46* @return void
7c3e0802 47*/
48function sqimap_msgs_list_move ($imap_stream, $id, $mailbox) {
7c3e0802 49 $msgs_id = sqimap_message_list_squisher($id);
6201339c 50 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
51 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response,$message, TRUE);
034fddf9 52}
53
54
d6c32258 55/**
0fdc2fb6 56* Deletes specified messages and moves them to trash if possible
57* @deprecated This function is obsolete and should no longer be used
58* @param int $imap_steam The resource ID for the IMAP connection
59* @param string $start Start of range
60* @param string $end End of range
61* @param string $mailbox Mailbox messages are being deleted from
62* @return void
63*/
abafb676 64function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
6201339c 65 global $move_to_trash, $trash_folder, $auto_expunge;
97f7ddf2 66
abafb676 67 if (($move_to_trash == true) && ($bypass_trash != true) &&
68 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
97f7ddf2 69 sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
97f7ddf2 70 }
d8a8203a 71 sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
97f7ddf2 72}
73
6c540963 74function sqimap_msgs_list_delete ($imap_stream, $mailbox, $id, $bypass_trash=false) {
6201339c 75 global $move_to_trash, $trash_folder;
034fddf9 76 $msgs_id = sqimap_message_list_squisher($id);
abafb676 77 if (($move_to_trash == true) && ($bypass_trash != true) &&
78 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
6201339c 79 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($trash_folder), true, $response, $message, TRUE);
034fddf9 80 }
6201339c 81 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response, $message, TRUE);
034fddf9 82}
83
84
d6c32258 85/**
0fdc2fb6 86* Sets the specified messages with specified flag
87*/
d8a8203a 88function sqimap_messages_flag ($imap_stream, $start, $end, $flag, $handle_errors) {
6201339c 89 $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
97f7ddf2 90}
91
034fddf9 92function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
034fddf9 93 $msgs_id = sqimap_message_list_squisher($id);
94 $set_string = ($set ? '+' : '-');
6201339c 95 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
034fddf9 96}
97
48af4b64 98/** @deprecated */
97f7ddf2 99function sqimap_get_small_header ($imap_stream, $id, $sent) {
098ea084 100 $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
97f7ddf2 101 return $res[0];
102}
3411d4ec 103
48af4b64 104/**
0fdc2fb6 105* Sort the message list and crunch to be as small as possible
106* (overflow could happen, so make it small if possible)
107*/
97f7ddf2 108function sqimap_message_list_squisher($messages_array) {
109 if( !is_array( $messages_array ) ) {
fe70ae27 110 return $messages_array;
97f7ddf2 111 }
2d34da11 112
97f7ddf2 113 sort($messages_array, SORT_NUMERIC);
114 $msgs_str = '';
115 while ($messages_array) {
116 $start = array_shift($messages_array);
117 $end = $start;
118 while (isset($messages_array[0]) && $messages_array[0] == $end + 1) {
119 $end = array_shift($messages_array);
120 }
121 if ($msgs_str != '') {
122 $msgs_str .= ',';
123 }
124 $msgs_str .= $start;
125 if ($start != $end) {
126 $msgs_str .= ':' . $end;
127 }
128 }
97f7ddf2 129 return $msgs_str;
3411d4ec 130}
97f7ddf2 131
48af4b64 132/**
ffb776c4 133* Retrieves an array with a sorted uid list. Sorting is done on the imap server
134*
135* @param resource $imap_stream IMAP socket connection
136* @param string $sSortField Field to sort on
137* @param bool $reverse Reverse order search
138* @return array $id sorted uid list
0fdc2fb6 139*/
e0e30169 140function sqimap_get_sort_order ($imap_stream, $sSortField,$reverse) {
ffb776c4 141 global $default_charset,
142 $sent_folder;
2d34da11 143
ffb776c4 144 $id = array();
aa0da530 145 $sort_test = array();
146 $sort_query = '';
2d34da11 147
ffb776c4 148 if ($sSortField) {
149 if ($reverse) {
150 $sSortField = 'REVERSE '.$sSortField;
151 }
152 $query = "SORT ($sSortField) ".strtoupper($default_charset).' ALL';
6201339c 153 $sort_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
aa0da530 154 }
2728fa19 155 if (isset($sort_test[0])) {
ffb776c4 156 for ($i=0,$iCnt=count($sort_test);$i<$iCnt;++$i) {
157 if (preg_match("/^\* SORT (.+)$/", $sort_test[$i], $regs)) {
158 $id = preg_split("/ /", trim($regs[1]));
159 break;
160 }
cdca177a 161 }
0fdc2fb6 162 }
26eca02e 163 if (!preg_match("/OK/", $response)) {
ffb776c4 164 return false;
165 } else {
166 return $id;
cdca177a 167 }
aa0da530 168}
2d34da11 169
26b22b20 170/**
ffb776c4 171* Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
0fdc2fb6 172*
ffb776c4 173* @param resource $imap_stream IMAP socket connection
174* @param string $sSortField Field to sort on
175* @param bool $reverse Reverse order search
76f29d49 176* @return array $aUid sorted uid list
0fdc2fb6 177*/
ffb776c4 178function get_squirrel_sort ($imap_stream, $sSortField, $reverse = false) {
e0e30169 179 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
ffb776c4 180 $msgs = sqimap_get_small_header_list($imap_stream, false, '*',
e0e30169 181 array($sSortField), array());
ffb776c4 182 } else {
183 $msgs = sqimap_get_small_header_list($imap_stream, false, '*',
e0e30169 184 array(), array($sSortField));
ffb776c4 185 }
c2e29558 186 $aUid = array();
76f29d49 187 $walk = false;
ffb776c4 188 switch ($sSortField) {
76f29d49 189 // natcasesort section
ffb776c4 190 case 'FROM':
ffb776c4 191 case 'TO':
76f29d49 192 case 'CC':
193 if(!$walk) {
194 array_walk($msgs, create_function('&$v,&$k,$f',
195 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
196 $addr = parseAddress($v[$f]);
197 $v[$f] = ($addr[0][1]) ? decodeHeader($addr[0][1]):$addr[0][0];'),$sSortField);
198 $walk = true;
cdca177a 199 }
76f29d49 200 // nobreak
ffb776c4 201 case 'SUBJECT':
76f29d49 202 if(!$walk) {
203 array_walk($msgs, create_function('&$v,&$k,$f',
204 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
205 $v[$f] = strtolower(decodeHeader(trim($v[$f])));
206 $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
207 $matches[2] : $v[$f];'),$sSortField);
208 $walk = true;
209 }
ffb776c4 210 foreach ($msgs as $item) {
76f29d49 211 $aUid[$item['ID']] = $item[$sSortField];
ffb776c4 212 }
76f29d49 213 natcasesort($aUid);
214 $aUid = array_keys($aUid);
ffb776c4 215 if ($reverse) {
e432a21c 216 $aUid = array_reverse($aUid);
ffb776c4 217 }
218 break;
76f29d49 219 // \natcasesort section
220 // sort_numeric section
ffb776c4 221 case 'DATE':
76f29d49 222 case 'INTERNALDATE':
223 if(!$walk) {
224 array_walk($msgs, create_function('&$v,$k,$f',
225 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
226 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
227 $walk = true;
ffb776c4 228 }
76f29d49 229 // nobreak;
ffb776c4 230 case 'RFC822.SIZE':
c2e29558 231 if(!$walk) {
232 // redefine $sSortField to maintain the same namespace between
233 // server-side sorting and squirrelmail sorting
234 $sSortField = 'SIZE';
235 }
ffb776c4 236 foreach ($msgs as $item) {
c2e29558 237 $aUid[$item['ID']] = (isset($item[$sSortField])) ? $item[$sSortField] : 0;
ffb776c4 238 }
239 if ($reverse) {
76f29d49 240 arsort($aUid,SORT_NUMERIC);
ffb776c4 241 } else {
76f29d49 242 asort($aUid, SORT_NUMERIC);
ffb776c4 243 }
76f29d49 244 $aUid = array_keys($aUid);
ffb776c4 245 break;
76f29d49 246 // \sort_numeric section
ffb776c4 247 case 'UID':
76f29d49 248 $aUid = array_reverse($msgs);
ffb776c4 249 break;
6201339c 250 }
76f29d49 251 return $aUid;
cdca177a 252}
253
48af4b64 254/**
0fdc2fb6 255* Returns an indent array for printMessageinfo()
256* This represents the amount of indent needed (value),
257* for this message number (key)
258*/
76f29d49 259
260/*
261 * Notes for future work:
262 * indent_array should contain: indent_level, parent and flags,
263 * sibling notes ..
264 * To achieve that we need to define the following flags:
265 * 0: hasnochildren
266 * 1: haschildren
267 * 2: is first
268 * 4: is last
269 * a node has sibling nodes if it's not the last node
270 * a node has no sibling nodes if it's the last node
271 * By using binary comparations we can store the flag in one var
272 *
273 * example:
274 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
275 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
276 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
277 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
278 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
279 */
ffb776c4 280function get_parent_level ($thread_new) {
48af4b64 281 $parent = '';
282 $child = '';
283 $cutoff = 0;
cdca177a 284
76f29d49 285 /*
286 * loop through the threads and take unwanted characters out
287 * of the thread string then chop it up
288 */
7c612fdd 289 for ($i=0;$i<count($thread_new);$i++) {
290 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
291 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
292 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY);
1c198ef7 293 }
7c612fdd 294 $indent_array = array();
76f29d49 295 if (!$thread_new) {
296 $thread_new = array();
297 }
288bbce0 298 /* looping through the parts of one message thread */
cdca177a 299
7c612fdd 300 for ($i=0;$i<count($thread_new);$i++) {
76f29d49 301 /* first grab the parent, it does not indent */
cdca177a 302
7c612fdd 303 if (isset($thread_new[$i][0])) {
288bbce0 304 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
305 $parent = $regs[1];
306 }
7c612fdd 307 }
308 $indent_array[$parent] = 0;
288bbce0 309
76f29d49 310 /*
311 * now the children, checking each thread portion for
312 * ),(, and space, adjusting the level and space values
313 * to get the indent level
314 */
288bbce0 315 $level = 0;
474528eb 316 $spaces = array();
317 $spaces_total = 0;
7c612fdd 318 $indent = 0;
288bbce0 319 $fake = FALSE;
76f29d49 320 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++$k) {
7c612fdd 321 $chars = count_chars($thread_new[$i][$k], 1);
288bbce0 322 if (isset($chars['40'])) { /* testing for ( */
76f29d49 323 $level += $chars['40'];
7c612fdd 324 }
288bbce0 325 if (isset($chars['41'])) { /* testing for ) */
76f29d49 326 $level -= $chars['41'];
474528eb 327 $spaces[$level] = 0;
288bbce0 328 /* if we were faking lets stop, this portion
76f29d49 329 * of the thread is over
330 */
288bbce0 331 if ($level == $cutoff) {
332 $fake = FALSE;
7c612fdd 333 }
334 }
288bbce0 335 if (isset($chars['32'])) { /* testing for space */
474528eb 336 if (!isset($spaces[$level])) {
337 $spaces[$level] = 0;
338 }
76f29d49 339 $spaces[$level] += $chars['32'];
474528eb 340 }
341 for ($x=0;$x<=$level;$x++) {
342 if (isset($spaces[$x])) {
76f29d49 343 $spaces_total += $spaces[$x];
474528eb 344 }
288bbce0 345 }
474528eb 346 $indent = $level + $spaces_total;
288bbce0 347 /* must have run into a message that broke the thread
76f29d49 348 * so we are adjusting for that portion
349 */
288bbce0 350 if ($fake == TRUE) {
351 $indent = $indent +1;
7c612fdd 352 }
353 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
354 $child = $regs[1];
355 }
288bbce0 356 /* the thread must be broken if $indent == 0
76f29d49 357 * so indent the message once and start faking it
358 */
288bbce0 359 if ($indent == 0) {
360 $indent = 1;
361 $fake = TRUE;
362 $cutoff = $level;
363 }
364 /* dont need abs but if indent was negative
76f29d49 365 * errors would occur
366 */
367 $indent_array[$child] = ($indent < 0) ? 0 : $indent;
474528eb 368 $spaces_total = 0;
cdca177a 369 }
7c612fdd 370 }
371 return $indent_array;
372}
373
374
48af4b64 375/**
0fdc2fb6 376* Returns an array with each element as a string representing one
377* message-thread as returned by the IMAP server.
378*/
7c612fdd 379function get_thread_sort ($imap_stream) {
ffb776c4 380 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
d7c82551 381 if (sqsession_is_registered('thread_new')) {
9eb0fbd4 382 sqsession_unregister('thread_new');
7c612fdd 383 }
ffb776c4 384 if (sqsession_is_registered('indent_array')) {
385 sqsession_unregister('indent_array');
386 }
d7c82551 387 if (sqsession_is_registered('server_sort_array')) {
9eb0fbd4 388 sqsession_unregister('server_sort_array');
60a3e687 389 }
7c612fdd 390 $thread_temp = array ();
391 if ($sort_by_ref == 1) {
392 $sort_type = 'REFERENCES';
76f29d49 393 } else {
7c612fdd 394 $sort_type = 'ORDEREDSUBJECT';
395 }
a18594b2 396 $query = "THREAD $sort_type ".strtoupper($default_charset)." ALL";
6201339c 397 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
2728fa19 398 if (isset($thread_test[0])) {
9978560b 399 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
76f29d49 400 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
401 $thread_list = trim($regs[1]);
402 break;
403 }
1c198ef7 404 }
76f29d49 405 } else {
406 $thread_list = "";
7c612fdd 407 }
26eca02e 408 if (!preg_match("/OK/", $response)) {
76f29d49 409 $server_sort_array = 'no';
410 return $server_sort_array;
cdca177a 411 }
474528eb 412 if (isset($thread_list)) {
413 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
414 }
76f29d49 415
7c612fdd 416 $char_count = count($thread_temp);
417 $counter = 0;
418 $thread_new = array();
419 $k = 0;
420 $thread_new[0] = "";
76f29d49 421 /*
422 * parse the thread response into separate threads
423 *
424 * example:
425 * [0] => (540)
426 * [1] => (1386)
427 * [2] => (1599 759 959 37)
428 * [3] => (492 1787)
429 * [4] => ((933)(1891))
430 * [5] => (1030 (1497)(845)(1637))
431 */
432 for ($i=0,$iCnt=count($thread_temp);$i<$iCnt;$i++) {
ffb776c4 433 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
434 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
76f29d49 435 } elseif ($thread_temp[$i] == '(') {
ffb776c4 436 $thread_new[$k] .= $thread_temp[$i];
437 $counter++;
76f29d49 438 } elseif ($thread_temp[$i] == ')') {
439 if ($counter > 1) {
440 $thread_new[$k] .= $thread_temp[$i];
441 $counter = $counter - 1;
442 } else {
443 $thread_new[$k] .= $thread_temp[$i];
444 $k++;
445 $thread_new[$k] = "";
446 $counter = $counter - 1;
447 }
ffb776c4 448 }
7c612fdd 449 }
9eb0fbd4 450 sqsession_register($thread_new, 'thread_new');
7c612fdd 451 $thread_new = array_reverse($thread_new);
76f29d49 452 /* place the threads after each other in one string */
7c612fdd 453 $thread_list = implode(" ", $thread_new);
454 $thread_list = str_replace("(", " ", $thread_list);
455 $thread_list = str_replace(")", " ", $thread_list);
456 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
60a3e687 457 $server_sort_array = $thread_list;
ffb776c4 458
459 $indent_array = get_parent_level ($thread_new);
460 sqsession_register($indent_array, 'indent_array');
461
9eb0fbd4 462 sqsession_register($server_sort_array, 'server_sort_array');
7c612fdd 463 return $thread_list;
464}
465
034fddf9 466
7b07404c 467function elapsedTime($start) {
0fdc2fb6 468 $stop = gettimeofday();
469 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
470 return $timepassed;
7b07404c 471}
7c612fdd 472
ea5fa593 473// only used in sqimap_get_small_header_list
a18594b2 474function parseString($read,&$i) {
475 $char = $read{$i};
476 $s = '';
477 if ($char == '"') {
0fdc2fb6 478 $iPos = ++$i;
479 while (true) {
480 $iPos = strpos($read,'"',$iPos);
481 if (!$iPos) break;
482 if ($iPos && $read{$iPos -1} != '\\') {
483 $s = substr($read,$i,($iPos-$i));
484 $i = $iPos;
485 break;
486 }
487 $iPos++;
488 if ($iPos > strlen($read)) {
489 break;
490 }
491 }
a18594b2 492 } else if ($char == '{') {
493 $lit_cnt = '';
494 ++$i;
495 $iPos = strpos($read,'}',$i);
496 if ($iPos) {
0fdc2fb6 497 $lit_cnt = substr($read, $i, $iPos - $i);
498 $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
499 /* Now read the literal */
500 $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
501 $i += $lit_cnt;
502 /* temp bugfix (SM 1.5 will have a working clean version)
503 too much work to implement that version right now */
504 --$i;
505 } else { /* should never happen */
a18594b2 506 $i += 3; /* } + \r + \n */
507 $s = '';
0fdc2fb6 508 }
a18594b2 509 } else {
0fdc2fb6 510 return false;
a18594b2 511 }
512 ++$i;
513 return $s;
514}
515
ea5fa593 516// only used in sqimap_get_small_header_list
a18594b2 517function parseArray($read,&$i) {
518 $i = strpos($read,'(',$i);
519 $i_pos = strpos($read,')',$i);
520 $s = substr($read,$i+1,$i_pos - $i -1);
521 $a = explode(' ',$s);
522 if ($i_pos) {
523 $i = $i_pos+1;
524 return $a;
525 } else {
526 return false;
527 }
528}
529
ffb776c4 530function sqimap_get_small_header_list ($imap_stream, $msg_list, $show_num=false,
531 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
8cc8ec79 532 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
ffb776c4 533
534 $messages = array();
535 $read_list = array();
536
8cc8ec79 537 if (array_search('UID',$aFetchItems,true) !== false) {
538 $bUidFetch = false;
539 } else {
540 $bUidFetch = true;
541 }
542
97f7ddf2 543 /* Get the small headers for each message in $msg_list */
ffb776c4 544 if ($show_num != '999999' && $show_num != '*' ) {
a18594b2 545 $msgs_str = sqimap_message_list_squisher($msg_list);
ffb776c4 546 /*
547 * We need to return the data in the same order as the caller supplied
548 * in $msg_list, but IMAP servers are free to return responses in
549 * whatever order they wish... So we need to re-sort manually
550 */
8cc8ec79 551 if ($bUidFetch) {
552 for ($i = 0; $i < sizeof($msg_list); $i++) {
553 $messages["$msg_list[$i]"] = array();
554 }
ffb776c4 555 }
1c198ef7 556 } else {
a18594b2 557 $msgs_str = '1:*';
558 }
ffb776c4 559
560
a18594b2 561
3411d4ec 562 /*
ffb776c4 563 * Create the query
564 */
cdca177a 565
ffb776c4 566 $sFetchItems = '';
567 $query = "FETCH $msgs_str (";
568 if (count($aFetchItems)) {
569 $sFetchItems = implode(' ',$aFetchItems);
570 }
571 if (count($aHeaderFields)) {
572 $sHeaderFields = implode(' ',$aHeaderFields);
573 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
7b07404c 574 }
ffb776c4 575 $query .= trim($sFetchItems) . ')';
8cc8ec79 576
577 $read_list = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
2d34da11 578 $i = 0;
1c198ef7 579
a18594b2 580 foreach ($read_list as $r) {
2a9b0fad 581 // use unset because we do isset below
a18594b2 582 $read = implode('',$r);
583
1c198ef7 584 /*
a18594b2 585 * #id<space>FETCH<space>(
586 */
1c198ef7 587
a18594b2 588 /* extract the message id */
589 $i_space = strpos($read,' ',2);
590 $id = substr($read,2,$i_space-2);
591 $fetch = substr($read,$i_space+1,5);
592 if (!is_numeric($id) && $fetch !== 'FETCH') {
8cc8ec79 593 $msg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
594 break;
a18594b2 595 }
596 $i = strpos($read,'(',$i_space+5);
597 $read = substr($read,$i+1);
598 $i_len = strlen($read);
599 $i = 0;
600 while ($i < $i_len && $i !== false) {
601 /* get argument */
602 $read = trim(substr($read,$i));
603 $i_len = strlen($read);
604 $i = strpos($read,' ');
605 $arg = substr($read,0,$i);
606 ++$i;
607 switch ($arg)
608 {
609 case 'UID':
610 $i_pos = strpos($read,' ',$i);
611 if (!$i_pos) {
612 $i_pos = strpos($read,')',$i);
cdca177a 613 }
a18594b2 614 if ($i_pos) {
615 $unique_id = substr($read,$i,$i_pos-$i);
616 $i = $i_pos+1;
617 } else {
618 break 3;
cdca177a 619 }
a18594b2 620 break;
621 case 'FLAGS':
622 $flags = parseArray($read,$i);
623 if (!$flags) break 3;
ffb776c4 624 $aFlags = array();
a18594b2 625 foreach ($flags as $flag) {
626 $flag = strtolower($flag);
ffb776c4 627 $aFlags[$flag] = true;
cdca177a 628 }
ffb776c4 629 $msg['FLAGS'] = $aFlags;
a18594b2 630 break;
631 case 'RFC822.SIZE':
632 $i_pos = strpos($read,' ',$i);
633 if (!$i_pos) {
634 $i_pos = strpos($read,')',$i);
cdca177a 635 }
a18594b2 636 if ($i_pos) {
ffb776c4 637 $msg['SIZE'] = substr($read,$i,$i_pos-$i);
a18594b2 638 $i = $i_pos+1;
639 } else {
640 break 3;
641 }
1c198ef7 642
a18594b2 643 break;
8cc8ec79 644 case 'ENVELOPE':
645 break; // to be implemented, moving imap code out of the nessages class
646 sqimap_parse_address($read,$i,$msg);
647 break; // to be implemented, moving imap code out of the nessages class
648 case 'BODYSTRUCTURE':
649 break;
a18594b2 650 case 'INTERNALDATE':
c2e29558 651 $msg['INTERNALDATE'] = str_replace(' ', ' ',parseString($read,$i));
a18594b2 652 break;
653 case 'BODY.PEEK[HEADER.FIELDS':
654 case 'BODY[HEADER.FIELDS':
655 $i = strpos($read,'{',$i);
656 $header = parseString($read,$i);
92a52cda 657 if ($header === false) break 2;
2a9b0fad 658 /* First we replace all \r\n by \n, and unfold the header */
659 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
a18594b2 660 /* Now we can make a new header array with */
661 /* each element representing a headerline */
2a9b0fad 662 $hdr = explode("\n" , $hdr);
2714d4ff 663 $aReceived = array();
a18594b2 664 foreach ($hdr as $line) {
665 $pos = strpos($line, ':');
666 if ($pos > 0) {
667 $field = strtolower(substr($line, 0, $pos));
668 if (!strstr($field,' ')) { /* valid field */
669 $value = trim(substr($line, $pos+1));
670 switch($field)
671 {
ffb776c4 672 case 'to': $msg['TO'] = $value; break;
673 case 'cc': $msg['CC'] = $value; break;
674 case 'from': $msg['FROM'] = $value; break;
675 case 'date':
676 $msg['DATE'] = str_replace(' ', ' ', $value);
cdca177a 677 break;
ffb776c4 678 case 'x-priority': $msg['PRIORITY'] = $value; break;
679 case 'subject': $msg['SUBJECT'] = $value; break;
a18594b2 680 case 'content-type':
681 $type = $value;
cdca177a 682 if ($pos = strpos($type, ";")) {
683 $type = substr($type, 0, $pos);
684 }
685 $type = explode("/", $type);
cef054e4 686 if(!is_array($type)) {
ffb776c4 687 $msg['TYPE0'] = 'text';
688 $msg['TYPE1'] = 'plain';
cef054e4 689 }
cdca177a 690 break;
2714d4ff 691 case 'received':
692 $aReceived[] = $value;
693 break;
a18594b2 694 default: break;
695 }
cdca177a 696 }
697 }
698 }
2714d4ff 699 if (count($aReceived)) {
700 $msg['RECEIVED'] = $aReceived;
701 }
a18594b2 702 break;
703 default:
704 ++$i;
705 break;
cdca177a 706 }
cdca177a 707 }
6201339c 708 $msgi ="$unique_id";
ffb776c4 709 $msg['ID'] = $unique_id;
710
711 $messages[$msgi] = $msg;
a18594b2 712 ++$msgi;
97f7ddf2 713 }
a18594b2 714 array_reverse($messages);
1c198ef7 715 return $messages;
97f7ddf2 716}
717
8cc8ec79 718function sqimap_parse_envelope($read, &$i, &$msg) {
719 $arg_no = 0;
720 $arg_a = array();
721 ++$i;
722 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
723 $char = strtoupper($read{$i});
724 switch ($char) {
725 case '{':
726 case '"':
727 $arg_a[] = parseString($read,$i);
728 ++$arg_no;
729 break;
730 case 'N':
731 /* probably NIL argument */
732 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
733 $arg_a[] = '';
734 ++$arg_no;
735 $i += 2;
736 }
737 break;
738 case '(':
739 /* Address structure (with group support)
740 * Note: Group support is useless on SMTP connections
741 * because the protocol doesn't support it
742 */
743 $addr_a = array();
744 $group = '';
745 $a=0;
746 for (; $i < $cnt && $read{$i} != ')'; ++$i) {
747 if ($read{$i} == '(') {
748 $addr = sqimap_parse_address($read, $i);
749 if (($addr[3] == '') && ($addr[2] != '')) {
750 /* start of group */
751 $group = $addr[2];
752 $group_addr = $addr;
753 $j = $a;
754 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
755 /* end group */
756 if ($a == ($j+1)) { /* no group members */
757 $group_addr[4] = $group;
758 $group_addr[2] = '';
759 $group_addr[0] = "$group: Undisclosed recipients;";
760 $addr_a[] = $group_addr;
761 $group ='';
762 }
763 } else {
764 $addr[4] = $group;
765 $addr_a[] = $addr;
766 }
767 ++$a;
768 }
769 }
770 $arg_a[] = $addr_a;
771 break;
772 default: break;
773 }
774 }
775
776 if (count($arg_a) > 9) {
777 $d = strtr($arg_a[0], array(' ' => ' '));
778 $d = explode(' ', $d);
779 if (!$arg_a[1]) $arg_1[1] = '';
780 $msg['DATE'] = $d; /* argument 1: date */
781 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
782 $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
783 $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
784 $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
785 $msg['TO'] = $arg_a[5]; /* argument 6: to */
786 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
787 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
788 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
789 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
790 }
791}
792
793function sqimap_parse_address($read, &$i) {
794 $arg_a = array();
795 for (; $read{$i} != ')'; ++$i) {
796 $char = strtoupper($read{$i});
797 switch ($char) {
798 case '{':
799 case '"': $arg_a[] = parseString($read,$i); break;
800 case 'n':
801 case 'N':
802 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
803 $arg_a[] = '';
804 $i += 2;
805 }
806 break;
807 default: break;
808 }
809 }
810
811 if (count($arg_a) == 4) {
812 return $arg_a;
813
814// $adr = new AddressStructure();
815// $adr->personal = $arg_a[0];
816// $adr->adl = $arg_a[1];
817// $adr->mailbox = $arg_a[2];
818// $adr->host = $arg_a[3];
819 } else {
820 $adr = '';
821 }
822 return $adr;
823}
824
48af4b64 825/**
0fdc2fb6 826* Returns a message array with all the information about a message.
827* See the documentation folder for more information about this array.
828*/
97f7ddf2 829function sqimap_get_message ($imap_stream, $id, $mailbox) {
461eda6c 830 // typecast to int to prohibit 1:* msgs sets
831 $id = (int) $id;
2d34da11 832 $flags = array();
6201339c 833 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
114f2a24 834 if ($read) {
b69a13a4 835 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
836 if (trim($regs[1])) {
837 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
838 }
839 }
114f2a24 840 } else {
b69a13a4 841 /* the message was not found, maybe the mailbox was modified? */
842 global $sort, $startMessage, $color;
843
844 $errmessage = _("The server couldn't find the message you requested.") .
0fdc2fb6 845 '<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 846 /* this will include a link back to the message list */
461eda6c 847 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
b69a13a4 848 exit;
1c198ef7 849 }
2d34da11 850 $bodystructure = implode('',$read);
851 $msg = mime_structure($bodystructure,$flags);
6201339c 852 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
19d470aa 853 $rfc822_header = new Rfc822Header();
767ace1f 854 $rfc822_header->parseHeader($read);
855 $msg->rfc822_header = $rfc822_header;
2d34da11 856 return $msg;
97f7ddf2 857}
858
052e0c26 859?>