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